问:
Images on bxslider that has bx-clone class didnt open in lightbox
I have built up a slider with bxlider which images must open with lightbox.I am using fancybox.When turn came to images that has bx-clone class they didnt open in lightbox opened directly in browser.Here is my code for bxslider

```<code>jQuery('.inner_gallery').bxSlider({
            slideWidth: 185,
            minSlides: 2,
            maxSlides: 3,
            moveSlides: 1,
           pager : false,
           nextSelector: '#news_gallery_slider-next-think',
             prevSelector: '#news_gallery_slider-prev-think',
             nextText: '',
              prevText: '' ,
              onSliderLoad: function(){
                    // Event fires when you click on a clone slide
                    $('.bx-clone a').click(function(event){
                        // Prevent click event for clone slides
                       // event.preventDefault();
                        // Get the href attribute (url) of the clone slide image
                        urlOfImage = $(this).attr('href');
                        // Select the real slide by looking for a matching href attribute
                        realSlide = $(".bxslider li").not(".bx-clone").has('a[href="'+urlOfImage+'"]');
                        // Get the index of the real slide
                        realSlideIndex = $('.bxslider li').not(".bx-clone").index(realSlide);
                        // Tell magnific-popup to open the slide at the index
                        $(this).parents('.bxslider').fancybox();
                    });
                },
            slideMargin: 10
          });
</code>```

Please help me to fix this.

答:
```<code><!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}

/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>

</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
}
}
</script>

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

Body:
I have built up a slider with bxlider which images must open with lightbox.I am using fancybox.When turn came to images that has bx-clone class they didnt open in lightbox opened directly in browser.Here is my code for bxslider

jQuery('.inner_gallery').bxSlider({
            slideWidth: 185,
            minSlides: 2,
            maxSlides: 3,
            moveSlides: 1,
           pager : false,
           nextSelector: '#news_gallery_slider-next-think',
             prevSelector: '#news_gallery_slider-prev-think',
             nextText: '',
              prevText: '' ,
              onSliderLoad: function(){
                    // Event fires when you click on a clone slide
                    $('.bx-clone a').click(function(event){
                        // Prevent click event for clone slides
                       // event.preventDefault();
                        // Get the href attribute (url) of the clone slide image
                        urlOfImage = $(this).attr('href');
                        // Select the real slide by looking for a matching href attribute
                        realSlide = $(".bxslider li").not(".bx-clone").has('a[href="'+urlOfImage+'"]');
                        // Get the index of the real slide
                        realSlideIndex = $('.bxslider li').not(".bx-clone").index(realSlide);
                        // Tell magnific-popup to open the slide at the index
                        $(this).parents('.bxslider').fancybox();
                    });
                },
            slideMargin: 10
          });

Please help me to fix this.

Body:
<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}

/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p>Some text in the Modal..</p>
</div>

</div>

<script>
// Get the modal
var modal = document.getElementById('myModal');

// Get the button that opens the modal
var btn = document.getElementById("myBtn");

// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
    modal.style.display = "none";
}
}
</script>

</body>
</html>


来源: stackexchange

问:
Getting specific data in a JSON format using angularjs
I am getting a JSON format in a manner.But I want to get only specific data in a JSON format.

Here is my code.

```<code><tbody>
    <tr ng-repeat="x in studyTeamObj" align="center">
    <td>
      <select class="form-control" ng-model="x.designation" ng-options="item as item.Emp_Name for item in createStudyObj.Study_User">
        <option value=""></option>
      </select>
    </td>
    <td>
      {{x.designation.Emp_Id}}
    </td>
    <td>
      {{x.designation.Designation}}
    </td>
    <td class="mdrf-add-row-col">
      <i class="fa  fa-minus-circle" data-ng-click="deleteMem($index)"></i>
    </td>
  </tr>
</tbody>
</code>```

Here is my controller.

```<code>$scope.studyTeamObj = [
    { }
];

$scope.addStudyTeam = function () {
    $scope.studyTeamObj.push({
        designation:'',
    });
}

var formList = [];
formList.push(
    { Study_Team: $scope.studyTeamObj },
);
</code>```

While adding I am getting this json format

```<code>{
  "Study_Team": [
    {
      "designation": {
        "Emp_Name": "mdrf",
        "Emp_Id": 2,
        "Designation": "Research Dietitian",
        "DesignationID": 20
      }
    }
  ]
}
</code>```

But I need to get like this,

```<code>{
  "Study_Team":[
    {
      "Study_Id":"1",
      "DesignationID":"20",
    }
  ]
}
</code>```

Can anyone help?

```<code>createStudyService.saveStudy(data).then(function (response)
{ if (response.data === 'Study Master Saved Successfully')
{ alertService.showDialog('md', 'Message', 'Study has been created', 'success', 'studyList');
 } else
 { alertService.showDialog('sm', 'Alert', 'Study Details Not Added Successfully', 'warning'); }
</code>```

答:
```<code>createStudyService.saveStudy(data).then(function (response)
{
if (response.data === 'Study Master Saved Successfully')
{ alertService.showDialog('md', 'Message', 'Study has been created', 'success', 'studyList');
} else
{ alertService.showDialog('sm', 'Alert', 'Study Details Not Added Successfully', 'warning'); } }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am getting a JSON format in a manner.But I want to get only specific data in a JSON format.

Here is my code.

      <select class="form-control" ng-model="x.designation" ng-options="item as item.Emp_Name for item in createStudyObj.Study_User">
        <option value=""></option>
      </select>

      {{x.designation.Emp_Id}}

      {{x.designation.Designation}}

Here is my controller.

$scope.studyTeamObj = [
    { }
];

$scope.addStudyTeam = function () {
    $scope.studyTeamObj.push({
        designation:'',
    });
}

var formList = [];
formList.push(
    { Study_Team: $scope.studyTeamObj },
);

While adding I am getting this json format

{
  "Study_Team": [
    {
      "designation": {
        "Emp_Name": "mdrf",
        "Emp_Id": 2,
        "Designation": "Research Dietitian",
        "DesignationID": 20
      }
    }
  ]
}

But I need to get like this,

{
  "Study_Team":[
    {
      "Study_Id":"1",
      "DesignationID":"20",
    }
  ]
}

Can anyone help?

createStudyService.saveStudy(data).then(function (response)
{ if (response.data === 'Study Master Saved Successfully')
{ alertService.showDialog('md', 'Message', 'Study has been created', 'success', 'studyList');
 } else
 { alertService.showDialog('sm', 'Alert', 'Study Details Not Added Successfully', 'warning'); }


问:
How to call a promise on every value of an array sequentially?
I have an array of values and I want to call a promise function on every value of the array. But this has to happen sequentially. I also want to wait calling the next promise before the previous promise is resolved. </p>

```<code>let array = [ 1, 2, 3 ];

for (var i = 0; i < array.length; i++) {
  MyPromiseFunction(array[i]).then(
     // goToNextPromise
  );
}
</code>```

答:
Using the Array#reduce approach:

```<code>let array = [1, 2, 3, 4];
array.reduce((p, value) => {
    return p.then(() => MyPromiseFunction(value));
}, Promise.resolve());
</code>```

Body:
I have an array of values and I want to call a promise function on every value of the array. But this has to happen sequentially. I also want to wait calling the next promise before the previous promise is resolved.

let array = [ 1, 2, 3 ];

for (var i = 0; i < array.length; i++) {
  MyPromiseFunction(array[i]).then(
     // goToNextPromise
  );
}

Body:
Using the Array#reduce approach:

let array = [1, 2, 3, 4];
array.reduce((p, value) => {
    return p.then(() => MyPromiseFunction(value));
}, Promise.resolve());


问:
SQL if/case statement - returning value from db
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

```<code>Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?
</code>```

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance

答:
```<code>  Select case when name in ('Carl','Manfred',....)
   Then 'Man' else 'Women' end as gender
    from your_table
</code>```

Body:
I have trouble with sql command in MS Sql server .....
I would like to  check names in table. in Column are e.g. Carl, Loius, Manfred, Jenny ....
Is there any way, to create case or if statement :

Case  when name = 'Carl' then 'Man'
else Return original value(name) from table?

(Louis, Manfred, Jenny) ?

If yes, how can i achieve that ? Case statement? If statement?
Thanks in advance


问:
MySQL query with a JOIN and WHERE clause not working
I'm trying to get a MySQL query to work but keep getting an error. I want to join two tables tbl_collab and tbl.uploads with a WHERE clause but can't figure out what I've got wrong. Thanks.

```<code> SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id,
    tbl_uploads.id,tbl_uploads.title,
    FROM tbl_uploads
    LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'
</code>```

I get this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE ' at line 3

答:
```<code>SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id, tbl_uploads.id,tbl_uploads.title FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE tbl_collab.collab_userid='2`
</code>```

<p>Just remove comma before FROM </p>

Body:
I'm trying to get a MySQL query to work but keep getting an error. I want to join two tables tbl_collab and tbl.uploads with a WHERE clause but can't figure out what I've got wrong. Thanks.

 SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id,
    tbl_uploads.id,tbl_uploads.title,
    FROM tbl_uploads
    LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'

I get this error:

#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE ' at line 3

Body:
SELECT tbl_collab.collab_userid, tbl_collab.file, tbl_collab.tbl_upload_id, tbl_uploads.id,tbl_uploads.title FROM tbl_uploads LEFT JOIN tbl_uploads.id ON tbl_collab.tbl_upload_id WHERE tbl_collab.collab_userid='2`

Just remove comma before FROM


问:
php built in webserver not reacheable with ip:port via network cable
I have been trying to make things work for a while now but I did not succeed. I also have done a lot of research, in vain. I really hope that someone is able to help me find the root cause of that issue:

I am trying to connect to my localhost:8000 from another computer (which actually is an arduino ethernet but that doesn't make a difference I guess) by using an ip address. I set the ip address manually in network settings (192.168.1.5).

funny enough, the connection from the external device to 192.168.1.5:80 (which is the normal apache server) works, hence the problem cannot be IP-based.

However, the connection to the php built in webserver running on localhost:8000 does not work. I am trying to access it with '192.168.1.5:8000' obviously - I guess this can not be the mistake?

Now I am wondering what the cause of the problem is. Is anything preventing the connection to port 8000 or does the php built in webserver not respond to the manually given ip? Why does the apache respond to that IP though?

Thanks so much for any hint!!
Steffen

答:
The built in server is, by default, only available on localhost. You have to provide a address wildcard mask, if you want to access it over the local network.

```<code>$ php -S 0.0.0.0:8000
</code>```

However, please be aware of the security implications. If your machine is connected to the internet directly, automatic port scanners will find it sooner or later and may take advantage of security problems.
An address mask of 0.255.255.255 will do fine for 10...* networks, and 0.0.255.255 will do fine for 192.168.. networks.

Body:
The built in server is, by default, only available on localhost. You have to provide a address wildcard mask, if you want to access it over the local network.

$ php -S 0.0.0.0:8000

However, please be aware of the security implications. If your machine is connected to the internet directly, automatic port scanners will find it sooner or later and may take advantage of security problems.
An address mask of 0.255.255.255 will do fine for 10...* networks, and 0.0.255.255 will do fine for 192.168.. networks.

ContentLicense: CC BY-SA 4.0


问:
How to return mocked Data in Observable?
Suppose we have this method in a service that return an Observable:

```<code>getSearchResults(request: LocationSearchRequest){
      return this.http.get(this.getApiUrl(request))
            .map(res => <LocationSearchResponse> res.json())
            .catch(this.handleError);
}
</code>```

How can I modify this code to return the mocked data ratehr then making an actual GET requesr?

```<code>import { MOCKEDDATA } from './mocked-data';
</code>```

It's not a duplicate question. This has nothing to do with testing, jasmine and angualr2 testing api.

答:
You can do:

Observable.of(MOCKEDDATA)

You can also add a delay:

Observable.of(MOCKEDDATA).delay(1000)

Body:
Suppose we have this method in a service that return an Observable:

getSearchResults(request: LocationSearchRequest){
      return this.http.get(this.getApiUrl(request))
            .map(res => <LocationSearchResponse> res.json())
            .catch(this.handleError);
}

How can I modify this code to return the mocked data ratehr then making an actual GET requesr?

import { MOCKEDDATA } from './mocked-data';

It's not a duplicate question. This has nothing to do with testing, jasmine and angualr2 testing api.


问:
My app will not update the values in the array (Mongoose)
It will update all the values except for the ones in the array, it won't do that .

This is my update

```<code>exports.update = function(req, res) {
    if (req.body._id) {
        delete req.body._id;
    }
    plan.findById(req.params.id, function(err, plan) {
        if (err) {
            return handleError(res, err);
        }
        if (!plan) {
            return res.send(404);
        }
        var updated = _.merge(plan, req.body);
        updated.save(function(err) {
            if (err) {
                return handleError(res, err);
            }
            return res.json(200, plan);
        });
    });
};
</code>```

This is my schema

```<code>var ContactSchema = new Schema({
    location: {
        type: String,
        required: true
    },
    total_cost: {
        type: Number,
        required: true
    },
    detailed_expenses: {
        transport: {
            type: String,
            required: true,
            trim: true
        },
        Hotel: {
            type: Number,
            required: true,
            trim: true
        },
        Food: {
            type: Number,
            required: true,
            trim: true
        },
        Attractions: {
            type: Number,
            required: true,
            trim: true
        }
    },
    holiday_type: {
        type: String,
        required: true
    },
    transport_type: {
        type: String,
        required: true
    },
    updated: {
        type: Date,
        default: Date.now
    }
});
</code>```

答:
```<code>var updated = _.merge(plan, req.body);
</code>```

since updated is simple object not the instance of ContactSchema hence it wont contain save function. So you need to create the instance of ContactSchema using updated then only you can use save function on that. Below is your code with update.

```<code>exports.update = function(req, res) {
if (req.body._id) {
    delete req.body._id;
}
plan.findById(req.params.id, function(err, plan) {
    if (err) {
        return handleError(res, err);
    }
    if (!plan) {
        return res.send(404);
    }
    var updated = new plan(req.body); //if req.body is document to be saved
    updated.save(function(err) {
        if (err) {
            return handleError(res, err);
        }
        return res.json(200, plan);
    });
});
</code>```

};

Body:
It will update all the values except for the ones in the array, it won't do that .

This is my update

exports.update = function(req, res) {
    if (req.body._id) {
        delete req.body._id;
    }
    plan.findById(req.params.id, function(err, plan) {
        if (err) {
            return handleError(res, err);
        }
        if (!plan) {
            return res.send(404);
        }
        var updated = _.merge(plan, req.body);
        updated.save(function(err) {
            if (err) {
                return handleError(res, err);
            }
            return res.json(200, plan);
        });
    });
};

This is my schema

var ContactSchema = new Schema({
    location: {
        type: String,
        required: true
    },
    total_cost: {
        type: Number,
        required: true
    },
    detailed_expenses: {
        transport: {
            type: String,
            required: true,
            trim: true
        },
        Hotel: {
            type: Number,
            required: true,
            trim: true
        },
        Food: {
            type: Number,
            required: true,
            trim: true
        },
        Attractions: {
            type: Number,
            required: true,
            trim: true
        }
    },
    holiday_type: {
        type: String,
        required: true
    },
    transport_type: {
        type: String,
        required: true
    },
    updated: {
        type: Date,
        default: Date.now
    }
});

Body:
var updated = _.merge(plan, req.body);

since updated is simple object not the instance of ContactSchema hence it wont contain save function. So you need to create the instance of ContactSchema using updated then only you can use save function on that. Below is your code with update.

exports.update = function(req, res) {
if (req.body._id) {
    delete req.body._id;
}
plan.findById(req.params.id, function(err, plan) {
    if (err) {
        return handleError(res, err);
    }
    if (!plan) {
        return res.send(404);
    }
    var updated = new plan(req.body); //if req.body is document to be saved
    updated.save(function(err) {
        if (err) {
            return handleError(res, err);
        }
        return res.json(200, plan);
    });
});

};


答:
You can use .reduce() for this:

```<code>let array = [ 1, 2, 3 ];

let p = array.reduce(function (p, e) {
    return p.then(function () {
        return MyPromiseFunction(e);
    });
}, Promise.resolve());
</code>```

Title: How to call a promise on every value of an array sequentially?

Body:
You can use .reduce() for this:

let array = [ 1, 2, 3 ];

let p = array.reduce(function (p, e) {
    return p.then(function () {
        return MyPromiseFunction(e);
    });
}, Promise.resolve());


问:
How change Powered By Liferay
How can i change powered by liferay to custom label and hyperlink when clicking liferay .  I am new to liferay development . Can some suggest to create hook for changing basic functionalities in liferay 7. </p>

答:
To change powered by liferay you must create your custom theme for the liferay.

In liferay you can customize the liferay default theme and there you can modify powered by and liferay with any message as per your requirement.

For  more info use these links: Creating theme and Creating basic theme.

Title: How change Powered By Liferay


问:
regarding using of Property sheets VS 2008 c++
I am trying to run a project in c++ using visual studio 2008... in vc++ . Now I have a sample project which takes care of the additional included libraries and some other settings... I want to import these settings into my new project. I tried to save the settings of sample project and include them in mine. But I can't see those properties in my new project.
for eg. sample project displays the linker->input->additional dependencies as cv210d.lib cvaux210d.lib highgui210d.lib cxcore210d.lib cvblobslib.lib but the same thing in my new project shows blank...
CAn you please give me the steps for linking properties??
What I did was save the property page and then added existing property page in my new project.. That doesn't help

答:
This is maybe not exactly what you wanted, but you can fix this problem by just copying the stuff you want (cv210d.lib cvaux210d.lib highgui210d.lib cxcore210d.lib cvblobslib.lib) into the blank space in your project. It's editable, you know what should be there, so just go ahead and put it there.

I guess this will only solve one problem (link dependencies) and you want to solve all such problems by importing. How to do the latter i don't know.

ContentLicense: CC BY-SA 2.5


问:
Type 'void' is not assignable to type 'ObservableInput<{}>'
This error started to pop up after I migrated to TS 2.2.2, so I'm assuming that's the problem... The code did not stop working, but now I receive that error and I tried a few things like returning an empty observable, catching the re-thrown exception and returning an object, nothing seemed to work. Why is this happening now? Shouldn't it understand I'm re-throwing the exception and not expect a return? Am I misreading the error?

This is the complete error description:

Here's the complete code:

```<code>return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        Observable.throw(error.statusText);
    });
</code>```

I tried returning the Observable, but my wrapper method expects a return of type T, which is the return of my deserialized request (map(...)). If I do return the throw this is the error I get:

[ts] Type 'Observable' is not assignable to type 'T'

I'm using:

Angular4

Typescript 2.2.2

答:
you have to return the Observable</p>

```<code> return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        return Observable.throw(error.statusText);
    });
</code>```

Body:
This error started to pop up after I migrated to TS 2.2.2, so I'm assuming that's the problem... The code did not stop working, but now I receive that error and I tried a few things like returning an empty observable, catching the re-thrown exception and returning an object, nothing seemed to work. Why is this happening now? Shouldn't it understand I'm re-throwing the exception and not expect a return? Am I misreading the error?

This is the complete error description:

Here's the complete code:

return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        Observable.throw(error.statusText);
    });

I tried returning the Observable, but my wrapper method expects a return of type T, which is the return of my deserialized request (map(...)). If I do return the throw this is the error I get:

[ts] Type 'Observable' is not assignable to type 'T'

I'm using:

Angular4

Typescript 2.2.2

Body:
you have to return the Observable

 return request
    .map((res: Response) => res.json())
    .catch((error: any) => {
        // todo: log?

        if (error.status == 500) {
            this.alertService.showError(error.statusText);
        } else if (error.status == 588) {
            this.alertService.showAlert(error.statusText);
        }

        return Observable.throw(error.statusText);
    });


问:
Table of totals for the last 12 months, both by month and running
I'd like to have a table that contains 12 rows, one for each of the last 12 months, and two additional columns:

That month's (and only that month's) total spend

Total spend to date, since the beginning of time

The table could look like:

```<code>Month   MonthTotal      RunningTotal
Apr 16  0               6710
May 16  0               6710
Jun 16  2000            8710
Jul 16  0               8710
Aug 16  0               8710
Sep 16  0               8710
Oct 16  1000            9710
Nov 16  0               9710
Dec 16  0               9710
Jan 17  500             10210
Feb 17  0               10210
Mar 17  0               10210
</code>```

I'm almost there but I'm hitting an issue when I have months with no purchases in them - that column is being output as null. Here's my current query:

```<code>with Y(n) as
(
    select 0
    union all
    select n + 1
    from Y
    where n < 11
)

select
    convert(varchar, M.Month) + '/' + convert(varchar, M.Year % 100) as Month,
    isnull(sum(A.Value), 0) as MonthAssetValue,
    sum(A.Value) over (order by A.DateAquired rows between unbounded preceding and current row) as TotalAssetValue

from (
    select
        datepart(year, dateadd(month, -n, getdate())) as [Year],
        datepart(month, dateadd(month, -n, getdate())) as [Month]

    from
        Y
) M

left outer join Asset A
    on (datepart(year, A.DateAquired) = M.Year and datepart(month, A.DateAquired) = M.Month)

group by
    M.Year,
    M.Month,
    A.DateAquired,
    A.Value

order by
    M.Year,
    M.Month
</code>```

Any ideas where I'm going wrong?

Edit:

This is the output I currently get:

```<code>Month   MonthTotal      RunningTotal
Apr 16  0               null
May 16  0               null
Jun 16  2000            8710
Jul 16  0               null
Aug 16  0               null
Sep 16  0               null
Oct 16  1000            9710
Nov 16  0               null
Dec 16  0               null
Jan 17  500             10210
Feb 17  0               null
Mar 17  0               null
</code>```

答:
Your problem is the group by.  It should only have the year and the month:

```<code>group by M.Year, M.Month
</code>```

In addition, don't use varchar() without a length.  And, I think there is a syntax error in the windows function call.  You need to mix the aggregation and window functions.

I would write the query as:

```<code>with Y(n) as (
      select 0
      union all
      select n + 1
      from Y
      where n < 11
     )
select left(m.mmm, 3) + '/' + right(yyyymm.yyyy, 2) as mmmyy,
       coalesce(sum(A.Value), 0) as MonthAssetValue,
       sum(coalesce(sum(A.Value), 0)) over (order by min(dte)) as TotalAssetValue
from (select datename(year, dateadd(month, -n, getdate())) as yyyy,
             datename(month, dateadd(month, -n, getdate())) as mmm,
             dateadd(month, -n, getdate()) as dte
      from Y
     ) yyyymm left outer join
     Asset A
     on datename(year, A.DateAquired) = yyyymm.yyyy and
        datename(month, A.DateAquired) = yyyymm.mmm
group by yyyymm.yyyy, yyyymm.mmm
order by min(dte);
</code>```

Actually, to be honest, I would represent the year/month as YYYY-MM, but I kept your format.

Body:
I'd like to have a table that contains 12 rows, one for each of the last 12 months, and two additional columns:

That month's (and only that month's) total spend

Total spend to date, since the beginning of time

The table could look like:

Month   MonthTotal      RunningTotal
Apr 16  0               6710
May 16  0               6710
Jun 16  2000            8710
Jul 16  0               8710
Aug 16  0               8710
Sep 16  0               8710
Oct 16  1000            9710
Nov 16  0               9710
Dec 16  0               9710
Jan 17  500             10210
Feb 17  0               10210
Mar 17  0               10210

I'm almost there but I'm hitting an issue when I have months with no purchases in them - that column is being output as null. Here's my current query:

with Y(n) as
(
    select 0
    union all
    select n + 1
    from Y
    where n < 11
)

select
    convert(varchar, M.Month) + '/' + convert(varchar, M.Year % 100) as Month,
    isnull(sum(A.Value), 0) as MonthAssetValue,
    sum(A.Value) over (order by A.DateAquired rows between unbounded preceding and current row) as TotalAssetValue

from (
    select
        datepart(year, dateadd(month, -n, getdate())) as [Year],
        datepart(month, dateadd(month, -n, getdate())) as [Month]

    from
        Y
) M

left outer join Asset A
    on (datepart(year, A.DateAquired) = M.Year and datepart(month, A.DateAquired) = M.Month)

group by
    M.Year,
    M.Month,
    A.DateAquired,
    A.Value

order by
    M.Year,
    M.Month

Any ideas where I'm going wrong?

Edit:

This is the output I currently get:

Month   MonthTotal      RunningTotal
Apr 16  0               null
May 16  0               null
Jun 16  2000            8710
Jul 16  0               null
Aug 16  0               null
Sep 16  0               null
Oct 16  1000            9710
Nov 16  0               null
Dec 16  0               null
Jan 17  500             10210
Feb 17  0               null
Mar 17  0               null

Body:
Your problem is the group by.  It should only have the year and the month:

group by M.Year, M.Month

In addition, don't use varchar() without a length.  And, I think there is a syntax error in the windows function call.  You need to mix the aggregation and window functions.

I would write the query as:

with Y(n) as (
      select 0
      union all
      select n + 1
      from Y
      where n < 11
     )
select left(m.mmm, 3) + '/' + right(yyyymm.yyyy, 2) as mmmyy,
       coalesce(sum(A.Value), 0) as MonthAssetValue,
       sum(coalesce(sum(A.Value), 0)) over (order by min(dte)) as TotalAssetValue
from (select datename(year, dateadd(month, -n, getdate())) as yyyy,
             datename(month, dateadd(month, -n, getdate())) as mmm,
             dateadd(month, -n, getdate()) as dte
      from Y
     ) yyyymm left outer join
     Asset A
     on datename(year, A.DateAquired) = yyyymm.yyyy and
        datename(month, A.DateAquired) = yyyymm.mmm
group by yyyymm.yyyy, yyyymm.mmm
order by min(dte);

Actually, to be honest, I would represent the year/month as YYYY-MM, but I kept your format.


问:
How I can to convert my .net WinForms app to Windows 10 Mobile?
I have a program that edits some files. It use .net 4.0. There is TreeView, TextBoxes and Buttons. It does not use any system features. Mostly it do byte converts, serialization and file saving.

I never coded for mobile platforms and this is totally new for me. Now I need to make my program to run on Microsoft Lumia smartphone with Windows 10 Mobile. Is there any easy way for me to do it? Like simple recompiling with another target framework? I don't want to redesign GUI and etc.

答:
This is not possible, as the difference's between the 2 products is too great (e.g. most of the win32/UWP api's are not available on windows phone). However if you want to "repackage" your winforms app for the Universal Windows desktop platform then it is possible.

Microsoft has a toolkit called Windows Bridge. It allows you to repackage existing binaries(which includes winforms) into a Universal windows App. The documentation for converting a winforms app to a Universal Windows App can be found here.

Please note the following requirements/caveats BEFORE repackaging your app

the winforms app has to target the .Net framework 4.6.1

the winforms app may not use elevated mode

the UWP app created after conversion only runs on Windows (10) Desktop

Check here for the full requirements


答:
Your whole syntax after from and left join are wrong.
Please update it as per below query.

Try this:

```<code>SELECT tbl_collab.collab_userid,
       tbl_collab.file,
       tbl_collab.tbl_upload_id,
       tbl_uploads.id,
       tbl_uploads.title
FROM tbl_collab
LEFT JOIN tbl_uploads ON tbl_uploads.id = tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'
</code>```

Title: MySQL query with a JOIN and WHERE clause not working

Body:
Your whole syntax after from and left join are wrong.
Please update it as per below query.

Try this:

SELECT tbl_collab.collab_userid,
       tbl_collab.file,
       tbl_collab.tbl_upload_id,
       tbl_uploads.id,
       tbl_uploads.title
FROM tbl_collab
LEFT JOIN tbl_uploads ON tbl_uploads.id = tbl_collab.tbl_upload_id
WHERE tbl_collab.collab_userid='2'


问:
Example of code which incorrectly tries to re-seat a reference
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

```<code>CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();
</code>```

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

答:
My understanding is that the compiler
  will always generate a default
  assignment operator if you don't
  provide one, which does a shallow copy
  (similar to the default copy
  constructor).

Since a reference is typed (just like
  the underlying object that it refers
  to), doesn't that mean that we will
  always invoke the assignment operator
  when attempting to re-seat a
  reference, thus preventing the
  compiler from complaining about this?

It's not quite like that. Implicit copy (assignment) performs memberwise copying (not necessarily shallow), and the compiler won't let bad things happen implicitly to reference members.

```<code>class X
{
    int& ref;
public:
    X(int& r): ref(r) {}
};

int main()
{
    int i;
    X a(i), b(i);
    a = b;
}
</code>```

Body:
As per my understanding, C++ does not allow you to re-seat a reference.  In other words, you cannot change the object that a reference "refers" to.  It's like a constant pointer in that regard (e.g. int* const a = 3;).

In some code I looked at today, I saw the following:

CMyObject& object = ObjectA().myObject();
// ...
object = ObjectB().myObject();

Immediately my alarm bells went off on the last line of code above.  Wasn't the code trying to re-seat a reference?  Yet the code compiled.

Then I realised that what the code was doing was simply invoking the assignment operator (i.e. operator=) to reassign ObjectA's internal object to ObjectB's internal object.  The object reference still referred to ObjectA, it's just that the contents of ObjectA now matched that of ObjectB.

My understanding is that the compiler will always generate a default assignment operator if you don't provide one, which does a shallow copy (similar to the default copy constructor).

Since a reference is typed (just like the underlying object that it refers to), doesn't that mean that we will always invoke the assignment operator when attempting to re-seat a reference, thus preventing the compiler from complaining about this?

I've been racking my brains out trying to come up with an illegal line of code which will incorrectly try to re-seat a reference, to get the compiler to complain.

Can anyone point me to an example of such code?

Body:
My understanding is that the compiler
  will always generate a default
  assignment operator if you don't
  provide one, which does a shallow copy
  (similar to the default copy
  constructor).

Since a reference is typed (just like
  the underlying object that it refers
  to), doesn't that mean that we will
  always invoke the assignment operator
  when attempting to re-seat a
  reference, thus preventing the
  compiler from complaining about this?

It's not quite like that. Implicit copy (assignment) performs memberwise copying (not necessarily shallow), and the compiler won't let bad things happen implicitly to reference members.

class X
{
    int& ref;
public:
    X(int& r): ref(r) {}
};

int main()
{
    int i;
    X a(i), b(i);
    a = b;
}


问:
Pass a file download from protected route to browser
I have a react frontend and a nodejs/express backend. The backend can serve files (downloads) via a protected route:

```<code>GET /api/file/:id
</code>```

When the frontend wants to start a file download, it sends a request to this endpoint using this code (and the Authorization header is set with a valid token):

```<code>axios.get(`${apiURL}/file/${id}`)
  .then(file => {
   ...
  })
</code>```

The backend responds with this code:

```<code>router.get('/file/:id', requireAuth, = (req, res, next) => {
  ...
  res.set('Content-Type', 'application/pdf');
  res.download(file.path, file.filename);
};);
</code>```

This works fine: the download starts and the binary data is present in the file object of the .then() case of the axios call.

My question:

Instead of downloading the complete file I would like to pass the file to the browser BEFORE the file download starts, so that the browser handles the download like a usual browser-triggered-download, where the browser prompts wether it should download or display the file. How can this be done...?

The solution:

Thanks to @FakeRainBrigand tip I added token based authorization via request parameters to the route (using passport strategy):

```<code>const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromExtractors([
    ExtractJwt.fromHeader('authorization'),
    ExtractJwt.fromUrlQueryParameter('token'),
  ]),
  secretOrKey: secretKey,
};
</code>```

Now I can pass the download directly to the browser to handle it:

```<code>window.location.href = `${apiURL}/file/${_id}?token=${token}`;
</code>```

答:
The Authorization header is going to cause issues here. You should use cookies, at least for this feature. Otherwise, you'll have to include a token in the URL.

The two solutions are window.open in response to an event, or navigating to the url (e.g. location.href = '...').

At least in some browsers, they won't actually navigate when there's a file download, despite you changing the location.

Body:
I have a react frontend and a nodejs/express backend. The backend can serve files (downloads) via a protected route:

GET /api/file/:id

When the frontend wants to start a file download, it sends a request to this endpoint using this code (and the Authorization header is set with a valid token):

axios.get(`${apiURL}/file/${id}`)
  .then(file => {
   ...
  })

The backend responds with this code:

router.get('/file/:id', requireAuth, = (req, res, next) => {
  ...
  res.set('Content-Type', 'application/pdf');
  res.download(file.path, file.filename);
};);

This works fine: the download starts and the binary data is present in the file object of the .then() case of the axios call.

My question:

Instead of downloading the complete file I would like to pass the file to the browser BEFORE the file download starts, so that the browser handles the download like a usual browser-triggered-download, where the browser prompts wether it should download or display the file. How can this be done...?

The solution:

Thanks to @FakeRainBrigand tip I added token based authorization via request parameters to the route (using passport strategy):

const jwtOptions = {
  jwtFromRequest: ExtractJwt.fromExtractors([
    ExtractJwt.fromHeader('authorization'),
    ExtractJwt.fromUrlQueryParameter('token'),
  ]),
  secretOrKey: secretKey,
};

Now I can pass the download directly to the browser to handle it:

window.location.href = `${apiURL}/file/${_id}?token=${token}`;


问:
React not starting with node.js behind Nginx Reverse Proxy
It's the first time I try to set up a Node.js server in production (apart from one Meteor server), and I am encountering a problem I am not able to solve on my own.

I build an application which is using React. Here is the server code:

```<code>// Import part
var react = require('react');
var express = require('express');
var hogan = require('hogan-express');

// Express
const app = express()
app.engine('html', hogan)
app.set('views', __dirname + '/views')
app.use('/', express.static(__dirname + '/public'))
app.set('port', (process.env.PORT || 8100))

app.get('*',(req, res) => {
    res.status(200).render('index.html')
})
</code>```

I set up everything according to https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04 i.e. managing the server using pm2 and configuring Nginx as a reverse proxy. Here is my nginx conf file, which is a copy of the one I am using with Meteor and React :

```<code>upstream node {
    server localhost:8100;
}

server {
    listen 80;
    listen [::]:80;

    server_name subdomain.example.com;
    server_tokens off;

    access_log /var/log/nginx/node_access.log;
    error_log /var/log/nginx/node_error.log;

    location / {
        client_max_body_size 0;
        gzip off;
        proxy_read_timeout 300;
        proxy_connect_timeout 300;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header    Host            $http_host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_pass http://node;
    }
}
</code>```

On one hand, when I hit subdomain.example.com, I got my index.html page served  without React. On the other hand, when using subdomain.example.com:8100, React starts as expected.

How could I solve this ?

答:
I found the solution, so here it is !

It was coming from nginx which needed to access some files it was not allowed to. In my error_log, I got that trace :

```<code>*1 open() "/var/lib/nginx/proxy/3/00/0000000003" failed (13: Permission denied) while reading upstream
</code>```

Using Google lead me to this page https://github.com/dockerfile/nginx/issues/4, which gave me the solution :

```<code>chown -R www-data:www-data /var/lib/nginx
</code>```

Body:
It's the first time I try to set up a Node.js server in production (apart from one Meteor server), and I am encountering a problem I am not able to solve on my own.

I build an application which is using React. Here is the server code:

// Import part
var react = require('react');
var express = require('express');
var hogan = require('hogan-express');

// Express
const app = express()
app.engine('html', hogan)
app.set('views', __dirname + '/views')
app.use('/', express.static(__dirname + '/public'))
app.set('port', (process.env.PORT || 8100))

app.get('*',(req, res) => {
    res.status(200).render('index.html')
})

I set up everything according to https://www.digitalocean.com/community/tutorials/how-to-set-up-a-node-js-application-for-production-on-ubuntu-16-04 i.e. managing the server using pm2 and configuring Nginx as a reverse proxy. Here is my nginx conf file, which is a copy of the one I am using with Meteor and React :

upstream node {
    server localhost:8100;
}

server {
    listen 80;
    listen [::]:80;

    server_name subdomain.example.com;
    server_tokens off;

    access_log /var/log/nginx/node_access.log;
    error_log /var/log/nginx/node_error.log;

    location / {
        client_max_body_size 0;
        gzip off;
        proxy_read_timeout 300;
        proxy_connect_timeout 300;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header    Host            $http_host;
        proxy_set_header    X-Real-IP       $remote_addr;
        proxy_set_header    X-Forwarded-Proto   $scheme;
        proxy_pass http://node;
    }
}

On one hand, when I hit subdomain.example.com, I got my index.html page served  without React. On the other hand, when using subdomain.example.com:8100, React starts as expected.

How could I solve this ?

Body:
I found the solution, so here it is !

It was coming from nginx which needed to access some files it was not allowed to. In my error_log, I got that trace :

*1 open() "/var/lib/nginx/proxy/3/00/0000000003" failed (13: Permission denied) while reading upstream

Using Google lead me to this page https://github.com/dockerfile/nginx/issues/4, which gave me the solution :

chown -R www-data:www-data /var/lib/nginx


问:
Android, set JCIFS log level
From the web, I have seen two answers. One is setting -Djcifs.util.loglevel=3 and another is calling jcifs.Config.setProperty("jcifs.util.loglevel", "3").

I do not know how to do the former one in Android Studio, so I did the latter one. But I see no addditional logs (or any difference), so I am not sure whether it worked or not.

Is it possible to use the former method in Android?

How can I know the log level is correctly set? Any way to confirm that additional log is coming from JCIFS?

Android SDK 25 (7.1.1 Nougat) and JCIFS 1.3.17.

答:
I looked into its source code. It was checking LogStream.level. So, I did the following, and it started printing debug messages.

```<code>LogStream.setLevel(10);
</code>```

Why didn't the methods that the web sites showed work?

Title: Android, set JCIFS log level

Body:
I looked into its source code. It was checking LogStream.level. So, I did the following, and it started printing debug messages.

LogStream.setLevel(10);

Why didn't the methods that the web sites showed work?


答:
Try replace  sum(A.Value) as MonthAssetValue,
    sum(A.Value) over (order by A.DateAquired) rows between unbounded preceding and current row) as TotalAssetValue

with below

SUM(COALESCE(A.Value, 0)) as MonthAssetValue,

SUM(COALESCE(A.Value, 0))  over (order by A.DateAquired) rows between unbounded preceding and current row) as TotalAssetValue

Title: Table of totals for the last 12 months, both by month and running


问:
How do I handle optional functions in a large analysis application?
I'm re-writing an analysis application that calculates dozens of factors that are later used in a statistical model. Currently, the application is structured where the various factors are calculated as such...

```<code>factor1 = calculate_factor1()
factor2 = calculate_factor2()
factor3 = calculate_factor3()
</code>```

...and so on.

But what if the function calculate_factor2() is updated? Because the factors are stored in a database, every other factor does not need to be re-calculated every time the program runs. Or, as another example, we might add factor67 and do not need to calculate the rest.

Right now, we are currently commenting out the lines of factors we don't need to calculate. There has to be a better way?

答:
Without knowing how each function is structured, you can simply create another python script which calls the functions you have created.
I mean - in one doc:

```<code>def calculate_factor_1()

def calculate factor_2()
   ....
</code>```

In another

```<code>factor = calculate_factor_1()
</code>```

This way you need only call the calculation functions individually when you need them. You could also make them callable from the command line so you only call the functions you need as and when.

Python: Run function from the command line  like this :)

Body:
I'm re-writing an analysis application that calculates dozens of factors that are later used in a statistical model. Currently, the application is structured where the various factors are calculated as such...

factor1 = calculate_factor1()
factor2 = calculate_factor2()
factor3 = calculate_factor3()

...and so on.

But what if the function calculate_factor2() is updated? Because the factors are stored in a database, every other factor does not need to be re-calculated every time the program runs. Or, as another example, we might add factor67 and do not need to calculate the rest.

Right now, we are currently commenting out the lines of factors we don't need to calculate. There has to be a better way?

Body:
Without knowing how each function is structured, you can simply create another python script which calls the functions you have created.
I mean - in one doc:

def calculate_factor_1()

def calculate factor_2()
   ....

In another

factor = calculate_factor_1()

This way you need only call the calculation functions individually when you need them. You could also make them callable from the command line so you only call the functions you need as and when.

Python: Run function from the command line  like this :)


问:
How many parallel execution possible using executeOnExecuter?
In my application I need to provide download functionality for document when user tap on document from list.

So, for multiple active threads AsyncTask come into my mind. But I also noticed that people have not recommended AsyncTask for this kind of operation. Because in this case large no. of thread will get start on tapping of document.

Another reason to don't take AsynTask is that "The modern AsyncTask is limited to 128 concurrent tasks". Means that if you queue up more than 138 tasks before they can complete, your app will crash.

Will executeOnExecutor() method solve my purpose or I need to rethink over it?

If I start 50 task at same time then all these task run simeltenioulsy by executeOnExecutor()?

Concurrent task limit(128) also applicable to executeOnExecutor()?

I expect perfect answer.

答:
Another reason to don't take AsynTask is that "The modern AsyncTask is limited to 128 concurrent tasks". Means that if you queue up more than 138 tasks before they can complete, your app will crash.

More accurately, AsyncTask's built-in executors use a 128-element work queue to handle requests that are waiting for threads. Note, though, that this limit is not documented and is subject to change.

Will executeOnExecutor() method solve my purpose

That depends entirely upon what sort of Executor that you supply to executeOnExecutor().

If I start 50 task at same time then all these task run simeltenioulsy by executeOnExecutor()?

No. For starters, your CPU does not have that many cores.

Concurrent task limit(128) also applicable to executeOnExecutor()?

Only if you set up your Executor with that limit. If you use one of the two built-in AsyncTask executors (SERIAL_EXECUTOR, THREAD_POOL_EXECUTOR), then yes, that queue limit should be in place.


问:
Hibernate using Criteria setMaxResults giving SQLGrammarException
I have made criteria, but when I use setMaxResults, it will give me exception SQLGrammarException. But when I comment setMaxResults, it will work an return all entries after first result. I'm using MySQL database.

Code:

```<code>return criteria
            .setFirstResult(start)
            .setMaxResults(end)
            .setFetchSize(end)
            .list();
</code>```

Exception:

```<code>org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.doList(Loader.java:2536)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
    at org.hibernate.loader.Loader.list(Loader.java:2271)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)

....

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ...
</code>```

答:
Problem is now solved. I had wrong dialect in hibernate properties. I had copied my properties from other project that used SQL Server, but this one uses MySQL, so wrong dialect was causing this error.</p>

```<code>hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect
</code>```

Body:
I have made criteria, but when I use setMaxResults, it will give me exception SQLGrammarException. But when I comment setMaxResults, it will work an return all entries after first result. I'm using MySQL database.

Code:

return criteria
            .setFirstResult(start)
            .setMaxResults(end)
            .setFetchSize(end)
            .list();

Exception:

org.hibernate.exception.SQLGrammarException: could not execute query
    at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:92)
    at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
    at org.hibernate.loader.Loader.doList(Loader.java:2536)
    at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2276)
    at org.hibernate.loader.Loader.list(Loader.java:2271)
    at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:119)
    at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1716)
    at org.hibernate.impl.CriteriaImpl.list(CriteriaImpl.java:347)

....

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ...

Body:
Problem is now solved. I had wrong dialect in hibernate properties. I had copied my properties from other project that used SQL Server, but this one uses MySQL, so wrong dialect was causing this error.

hibernate.dialect=org.hibernate.dialect.MySQLInnoDBDialect


问:
c# most efficient way to extract non-overlapping sorted ranges
In order to highlight multiple search text elements in a single string, I have a routine computing the ranges to be highlighted within the string itself.

For example, if I search his+is string in string "this is my misk test" I get higlighted ranges [1,3], [2,3], [5,6], and [12,13].

So my desired result here would be [1,3], [5,6], and [12,13].

Is there a general way to extract non-overlapping ranges from the above list? Or event better, is there a string-specific way to get those?

答:
Sort the ranges by start-index. (Your procedure most likely already does this)

Select the first range

Skip all ranges that start before the currently selected range ends (keep checking the next until you find a range that starts after the currently selected range ends)

Select the new range

Goto 3

If you want to do it text based, it depends on the complexity of your possible search patterns (regexes?). If you specify this, I'd be happy to try to help you out.


问:
Get countries with more than a 50% of Roman Catholic poblation
I'm using cooktop and I want to get a la list of countries that have more than a 50 percent of Roman Catholic poblation.
I've tried the following code:

```<code><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
    <head>
        <title>Example</title>
    </head>
    <body>
        <ul>
        <xsl:for-each select="mondial">
            <xsl:for-each select="country">
            <xsl:sort select="name"/>

            <xsl:if test="contains(religions,'Roman Catholic')">
                <xsl:if test="religions[@percentage > 50]">
                        <li><xsl:value-of select="name"/>
                        <xsl:value-of select="religions"/>
                        <xsl:value-of select="religions/@percentage"/>%
                        </li>
                </xsl:if>
            </xsl:if>
            </xsl:for-each>
        </xsl:for-each>
        </ul>
    </body>
</html>
</xsl:template>
</xsl:stylesheet>
</code>```

The problem is that I'm getting some countries that have less than a 50%.
xml extract from where I'm getting this problem:

```<code><mondial>
<country id='f0_772'
     name='British Virgin Islands'
     capital='f0_1852'
     population='13195'
     datacode='VI'
     total_area='150'
     population_growth='1.29'
     infant_mortality='19.16'
     gdp_total='133'
     inflation='2.5'
     government='dependent territory of the UK'>
     <name >
       British Virgin Islands
     </name>
     <city id='f0_1852'
       country='f0_772'>
       <name >
         Road Town
       </name>
     </city>
     <ethnicgroups  percentage='100'>
       Asian
     </ethnicgroups>
     <religions  percentage='6'>
       Roman Catholic
     </religions>
     <religions  percentage='86'>
       Protestant
     </religions>
     <languages  percentage='100'>
       English
     </languages>
     <encompassed
       continent='f0_126'
       percentage='100'/>
   </country>
</mondial>
</code>```

I think my mistake is that I'm looking if one of the religions have more than a 50% but not taking especifically the Roman Catholic one. If I'm right how can I solve this? Thanks for helping.

答:
You currently have two xsl:if conditions...

```<code><xsl:if test="contains(religions,'Roman Catholic')">
      <xsl:if test="religions[@percentage > 50]">
</code>```

The first is checking, for the current country, if they have a Roman Catholic regligion (so, for your example, that is true)

The second condition then checks if there is a religion that has a percentage greater than 50. It is not checking that the religion is Roman Catholic. The two if conditions are checked separately.

You need to combine the two conditions into one

```<code><xsl:if test="religions[contains(.,'Roman Catholic')][@percentage > 50]">
     ....
</xsl:if>
</code>```

Note that, you may still have an issue with displaying the religion, as this line will only display the first religion.

```<code><xsl:value-of select="religions"/>
</code>```

It might be better if you move the test on religions into the xsl:for-each instead

Try this XSLT

```<code><xsl:for-each select="country[religions[contains(.,'Roman Catholic') and @percentage > 50]]">
    <xsl:sort select="name"/>
    <li>
        <xsl:value-of select="name"/>
        <xsl:variable name="religions" select="religions[contains(.,'Roman Catholic')]" />
        <xsl:value-of select="$religions"/>
        <xsl:value-of select="$religions/@percentage"/>%
    </li>
</xsl:for-each>
</code>```

Body:
I'm using cooktop and I want to get a la list of countries that have more than a 50 percent of Roman Catholic poblation.
I've tried the following code:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">

        <title>Example</title>

        <xsl:for-each select="mondial">
            <xsl:for-each select="country">
            <xsl:sort select="name"/>

            <xsl:if test="contains(religions,'Roman Catholic')">
                <xsl:if test="religions[@percentage > 50]">

<xsl:value-of select="name"/>
                        <xsl:value-of select="religions"/>
                        <xsl:value-of select="religions/@percentage"/>%

                </xsl:if>
            </xsl:if>
            </xsl:for-each>
        </xsl:for-each>

</xsl:template>
</xsl:stylesheet>

The problem is that I'm getting some countries that have less than a 50%.
xml extract from where I'm getting this problem:

<mondial>
<country id='f0_772'
     name='British Virgin Islands'
     capital='f0_1852'
     population='13195'
     datacode='VI'
     total_area='150'
     population_growth='1.29'
     infant_mortality='19.16'
     gdp_total='133'
     inflation='2.5'
     government='dependent territory of the UK'>
     <name >
       British Virgin Islands
     </name>
     <city id='f0_1852'
       country='f0_772'>
       <name >
         Road Town
       </name>
     </city>
     <ethnicgroups  percentage='100'>
       Asian
     </ethnicgroups>
     <religions  percentage='6'>
       Roman Catholic
     </religions>
     <religions  percentage='86'>
       Protestant
     </religions>
     <languages  percentage='100'>
       English
     </languages>
     <encompassed
       continent='f0_126'
       percentage='100'/>
   </country>
</mondial>

I think my mistake is that I'm looking if one of the religions have more than a 50% but not taking especifically the Roman Catholic one. If I'm right how can I solve this? Thanks for helping.

Body:
You currently have two xsl:if conditions...

<xsl:if test="contains(religions,'Roman Catholic')">
      <xsl:if test="religions[@percentage &gt; 50]">

The first is checking, for the current country, if they have a Roman Catholic regligion (so, for your example, that is true)

The second condition then checks if there is a religion that has a percentage greater than 50. It is not checking that the religion is Roman Catholic. The two if conditions are checked separately.

You need to combine the two conditions into one

<xsl:if test="religions[contains(.,'Roman Catholic')][@percentage &gt; 50]">
     ....
</xsl:if>

Note that, you may still have an issue with displaying the religion, as this line will only display the first religion.

<xsl:value-of select="religions"/>

It might be better if you move the test on religions into the xsl:for-each instead

Try this XSLT

<xsl:for-each select="country[religions[contains(.,'Roman Catholic') and @percentage &gt; 50]]">
    <xsl:sort select="name"/>
    <li>
        <xsl:value-of select="name"/>
        <xsl:variable name="religions" select="religions[contains(.,'Roman Catholic')]" />
        <xsl:value-of select="$religions"/>
        <xsl:value-of select="$religions/@percentage"/>%
    </li>
</xsl:for-each>


问:
Specflow Contextual Assertions
We use Specflow and currently, most of our assertions are done using Fluent Assertions, ie look something like:

myval.Should().NotBe(null)

All is working well, however there are some cases in which we want the same code to sometimes Assert Inconclusive, and sometimes not.

For example, let us assume we have a step which calls a method to install the AUT.

The test which asserts that the AUT can be installed correctly will use this method as part of a WHEN/THEN step.

In this instance, if installation fails, we want to proceed as normal and fail the test.

GIVEN The AUT is NOT installed
WHEN I install the AUT

However, for all other tests, the same method may be called as part of a GIVEN step or as part of a BeforeScenario / BeforeFeature hook, and in that instance, if the installation fails, the test should be failed as inconclusive, because it was not the test itself that failed, but the Setup stage.

GIVEN the AUT is installed
WHEN I perform function X of the AUT

So in this example, let us assume that the step definitions for WHEN I install the AUT in the first test, and GIVEN the AUT is installed in the second test simply call a helper method with something like AppFacade.Install()

Of course we can litter AppFacade.Install() and all our other helper methods with conditionals etc, but I was wondering if anyone out there has a more elegant solution - ie way to extend an assertion engine so that it automatically applies this logic - I see no barriers on the Specflow side to achieving this insofar as you can examine the Specflow context objects to detect what kind of step you are on.

Ideally we would like to stick with Fluent Assertions, but if this overly complicates things, we would be willing to reconsider.

答:
Seems to me that you have different requirements for the step when it is a given vs a when or then. Specflow already has something built in to handle this, the fact that the engine will call the method tagged as given for given steps and not for when and then steps.

It feels to me like the simplest solution is to not use the same code for the step when its a given and a when, but have dedicated code for the given step which does what you want differently to the when and then steps.

I'm not sure that you are going to be able to make it bend to your desires and be able to reuse the same steps

Title: Specflow Contextual Assertions


问:
Switch in Xamarin.Android not rendering its UI
I have a Xamarin.Android project that has been in development for awhile.  I went to use my first Android Switch control yesterday.  When the UI rendered on my device (I don't use Xamarion.Android preview editor cause it continually crashes VS).  It only showed off/on text, and no UI for the switch control at all.  This seemed to happen regardless of what width/height I specified for the control etc.

I created a new Android project, dropped the switch on and it renders fine.  I then changed the API level to match my API level (21) and it rendered a bit differently, but again rendered fine.

After much debugging and frustration I discovered that if I implement by own custom drawables for the Thumb and Track that the UI seems to function.

So I was wondering:  Has anyone run into this before?  Do we know what the cause is?

I wanted to document this in case anyone else ran into problems.

Someone requested layout code.  There's not much, but here it is:

```<code><LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content>
<Switch
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>
</LinearLayout>
</code>```

答:
Yes I managed to get this figured out, then forgot to update this.  Unfortunately I couldn't get it working through Xamarin.  Something was messed up and I didn't know what it was and couldn't get an answer from anyone.  So:  I drew it myself (which I ended up needing to do anyway for my app).

In my layout for the switch I set these two drawables:

```<code>android:thumb="@drawable/SwitchThumbTrack"
android:track="@drawable/SwitchTrack"
</code>```

Then in my code when someone toggles it I have a drawable for SwitchTrackOn as well.  If you want, here's some code to make it kind of look like an iOS switch:

SwitchThumbTrack.xml

```<code><?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
   <solid android:color="#FFFFFF"/>
   <size android:width="30dp" android:height="30dp"/>
</shape>
</code>```

SwitchTrack

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <corners android:radius="15dp"/>
   <stroke android:width="1dp" android:color="#ffffff"/>
   <solid android:color="#0000FF" />
   <size android:width="80dp" android:height="30dp"/>
</shape>
</code>```

SwitchTrackOn

```<code><shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <corners android:radius="15dp"/>
  <stroke android:width="1dp" android:color="@color/White"/>
  <solid android:color="#4ED164" />
  <size android:width="80dp" android:height="30dp"/>
</shape>
</code>```

Hope this helps!

James

Body:
I have a Xamarin.Android project that has been in development for awhile.  I went to use my first Android Switch control yesterday.  When the UI rendered on my device (I don't use Xamarion.Android preview editor cause it continually crashes VS).  It only showed off/on text, and no UI for the switch control at all.  This seemed to happen regardless of what width/height I specified for the control etc.

I created a new Android project, dropped the switch on and it renders fine.  I then changed the API level to match my API level (21) and it rendered a bit differently, but again rendered fine.

After much debugging and frustration I discovered that if I implement by own custom drawables for the Thumb and Track that the UI seems to function.

So I was wondering:  Has anyone run into this before?  Do we know what the cause is?

I wanted to document this in case anyone else ran into problems.

Someone requested layout code.  There's not much, but here it is:

<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content>
<Switch
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"/>
</LinearLayout>

Body:
Yes I managed to get this figured out, then forgot to update this.  Unfortunately I couldn't get it working through Xamarin.  Something was messed up and I didn't know what it was and couldn't get an answer from anyone.  So:  I drew it myself (which I ended up needing to do anyway for my app).

In my layout for the switch I set these two drawables:

android:thumb="@drawable/SwitchThumbTrack"
android:track="@drawable/SwitchTrack"

Then in my code when someone toggles it I have a drawable for SwitchTrackOn as well.  If you want, here's some code to make it kind of look like an iOS switch:

SwitchThumbTrack.xml

<?xml version="1.0" encoding="utf-8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
   <solid android:color="#FFFFFF"/>
   <size android:width="30dp" android:height="30dp"/>
</shape>

SwitchTrack

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
   <corners android:radius="15dp"/>
   <stroke android:width="1dp" android:color="#ffffff"/>
   <solid android:color="#0000FF" />
   <size android:width="80dp" android:height="30dp"/>
</shape>

SwitchTrackOn

<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
  <corners android:radius="15dp"/>
  <stroke android:width="1dp" android:color="@color/White"/>
  <solid android:color="#4ED164" />
  <size android:width="80dp" android:height="30dp"/>
</shape>

Hope this helps!

James


问:
Sort a List of users based on statistics from a seperate Table
I have a table of friends where I can get userIds. I also have a table of Stats where the Key is userId.

I want to create a highscore (List) of friends sorted by the score in the stats-table, what would be the best way to sort this list?

I can fill an Array of friends stats like this:

```<code>List<Player> friendsList = getFriends(playerID, limit);
List<Stats> stats = new ArrayList<Stats>();

        for(Player player: friendsList){
            stats.add(ofy().load().type(Stats.class).filter("player", player).first().now());
        }
</code>```

Now I want to sort it and return a List of friends (Player) + score sorted by the highest score.

答:
The first step is to sort stats. In my oppinion the easiest possibilities are:

let Stats implements Comparable and invoke Collections.sort(stats);

create a new Comparator and invoke Collections.sort(stats, new StatsComparator());

Now you can iterate through this list, get the Player by its ID and put it into a new list.

Body:
I have a table of friends where I can get userIds. I also have a table of Stats where the Key is userId.

I want to create a highscore (List) of friends sorted by the score in the stats-table, what would be the best way to sort this list?

I can fill an Array of friends stats like this:

List<Player> friendsList = getFriends(playerID, limit);
List<Stats> stats = new ArrayList<Stats>();

        for(Player player: friendsList){
            stats.add(ofy().load().type(Stats.class).filter("player", player).first().now());
        }

Now I want to sort it and return a List of friends (Player) + score sorted by the highest score.


问:
Creating and clearing rectangles in Flash CS5
I have an XML document that I am reading in and drawing a bunch of rectangles from the data that I get.  This bit of code is inserted in one frame.  Buttons are used to navigate through the frames. A button on the main screen takes you to the frame that draws the rectangles.  I have a Back button on the frame that draws the rectangles that takes you back to the main screen and that works fine but when I click Back, the rectangles that I drew still remain on the scene.  Is there anyway that I can erase all of the rectangles at once?

Thanks

答:
if you want to remove everything in the current frame:</p>

```<code>function disposeFrameContent() : void
{
    while(numChildren)
        removeChildAt(0);
}

// run this code before you change frame
disposeFrameContent();
</code>```

Body:
if you want to remove everything in the current frame:

function disposeFrameContent() : void
{
    while(numChildren)
        removeChildAt(0);
}

// run this code before you change frame
disposeFrameContent();


问:
How do I avoid initializing variables when using recursion?
I'm using a recursive function, but I'm initializing a queue that stores values  within the function. I want to avoid initializing the queue every time I use recursion, because then I lose the values that I need to store. Unfortunately the code I was given is structured in such a way that I can't modify the function definition. </p>

```<code>void function(Graph* graph, int edge_id) {

    Queue * queue = new_queue();

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }
    queue_print(queue);

    if(temp == NULL){
        function(graph, queue->elements->head->data);
    }
</code>```

答:
You need to make your queue static, that way it will live on across multiple calls to your function and only be initialised once. There are numerous questions and answers here about what static does.</p>

```<code>    void function(Graph* graph, int edge_id) {
        static Queue * queue = NULL;
        if (queue == NULL) {
            queue = new_queue();
        }

        Edge* temp = graph->vertices[edge_id]->first_edge;

        while(temp!=NULL){
            queue_enqueue(queue, temp->v);
            temp=temp->next_edge;
        }
        queue_print(queue);

        if(temp == NULL){
            function(graph, queue->elements->head->data);
        }
    }
</code>```

Body:
I'm using a recursive function, but I'm initializing a queue that stores values  within the function. I want to avoid initializing the queue every time I use recursion, because then I lose the values that I need to store. Unfortunately the code I was given is structured in such a way that I can't modify the function definition.

void function(Graph* graph, int edge_id) {

    Queue * queue = new_queue();

    Edge* temp = graph->vertices[edge_id]->first_edge;

    while(temp!=NULL){
        queue_enqueue(queue, temp->v);
        temp=temp->next_edge;
    }
    queue_print(queue);

    if(temp == NULL){
        function(graph, queue->elements->head->data);
    }

Body:
You need to make your queue static, that way it will live on across multiple calls to your function and only be initialised once. There are numerous questions and answers here about what static does.

    void function(Graph* graph, int edge_id) {
        static Queue * queue = NULL;
        if (queue == NULL) {
            queue = new_queue();
        }

        Edge* temp = graph->vertices[edge_id]->first_edge;

        while(temp!=NULL){
            queue_enqueue(queue, temp->v);
            temp=temp->next_edge;
        }
        queue_print(queue);

        if(temp == NULL){
            function(graph, queue->elements->head->data);
        }
    }


问:
ValueError: could not convert string to float: left_column_pixel
l can't read values of pixels from pandas in img() opencv here are my code and the reported errorr

```<code>import cv2
import numpy as np
import csv
import os
import pandas as pd
path_csv='/home/'
npa=pd.read_csv(path_csv+"char.csv", usecols=[2,3,4,5], header=None)
nb_charac=npa.shape[0]-1

#stock the actual letters of your csv in an array
characs=[]
cpt=0
#take characters
f = open(path_csv+"char.csv", 'rt')
reader = csv.reader(f)
for row in reader:
    if cpt>=1: #skip header
        characs.append(str(row[1]))
    cpt+=1

#open your image
path_image= '/home/'
img=cv2.imread(os.path.join(path_image,'image1.png'))

path_save= '/home/2/'
i=0
#for every line on your csv,
for i in range(nb_charac):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i]

    #actual cropping of the image (easy with numpy)
    img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    i+=1

    #charac=charac.strip('"\'')
    #x=switch(charac)
    #saving the image
    cv2.imwrite(path_save+str(charac)+"_"+str(i)+"_"+str(img_charac.shape)+".png",img_charac)
    img_charac2 = 255 - img_charac
    cv2.imwrite(path_save +str(charac)+ "_switched" + str(i) + "_" + str(img_charac2.shape) + ".png", img_charac2)
    print(i)
</code>```

l got the following error

```<code>  img_charac=img[int(coords[2]):int(coords[3]),int(coords[0]):int(coords[1])]
  File "/usr/lib/python2.7/dist-packages/pandas/core/series.py", line 79, in wrapper
    return converter(self.iloc[0])
ValueError: invalid literal for int() with base 10: 'left_column_pixel'
</code>```

the error is related to this line of code :

```<code>img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
</code>```

such that my variable coords is as follow :

```<code>>>> coords=npa.iloc[[1]]
>>> coords
    2    3     4     5
1  38  104  2456  2492
</code>```

and the different values of the column 2,3,4,5 needed in image_char are :

```<code>>>> coords[2]
1    38
Name: 2, dtype: object
>>> coords[3]
1    104
Name: 3, dtype: object
>>> coords[4]
1    2456
Name: 4, dtype: object
>>> coords[5]
1    2492
Name: 5, dtype: object
</code>```

l updated the line of img_charac as follow

```<code> img_charac = img[int(float(coords[2].values[0])):int(float(coords[4].values[0])), int(float(coords[3].values[0])):int(float(coords[5].values[0]))]
</code>```

l don't have anymore

```<code>ValueError: invalid literal for int() with base 10: 'left_column_pixel'
</code>```

but l got the following error :

```<code>ValueError: could not convert string to float: left_column_pixel
</code>```

l noticed that outside the loop img_charac works

答:
I think the ValueError occurs because you are reading the header row of your csv file within the first iteration of your for-loop. The header contains string labels which can't converted to integers:

for i in range(nb_charac) will start with i having 0 as the first value.

Then, coords=npa.iloc[[i]] will return the first row (0th row) of your csv-file.

Since you've set header=None in npa=pd.read_csv(path_csv+"char.csv", usecols=[2,3,4,5], header=None), you iterate over strings within your header row.

So either set header=0 or for i in range(1, nb_charac).

Body:
l can't read values of pixels from pandas in img() opencv here are my code and the reported errorr

import cv2
import numpy as np
import csv
import os
import pandas as pd
path_csv='/home/'
npa=pd.read_csv(path_csv+"char.csv", usecols=[2,3,4,5], header=None)
nb_charac=npa.shape[0]-1

#stock the actual letters of your csv in an array
characs=[]
cpt=0
#take characters
f = open(path_csv+"char.csv", 'rt')
reader = csv.reader(f)
for row in reader:
    if cpt>=1: #skip header
        characs.append(str(row[1]))
    cpt+=1

#open your image
path_image= '/home/'
img=cv2.imread(os.path.join(path_image,'image1.png'))

path_save= '/home/2/'
i=0
#for every line on your csv,
for i in range(nb_charac):

    #get coordinates
    #coords=npa[i,:]
    coords=npa.iloc[[i]]
    charac=characs[i]

    #actual cropping of the image (easy with numpy)
    img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]
    img_charac=cv2.resize(img_charac, (32, 32), interpolation=cv2.INTER_NEAREST)
    i+=1

    #charac=charac.strip('"\'')
    #x=switch(charac)
    #saving the image
    cv2.imwrite(path_save+str(charac)+"_"+str(i)+"_"+str(img_charac.shape)+".png",img_charac)
    img_charac2 = 255 - img_charac
    cv2.imwrite(path_save +str(charac)+ "_switched" + str(i) + "_" + str(img_charac2.shape) + ".png", img_charac2)
    print(i)

l got the following error

  img_charac=img[int(coords[2]):int(coords[3]),int(coords[0]):int(coords[1])]
  File "/usr/lib/python2.7/dist-packages/pandas/core/series.py", line 79, in wrapper
    return converter(self.iloc[0])
ValueError: invalid literal for int() with base 10: 'left_column_pixel'

the error is related to this line of code :

img_charac=img[int(coords[2]):int(coords[4]),int(coords[3]):int(coords[5])]

such that my variable coords is as follow :

>>> coords=npa.iloc[[1]]
>>> coords
    2    3     4     5
1  38  104  2456  2492

and the different values of the column 2,3,4,5 needed in image_char are :

>>> coords[2]
1    38
Name: 2, dtype: object
>>> coords[3]
1    104
Name: 3, dtype: object
>>> coords[4]
1    2456
Name: 4, dtype: object
>>> coords[5]
1    2492
Name: 5, dtype: object

l updated the line of img_charac as follow

 img_charac = img[int(float(coords[2].values[0])):int(float(coords[4].values[0])), int(float(coords[3].values[0])):int(float(coords[5].values[0]))]

l don't have anymore

ValueError: invalid literal for int() with base 10: 'left_column_pixel'

but l got the following error :

ValueError: could not convert string to float: left_column_pixel

l noticed that outside the loop img_charac works


问:
Is there a way to reshape an array that does not maintain the original size (or a convenient work-around)?
As a simplified example, suppose I have a dataset composed of 40 sorted values. The values of this example are all integers, though this is not necessarily the case for the actual dataset.

```<code>import numpy as np
data = np.linspace(1,40,40)
</code>```

I am trying to find the maximum value inside the dataset for certain window sizes. The formula to compute the window sizes yields a pattern that is best executed with arrays (in my opinion). For simplicity sake, let's say the indices denoting the window sizes are a list [1,2,3,4,5]; this corresponds to window sizes of [2,4,8,16,32] (the pattern is 2**index).

```<code>## this code looks long because I've provided docstrings
## just in case the explanation was unclear

def shapeshifter(num_col, my_array=data):
    """
    This function reshapes an array to have 'num_col' columns, where
    'num_col' corresponds to index.
    """
    return my_array.reshape(-1, num_col)

def looper(num_col, my_array=data):
    """
    This function calls 'shapeshifter' and returns a list of the
    MAXimum values of each row in 'my_array' for 'num_col' columns.
    The length of each row (or the number of columns per row if you
    prefer) denotes the size of each window.
    EX:
        num_col = 2
        ==> window_size = 2
        ==> check max( data[1], data[2] ),
                  max( data[3], data[4] ),
                  max( data[5], data[6] ),
                               .
                               .
                               .
                  max( data[39], data[40] )
            for k rows, where k = len(my_array)//num_col
    """
    my_array = shapeshifter(num_col=num_col, my_array=data)
    rows = [my_array[index] for index in range(len(my_array))]
    res = []
    for index in range(len(rows)):
        res.append( max(rows[index]) )
    return res
</code>```

So far, the code is fine. I checked it with the following:

```<code>check1 = looper(2)
check2 = looper(4)
print(check1)
>> [2.0, 4.0, ..., 38.0, 40.0]
print(len(check1))
>> 20
print(check2)
>> [4.0, 8.0, ..., 36.0, 40.0]
print(len(check2))
>> 10
</code>```

So far so good. Now here is my problem.

```<code>def metalooper(col_ls, my_array=data):
    """
    This function calls 'looper' - which calls
    'shapeshifter' - for every 'col' in 'col_ls'.

    EX:
        j_list = [1,2,3,4,5]
        ==> col_ls = [2,4,8,16,32]
        ==> looper(2), looper(4),
            looper(8), ..., looper(32)
        ==> shapeshifter(2), shapeshifter(4),
            shapeshifter(8), ..., shapeshifter(32)
                such that looper(2^j) ==> shapeshifter(2^j)
                for j in j_list
    """
    res = []
    for col in col_ls:
        res.append(looper(num_col=col))
    return res

j_list = [2,4,8,16,32]
check3 = metalooper(j_list)
</code>```

Running the code above provides this error:

```<code>ValueError: total size of new array must be unchanged
</code>```

With 40 data points, the array can be reshaped into 2 columns of 20 rows, or 4 columns of 10 rows, or 8 columns of 5 rows, BUT at 16 columns, the array cannot be reshaped without clipping data since 40/16 ≠ integer. I believe this is the problem with my code, but I do not know how to fix it.

I am hoping there is a way to cutoff the last values in each row that do not fit in each window. If this is not possible, I am hoping I can append zeroes to fill the entries that maintain the size of the original array, so that I can remove the zeroes after. Or maybe even some complicated if - try - break block. What are some ways around this problem?

答:
Here's a generalized way to reshape with truncation:

```<code>def reshape_and_truncate(arr, shape):
    desired_size_factor = np.prod([n for n in shape if n != -1])
    if -1 in shape:  # implicit array size
        desired_size = arr.size // desired_size_factor * desired_size_factor
    else:
        desired_size = desired_size_factor
    return arr.flat[:desired_size].reshape(shape)
</code>```

Which your shapeshifter could use in place of reshape

Body:
As a simplified example, suppose I have a dataset composed of 40 sorted values. The values of this example are all integers, though this is not necessarily the case for the actual dataset.

import numpy as np
data = np.linspace(1,40,40)

I am trying to find the maximum value inside the dataset for certain window sizes. The formula to compute the window sizes yields a pattern that is best executed with arrays (in my opinion). For simplicity sake, let's say the indices denoting the window sizes are a list [1,2,3,4,5]; this corresponds to window sizes of [2,4,8,16,32] (the pattern is 2**index).

## this code looks long because I've provided docstrings
## just in case the explanation was unclear

def shapeshifter(num_col, my_array=data):
    """
    This function reshapes an array to have 'num_col' columns, where
    'num_col' corresponds to index.
    """
    return my_array.reshape(-1, num_col)

def looper(num_col, my_array=data):
    """
    This function calls 'shapeshifter' and returns a list of the
    MAXimum values of each row in 'my_array' for 'num_col' columns.
    The length of each row (or the number of columns per row if you
    prefer) denotes the size of each window.
    EX:
        num_col = 2
        ==> window_size = 2
        ==> check max( data[1], data[2] ),
                  max( data[3], data[4] ),
                  max( data[5], data[6] ),
                               .
                               .
                               .
                  max( data[39], data[40] )
            for k rows, where k = len(my_array)//num_col
    """
    my_array = shapeshifter(num_col=num_col, my_array=data)
    rows = [my_array[index] for index in range(len(my_array))]
    res = []
    for index in range(len(rows)):
        res.append( max(rows[index]) )
    return res

So far, the code is fine. I checked it with the following:

check1 = looper(2)
check2 = looper(4)
print(check1)
>> [2.0, 4.0, ..., 38.0, 40.0]
print(len(check1))
>> 20
print(check2)
>> [4.0, 8.0, ..., 36.0, 40.0]
print(len(check2))
>> 10

So far so good. Now here is my problem.

def metalooper(col_ls, my_array=data):
    """
    This function calls 'looper' - which calls
    'shapeshifter' - for every 'col' in 'col_ls'.

    EX:
        j_list = [1,2,3,4,5]
        ==> col_ls = [2,4,8,16,32]
        ==> looper(2), looper(4),
            looper(8), ..., looper(32)
        ==> shapeshifter(2), shapeshifter(4),
            shapeshifter(8), ..., shapeshifter(32)
                such that looper(2^j) ==> shapeshifter(2^j)
                for j in j_list
    """
    res = []
    for col in col_ls:
        res.append(looper(num_col=col))
    return res

j_list = [2,4,8,16,32]
check3 = metalooper(j_list)

Running the code above provides this error:

ValueError: total size of new array must be unchanged

With 40 data points, the array can be reshaped into 2 columns of 20 rows, or 4 columns of 10 rows, or 8 columns of 5 rows, BUT at 16 columns, the array cannot be reshaped without clipping data since 40/16 ≠ integer. I believe this is the problem with my code, but I do not know how to fix it.

I am hoping there is a way to cutoff the last values in each row that do not fit in each window. If this is not possible, I am hoping I can append zeroes to fill the entries that maintain the size of the original array, so that I can remove the zeroes after. Or maybe even some complicated if - try - break block. What are some ways around this problem?

Body:
Here's a generalized way to reshape with truncation:

def reshape_and_truncate(arr, shape):
    desired_size_factor = np.prod([n for n in shape if n != -1])
    if -1 in shape:  # implicit array size
        desired_size = arr.size // desired_size_factor * desired_size_factor
    else:
        desired_size = desired_size_factor
    return arr.flat[:desired_size].reshape(shape)

Which your shapeshifter could use in place of reshape


问:
Can we use Facebook API in modern java batch?
Can we use Facebook API in modern java batch?
Need some information like is that possible to use that API in modern java batch, if so how can we implement it?</p>

答:
The below link shows all the instructions of using Facebook API in java, not from the official site, but this works so far. Just Add facebook4j-core-2.4.8.jar to your application classpath.

http://facebook4j.github.io/en/index.html


问:
How to get DOM nodes class list using Renderer2
Since Angular 4.0.0, Renderer2 should be used to access DOM nodes. I can’t find a way to access the class List of a DOM node. I can easily add or remove a class but I can’t get a class List. Am I missing something?

    import { Component, ElementRef, Renderer2 } from '@angular/core';
    @Component({
      selector: 'auto-form',
      template: `<form formContainer class="test"></form>
    `
    })
    export class AutoFormComponent {

      constructor(private formContainer:Renderer2) {

      }

    }
```

Renderer2 Documentation

答:
There is no way to get any information from the DOM using Renderer. The renderer is only one-way - from code to DOM.

https://angular.io/docs/ts/latest/api/core/index/Renderer2-class.html

Ok, it seems there are 3 exceptions:

selectRootElement

parentNode

nextSibling

Body:
Since Angular 4.0.0, Renderer2 should be used to access DOM nodes. I can’t find a way to access the class List of a DOM node. I can easily add or remove a class but I can’t get a class List. Am I missing something?

    import { Component, ElementRef, Renderer2 } from '@angular/core';
    @Component({
      selector: 'auto-form',
      template: `<form formContainer class="test"></form>
    `
    })
    export class AutoFormComponent {

      constructor(private formContainer:Renderer2) {

      }

    }

Renderer2 Documentation


问:
Eclipse Java Maven Project Java file which is not on a build path
I met a problem:

when I double click java files in a Maven project the JDT icon tells its not on a build path,

and if I double click java files in normal project it would be normal and I can use ctrl+click to trace the declaration of classes.

How do I set the build path right for those java files in Maven projects?

答: In maven projects, all the files inside the folders src/main/java and src/test/java are in the build path. Usually, there is no need to change that. You should use other folders only in special cases.