问:
How to select record from COSMOS DB dependent upon condition
I have a document in Azure Cosmos DB.

Its Contains :

{
  "id": "58d56db3b3f730153cab383c",
  "activityDate": "2017-02-11T19:04:18Z",
  ...
  ...
  }

I Have a requirement to select the document which is older than 3 days only.

for that I have written :
// SAMPLE STORED PROCEDURE

```<code>function deleteActivitiesBackDate(numberOfDays) {
  var context = getContext();
  var collection = context.getCollection();
  var link = collection.getSelfLink();
  var response = context.getResponse();

 var targetDate = new Date();

 targetDate.setDate(targetDate.getDate() - 3);
 console.log("targetDate is "+targetDate);

  var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate+ '"';
  var run = collection.queryDocuments(link, query, {}, callback);
  function callback(err, docs) {
    if (err){
        return errorResponse(400, err.message);
    }
    if (docs.length > 0){
        for(var i =0;i<docs.length;i++){
        deleteDoc(docs[i]);
       }
    }else {
        return errorResponse(400, "The document was not found.");
    }
  }

  if (!run) {
      return errorResponse(400, "The document could not be deleted.");
  }

  function deleteDoc(document) {
    var docDeleted = collection.deleteDocument(document._self, function(err, result){
        if (err){
            return errorResponse(400, err.message);
        }
        response.setBody(result);
    });

    if (!docDeleted) {
      return errorResponse(400, "The document could not be deleted.");
    }
  };

  function errorResponse(code,message){
    var errorObj = {};
    errorObj.code = code;
    errorObj.message = message;
    errorObj.date = getDateTime();
    return response.setBody(errorObj);
  }

  function getDateTime(){
    var currentdate = new Date();
    var dateTime = currentdate.getFullYear() + "-" +(currentdate.getMonth()+1)+ "-" +     currentdate.getDate()+ " "  +currentdate.getHours()+":"+currentdate.getMinutes()+":"+currentdate.getSeconds();
      return dateTime;
    }
}
</code>```

What can I do to get it fixed?

答:
I think you want to change the select statement to look use the .toISOString() function like this:

```<code>var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate.toISOString()+ '"';
</code>```

You current select statement is comparing a string property to a Date() object.

Also, I think you want to change this line:

```<code>targetDate.setDate(targetDate.getDate() - 3);
</code>```

to this:

```<code>targetDate.setDate(targetDate.getDate() - numberOfDays);
</code>```

Body:
I have a document in Azure Cosmos DB.

Its Contains :

{
  "id": "58d56db3b3f730153cab383c",
  "activityDate": "2017-02-11T19:04:18Z",
  ...
  ...
  }

I Have a requirement to select the document which is older than 3 days only.

for that I have written :
// SAMPLE STORED PROCEDURE

function deleteActivitiesBackDate(numberOfDays) {
  var context = getContext();
  var collection = context.getCollection();
  var link = collection.getSelfLink();
  var response = context.getResponse();

 var targetDate = new Date();

 targetDate.setDate(targetDate.getDate() - 3);
 console.log("targetDate is "+targetDate);

  var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate+ '"';
  var run = collection.queryDocuments(link, query, {}, callback);
  function callback(err, docs) {
    if (err){
        return errorResponse(400, err.message);
    }
    if (docs.length > 0){
        for(var i =0;i<docs.length;i++){
        deleteDoc(docs[i]);
       }
    }else {
        return errorResponse(400, "The document was not found.");
    }
  }

  if (!run) {
      return errorResponse(400, "The document could not be deleted.");
  }

  function deleteDoc(document) {
    var docDeleted = collection.deleteDocument(document._self, function(err, result){
        if (err){
            return errorResponse(400, err.message);
        }
        response.setBody(result);
    });

    if (!docDeleted) {
      return errorResponse(400, "The document could not be deleted.");
    }
  };

  function errorResponse(code,message){
    var errorObj = {};
    errorObj.code = code;
    errorObj.message = message;
    errorObj.date = getDateTime();
    return response.setBody(errorObj);
  }

  function getDateTime(){
    var currentdate = new Date();
    var dateTime = currentdate.getFullYear() + "-" +(currentdate.getMonth()+1)+ "-" +     currentdate.getDate()+ " "  +currentdate.getHours()+":"+currentdate.getMinutes()+":"+currentdate.getSeconds();
      return dateTime;
    }
}

What can I do to get it fixed?

Body:
I think you want to change the select statement to look use the .toISOString() function like this:

var query = 'SELECT * FROM activities a WHERE a.activityDate < "' + targetDate.toISOString()+ '"';

You current select statement is comparing a string property to a Date() object.

Also, I think you want to change this line:

targetDate.setDate(targetDate.getDate() - 3);

to this:

targetDate.setDate(targetDate.getDate() - numberOfDays);


来源: stackexchange

问:
Back button with ajax and iframe
Here is a situation. We have a search feature which uses ajax so that search results can be updated when user changes one of the search filters. The search results page also has 3 ad units that are using iframes. We are using iframes so that when usees use pagination to go different pages or update search results using search filters, the ads can be refreshed.
Now the problem is if user uses pagination to go to different pages and then try to use browser back button, it does not work properly because when you change iframe source, browser add this in history

I would apprecaite any help on how to solve this issue.

答:
You may want to consider loading ads dynamically (i.e. AJAX), instead of using iframes. So, you would simply use a
 to display the ad (loaded with AJAX) instead of an .

ContentLicense: CC BY-SA 2.5

Title: Back button with ajax and iframe

Body: You may want to consider loading ads dynamically (i.e. AJAX), instead of using iframes. So, you would simply use a <div> to display the ad (loaded with AJAX) instead of an <iframe>.


问:
Code Sign Failing from Jenkins for iOS application
I recently updated my Jenkins mac mini machine from yosemite to sierra along with latest xcode ( 8.3.2 ).

Now whenever I try to build my app and code sign from jenkins job, it fails with the following cryptic error

```<code>unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1
</code>```

When i ssh into my jenkins mac mini box as jenkins user and run the same build command everything works fine. Also, It works fine when building and signing the app from xcode. Has anyone seen this problem happening?

答:
I think it's related to this open issue on Fastlane. You could start here:

https://github.com/fastlane/fastlane/issues/8797

ContentLicense: CC BY-SA 3.0

Body:
I recently updated my Jenkins mac mini machine from yosemite to sierra along with latest xcode ( 8.3.2 ).

Now whenever I try to build my app and code sign from jenkins job, it fails with the following cryptic error

unknown error -1=ffffffffffffffff
Command /usr/bin/codesign failed with exit code 1

When i ssh into my jenkins mac mini box as jenkins user and run the same build command everything works fine. Also, It works fine when building and signing the app from xcode. Has anyone seen this problem happening?


问:
Flipping an angle using radians
Hello all you math whizzes out there!

I am struggling with a math problem I am hoping you can help me with.  I have calculated an angle of direction using radians. Within OpenGL ES I move my guy by changing my point value as such:

```<code>

spriteLocation.x -= playerSpeed * cosf(playerRadAngle);
spriteLocation.y -= playerSpeed * sinf(playerRadAngle);

// playerRadAgnle is my angle of direction using radians

</code>```

This works very well to move my sprite in the correct direction.  However, I have decided to keep my sprite "locked" in the middle of the screen and move the background instead.  This requires me to Reverse my calculated angle.  If my sprite's direction in radians is equivalent to 90 degrees, I want to convert it to 270 degrees.  Again, keeping everything in radians.

I will admit that my knowledge of Trig is poor at best.  Is there a way to figure out the opposite angle using radians?  I know I could convert my radians into degrees, then add/subtract 180 degrees, then convert back to radians, but I'm looking for something more efficient.

Thanks in advance....

-Scott

答: object_sprite.rotation = warp_direction - 3.14;</p>

Title: Flipping an angle using radians

Body:
Hello all you math whizzes out there!

I am struggling with a math problem I am hoping you can help me with.  I have calculated an angle of direction using radians. Within OpenGL ES I move my guy by changing my point value as such:

spriteLocation.x -= playerSpeed * cosf(playerRadAngle);
spriteLocation.y -= playerSpeed * sinf(playerRadAngle);

// playerRadAgnle is my angle of direction using radians

This works very well to move my sprite in the correct direction.  However, I have decided to keep my sprite "locked" in the middle of the screen and move the background instead.  This requires me to Reverse my calculated angle.  If my sprite's direction in radians is equivalent to 90 degrees, I want to convert it to 270 degrees.  Again, keeping everything in radians.

I will admit that my knowledge of Trig is poor at best.  Is there a way to figure out the opposite angle using radians?  I know I could convert my radians into degrees, then add/subtract 180 degrees, then convert back to radians, but I'm looking for something more efficient.

Thanks in advance....

-Scott


问:
Sort documents by a present field and a calculated value
How would I go about displaying the best reviews and the worst reviews at the top of the page.

I think the user's "useful" and "notUseful" votes should have an effect on the result.

I have reviews and if people click on the useful and notUseful buttons their Id gets added to the appropriate array (useful or notUseful).

you can tell what a positive or a negative score is by the "overall" score. that is 1 through 5. so 1 would be the worst and 5 would be the best.

I guess If someone gave a review with a 5 overall score but only got one useful but someone gave a score with a 4 overall and 100 people clicking on "useful" the one with 100 people should be shown as the best positive?

I only want to show 2 reviews at the top of the page the best and the worst worst review if there are ties with the overall scores the deciding factor should be the usefulness. so if there are 2 reviews with the same overall score and one of them has 5 usefuls and 10 notUsefuls that would be -5 usefuls and in the other review someone has 5 usefuls and and 4 notUsefuls that would be 1 usefuls so that would be shown to break the tie.

I'm hopping to do it with one mongoose query and not aggregation but I think the answer will be aggregation.

I guess there could be a cut off like scores greater than 3 is a positive review and lower is negative review.

I use mongoose.
Thanks in advance for your help.

some sample data.

```<code>{
    "_id" : ObjectId("5929f89a54aa92274c4e4677"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f88154aa92274c4e4675"),
    "overall" : 3,
    "titleReview" : "53",
    "reviewText" : "53",
    "companyName" : "store1",
    "replies" : [],
    "version" : 2,
    "notUseful" : [ObjectId("58d94c441eb9e52454932db6")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:07:22.207Z"),
    "images" : [],
    "__v" : 0
}

{
    "_id" : ObjectId("5929f8dfa1435135fc5e904b"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f8bab0bc8834f41e9cf8"),
    "overall" : 3,
    "titleReview" : "54",
    "reviewText" : "54",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [ObjectId("5929f83bf371672714bb8d44"), ObjectId("5929f853f371672714bb8d46")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:08:31.516Z"),
    "images" : [],

    "__v" : 0
}

{
    "_id" : ObjectId("5929f956a692e82398aaa2f2"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f93da692e82398aaa2f0"),
    "overall" : 3,
    "titleReview" : "56",
    "reviewText" : "56",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:10:30.608Z"),
    "images" : [],
    "__v" : 0
}
</code>```

答:
If I am reading your question correctly then it appears you want a calculated difference of the "useful" and "nonUseful" votes to also be taken into account when sorting on the "overall" score of the documents.

The better option here is include that calculation in your stored documents, but for totality we will cover both options.

Aggregation

Without changes to your schema and other logic, then aggregation is indeed required to do that calculation. This is best presented as:

```<code>Model.aggregate([
  { "$addFields": {
     "netUseful": {
       "$subtract": [
         { "$size": "$useful" },
         { "$size": "$notUseful" }
       ]
     }
  }},
  { "$sort": { "overall": 1, "netUseful": -1 } }
],function(err, result) {

})
</code>```

So you are basically getting the difference between the two arrays, where more "useful" responses have a positive impact boosting the ranking ans more "notUseful" will reduce that impact. Depending on the MongoDB version you have available you use either $addFields with only the additional field or $project with all the fields you need to return.

The $sort is then performed on the combination of the "overall" score in ascending order as per your rules, and the new field of "netUseful" in descending order ranking "positive" to "negative".

Re-Modelling

Foregoing aggregation altogether, you get a faster result from the plain query. But this of course means maintaining that "score" in the document as you add members to the array.

In basic options, you are using the $inc update operator along with $push to change the score.

So for a "useful" entry, you would do something like this:

```<code>Model.update(
  { "_id": docId, "useful": { "$ne": userId } },
  {
    "$push": { "useful": userId },
    "$inc": { "netUseful": 1 }
  },
  function(err, status) {

  }
)
</code>```

And for a "notUseful" you do the opposite by "decrementing" with a negative value to $inc:

```<code>Model.update(
  { "_id": docId, "nonUseful": { "$ne": userId } },
  {
    "$push": { "nonUseful": userId },
    "$inc": { "netUseful": -1 }
  },
  function(err, status) {

  }
)
</code>```

To cover all cases including where a vote is "changed" from "useFul" to "nonUseful" then you would expand on the logic and implement the appropriate reverse actions with $pull. But this should give the general idea.

N.B The reason we do not use the $addToSet operation here is because we want to make sure the user id is not present in the array when "incrementing" or "decrementing". Thus instead the $ne operator is used to test the value does not exist. If it does, then we do not attempt to modify the array or affect the "netUseful" value. The same applies to the reverse case of "removing" the user from those votes.

Since the calculation is always maintained with each update, you simply perform as query with a standard .sort()

```<code>Model.find().sort({ "overall": 1, "netUseful": -1 }).exec(function(err,results) {

})
</code>```

So by moving the "cost" into the maintenance of the "votes", you remove the overhead of running the aggregation later. For my money, where this is a regular operation and the "sort" does not rely on other run-time parameters which force the calculation to be dynamic, then you use the stored result instead.

Body:
How would I go about displaying the best reviews and the worst reviews at the top of the page.

I think the user's "useful" and "notUseful" votes should have an effect on the result.

I have reviews and if people click on the useful and notUseful buttons their Id gets added to the appropriate array (useful or notUseful).

you can tell what a positive or a negative score is by the "overall" score. that is 1 through 5. so 1 would be the worst and 5 would be the best.

I guess If someone gave a review with a 5 overall score but only got one useful but someone gave a score with a 4 overall and 100 people clicking on "useful" the one with 100 people should be shown as the best positive?

I only want to show 2 reviews at the top of the page the best and the worst worst review if there are ties with the overall scores the deciding factor should be the usefulness. so if there are 2 reviews with the same overall score and one of them has 5 usefuls and 10 notUsefuls that would be -5 usefuls and in the other review someone has 5 usefuls and and 4 notUsefuls that would be 1 usefuls so that would be shown to break the tie.

I'm hopping to do it with one mongoose query and not aggregation but I think the answer will be aggregation.

I guess there could be a cut off like scores greater than 3 is a positive review and lower is negative review.

I use mongoose.
Thanks in advance for your help.

some sample data.

{
    "_id" : ObjectId("5929f89a54aa92274c4e4677"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f88154aa92274c4e4675"),
    "overall" : 3,
    "titleReview" : "53",
    "reviewText" : "53",
    "companyName" : "store1",
    "replies" : [],
    "version" : 2,
    "notUseful" : [ObjectId("58d94c441eb9e52454932db6")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:07:22.207Z"),
    "images" : [],
    "__v" : 0
}

{
    "_id" : ObjectId("5929f8dfa1435135fc5e904b"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f8bab0bc8834f41e9cf8"),
    "overall" : 3,
    "titleReview" : "54",
    "reviewText" : "54",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [ObjectId("5929f83bf371672714bb8d44"), ObjectId("5929f853f371672714bb8d46")],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:08:31.516Z"),
    "images" : [],

    "__v" : 0
}

{
    "_id" : ObjectId("5929f956a692e82398aaa2f2"),
    "compId" : ObjectId("58d94c441eb9e52454932db6"),
    "anonId" : ObjectId("5929f93da692e82398aaa2f0"),
    "overall" : 3,
    "titleReview" : "56",
    "reviewText" : "56",
    "companyName" : "store1",
    "replies" : [],
    "version" : 1,
    "notUseful" : [],
    "useful" : [],
    "dateCreated" : ISODate("2017-05-27T22:10:30.608Z"),
    "images" : [],
    "__v" : 0
}

Body:
If I am reading your question correctly then it appears you want a calculated difference of the "useful" and "nonUseful" votes to also be taken into account when sorting on the "overall" score of the documents.

The better option here is include that calculation in your stored documents, but for totality we will cover both options.

Aggregation

Without changes to your schema and other logic, then aggregation is indeed required to do that calculation. This is best presented as:

Model.aggregate([
  { "$addFields": {
     "netUseful": {
       "$subtract": [
         { "$size": "$useful" },
         { "$size": "$notUseful" }
       ]
     }
  }},
  { "$sort": { "overall": 1, "netUseful": -1 } }
],function(err, result) {

})

So you are basically getting the difference between the two arrays, where more "useful" responses have a positive impact boosting the ranking ans more "notUseful" will reduce that impact. Depending on the MongoDB version you have available you use either $addFields with only the additional field or $project with all the fields you need to return.

The $sort is then performed on the combination of the "overall" score in ascending order as per your rules, and the new field of "netUseful" in descending order ranking "positive" to "negative".

Re-Modelling

Foregoing aggregation altogether, you get a faster result from the plain query. But this of course means maintaining that "score" in the document as you add members to the array.

In basic options, you are using the $inc update operator along with $push to change the score.

So for a "useful" entry, you would do something like this:

Model.update(
  { "_id": docId, "useful": { "$ne": userId } },
  {
    "$push": { "useful": userId },
    "$inc": { "netUseful": 1 }
  },
  function(err, status) {

  }
)

And for a "notUseful" you do the opposite by "decrementing" with a negative value to $inc:

Model.update(
  { "_id": docId, "nonUseful": { "$ne": userId } },
  {
    "$push": { "nonUseful": userId },
    "$inc": { "netUseful": -1 }
  },
  function(err, status) {

  }
)

To cover all cases including where a vote is "changed" from "useFul" to "nonUseful" then you would expand on the logic and implement the appropriate reverse actions with $pull. But this should give the general idea.

N.B The reason we do not use the $addToSet operation here is because we want to make sure the user id is not present in the array when "incrementing" or "decrementing". Thus instead the $ne operator is used to test the value does not exist. If it does, then we do not attempt to modify the array or affect the "netUseful" value. The same applies to the reverse case of "removing" the user from those votes.

Since the calculation is always maintained with each update, you simply perform as query with a standard .sort()

Model.find().sort({ "overall": 1, "netUseful": -1 }).exec(function(err,results) {

})

So by moving the "cost" into the maintenance of the "votes", you remove the overhead of running the aggregation later. For my money, where this is a regular operation and the "sort" does not rely on other run-time parameters which force the calculation to be dynamic, then you use the stored result instead.


问:
TypeError: unhashable type: 'list' when use groupby in python
There is something wrong when I use groupby method:

```<code>data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))
keys = lambda x: [x.year,x.month]
data.groupby(keys).mean()
</code>```

but it has an error: TypeError: unhashable type: 'list'.
I want group by year and month, then calculate the means,why it has wrong?

答:
Convert the list to a str first before using it as groupby keys.</p>

```<code>data.groupby(lambda x: str([x.year,x.month])).mean()
Out[587]:
[2001, 1]   -0.026388
[2001, 2]   -0.076484
[2001, 3]    0.155884
[2001, 4]    0.046513
dtype: float64
</code>```

Body:
There is something wrong when I use groupby method:

data = pd.Series(np.random.randn(100),index=pd.date_range('01/01/2001',periods=100))
keys = lambda x: [x.year,x.month]
data.groupby(keys).mean()

but it has an error: TypeError: unhashable type: 'list'.
I want group by year and month, then calculate the means,why it has wrong?

Body:
Convert the list to a str first before using it as groupby keys.

data.groupby(lambda x: str([x.year,x.month])).mean()
Out[587]:
[2001, 1]   -0.026388
[2001, 2]   -0.076484
[2001, 3]    0.155884
[2001, 4]    0.046513
dtype: float64


问:
Wrong use of forward declaration?
Sometimes I use foreward declaration for nested classes:

```<code>class A;

class B
{
  private:
    A* object_A;
  public:
    B(){}
};
</code>```

The question: What happens if I now use forward declaration of class B (B is declared and defined at this point) for the useage in class C? Does this cause any problems with class B, because it is defined (with implementation of methods etc.) but is used with forward declaration for class C? Does the syntax class B; in the following code-snippet overwrites somehow the previous declared, defined and implemented class B?

```<code>class B;

class C
{
  private:
    B* object_B;
  public:
    C(){}
};
</code>```

答:
Does the syntax class B; in the following code-snippet overwrites somehow the previous declared, defined and implemented class B?

Forward declarations are not about overwriting. It is just giving hint to the compiler that the type definition is implemented somewhere. For user defined pointer types, compiler does not require the definition but needs to know what is the type of the object.

Title: Wrong use of forward declaration?

Body:
Sometimes I use foreward declaration for nested classes:

class A;

class B
{
  private:
    A* object_A;
  public:
    B(){}
};

The question: What happens if I now use forward declaration of class B (B is declared and defined at this point) for the useage in class C? Does this cause any problems with class B, because it is defined (with implementation of methods etc.) but is used with forward declaration for class C? Does the syntax class B; in the following code-snippet overwrites somehow the previous declared, defined and implemented class B?

class B;

class C
{
  private:
    B* object_B;
  public:
    C(){}
};


问:
human body border detection using .NET
there is any body know any library that enable us to detect the body border or help me notify to body movment according to stream of images</p>

答:
Link to MSFT SDK site

Update:

Just in from ZD.NET "Microsoft readies hobbyist Kinect development kit; promises commercial version later" link

Prior Post

The makers/OEM of the Kinect is PrimeSense.  They make both the kinect and an independent devkit.  They recently released open source drivers that are compatible with both XBox's Kinect and the smaller DevKit.  You might as well get the drivers straight from the source.  I'm not sure what value a 3rd party library (openKinect) will offer.

Get the unified Kinect and DevKit drivers here: http://www.openni.org/  Windows and Unix support is available.

Title: human body border detection using .NET


问:
Error in jquery does not display FullCalendar
Make the insertion of the code as the official documentation of the FullCalendar says but at the time of running the page does not show me the calendar.
imagen

I think the error can be to a script that I attached on my web these are all I work with.

```<code>     <!-- calendar -->
        <link href='temporal/fullcalendar.min.css' rel='stylesheet' />
        <link href='temporal/fullcalendar.print.min.css' rel='stylesheet' media='print' />
        <script src='temporal/moment.min.js'></script>
        <script src='temporal/jquery.min.js'></script>
        <script src='temporal/fullcalendar.min.js'></script>

        <!-- CSS -->
        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/style-responsive.css">
        <link rel="stylesheet" href="css/animate.min.css">
        <link rel="stylesheet" href="css/vertical-rhythm.min.css">
        <link rel="stylesheet" href="css/owl.carousel.css">
        <link rel="stylesheet" href="css/magnific-popup.css">
        <script type="text/javascript" src="js/push.min.js"></script>

            <script>

    $(document).ready(function() {

        $('#calendar').fullCalendar({
            header: {
                left: 'prev,next today',
                center: 'title',
                right: 'month,basicWeek,basicDay'
            },
            defaultDate: '2017-05-12',
            navLinks: true, // can click day/week names to navigate views
            editable: true,
            eventLimit: true, // allow "more" link when too many events
            events: [
                {
                    title: 'All Day Event',
                    start: '2017-05-01'
                },
                {
                    title: 'Long Event',
                    start: '2017-05-07',
                    end: '2017-05-10'
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: '2017-05-09T16:00:00'
                },
                {
                    id: 999,
                    title: 'Repeating Event',
                    start: '2017-05-16T16:00:00'
                },
                {
                    title: 'Conference',
                    start: '2017-05-11',
                    end: '2017-05-13'
                },
                {
                    title: 'Meeting',
                    start: '2017-05-12T10:30:00',
                    end: '2017-05-12T12:30:00'
                },
                {
                    title: 'Lunch',
                    start: '2017-05-12T12:00:00'
                },
                {
                    title: 'Meeting',
                    start: '2017-05-12T14:30:00'
                },
                {
                    title: 'Happy Hour',
                    start: '2017-05-12T17:30:00'
                },
                {
                    title: 'Dinner',
                    start: '2017-05-12T20:00:00'
                },
                {
                    title: 'Birthday Party',
                    start: '2017-05-13T07:00:00'
                },
                {
                    title: 'Click for Google',
                    url: 'http://google.com/',
                    start: '2017-05-28'
                }
            ]
        });

    });

</script>
            <style type="text/css">
            #calendar {
        max-width: 900px;
        margin: 0 auto;
        font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
        font-size: 14px;

    }
            </style>

<div id="calendar"></div>

        <!-- JS -->
        <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
        <script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
        <script type="text/javascript" src="js/bootstrap.min.js"></script>
        <script type="text/javascript" src="js/SmoothScroll.js"></script>
        <script type="text/javascript" src="js/jquery.scrollTo.min.js"></script>
        <script type="text/javascript" src="js/jquery.localScroll.min.js"></script>
        <script type="text/javascript" src="js/jquery.viewport.mini.js"></script>
        <script type="text/javascript" src="js/jquery.countTo.js"></script>
        <script type="text/javascript" src="js/jquery.appear.js"></script>
        <script type="text/javascript" src="js/jquery.sticky.js"></script>
        <script type="text/javascript" src="js/jquery.parallax-1.1.3.js"></script>
        <script type="text/javascript" src="js/jquery.fitvids.js"></script>
        <script type="text/javascript" src="js/owl.carousel.min.js"></script>
        <script type="text/javascript" src="js/isotope.pkgd.min.js"></script>
        <script type="text/javascript" src="js/imagesloaded.pkgd.min.js"></script>
        <script type="text/javascript" src="js/jquery.magnific-popup.min.js"></script>
        <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAZsDkJFLS0b59q7cmW0EprwfcfUA8d9dg"></script>
        <script type="text/javascript" src="js/gmap3.min.js"></script>
        <script type="text/javascript" src="js/wow.min.js"></script>
        <script type="text/javascript" src="js/masonry.pkgd.min.js"></script>
        <script type="text/javascript" src="js/jquery.simple-text-rotator.min.js"></script>
        <script type="text/javascript" src="js/all.js"></script>
        <script type="text/javascript" src="js/contact-form.js"></script>
        <script type="text/javascript" src="js/jquery.ajaxchimp.min.js"></script>
</code>```

答:
Modify Your code like this

```<code><!-- calendar -->
    <link href='temporal/fullcalendar.min.css' rel='stylesheet' />
    <link href='temporal/fullcalendar.print.min.css' rel='stylesheet' media='print' />

    <!-- CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/style-responsive.css">
    <link rel="stylesheet" href="css/animate.min.css">
    <link rel="stylesheet" href="css/vertical-rhythm.min.css">
    <link rel="stylesheet" href="css/owl.carousel.css">
    <link rel="stylesheet" href="css/magnific-popup.css">

        <style type="text/css">
        #calendar {
    max-width: 900px;
    margin: 0 auto;
    font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
    font-size: 14px;

}
        </style>
</code>```

```<code>    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/SmoothScroll.js"></script>
    <script type="text/javascript" src="js/jquery.scrollTo.min.js"></script>
    <script type="text/javascript" src="js/jquery.localScroll.min.js"></script>
    <script type="text/javascript" src="js/jquery.viewport.mini.js"></script>
    <script type="text/javascript" src="js/jquery.countTo.js"></script>
    <script type="text/javascript" src="js/jquery.appear.js"></script>
    <script type="text/javascript" src="js/jquery.sticky.js"></script>
    <script type="text/javascript" src="js/jquery.parallax-1.1.3.js"></script>
    <script type="text/javascript" src="js/jquery.fitvids.js"></script>
    <script type="text/javascript" src="js/owl.carousel.min.js"></script>
    <script type="text/javascript" src="js/isotope.pkgd.min.js"></script>
    <script type="text/javascript" src="js/imagesloaded.pkgd.min.js"></script>
    <script type="text/javascript" src="js/jquery.magnific-popup.min.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAZsDkJFLS0b59q7cmW0EprwfcfUA8d9dg"></script>
    <script type="text/javascript" src="js/gmap3.min.js"></script>
    <script type="text/javascript" src="js/wow.min.js"></script>
    <script type="text/javascript" src="js/masonry.pkgd.min.js"></script>
    <script type="text/javascript" src="js/jquery.simple-text-rotator.min.js"></script>
    <script type="text/javascript" src="js/all.js"></script>
    <script type="text/javascript" src="js/contact-form.js"></script>
    <script type="text/javascript" src="js/jquery.ajaxchimp.min.js"></script>
    <script src='temporal/moment.min.js'></script>
    <script src='temporal/fullcalendar.min.js'></script>
    <script type="text/javascript" src="js/push.min.js"></script>
<script>

$(document).ready(function() {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        defaultDate: '2017-05-12',
        navLinks: true, // can click day/week names to navigate views
        editable: true,
        eventLimit: true, // allow "more" link when too many events
        events: [
            {
                title: 'All Day Event',
                start: '2017-05-01'
            },
            {
                title: 'Long Event',
                start: '2017-05-07',
                end: '2017-05-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-05-09T16:00:00'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-05-16T16:00:00'
            },
            {
                title: 'Conference',
                start: '2017-05-11',
                end: '2017-05-13'
            },
            {
                title: 'Meeting',
                start: '2017-05-12T10:30:00',
                end: '2017-05-12T12:30:00'
            },
            {
                title: 'Lunch',
                start: '2017-05-12T12:00:00'
            },
            {
                title: 'Meeting',
                start: '2017-05-12T14:30:00'
            },
            {
                title: 'Happy Hour',
                start: '2017-05-12T17:30:00'
            },
            {
                title: 'Dinner',
                start: '2017-05-12T20:00:00'
            },
            {
                title: 'Birthday Party',
                start: '2017-05-13T07:00:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2017-05-28'
            }
        ]
    });

});
</code>```

Body:
Make the insertion of the code as the official documentation of the FullCalendar says but at the time of running the page does not show me the calendar.
imagen

I think the error can be to a script that I attached on my web these are all I work with.

        <link href='temporal/fullcalendar.min.css' rel='stylesheet' />
        <link href='temporal/fullcalendar.print.min.css' rel='stylesheet' media='print' />

        <link rel="stylesheet" href="css/bootstrap.min.css">
        <link rel="stylesheet" href="css/style.css">
        <link rel="stylesheet" href="css/style-responsive.css">
        <link rel="stylesheet" href="css/animate.min.css">
        <link rel="stylesheet" href="css/vertical-rhythm.min.css">
        <link rel="stylesheet" href="css/owl.carousel.css">
        <link rel="stylesheet" href="css/magnific-popup.css">

Body:
Modify Your code like this

<!-- calendar -->
    <link href='temporal/fullcalendar.min.css' rel='stylesheet' />
    <link href='temporal/fullcalendar.print.min.css' rel='stylesheet' media='print' />

    <!-- CSS -->
    <link rel="stylesheet" href="css/bootstrap.min.css">
    <link rel="stylesheet" href="css/style.css">
    <link rel="stylesheet" href="css/style-responsive.css">
    <link rel="stylesheet" href="css/animate.min.css">
    <link rel="stylesheet" href="css/vertical-rhythm.min.css">
    <link rel="stylesheet" href="css/owl.carousel.css">
    <link rel="stylesheet" href="css/magnific-popup.css">

        <style type="text/css">
        #calendar {
    max-width: 900px;
    margin: 0 auto;
    font-family: "Lucida Grande",Helvetica,Arial,Verdana,sans-serif;
    font-size: 14px;

}
        </style>

    <script type="text/javascript" src="js/jquery-1.11.2.min.js"></script>
    <script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
    <script type="text/javascript" src="js/bootstrap.min.js"></script>
    <script type="text/javascript" src="js/SmoothScroll.js"></script>
    <script type="text/javascript" src="js/jquery.scrollTo.min.js"></script>
    <script type="text/javascript" src="js/jquery.localScroll.min.js"></script>
    <script type="text/javascript" src="js/jquery.viewport.mini.js"></script>
    <script type="text/javascript" src="js/jquery.countTo.js"></script>
    <script type="text/javascript" src="js/jquery.appear.js"></script>
    <script type="text/javascript" src="js/jquery.sticky.js"></script>
    <script type="text/javascript" src="js/jquery.parallax-1.1.3.js"></script>
    <script type="text/javascript" src="js/jquery.fitvids.js"></script>
    <script type="text/javascript" src="js/owl.carousel.min.js"></script>
    <script type="text/javascript" src="js/isotope.pkgd.min.js"></script>
    <script type="text/javascript" src="js/imagesloaded.pkgd.min.js"></script>
    <script type="text/javascript" src="js/jquery.magnific-popup.min.js"></script>
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAZsDkJFLS0b59q7cmW0EprwfcfUA8d9dg"></script>
    <script type="text/javascript" src="js/gmap3.min.js"></script>
    <script type="text/javascript" src="js/wow.min.js"></script>
    <script type="text/javascript" src="js/masonry.pkgd.min.js"></script>
    <script type="text/javascript" src="js/jquery.simple-text-rotator.min.js"></script>
    <script type="text/javascript" src="js/all.js"></script>
    <script type="text/javascript" src="js/contact-form.js"></script>
    <script type="text/javascript" src="js/jquery.ajaxchimp.min.js"></script>
    <script src='temporal/moment.min.js'></script>
    <script src='temporal/fullcalendar.min.js'></script>
    <script type="text/javascript" src="js/push.min.js"></script>
<script>

$(document).ready(function() {

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,basicWeek,basicDay'
        },
        defaultDate: '2017-05-12',
        navLinks: true, // can click day/week names to navigate views
        editable: true,
        eventLimit: true, // allow "more" link when too many events
        events: [
            {
                title: 'All Day Event',
                start: '2017-05-01'
            },
            {
                title: 'Long Event',
                start: '2017-05-07',
                end: '2017-05-10'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-05-09T16:00:00'
            },
            {
                id: 999,
                title: 'Repeating Event',
                start: '2017-05-16T16:00:00'
            },
            {
                title: 'Conference',
                start: '2017-05-11',
                end: '2017-05-13'
            },
            {
                title: 'Meeting',
                start: '2017-05-12T10:30:00',
                end: '2017-05-12T12:30:00'
            },
            {
                title: 'Lunch',
                start: '2017-05-12T12:00:00'
            },
            {
                title: 'Meeting',
                start: '2017-05-12T14:30:00'
            },
            {
                title: 'Happy Hour',
                start: '2017-05-12T17:30:00'
            },
            {
                title: 'Dinner',
                start: '2017-05-12T20:00:00'
            },
            {
                title: 'Birthday Party',
                start: '2017-05-13T07:00:00'
            },
            {
                title: 'Click for Google',
                url: 'http://google.com/',
                start: '2017-05-28'
            }
        ]
    });

});


问:
Force CharField's Choices
I have few models.CharField objects in my Model, with the choices attribute.

This is working great as far as the GUI is concerned, But I want to block values other than these specified in the choices attribute in the code itself (to protect myself from bugs).

Is there a way to raise an exception (I believe it'll be a ValueError) when trying to save a string which is not in the choices list?

答:
You could override the save method of your model to raise your own exception:</p>

```<code>class MyModel:

    MY_CHOICES = (
        # choices here
    )

    myfield = models.CharField(max_length=100, choices=MY_CHOICES)

    def save(self, *args, **kwargs):
        choice = self.myfield
        if not any(choice in _tuple for _tuple in self.MY_CHOICES):
            raise ValueError('An error message.')
        super(MyModel, self).save(*args, **kwargs)
</code>```

Title: Force CharField's Choices

Body:
You could override the save method of your model to raise your own exception:

class MyModel:

    MY_CHOICES = (
        # choices here
    )

    myfield = models.CharField(max_length=100, choices=MY_CHOICES)

    def save(self, *args, **kwargs):
        choice = self.myfield
        if not any(choice in _tuple for _tuple in self.MY_CHOICES):
            raise ValueError('An error message.')
        super(MyModel, self).save(*args, **kwargs)


问:
Why are almost all cosine similarities positive between word or document vectors in gensim doc2vec?
I have calculated document similarities using Doc2Vec.docvecs.similarity() in gensim. Now, I would either expect the cosine similarities to lie in the range [0.0, 1.0] if gensim used the absolute value of the cosine as the similarity metric, or roughly half of them to be negative if it does not.

However, what I am seeing is that some similarities are negative, but they are very rare – less than 1% of pairwise similarities in my set of 30000 documents.

Why are almost all of the similarities positive?

答:
There's no inherent guarantee in Word2Vec/Doc2Vec that the generated set of vectors is symmetrically distributed around the origin point. They could be disproportionately in some directions, which would yield the results you've seen.

In a few tests I just did on the toy-sized dataset ('lee corpus') used in the bundled gensim docs/notebooks/doc2vec-lee.ipynb notebook, checking the cosine-similarities of all documents against the first document, it vaguely seems that:

using hierarchical-softmax rather than negative sampling (hs=1, negative=0) yields a balance between >0.0 and <0.0 cosine-similarities that is closer-to (but not yet quite) half and half

using a smaller number of negative samples (such as negative=1) yields a more balanced set of results; using a larger number (such as negative=10) yields relatively more >0.0 cosine-similarities

While not conclusive, this is mildly suggestive that the arrangement of vectors may be influenced by the negative parameter. Specifically, typical negative-sampling parameters, such as the default negative=5, mean words will be trained more times as non-targets, than as positive targets. That might push the preponderance of final coordinates in one direction. (More testing on larger datasets and modes, and more analysis of how the model setup could affect final vector positions, would be necessary to have more confidence in this idea.)

If for some reason you wanted a more balanced arrangement of vectors, you could consider transforming their positions, post-training.

There's an interesting recent paper in the word2vec space, "All-but-the-Top: Simple and Effective Postprocessing for Word Representations", that found sets of trained word-vectors don't necessarily have a 0-magnitude mean – they're on average in one direction from the origin. And further, this paper reports that subtracting the common mean (to 're-center' the set), and also removing a few other dominant directions, can improve the vectors' usefulness for certain tasks.

Intuitively, I suspect this 'all-but-the-top' transformation might serve to increase the discriminative 'contrast' in the resulting vectors.

A similar process might yield similar benefits for doc-vectors – and would likely make the full set of cosine-similarities, to any doc-vector, more balanced between >0.0 and <0.0 values.


问:
How to create a JSONObject from String in Kotlin?
I need to convert a string {\"name\":\"test name\", \"age\":25} to a JSONObject

答:
Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why

```<code>val answer = JSONObject("""{"name":"test name", "age":25}""")
</code>```

wouldn't be the best way to do it? What was wrong with the built in functionality of JSONObject?

Body:
Perhaps I'm misunderstanding the question but it sounds like you are already using org.json which begs the question about why

val answer = JSONObject("""{"name":"test name", "age":25}""")

wouldn't be the best way to do it? What was wrong with the built in functionality of JSONObject?


问:
How to use tabIndex (maybe?) with Angular components?
I have several material-input :

```<code>   <span *ngFor="let field of listfields">
        <material-input #keyp (keyup.tab)="keyupEnter(field,keyp.inputText,keyp)"
                        label="Edit {{getDisplayStr(field)}}"
                        floatingLabel="true"
                        [ngModel]="getFieldValue(field)">
        </material-input>
</code>```

When the user presses enter, the data is saved, but the focus remains on the current material-input. I would like it to automatically move focus / tab to the next material-input component. I can manually tab, and it works.

I have tried using (keyup.tab) (replacing keyup.enter), but the inputText is for the next (newly focused) material-input.

I looked into firing of a keyboard tab event, but that seems not to be allowed.

Thanks

Steve

答:
Not specific to angular_components but for any angular app you could do this in the form parent:
    @ViewChildren(MaterialInputComponent)
    QueryList materialInputs;

```<code>void onEnter(KeyboardEvent event, MaterialInputComponent input) {
  event.preventDefault();
  final inputs = materialInputs.toList();
  var index = inputs.indexOf(input) + 1;
  if (index >= inputs.length) index = 0;
  inputs[index].focus();
}
</code>```

Then do this in the template:

```<code><span *ngFor="let field of listfields">
  <material-input #keyp (keyup.enter)="onEnter($event, keyp)"
                label="Edit {{getDisplayStr(field)}}"
                floatingLabel="true"
                [ngModel]="getFieldValue(field)">
  </material-input>
</code>```

Body:
I have several material-input :

        <material-input #keyp (keyup.tab)="keyupEnter(field,keyp.inputText,keyp)"
                        label="Edit {{getDisplayStr(field)}}"
                        floatingLabel="true"
                        [ngModel]="getFieldValue(field)">
        </material-input>

When the user presses enter, the data is saved, but the focus remains on the current material-input. I would like it to automatically move focus / tab to the next material-input component. I can manually tab, and it works.

I have tried using (keyup.tab) (replacing keyup.enter), but the inputText is for the next (newly focused) material-input.

I looked into firing of a keyboard tab event, but that seems not to be allowed.

Thanks

Steve

Body:
Not specific to angular_components but for any angular app you could do this in the form parent:
    @ViewChildren(MaterialInputComponent)
    QueryList materialInputs;

void onEnter(KeyboardEvent event, MaterialInputComponent input) {
  event.preventDefault();
  final inputs = materialInputs.toList();
  var index = inputs.indexOf(input) + 1;
  if (index >= inputs.length) index = 0;
  inputs[index].focus();
}

Then do this in the template:

<span *ngFor="let field of listfields">
  <material-input #keyp (keyup.enter)="onEnter($event, keyp)"
                label="Edit {{getDisplayStr(field)}}"
                floatingLabel="true"
                [ngModel]="getFieldValue(field)">
  </material-input>


问:
Responsive Web Design Not working
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

```<code>    <!doctype html>
<html>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">
<head>
<meta charset="utf-8">
<title>OneClickLearn - Home</title>
</head>

<body>
<ul>
  <li><a href="#home">Home</a></li>
  <li><a href="#news">News</a></li>
  <li><a href="#contact">Contact</a></li>
  <li><a href="#about">About</a></li>
</ul>

<div class="head">
<center>
  <h1 class="centered-divcontent txt-jumbo">OneClickLearn</h1>
  </center>
</div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent"><h3>Learn the Cascading Style Sheet of web development!<br><br>Start Learning CSS <em>now</em></h3>
        <button class="blue-btn txt-marginall">Learn CSS!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn data storing in web development!<br><br>Start Learning PHP <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn PHP!</button>
        </div>
    </div>

<div class="sidecontentleft">

  <div class="sidecontent">
    <h3>Create actions and animations!<br>
      <br>
      Start Learning Javascript <em>now</em></h3>
    <button class="blue-btn txt-marginall">Learn Javascript!</button>
        </div>
    </div>
<div class="sidecontentleft">

  <div class="sidecontent">
        <h3 class="txt-marginall">Learn how to construct the blocks of a website!<br><br>Start Learning HTML5 <em>now</em></h3>
        <button class="green-btn txt-marginall">Learn HTML5!</button>
        </div>
    </div>
</body>
</html>
</code>```

CSS

```<code>    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}
</code>```

Your help would be appreciated! Thanks!

答: As much as I can appreciate building responsiveness from the ground up, you'll get a clean, crisp, and simple solution by using Flexbox. For more control, use Bootstrap or Materialize, or another framework. It will also be much quicker. No person in their right mind would frown on going simpler. </p>

Title: Responsive Web Design Not working

Body:
I'm new to responsive web design, so I'm not sure why this isn't working, but it definitely has something to do with me. I'm not exactly sure how to make this current website "responsive", and I've been trying for a good while. Code shown below. It may help to run it via browser. NOTE: I would like to not use a 3rd party css library like Bootstrap

HTML

    <!doctype html>

<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="css/style.css" rel="stylesheet" type="text/css">
<link rel="icon" href="img/favicon.ico" sizes="16x16" type="image/ico">

<meta charset="utf-8">
<title>OneClickLearn - Home</title>

Home

News

Contact

About

OneClickLearn

Learn how to construct the blocks of a website!

Start Learning HTML now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

Learn the Cascading Style Sheet of web development!

Start Learning CSS now

        <button class="blue-btn txt-marginall">Learn CSS!</button>

Learn data storing in web development!

Start Learning PHP now

        <button class="green-btn txt-marginall">Learn PHP!</button>

Create actions and animations!

      Start Learning Javascript now

    <button class="blue-btn txt-marginall">Learn Javascript!</button>

Learn how to construct the blocks of a website!

Start Learning HTML5 now

        <button class="green-btn txt-marginall">Learn HTML5!</button>

CSS

    @import url('https://fonts.googleapis.com/css?family=Source+Code+Pro');

body {
    margin:0;
    padding:0;
    }

/*nav*/
@media (min-width:600px) {
    .txt-jumbo {
        font-size:-40px;
    }
}

ul {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #333;
}

li {
    float:left;
}

li a {
    display: block;
    color: white;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
}

li a:hover {
    background-color: #111;
}

/*divs*/

.sidecontentleft {
    align-self:center;
    height:300px;
    width:300px;
    float:left;
    }

.sidecontentright {
    align-self:center;
    height:300px;
    width:300px;
    float:right;
    }

.sidecontent {
    text-align:center;
    height: 300px;
    display: table-cell;
    vertical-align: middle;
    }

.head {
    width:100%;
    height:350px;
    background-color:#05D7C6;
    color:white;
    text-align:center;
    }

.centered-divcontent {
    text-align:center;
    height: 350px;
    display: table-cell;
    vertical-align: middle;
    }

/*buttons*/

.green-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#04D43C;
    border:none;
    color:white;
    }

.green-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00F040;
    border:none;
    color:white;
    cursor:pointer;
    }

.blue-btn {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#05D7C6;
    border:none;
    color:white;
    }

.blue-btn:hover {
    height:40px;
    width:auto;
    border-radius:5px;
    background-color:#00E9D6;
    border:none;
    color:white;
    cursor:pointer;
    }

.white-btn {
    border-radius:5px;
    height:40px;
    width:auto;
    text-align:center;
    border: #BFBFBF 1px solid;
    text-decoration:none;
    color:black;
    background-color:white;
    }

/*Fonts*/

.txt-jumbo {
    font-size:100px;
    }

.txt-centered {
    text-align:center;
    }

.txt-margin {
    margin-left:25px;
    }

.txt-marginall {
    margin-left:15px;
    margin-right:15px;
    margin-top:15px;
    margin-bottom:15px;
    }

h1 {font-family: 'Source Code Pro', monospace;}
h2 {font-family: 'Source Code Pro', monospace;}
h3 {font-family: 'Source Code Pro', monospace;}
h4 {font-family: 'Source Code Pro', monospace;}
h5{font-family: 'Source Code Pro', monospace;}
h6 {font-family: 'Source Code Pro', monospace;}
a {font-family: 'Source Code Pro', monospace;}
p {font-family: 'Source Code Pro', monospace;}

Your help would be appreciated! Thanks!


问:
PHP: How to activate class "active" in pagination, If $_GET['page']==$pagenumber
This is my pagination code:

```<code><?php
   while($pagenumber != $totalpages)
     {
        echo"<a href='?page=" . ++$pagenumber. "' >" . $pagenumber. "</a>     ";
     }
 ?>
</code>```

The above code will look like this in normal html:

```<code><a href="?page=1">1</a>
<a href="?page=2">2</a>
</code>```

I want to add class="active" with this condition

```<code>If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";
</code>```

I do not know, how to insert if statement inside echo command.

`

答:
Please try:

```<code><?php
while($pagenumber != $totalpages) {
    $active = ($_GET['page'] == $pagenumber) ? ' class="active"' : '' ;
    echo '<a href="?page='.++$pagenumber.'"'.$active.'>'.$pagenumber.'</a>';
}
?>
</code>```

You will have a very clean HTML code without the class attribute empty on the non-active elements.

Body:
This is my pagination code:

<?php
   while($pagenumber != $totalpages)
     {
        echo"" . $pagenumber. "     ";
     }
 ?>

The above code will look like this in normal html:

1
2

I want to add class="active" with this condition

If ($_GET['page'] == " . $pagenumber . ")
echo "class="active" ";

I do not know, how to insert if statement inside echo command.

`

Body:
Please try:

<?php
while($pagenumber != $totalpages) {
    $active = ($_GET['page'] == $pagenumber) ? ' class="active"' : '' ;
    echo '<a href="?page='.++$pagenumber.'"'.$active.'>'.$pagenumber.'</a>';
}
?>

You will have a very clean HTML code without the class attribute empty on the non-active elements.


问:
VB.NET - Delete excess white spaces between words in a sentence
I'm a programing student, so I've started with vb.net as my first language and I need some help.

I need to know how I delete excess white spaces between words in a sentence, only using these string functions: Trim, instr, char, mid, val and len.

I made a part of the code but it doesn't work, Thanks.
enter image description here

答:
Knocked up a quick routine for you.

```<code>Public Function RemoveMyExcessSpaces(str As String) As String
    Dim r As String = ""
    If str IsNot Nothing AndAlso Len(str) > 0 Then
        Dim spacefound As Boolean = False
        For i As Integer = 1 To Len(str)
            If Mid(str, i, 1) = " " Then
                If Not spacefound Then
                    spacefound = True
                End If
            Else
                If spacefound Then
                    spacefound = False
                    r += " "
                End If
                r += Mid(str, i, 1)
            End If
        Next
    End If
    Return r
End Function
</code>```

I think it meets your criteria.

Hope that helps.

Body:
Knocked up a quick routine for you.

Public Function RemoveMyExcessSpaces(str As String) As String
    Dim r As String = ""
    If str IsNot Nothing AndAlso Len(str) > 0 Then
        Dim spacefound As Boolean = False
        For i As Integer = 1 To Len(str)
            If Mid(str, i, 1) = " " Then
                If Not spacefound Then
                    spacefound = True
                End If
            Else
                If spacefound Then
                    spacefound = False
                    r += " "
                End If
                r += Mid(str, i, 1)
            End If
        Next
    End If
    Return r
End Function

I think it meets your criteria.

Hope that helps.


问:
WinDivert connection loss
I am using WinDivert 1.1.8 MSVC x64 in Visual Studio 2015 along with a P/Invoke wrapper for C# to create a simple latency simulator, but the connection fails when performing bandwidth intensive tasks, such as a speedtest.

Output

ERROR_IO_PENDING 997 (0x3E5) Overlapped I/O operation is in progress.

ERROR_INSUFFICIENT_BUFFER 122 (0x7A) The data area passed to a system call is too small.

Notes

Possible deadlocking caused by x64 remote debugging?

Possibly overwhelming the WinDivert queue?

Update

I have tried parallel threading and this produced the same errors.

```<code>Parallel.ForEach(Enumerable.Range(0, Environment.ProcessorCount), x => RunDiversion());
</code>```

Update 2

After further testing the code the offending line may be:

packet.CopyTo(newpacket.data, 0);

Update 3

CPU Stack

WinDivert queue possibly needs marshalling?

答:
You should be using WinDivertRecvEx instead of WinDivertRecv to avoid overlapped I/O. Also, you're using Queue<T> on multithreaded app, which I believe you should use ConcurrentQueue<T> instead.

I think x64 debugger may cause problems too. I'm running the app without debugging and it works (CTRL+F5).

Working code: https://gist.github.com/fahminlb33/16f69460466eb07f88e7588a285fb4f8

Title: WinDivert connection loss

Body:
I am using WinDivert 1.1.8 MSVC x64 in Visual Studio 2015 along with a P/Invoke wrapper for C# to create a simple latency simulator, but the connection fails when performing bandwidth intensive tasks, such as a speedtest.

Output

ERROR_IO_PENDING 997 (0x3E5) Overlapped I/O operation is in progress.

ERROR_INSUFFICIENT_BUFFER 122 (0x7A) The data area passed to a system call is too small.

Notes

Possible deadlocking caused by x64 remote debugging?

Possibly overwhelming the WinDivert queue?

Update

I have tried parallel threading and this produced the same errors.

Parallel.ForEach(Enumerable.Range(0, Environment.ProcessorCount), x => RunDiversion());

Update 2

After further testing the code the offending line may be:

packet.CopyTo(newpacket.data, 0);

Update 3

CPU Stack

WinDivert queue possibly needs marshalling?


问:
Lambda variable names - to short name, or not to short name?
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);
</code>```

Some question this naming, and would prefer to see long typed out names, like this:

```<code>var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);
</code>```

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

答: I like the shortname thing. I do that all the time. I mostly use i,y,x in lambdas, but I use a,b,c,d in sql.</p>

OwnerDisplayName: TheSoftwareJedi

Body:
Typically, when I use lambdas, I just use "a, b, c, d..." as variable names as the types are easily inferred, and I find short names to be easier to read.  Here is an example:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(a => a.SomeProperty)
                                      .OrderBy(a => a.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(a => new SomeClass(a.Prop1),
                                                    a => a);

Some question this naming, and would prefer to see long typed out names, like this:

var someEnumerable = GetSomeEnumerable();
var somethingElseList = someEnumerable.Select(importantObj => importantObj.SomeProperty)
                                      .OrderBy(objsInfo => objsInfo.SomePropertyField);
var someDictionary = somethingElseList.ToDictionary(theInfoId => new SomeClass(theInfoId.Prop1),
                                                    theInfoId2 => theInfoId2);

Since the scope is so narrow (between the parens), unless you're getting stupid and nesting them, I find it easier to read short names.

Without getting caught up in the silly naming examples I used above, what is the general consensus on Lambda variable names?  To short name, or not to short name?

LastEditorDisplayName: TheSoftwareJedi

OwnerDisplayName: Arni Gunnar Ragnarsson


问:
Writing reusable JsonConverters for json.net
I'm querying a service which returns a list of tags in multiple formats:

```<code>{
  "tags": "a,b,c"
}
</code>```

or

```<code>{
  "tags": "a b c"
}
</code>```

or

```<code>{
  "tags": "a+b+c"
}
</code>```

The object that I want to deserialize this to is a List<string>. I've written a TagsConverter that implements the necessary methods in JsonConverter like so:

```<code>public class TagsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(' ')
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(" ", list);

        writer.WriteValue(delimitedList);
    }
}
</code>```

Then I annotate the field in the object like so:

```<code>public class Foo
{
  [JsonConverter(typeof(TagsConverter))]
  public List<string> Tags { get; set; }
}
</code>```

And this works, but only for tags that are separated by spaces.

However the TagsConverter can work in all 3 scenarios if I'm able to just change the Split and the Join functions in a parameterized fashion. But since we pass only the type to the JsonConverter attribute, I understand that we can't pass a "delimiter" as an argument there.

Is there any way to achieve this?

答:
There is an additional JsonConverter constructor overload that takes both a type and a params object[] converterParameters that is injected into the concrete instance of your converter.  You can take advantage of this overload to maximize your reusability.

```<code>public class TagsConverter : JsonConverter
{
    private readonly string _delimiter;

    public TagsConverter(string delimiter)
    {
        _delimiter = delimiter;
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(_delimiter.ToCharArray())
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value,
        JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(_delimiter, list);

        writer.WriteValue(delimitedList);
    }
}
</code>```

Utilizing the overload is as easy as passing it as a second parameter:

```<code>public class Foo
{
    [JsonConverter(typeof(TagsConverter), " ")]
    public List<string> Tags { get; set; }
}
</code>```

Body:
I'm querying a service which returns a list of tags in multiple formats:

{
  "tags": "a,b,c"
}

or

{
  "tags": "a b c"
}

or

{
  "tags": "a+b+c"
}

The object that I want to deserialize this to is a List<string>. I've written a TagsConverter that implements the necessary methods in JsonConverter like so:

public class TagsConverter : JsonConverter
{
    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(' ')
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(" ", list);

        writer.WriteValue(delimitedList);
    }
}

Then I annotate the field in the object like so:

public class Foo
{
  [JsonConverter(typeof(TagsConverter))]
  public List<string> Tags { get; set; }
}

And this works, but only for tags that are separated by spaces.

However the TagsConverter can work in all 3 scenarios if I'm able to just change the Split and the Join functions in a parameterized fashion. But since we pass only the type to the JsonConverter attribute, I understand that we can't pass a "delimiter" as an argument there.

Is there any way to achieve this?

Body:
There is an additional JsonConverter constructor overload that takes both a type and a params object[] converterParameters that is injected into the concrete instance of your converter.  You can take advantage of this overload to maximize your reusability.

public class TagsConverter : JsonConverter
{
    private readonly string _delimiter;

    public TagsConverter(string delimiter)
    {
        _delimiter = delimiter;
    }

    public override bool CanConvert(Type objectType)
    {
        return (objectType == typeof(string));
    }

    public override object ReadJson(JsonReader reader, Type objectType,
        object existingValue, JsonSerializer serializer)
    {
        return reader
                .Value
                .ToString()
                .Split(_delimiter.ToCharArray())
                .ToList();
    }

    public override void WriteJson(JsonWriter writer, object value,
        JsonSerializer serializer)
    {
        var list = (List<string>)value;
        var delimitedList = string.Join(_delimiter, list);

        writer.WriteValue(delimitedList);
    }
}

Utilizing the overload is as easy as passing it as a second parameter:

public class Foo
{
    [JsonConverter(typeof(TagsConverter), " ")]
    public List<string> Tags { get; set; }
}


问:
Using AWK to replace some special codes
lets say I have a file called somedata.txt, I am trying to replace:

\"

with

"

i.e. removing the \
I am trying to do this using AWK. Can you please help?

答:
You can also open file in vim editor and try this:
Press esc and then

```<code>:%s_oldString_newString_g
</code>```

For your case, it's

```<code>:%s_\\\"_\"_g
</code>```

Since " and \ are special characters, you need to add a \ before the chars to make the command execute.

Title: Using AWK to replace some special codes

Body:
You can also open file in vim editor and try this:
Press esc and then

:%s_oldString_newString_g

For your case, it's

:%s_\\\"_\"_g

Since " and \ are special characters, you need to add a \ before the chars to make the command execute.


问:
How do I change the language of moment.js?
I am trying to change the language of the date which is being set by moment.js. The default one is English, but I want to set the German language. These is what I tried:

```<code>var now = moment().format("LLL").lang("de");
</code>```

It’s giving NaN.

```<code>var now = moment("de").format("LLL");
</code>```

This isn’t even reacting.

```<code>var now = moment().format("LLL", "de");
</code>```

No change: this is still producing a result in English.

How is this possible?

答: work fine like that: return moment(status.created_at).locale('es').fromNow();

ContentLicense: CC BY-SA 4.0

Body:
I am trying to change the language of the date which is being set by moment.js. The default one is English, but I want to set the German language. These is what I tried:

var now = moment().format("LLL").lang("de");

It’s giving NaN.

var now = moment("de").format("LLL");

This isn’t even reacting.

var now = moment().format("LLL", "de");

No change: this is still producing a result in English.

How is this possible?


问:
How to use rvest to web crawling correctly?
I try to web crawl this page http://www.funda.nl/en/koop/leiden/ to get the max page it could show which is 29. I followed some online tutorial and  located where 29 is in the html code,  wrote this R  code

```<code>url<-  read_html("http://www.funda.nl/en/koop/leiden/")

url %>% html_nodes("#pagination-number.pagination-last") %>% html_attr("data-
pagination-page") %>% as.numeric()
</code>```

However, what I got is numeric(0). If I remove as.numeric(), I get character(0).

How is this done ?

答:
I believe that both your identification of the html and your parsing of the html are wrong. To easily find the name of a CSS id, you can use a chrome extension called Selector Gadget. In your case, it also requires some parsing, accomplished in the str_extract_all() function.

This will work:

```<code>url <-  read_html("http://www.funda.nl/en/koop/leiden/")

pagination.last <- url %>%
  html_node(".pagination-last") %>%
  html_text() %>%
  stringr::str_extract_all("[:number:]{1,2}", simplify = TRUE) %>%
  as.numeric()

> pagination.last
[1] 29
</code>```

You might find this other question helpful as well: R: Rvest - got hidden text i don't want

Body:
I try to web crawl this page http://www.funda.nl/en/koop/leiden/ to get the max page it could show which is 29. I followed some online tutorial and  located where 29 is in the html code,  wrote this R  code

url<-  read_html("http://www.funda.nl/en/koop/leiden/")

url %>% html_nodes("#pagination-number.pagination-last") %>% html_attr("data-
pagination-page") %>% as.numeric()

However, what I got is numeric(0). If I remove as.numeric(), I get character(0).

How is this done ?

Body:
I believe that both your identification of the html and your parsing of the html are wrong. To easily find the name of a CSS id, you can use a chrome extension called Selector Gadget. In your case, it also requires some parsing, accomplished in the str_extract_all() function.

This will work:

url <-  read_html("http://www.funda.nl/en/koop/leiden/")

pagination.last <- url %>%
  html_node(".pagination-last") %>%
  html_text() %>%
  stringr::str_extract_all("[:number:]{1,2}", simplify = TRUE) %>%
  as.numeric()

> pagination.last
[1] 29

You might find this other question helpful as well: R: Rvest - got hidden text i don't want


问:
In Javascript, how do I generate a random element out of a list?
Suppose I have a list of strings. How do I generate a random one?</p>

答:
Alex and Mahesh are right on, just wanted to demonstrate how I might implement their solutions if I felt like living dangerously.  Which I do.</p>

```<code>Array.prototype.chooseRandom = function() {
  return this[Math.floor(Math.random() * this.length)];
};
var a = [1, 2, 3, 4, 5];
a.chooseRandom(); // => 2
a.chooseRandom(); // => 1
a.chooseRandom(); // => 5
</code>```

Body:
Alex and Mahesh are right on, just wanted to demonstrate how I might implement their solutions if I felt like living dangerously.  Which I do.

Array.prototype.chooseRandom = function() {
  return this[Math.floor(Math.random() * this.length)];
};
var a = [1, 2, 3, 4, 5];
a.chooseRandom(); // => 2
a.chooseRandom(); // => 1
a.chooseRandom(); // => 5


问:
AWS Beanstalk, how to reboot (or terminate) automatically an instance that is not responding
I have my Beanstalk environment with a "Scaling Trigger" using "CPUUtilization" and it works well.

The problem is that I can not combine this with a system that automatically reboots (or terminate) instances that have been considered "OutOfService" for a certain amount of time.

Into the "Scaling > Scaling Trigger > Trigger measurement" there is the option of "UnHealthyHostCount". But this won't solve my problem optimally, because it will create new instances as far there is one unhealthy, this will provoque my environment to grow until the limit without a real reason. Also, I can not combine 2 "Trigger measurements" and I need the CPU one.

The problem becomes crucial when there is only one instance in the environment, and it becomes OutOfService. The whole environment dies, the Trigger measurement is never triggered.

答:
AWS Elastic Beanstalk uses AWS Auto Scaling to manage the creation and termination of instances, including the replacement of unhealthy instances.

AWS Auto Scaling can integrate with the ELB (load balancer), also automatically created by Elastic Beanstalk, for health checks. ELB has a health check functionality. If the ELB detects that an instance is unhealthy, and if Auto Scaling has been configured to rely on ELB health checks (instead of the default EC2-based health checks), then Auto Scaling automatically replaces that instance that was deemed unhealthy by ELB.

So all you have to do is configure the ELB health check properly (you seem to have it correctly configured already, since you mentioned that you can see the instance being marked as OutOfService), and you also have to configure the Auto Scaling Group to use the ELB health check.

For more details on this subject, including the specific steps to configure all this, check these 2 links from the official documentation:

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features.healthstatus.html#using-features.healthstatus.understanding

http://docs.aws.amazon.com/elasticbeanstalk/latest/dg/environmentconfig-autoscaling-healthchecktype.html

This should solve the problem. If you have trouble with that, please add a comment with any additional info that you might have after trying this.

Cheers!


问:
How do you find the average of three numbers with input and output dialog boxes with JAVA?
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.</p>

```<code>import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}
</code>```

答:
I don't know what you find hard here. I think you are looking for this:

```<code>DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;

num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));

avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null,  "The average is: " + decimalFormat.format(avg));
</code>```

Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.

Body:
I've been playing around with this code for a little bit now and can't seem to find the correct way to sort it out. I used a program without JOptionPane and it worked and tried to use the same sequence but it didn't work. Do I need to add something else? The assignment is to have the user enter 3 integers and print the average with input and output dialog boxes. I've done the average and input/output dialog boxes before but putting it all together is harder than I thought.

import java.util.Scanner;
import javax.swing.JOptionPane;
import java.text.*;
import java.text.DecimalFormat;
public class Number3
{

  public static void main(String[] args)
  {
    System.out.println("Enter 3 numbers: ");
    Scanner input = new Scanner (System.in);
    DecimalFormat decimalFormat = new DecimalFormat("0.00##");

    int num1;
    int num2;
    int num3;
    double avg;

    num1=input.nextInt();
    num2=input.nextInt();
    num3=input.nextInt();

    avg=(double)(num1+num2+num3)/3.0;
    System.out.println("The average is: " + decimalFormat.format(avg));

  }
}

Body:
I don't know what you find hard here. I think you are looking for this:

DecimalFormat decimalFormat = new DecimalFormat("0.00##");
int num1;
int num2;
int num3;
double avg;

num1= Integer.valueOf(JOptionPane.showInputDialog("Enter #1"));
num2= Integer.valueOf(JOptionPane.showInputDialog("Enter #2"));
num3= Integer.valueOf(JOptionPane.showInputDialog("Enter #3"));

avg=(double)(num1+num2+num3)/3.0;
JOptionPane.showMessageDialog(null,  "The average is: " + decimalFormat.format(avg));

Please note that this code could be written better but for the sake of answering I just replaced the JOptionPane in your code where you need them.


问:
Build error on deploy only: cannot use appengine.AccessToken
A simple Go GAE (Flexible) app I'm writing fails to deploy as soon as I bring in cloud.google.com packages to use Google services. Snippet from deploy log:

```<code>...
golang.org/x/oauth2/google
# golang.org/x/oauth2/google
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:12: cannot use appengine.AccessToken (type func(appengine.Context, ...string) (string, time.Time, error)) as type func("golang.org/x/net/context".Context, ...string) (string, time.Time, error) in assignment
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:13: cannot use appengine.AppID (type func(appengine.Context) string) as type func("golang.org/x/net/context".Context) string in assignment
...
</code>```

This can be reproduced locally via go install -v -tags appenginevm within the app to deploy. The app builds and runs fine without the appenginevm tag.

I've just followed the helloworld example and modified it, and can't find anyone else with this problem (a few Google searches yielded nothing useful).

Anyone know how to fix this / what I'm missing?

Thanks in advance. The full program is below.

```<code>package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "cloud.google.com/go/storage"
)

var (
    client *storage.Client
)

func main() {
    ctx := context.Background()

    var err error
    client, err = storage.NewClient(ctx)
    if err != nil {
        log.Fatal(err)
        return
    }
    defer client.Close()

    http.HandleFunc("/_ah/health", healthCheckHandler)
    http.HandleFunc("/", indexHandler)
    log.Print("Listening on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func httpError(w http.ResponseWriter, err error) {
    log.Println(err)
    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()

    finish := time.Since(start)
    fmt.Fprintf(w, "Done %v %v", finish)
}
</code>```

Here is the app.yaml

```<code>env: flex
runtime: go
</code>```

答:
It turned out that I had an old version of the "google.golang.org/appengine" package locally, and what I wasn't aware of is that the "gcloud app deploy" command seems to upload all these dependencies instead of resolving dependencies remotely.

So my old local copy of this library was breaking the remote compilation process.

I figured this out purely through curiosity by running "go get -u google.golang.org/appengine" and having it fail:

```<code>package google.golang.org/appengine: google.golang.org/appengine is a custom import path
for https://github.com/golang/appengine, but
$GOPATH/src/google.golang.org/appengine is checked out from
https://github.com/golang/appengine.git
</code>```

So I nuked that and got a fresh copy, now it all works.

TL;DR make sure your local packages are all up to date if you get remote compile errors.

Body:
A simple Go GAE (Flexible) app I'm writing fails to deploy as soon as I bring in cloud.google.com packages to use Google services. Snippet from deploy log:

...
golang.org/x/oauth2/google
# golang.org/x/oauth2/google
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:12: cannot use appengine.AccessToken (type func(appengine.Context, ...string) (string, time.Time, error)) as type func("golang.org/x/net/context".Context, ...string) (string, time.Time, error) in assignment
_gopath/src/golang.org/x/oauth2/google/appengine_hook.go:13: cannot use appengine.AppID (type func(appengine.Context) string) as type func("golang.org/x/net/context".Context) string in assignment
...

This can be reproduced locally via go install -v -tags appenginevm within the app to deploy. The app builds and runs fine without the appenginevm tag.

I've just followed the helloworld example and modified it, and can't find anyone else with this problem (a few Google searches yielded nothing useful).

Anyone know how to fix this / what I'm missing?

Thanks in advance. The full program is below.

package main

import (
    "context"
    "fmt"
    "log"
    "net/http"
    "time"

    "cloud.google.com/go/storage"
)

var (
    client *storage.Client
)

func main() {
    ctx := context.Background()

    var err error
    client, err = storage.NewClient(ctx)
    if err != nil {
        log.Fatal(err)
        return
    }
    defer client.Close()

    http.HandleFunc("/_ah/health", healthCheckHandler)
    http.HandleFunc("/", indexHandler)
    log.Print("Listening on http://localhost:8080")
    log.Fatal(http.ListenAndServe(":8080", nil))
}

func httpError(w http.ResponseWriter, err error) {
    log.Println(err)
    http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
}

func healthCheckHandler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprint(w, "OK")
}

func indexHandler(w http.ResponseWriter, r *http.Request) {
    start := time.Now()

    finish := time.Since(start)
    fmt.Fprintf(w, "Done %v %v", finish)
}

Here is the app.yaml

env: flex
runtime: go

Body:
It turned out that I had an old version of the "google.golang.org/appengine" package locally, and what I wasn't aware of is that the "gcloud app deploy" command seems to upload all these dependencies instead of resolving dependencies remotely.

So my old local copy of this library was breaking the remote compilation process.

I figured this out purely through curiosity by running "go get -u google.golang.org/appengine" and having it fail:

package google.golang.org/appengine: google.golang.org/appengine is a custom import path
for https://github.com/golang/appengine, but
$GOPATH/src/google.golang.org/appengine is checked out from
https://github.com/golang/appengine.git

So I nuked that and got a fresh copy, now it all works.

TL;DR make sure your local packages are all up to date if you get remote compile errors.


问:
Returning rows with 0 count
Attempting to return the number of staff that has been booked to work a specific event by using a count function on tblEmployeeBooking ; This value will be used as a comparison against the number of staff required from tblEvent.

Currently, the below statement doesn't return any tblEvent records which have a zero count within tblEmployeeBooking

```<code>SELECT e.eventID
     , e.staffQuantity
     , Count(b.eventID) AS CountOfeventID
  FROM tblEmployeeBooking b
  LEFT
  JOIN tblEvent e
    ON b.eventID = e.eventID
GROUP
    BY e.eventID
     , e.staffQuantity
     , b.cancelled
HAVING (((b.cancelled)=0));
</code>```

答:
You either need to use RIGHT JOIN or switch the order of the tables in your LEFT JOIN. When you use LEFT JOIN, it selects all matching rows from the left table, it's the right table that's allowed to have non-matches in the ON condition.

Also, you need to move any conditions on the table that could have missing rows into the ON clause. Testing them in WHERE or HAVING will filter out those rows because columns are all NULL when there's no match, and that doesn't = 0.

And you shouldn't use any columns from the child table in GROUP BY, because when there's no match those columns will all be NULL, and they'll group together. In this case, there's no point in grouping by tblEmployeeBooking.cancelled because you're only selecting rows where cancelled = 0, so they'll all be in the same group anyway.

So it should be:

```<code>SELECT tblEvent.eventID, tblEvent.staffQuantity, Count(tblEmployeeBooking.eventID) AS CountOfeventID
FROM tblEvent
LEFT JOIN tblEmployeeBooking ON tblEmployeeBooking.eventID = tblEvent.eventID AND tblEmployeeBooking.cancelled = 0
GROUP BY tblEvent.eventID, tblEvent.staffQuantity
</code>```

Title: Returning rows with 0 count

Body:
Attempting to return the number of staff that has been booked to work a specific event by using a count function on tblEmployeeBooking ; This value will be used as a comparison against the number of staff required from tblEvent.

Currently, the below statement doesn't return any tblEvent records which have a zero count within tblEmployeeBooking

SELECT e.eventID
     , e.staffQuantity
     , Count(b.eventID) AS CountOfeventID
  FROM tblEmployeeBooking b
  LEFT
  JOIN tblEvent e
    ON b.eventID = e.eventID
GROUP
    BY e.eventID
     , e.staffQuantity
     , b.cancelled
HAVING (((b.cancelled)=0));

Body:
You either need to use RIGHT JOIN or switch the order of the tables in your LEFT JOIN. When you use LEFT JOIN, it selects all matching rows from the left table, it's the right table that's allowed to have non-matches in the ON condition.

Also, you need to move any conditions on the table that could have missing rows into the ON clause. Testing them in WHERE or HAVING will filter out those rows because columns are all NULL when there's no match, and that doesn't = 0.

And you shouldn't use any columns from the child table in GROUP BY, because when there's no match those columns will all be NULL, and they'll group together. In this case, there's no point in grouping by tblEmployeeBooking.cancelled because you're only selecting rows where cancelled = 0, so they'll all be in the same group anyway.

So it should be:

SELECT tblEvent.eventID, tblEvent.staffQuantity, Count(tblEmployeeBooking.eventID) AS CountOfeventID
FROM tblEvent
LEFT JOIN tblEmployeeBooking ON tblEmployeeBooking.eventID = tblEvent.eventID AND tblEmployeeBooking.cancelled = 0
GROUP BY tblEvent.eventID, tblEvent.staffQuantity