问:
Jquery ajax promise returning undefined
My second ajax call always returning undefined.

```<code>var getrpmData = fetchAjaxData(
                {
                    "MachineID": MachineID,
                    "diaVal": diaVal,
                    "ggVal": ggVal,
                    "ITEMID": ITEMID
                },
                "url_to_call");

            getrpmData.then((rpmData) => {
                console.log(rpmData.d);//getting desired value from this
                if (rpmData.d) {
                    shifHourUsigRPM(rpmData.d);
                }
            })
                .then((prodRate) => {

                    console.log(prodRate.d.KnittingQty);//not getting value
                })
                .fail((err) => {
                    console.log(err);
                }
                );

// Generic function to make an AJAX call
var fetchAjaxData = function (dataParam, dataURL) {
// Return the $.ajax promise
return $.ajax({
    beforeSend: function () { $.blockUI(); },
    complete: function () { $.unblockUI(); },
    type: "POST",
    url: dataURL,
    dataType: "JSON",
    contentType: "application/json;charset=utf-8",
    data: JSON.stringify(dataParam)
});
}

function shifHourUsigRPM(rpm) {

var KnittingWorkOrderId = GetValue($("#cmbKWO").val(), 'dlKWO');
var ITEMID = $("#cmbFabName").val();
var machineId = GetValue($("#cmbMachineID").val(), 'dlMachineID');

    //fetchAjaxData(
    //    { "this_RPM": rpm, "fab": ITEMID, "machineId": machineId, "KWOID": KnittingWorkOrderId },
    //    "pageKnittingProductionPlanning_MachineWise.aspx/KPP_Load_QtyByRPM");
   return $.ajax({
       type: "POST",
       beforeSend: function () { $.blockUI(); },
       complete: function () { $.unblockUI(); },
        url: "pageKnittingProductionPlanning_MachineWise.aspx/KPP_Load_QtyByRPM",
        dataType: "JSON",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({ "this_RPM": rpm, "fab": ITEMID, "machineId": machineId, "KWOID": KnittingWorkOrderId }),
        success: function (data) {
           //var result = data.d;
       }
   });
</code>```

my back end web service is working fine, and returning desired value but not getting that value on second console.log call

getting below response from network response:

```<code>{"d":{"__type":"BLL.Kniting_BLL.KnittingQty","TotalFabNeed":"5 is production rate","RemFabQty":null}}
</code>```

I'm expecting my second console.log should print

"5 is production rate"

, but getting undefined printed on console

答:
Your first then callback is not returning a value, so the second then callback
will get undefined as argument.

You should return the value that shifHourUsigRPM(rpmData.d) returns (i.e. a promise), so add return before that call.

```<code>getrpmData.then((rpmData) => {
    if (rpmData.d) {
        return shifHourUsigRPM(rpmData.d);
//      ^^^^^^
    }
})
</code>```

Title: Jquery ajax promise returning undefined

Body:
My second ajax call always returning undefined.

var getrpmData = fetchAjaxData(
                {
                    "MachineID": MachineID,
                    "diaVal": diaVal,
                    "ggVal": ggVal,
                    "ITEMID": ITEMID
                },
                "url_to_call");

            getrpmData.then((rpmData) => {
                console.log(rpmData.d);//getting desired value from this
                if (rpmData.d) {
                    shifHourUsigRPM(rpmData.d);
                }
            })
                .then((prodRate) => {

                    console.log(prodRate.d.KnittingQty);//not getting value
                })
                .fail((err) => {
                    console.log(err);
                }
                );

// Generic function to make an AJAX call
var fetchAjaxData = function (dataParam, dataURL) {
// Return the $.ajax promise
return $.ajax({
    beforeSend: function () { $.blockUI(); },
    complete: function () { $.unblockUI(); },
    type: "POST",
    url: dataURL,
    dataType: "JSON",
    contentType: "application/json;charset=utf-8",
    data: JSON.stringify(dataParam)
});
}

function shifHourUsigRPM(rpm) {

var KnittingWorkOrderId = GetValue($("#cmbKWO").val(), 'dlKWO');
var ITEMID = $("#cmbFabName").val();
var machineId = GetValue($("#cmbMachineID").val(), 'dlMachineID');

    //fetchAjaxData(
    //    { "this_RPM": rpm, "fab": ITEMID, "machineId": machineId, "KWOID": KnittingWorkOrderId },
    //    "pageKnittingProductionPlanning_MachineWise.aspx/KPP_Load_QtyByRPM");
   return $.ajax({
       type: "POST",
       beforeSend: function () { $.blockUI(); },
       complete: function () { $.unblockUI(); },
        url: "pageKnittingProductionPlanning_MachineWise.aspx/KPP_Load_QtyByRPM",
        dataType: "JSON",
        contentType: "application/json;charset=utf-8",
        data: JSON.stringify({ "this_RPM": rpm, "fab": ITEMID, "machineId": machineId, "KWOID": KnittingWorkOrderId }),
        success: function (data) {
           //var result = data.d;
       }
   });

my back end web service is working fine, and returning desired value but not getting that value on second console.log call

getting below response from network response:

{"d":{"__type":"BLL.Kniting_BLL.KnittingQty","TotalFabNeed":"5 is production rate","RemFabQty":null}}

I'm expecting my second console.log should print

"5 is production rate"

, but getting undefined printed on console

Body:
Your first then callback is not returning a value, so the second then callback
will get undefined as argument.

You should return the value that shifHourUsigRPM(rpmData.d) returns (i.e. a promise), so add return before that call.

getrpmData.then((rpmData) => {
    if (rpmData.d) {
        return shifHourUsigRPM(rpmData.d);
//      ^^^^^^
    }
})

ContentLicense: CC BY-SA 4.0


来源: stackexchange

问:
Will a Java stack pointing to an array use the same amount of memory?
I have a binary tree of Nodes and want to traverse it. The most common method I'm seeing is a Stack, or a LinkedList. I've also seen other methods that don't add each Node to a Stack/List, and seem to take up almost no memory (they use recursion instead to explore each element).

If I make a List<Node> to track each node in the tree, will I be taking up 2*n the amount of memory? Or, because the objects already exist in the tree, will the List only be a bunch of pointers to Node objects (which exist in the Tree), and therefore don't take up twice the memory?

Test Case:

```<code>Object objs[] = new Object[40];
/*
    Initialize the 40 objects here
*/
List<Object> objTracker = new List<>();
for(int i=0; i<objs.length; i++) {
    objTracker.add(objs[i]);
}
</code>```

Does this now take up 2x the amount of memory, or do all of the objTrackers just redirect/point to the objects stored in objs?

答:
In Java, stack memory is separate from heap memory. Stack memory is consumed for every method call, but usually this doesn't count as "occupied" memory because it's not managed by GC and because it gets released as soon as the call returns.

In the end, you have to store your objects somewhere. So it's either stack or heap. List and array have comparable space requirements if you're not overallocating their size. In your code, you are not allocating any Nodes - they already exist. You are only allocating space for array / List.

What you are doing with your code is most likely redundant. You can add your elemets to List in the first place. As you have it now, you first store objects in array, then copy them to List. If you have no further uses of objs, then objs will eventually be garbage collected, leaving only objTracker in memory.

ContentLicense: CC BY-SA 3.0

Body:
I have a binary tree of Nodes and want to traverse it. The most common method I'm seeing is a Stack, or a LinkedList. I've also seen other methods that don't add each Node to a Stack/List, and seem to take up almost no memory (they use recursion instead to explore each element).

If I make a List<Node> to track each node in the tree, will I be taking up 2*n the amount of memory? Or, because the objects already exist in the tree, will the List only be a bunch of pointers to Node objects (which exist in the Tree), and therefore don't take up twice the memory?

Test Case:

Object objs[] = new Object[40];
/*
    Initialize the 40 objects here
*/
List<Object> objTracker = new List<>();
for(int i=0; i<objs.length; i++) {
    objTracker.add(objs[i]);
}

Does this now take up 2x the amount of memory, or do all of the objTrackers just redirect/point to the objects stored in objs?


问:
Jquery onclick function called two time on dynamically added button element
I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.

Here is the js code:-

```<code>$(".panel-body").on("click", '#select_none', function(event) {
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});
</code>```

答:
Example:

```<code><input class="itemClass" type="checkbox" name="Items" value="Bike"> I have a bike<br>
<input class="itemClass" type="checkbox" name="Items" value="Car" checked> I have a car<br>
<button name="submit" onclick="getValue()" value="Submit">
</code>```

Then:

```<code>    function getValue() {
                var id;
                var name;
                var temp = [];

                $('.itemClass').each(function () {
                    var sThisVal = (this.checked ? $(this).val() : "");
                    console.log(sThisVal);

                    if (this.checked) {
                        // $("input[name=Items]:checked").map(function () {
                        temp.push(sThisVal);
                    }
                });
                console.log(temp);
                $('.itemCheckboxClass').prop('checked', false);
            }
</code>```

Body:
I have created a code on my HTML page that their multiple checkboxes and created one button dynamically in js snippet for performing some event, but when I clicked on the button to perform that even that, then it's making calls to that event snippet two times. I wanted to know how to add the event to that button.

Here is the js code:-

$(".panel-body").on("click", '#select_none', function(event) {
     $("input[name='nodelevel']:checkbox").each(function() {
         this.checked = false;
     });
});

Body:
Example:

<input class="itemClass" type="checkbox" name="Items" value="Bike"> I have a bike<br>
<input class="itemClass" type="checkbox" name="Items" value="Car" checked> I have a car<br>
<button name="submit" onclick="getValue()" value="Submit">

Then:

    function getValue() {
                var id;
                var name;
                var temp = [];

                $('.itemClass').each(function () {
                    var sThisVal = (this.checked ? $(this).val() : "");
                    console.log(sThisVal);

                    if (this.checked) {
                        // $("input[name=Items]:checked").map(function () {
                        temp.push(sThisVal);
                    }
                });
                console.log(temp);
                $('.itemCheckboxClass').prop('checked', false);
            }


问:
How to use \R in java 8 regex
I am trying to use the new \R regex matcher from java 8.
However, for the following code :

```<code>public static void main(String[] args)
  {
    String s = "This is \r\n a String with \n Different Newlines \r and other things.";
    System.out.println(s);
    System.out.println(Pattern.matches("\\R", s));
    if (Pattern.matches("\\R", s)) // <-- is always false
    {
      System.out.println("Matched");
    }

    System.out.println(s.replaceAll("\\R", "<br/>")); //This is a String with <br/> Different Newlines <br/> and other things.
  }
</code>```

The Pattern.matches always returns false, where as the replaceAll method does seem to find a match and does what I want it to. How do I make the Pattern.matches work ?

I have also tried the long about way and still can't get it to work :

```<code>   Pattern p = Pattern.compile("\\R");
    Matcher m = p.matcher(s);
    boolean b = m.matches();
    System.out.println(b);
</code>```

答:
Well matches (both in String and Matchers classes) attempts to match the complete input string.

You need to use matcher.find instead:

```<code>Pattern p = Pattern.compile("\\R");
Matcher m = p.matcher(s);
boolean b = m.find();
System.out.println(b);
</code>```

From Java docs:

\R    Matches any Unicode line-break sequence, that is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

PS; If you want to know if input contains a line-break then this one liner will work for you:

```<code>boolean b = s.matches("(?s).*?\\R.*");
</code>```

Note use of .* on either side of \R to make sure we are matching complete input. Also you need (?s) to enable DOTALL mode to be able to match multiline string with .*

Title: How to use \R in java 8 regex

Body:
I am trying to use the new \R regex matcher from java 8.
However, for the following code :

public static void main(String[] args)
  {
    String s = "This is \r\n a String with \n Different Newlines \r and other things.";
    System.out.println(s);
    System.out.println(Pattern.matches("\\R", s));
    if (Pattern.matches("\\R", s)) // <-- is always false
    {
      System.out.println("Matched");
    }

    System.out.println(s.replaceAll("\\R", "
")); //This is a String with
 Different Newlines
 and other things.
  }

The Pattern.matches always returns false, where as the replaceAll method does seem to find a match and does what I want it to. How do I make the Pattern.matches work ?

I have also tried the long about way and still can't get it to work :

   Pattern p = Pattern.compile("\\R");
    Matcher m = p.matcher(s);
    boolean b = m.matches();
    System.out.println(b);

Body:
Well matches (both in String and Matchers classes) attempts to match the complete input string.

You need to use matcher.find instead:

Pattern p = Pattern.compile("\\R");
Matcher m = p.matcher(s);
boolean b = m.find();
System.out.println(b);

From Java docs:

\R    Matches any Unicode line-break sequence, that is equivalent to \u000D\u000A|[\u000A\u000B\u000C\u000D\u0085\u2028\u2029]

PS; If you want to know if input contains a line-break then this one liner will work for you:

boolean b = s.matches("(?s).*?\\R.*");

Note use of .* on either side of \R to make sure we are matching complete input. Also you need (?s) to enable DOTALL mode to be able to match multiline string with .*


问:
Xamarin iOS navigation bar image
Hi im trying to include a logo into the navigation bar on my iOS app.
The logo has a size of 160x40 and im not using a custom navigation bar.

What I found was solutions to include like a small 40x40 button at the right side, but is there a way to include a larger item on the right side?

答:
You can add a UIImageView to the UINavigationBar

```<code>var navBar = NavigationController.NavigationBar;
var imageView = new UIImageView(UIImage.FromBundle("sushiLogo.png"));
imageView.Frame = new CGRect((navBar.Bounds.Width / 5) * 3, 0, imageView.Image.CGImage.Width, navBar.Bounds.Height);
navBar.AddSubview(imageView);
</code>```

Note: Remember to keep a reference to it and adjust its Frame upon device rotation.

Title: Xamarin iOS navigation bar image

Body:
You can add a UIImageView to the UINavigationBar

var navBar = NavigationController.NavigationBar;
var imageView = new UIImageView(UIImage.FromBundle("sushiLogo.png"));
imageView.Frame = new CGRect((navBar.Bounds.Width / 5) * 3, 0, imageView.Image.CGImage.Width, navBar.Bounds.Height);
navBar.AddSubview(imageView);

Note: Remember to keep a reference to it and adjust its Frame upon device rotation.


问:
How do I write a conditional (IF DATA EXISTS) LINQ statement without repetition?
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

```<code>bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}
</code>```

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?

答:
You Want like That?</p>

```<code>bool ifexists =  db.Users.Any(u => u.id== 1);

var query=ifexists==true ? (my inner join linq) : (my left join linq);

return query.ToList();
</code>```

Body:
I need to write a Linq query where the condition like this:

when data exists then the join will be  INNER JOIN

when data is not exists then the join will be  LEFT JOIN.

bool ifexists =  db.Users.Any(u => u.id== 1);
IQueryable<modelname> query;
if(ifexists == true)
{
    query=my inner join linq;
    query = from s in query select s;
    return query.ToList();
}
else
{
    query=my left join linq;
    query = from s in query select s;
    return query.ToList();
}

Now how I can write this Linq? Is there any way to write this linq in a single Linq statement - I don't want to write the linq twice?

Body:
You Want like That?

bool ifexists =  db.Users.Any(u => u.id== 1);

var query=ifexists==true ? (my inner join linq) : (my left join linq);

return query.ToList();


问:
jQuery - some beginner questions
I'm a very beginner to jQuery, and I'm having some basic questions:

Is it advisable to use jQuery whenever it is possible to replace something by using it? For example, is it prudent to bind all events to elements using it, instead of through HTML?

Is it better to host the jQuery .js file and all other relevant files (like JQuery UI) myself, or is it perhaps a better choice to use Google's link (they seem to host it for others too)?

When it comes to executing a script when the page is done loading, what way is preferred?

$(document).ready(function() {})

$(function() {})

$().ready(function() {})

They seem to all do the same thing, but what is the preferred way of scripting?

答:
1)  Keep all your event binding in your script.  This makes it easy to change later.  You'll also appreciate having a single place to look for all event-related logic.

2)  This has been answered very well already.

3)  I prefer #2 for its brevity, but really the ideal way to do it is like this:

```<code>jQuery(function($) {
  // Your code using failsafe $ alias here...
});
</code>```

That avoid conflicts if you are using other frameworks that define $.

Title: jQuery - some beginner questions

Body:
1)  Keep all your event binding in your script.  This makes it easy to change later.  You'll also appreciate having a single place to look for all event-related logic.

2)  This has been answered very well already.

3)  I prefer #2 for its brevity, but really the ideal way to do it is like this:

jQuery(function($) {
  // Your code using failsafe $ alias here...
});

That avoid conflicts if you are using other frameworks that define $.

ContentLicense: CC BY-SA 2.5


问:
modifying a function to apply class in correct place
With the following function:

```<code>function calculateLIsInRow() {
  var lisInRow = 0;
  $('.mobileversionworkflow ul li span:first-child').each(function() {
    $(this).removeClass("back");
    if ($(this).prev().length > 0) {
      if ($(this).position().top != $(this).prev().position().top) {
        $('.mobileversionworkflow ul li span:first-child').prev().addClass("back");
        //return false;
      }
      lisInRow++;
    } else {
      lisInRow++;
    }
    if ($(this).next().length > 0) {} else {
      $(this).addClass("back");
    }
  });
}
calculateLIsInRow();
</code>```

here is the issue, the li has the class as "back", i want to apply the class to the span after the class border_process like border_process back

```<code><li class="back"> <span class="border_process"></span>
                                 <span class="process_workflow_box">
                                 <span class="process_workflow_box_im">
                                 <img src="images/c2.png" alt="">
                                 </span>
                                 <span class="process_workflow_txt">
                                 discovery <br>& research
                                 </span>
                                 </span>
                              </li>
</code>```

where i want to apply it on the following

```<code><li> <span class="border_process back"></span>
                                     <span class="process_workflow_box">
                                     <span class="process_workflow_box_im">
                                     <img src="images/c2.png" alt="">
                                     </span>
                                     <span class="process_workflow_txt">
                                     discovery <br>& research
                                     </span>
                                     </span>
                                  </li>
</code>```

答:
function calculateLIsInRow() {
  var lisInRow = 0;
  $('li span:first-child').each(function() {
    $(this).addClass("back");
    if ($(this).prev().length > 0) {
      if ($(this).position().top != $(this).prev().position().top) {
        $('li span:first-child').prev().addClass("back");
        //return false;
      }
      lisInRow++;
    } else {
      lisInRow++;
    }
    if ($(this).next().length > 0) {} else {
      $(this).addClass("back");
    }
  });
}
calculateLIsInRow();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="back"> <span class="border_process"></span>
                                 <span class="process_workflow_box">
                                 <span class="process_workflow_box_im">
                                 <img src="images/c2.png" alt="">
                                 </span>
                                 <span class="process_workflow_txt">
                                 discovery <br>& research
                                 </span>
                                 </span>
                              </li></code>```

It seems i am able to add class back to spans. Hope it helps

Body:
With the following function:

function calculateLIsInRow() {
  var lisInRow = 0;
  $('.mobileversionworkflow ul li span:first-child').each(function() {
    $(this).removeClass("back");
    if ($(this).prev().length > 0) {
      if ($(this).position().top != $(this).prev().position().top) {
        $('.mobileversionworkflow ul li span:first-child').prev().addClass("back");
        //return false;
      }
      lisInRow++;
    } else {
      lisInRow++;
    }
    if ($(this).next().length > 0) {} else {
      $(this).addClass("back");
    }
  });
}
calculateLIsInRow();

here is the issue, the li has the class as "back", i want to apply the class to the span after the class border_process like border_process back

                                 discovery
& research

where i want to apply it on the following

                                     discovery
& research

Body:
function calculateLIsInRow() {
  var lisInRow = 0;
  $('li span:first-child').each(function() {
    $(this).addClass("back");
    if ($(this).prev().length > 0) {
      if ($(this).position().top != $(this).prev().position().top) {
        $('li span:first-child').prev().addClass("back");
        //return false;
      }
      lisInRow++;
    } else {
      lisInRow++;
    }
    if ($(this).next().length > 0) {} else {
      $(this).addClass("back");
    }
  });
}
calculateLIsInRow();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<li class="back"> <span class="border_process"></span>
                                 <span class="process_workflow_box">
                                 <span class="process_workflow_box_im">
                                 <img src="images/c2.png" alt="">
                                 </span>
                                 <span class="process_workflow_txt">
                                 discovery <br>&amp; research
                                 </span>
                                 </span>
                              </li>

It seems i am able to add class back to spans. Hope it helps


问:
I need to include a triangle as background on a div using css.

Need to add the triangle to the top right corner of a div and make text flow over it. Can we achieve this with plain css without using an image?

答:
I Hope this is what you are looking for.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
  width: 450px;
  margin: 0 auto;
  background-color: #777777;
}

.inner {
  padding: 40px;
  position: relative;
}

.text-area {
  display: flex;
  z-index: 10;
}

.text-area i {
  font-size: 60px;
  color: #ffffff;
  margin-right: 20px;
}

.text-area p {
  z-index: 99;
}

.text-area:after {
  content: "";
  display: block;
  background-color: rgba(255, 255, 255, 0.32);
  width: 150px;
  height: 304px;
  position: absolute;
  top: -75px;
  right: -73px;
  transform: rotate(150deg);
  z-index: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class="container">
  <div class="inner">
    <div class="text-area">
      <i class="fa fa-compass" aria-hidden="true"></i>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div></code>```

Body:
I Hope this is what you are looking for.

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container {
  width: 450px;
  margin: 0 auto;
  background-color: #777777;
}

.inner {
  padding: 40px;
  position: relative;
}

.text-area {
  display: flex;
  z-index: 10;
}

.text-area i {
  font-size: 60px;
  color: #ffffff;
  margin-right: 20px;
}

.text-area p {
  z-index: 99;
}

.text-area:after {
  content: "";
  display: block;
  background-color: rgba(255, 255, 255, 0.32);
  width: 150px;
  height: 304px;
  position: absolute;
  top: -75px;
  right: -73px;
  transform: rotate(150deg);
  z-index: 0;
}

<head>
<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<div class="container">
  <div class="inner">
    <div class="text-area">
      <i class="fa fa-compass" aria-hidden="true"></i>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</p>
    </div>
  </div>
</div>


问:
Android-Notification doesn't appear
This is a code for creating a notification by click a button and then turn to another class. The second class it totally empty. I don't know why it doesn't appear even it cannot turn to another class.

I have already checked the "sittings" of this file and the "notification" is "on". Could anyone help me to check it?

MainActivity.class

```<code>package com.example.ww.lab;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private int id = 1;
    private NotificationCompat.Builder notification_builder;
    private NotificationManagerCompat notification_manager;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_manager.notify(id, notification_builder.build());
            }
        });

        Intent open_activity_intent = new Intent(this, NotificationActivity.class);
        PendingIntent pending_intent = PendingIntent
            .getActivity(this, 0, open_activity_intent, PendingIntent.FLAG_CANCEL_CURRENT);

        notification_builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Notification Title")
            .setContentText("Notification Body")
            .setAutoCancel(true)
            .setContentIntent(pending_intent);

        notification_manager = NotificationManagerCompat.from(this);
    }
}
</code>```

activity_main.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.lab.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do it!"
        android:id="@+id/button"
        android:onClick="sendNotification"/>
    </android.support.constraint.ConstraintLayout>
</code>```

答:
As you have stated your compiled sdk version is 26. You need to set Channel of your notification before posting it. So it will be like

```<code>NotificationManager notification_manager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String chanel_id = "3000";
    CharSequence name = "Channel Name";
    String description = "Chanel Description";
    int importance = NotificationManager.IMPORTANCE_LOW;
    NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
    mChannel.setDescription(description);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.BLUE);
    notification_manager.createNotificationChannel(mChannel);
    notification_builder = new NotificationCompat.Builder(this, chanel_id)
} else {
    notification_builder = new NotificationCompat.Builder(this);
}
notification_builder.setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Notification Title")
        .setContentText("Notification Body")
        .setAutoCancel(true)
        .setContentIntent(pending_intent);
</code>```

For more please visit Developer Site

Title: Android-Notification doesn't appear

Body:
This is a code for creating a notification by click a button and then turn to another class. The second class it totally empty. I don't know why it doesn't appear even it cannot turn to another class.

I have already checked the "sittings" of this file and the "notification" is "on". Could anyone help me to check it?

MainActivity.class

package com.example.ww.lab;

import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.NotificationManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
    private int id = 1;
    private NotificationCompat.Builder notification_builder;
    private NotificationManagerCompat notification_manager;
    Button button;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                notification_manager.notify(id, notification_builder.build());
            }
        });

        Intent open_activity_intent = new Intent(this, NotificationActivity.class);
        PendingIntent pending_intent = PendingIntent
            .getActivity(this, 0, open_activity_intent, PendingIntent.FLAG_CANCEL_CURRENT);

        notification_builder = new NotificationCompat.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("Notification Title")
            .setContentText("Notification Body")
            .setAutoCancel(true)
            .setContentIntent(pending_intent);

        notification_manager = NotificationManagerCompat.from(this);
    }
}

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
    <android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.ww.lab.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Do it!"
        android:id="@+id/button"
        android:onClick="sendNotification"/>
    </android.support.constraint.ConstraintLayout>

Body:
As you have stated your compiled sdk version is 26. You need to set Channel of your notification before posting it. So it will be like

NotificationManager notification_manager = (NotificationManager) this
                .getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    String chanel_id = "3000";
    CharSequence name = "Channel Name";
    String description = "Chanel Description";
    int importance = NotificationManager.IMPORTANCE_LOW;
    NotificationChannel mChannel = new NotificationChannel(chanel_id, name, importance);
    mChannel.setDescription(description);
    mChannel.enableLights(true);
    mChannel.setLightColor(Color.BLUE);
    notification_manager.createNotificationChannel(mChannel);
    notification_builder = new NotificationCompat.Builder(this, chanel_id)
} else {
    notification_builder = new NotificationCompat.Builder(this);
}
notification_builder.setSmallIcon(R.drawable.ic_launcher)
        .setContentTitle("Notification Title")
        .setContentText("Notification Body")
        .setAutoCancel(true)
        .setContentIntent(pending_intent);

For more please visit Developer Site


问:
How would you make Flask(Python) recognize index.html for ALL static folders by default?
I want to make flask serve index.html for ALL folders in my static directory.
tree displays this:

```<code>static/
├── contact
│   └── index.html
├── index.html
└── notoken
    └── index.html
</code>```

I want /notoken or /contact to display what's in /notoken/index.html and /contact/index.html.
P.S: I DO NOT want to serve them using render_template or send_from_directory or anything like that because I don't want to do that for EVERY single file/folder

答:
Write a view that captures a path. Serve the index.html file under that path. Paths that don't exist will 404.

```<code>@app.route('/pages/')
@app.route('/pages/<path:path>')
def page(path=''):
    html = os.path.join(path, 'index.html')
    return app.send_static_file(html)
</code>```

Generate urls with url_for. You can only call that in templates though, not in static files.

```<code>url_for('page', path='contact')
# /page/contact
</code>```

The page prefix is added to distinguish it from other URLs, otherwise there may be conflicts since path is essentially a wildcard match.

Body:
I want to make flask serve index.html for ALL folders in my static directory.
tree displays this:

static/
├── contact
│   └── index.html
├── index.html
└── notoken
    └── index.html

I want /notoken or /contact to display what's in /notoken/index.html and /contact/index.html.
P.S: I DO NOT want to serve them using render_template or send_from_directory or anything like that because I don't want to do that for EVERY single file/folder

Body:
Write a view that captures a path. Serve the index.html file under that path. Paths that don't exist will 404.

@app.route('/pages/')
@app.route('/pages/<path:path>')
def page(path=''):
    html = os.path.join(path, 'index.html')
    return app.send_static_file(html)

Generate urls with url_for. You can only call that in templates though, not in static files.

url_for('page', path='contact')
# /page/contact

The page prefix is added to distinguish it from other URLs, otherwise there may be conflicts since path is essentially a wildcard match.


问:
Is there a Telnet library for JavaScript?
We have a network camera.  It has an HTTP server to provides the current image.  There is also a Telnet interface for controlling the camera (i.e. trigger, focus, etc.).  I would like to add an HTML page to the camera that would provide a simple interface (we already have client software we write).  I can "GET" the image and display that, but I would also like to have controls that use the Telnet interface to control the camera.  So a button might have JavaScript code behind it that connects to the camera via Telnet (logs in) and issues the command to trigger the camera.

I know that JavaScript/browsers support connecting to the same host via XMLHttpRequest.  In this case I would be looking to open a socket on port 23 and send text.  I also know that I can do this through Flash, Java, or some other technology, but I would prefer to use JavaScript only.  If that is possible.

答:
jsTerm is an HTML5 implementation of a Telnet client.

You'll need a browser that supports HTML5 WebSockets. WebSockets is the only method of doing non-HTTP requests with pure JavaScript.


问:
Azure Python SDK Error
I have written python code to get azure resources for a subscription using azure-python sdk,
the function to list all the resources inside a resource group is not working, this was working fine a week before, may be the microsoft have changed their api??
I am getting an attribute error,
AttributeError: 'ResourceGroupsOperations' object has no attribute 'list_resources'

Please Find the code below,

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
for rg in resource_client.resource_groups.list():
for item in resource_client.resource_groups.list_resources(rg.name):
print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()
</code>```

Plz do help on this! thanks in advance !

答:
Just an summary , you can find a description of the list_resources method has been removed in 2017-05-04 from SDK source code version statement.

```<code>resource_groups.list_resources has been moved to resources.list_by_resource_group
</code>```

Python SDK upgrade should be the reason for your issue.

Please modify your code as below and it will work.

```<code>from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
  for rg in resource_client.resource_groups.list():
    for item in resource_client.resources.list_by_resource_group(rg.name):
      print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()
</code>```

Title: Azure Python SDK Error

Body:
I have written python code to get azure resources for a subscription using azure-python sdk,
the function to list all the resources inside a resource group is not working, this was working fine a week before, may be the microsoft have changed their api??
I am getting an attribute error,
AttributeError: 'ResourceGroupsOperations' object has no attribute 'list_resources'

Please Find the code below,

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
for rg in resource_client.resource_groups.list():
for item in resource_client.resource_groups.list_resources(rg.name):
print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()

Plz do help on this! thanks in advance !

Body:
Just an summary , you can find a description of the list_resources method has been removed in 2017-05-04 from SDK source code version statement.

resource_groups.list_resources has been moved to resources.list_by_resource_group

Python SDK upgrade should be the reason for your issue.

Please modify your code as below and it will work.

from azure.common.credentials import ServicePrincipalCredentials
from azure.mgmt.resource.resources import ResourceManagementClient
from azure.mgmt.compute import ComputeManagementClient
from azure.mgmt.network import NetworkManagementClient
subscription_id = ''
credentials = ServicePrincipalCredentials(
client_id = '',
secret = '',
tenant = '',
)
resource_client = ResourceManagementClient(credentials,subscription_id)
resource_client.providers.register('Microsoft.Batch')
def get_resources():
  for rg in resource_client.resource_groups.list():
    for item in resource_client.resources.list_by_resource_group(rg.name):
      print "%s,%s,%s,%s,"%(item.name,item.type,item.location,rg.name)
get_resources()


问:
iterate through multiple lists with python
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

```<code>pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i
</code>```

My source data is as follows:

```<code>CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]
</code>```

UserID and Page Number
eeIDlist:

```<code>[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]
</code>```

Desired Output List:

```<code>[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]
</code>```

答:
I agree with Robbie that eeIDlist should be a dict... but otherwise, here's a solution using your lists.

```<code>for c in CompanyNameList:
    c.append([
        next(e[1] for e in eeIDlist if e[0] == int(c[0])),
        next(e[1] for e in eeIDlist if e[0] == int(c[1])),
    ])
    print(c)
</code>```

The use of next() with a generator means the list stops being search as soon as a match is found.

Body:
Hi I've searched through Stackoverflow and have been struggling with the following list-related challenge, but as a Python novice I'm stumped.

I currently have 2 lists of test data, one with user info, (both new and old user ID followed by name data) and the other a list of lists with user and page numbers (eeIDlist). I want to check if the page numbers associated with a particular user matches either the new or old ID , and if either ID matches, append the page numbers back to the original list.

I've gotten as far as matching and appending a list to the CompanyName list, but the list seems to grown exponentially and represents all of the user page data, rather than just the page numbers associated with the individuals.

Advice warmly welcomed!

My code is as follows:

pagenumbers=[]

for i in CompanyNameList:

    for ee in i:
        for eeid in eeIDlist:
            try:
                if (str(eeid[1]) in ee):
                    pagenumbers.extend([eeid[0]])
                    i.append(pagenumbers)
                    i.append([eeid[0]])
            except ValueError:
                print "Not a valid number"

print i

My source data is as follows:

CompanyNameList:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ'],['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ'],['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG'],['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE']]

UserID and Page Number
eeIDlist:

[[144128,1],[144138,12],[144130,6],[144131,9],[40013,153],[40074,310],[40023, 210],
[40050,250]]

Desired Output List:

[['144128', '40013', 'John', 'Dodge', 'F', 'DODGEJ',[1,153]],
['144130', '40023', 'John', 'Apple', 'Z', 'APPLEJ',[6,210]],
['144131', '40050', 'Gerald', 'Key', 'M', 'KEYG',[9,250]],
['144138', '40074', 'Saul', 'VanWinkle', 'VANWINKLE',[12,310]]]

Body:
I agree with Robbie that eeIDlist should be a dict... but otherwise, here's a solution using your lists.

for c in CompanyNameList:
    c.append([
        next(e[1] for e in eeIDlist if e[0] == int(c[0])),
        next(e[1] for e in eeIDlist if e[0] == int(c[1])),
    ])
    print(c)

The use of next() with a generator means the list stops being search as soon as a match is found.


问:
Failed to move file from tmp_dir to server_dir
```<code><?php
$msg = '';
if (array_key_exists('userfile', $_FILES))
    //$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));

        $fileName = $_FILES["userfile"]["name"];
    $fileTmpLoc = $_FILES["userfile"]["tmp_name"];

        $pathAndName = "uploads/".$fileName;
        $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);

    if ($moveResult == true) {
        // Upload handled successfully
        // Now create a message
        // This should be somewhere in your include_path
        require_once '/home/jaydeepkanada/public_html/phpMailer/PHPMailer-master/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('accounts@newedgesecurity.in', 'Mail From Website');
        $mail->addAddress('jaydeepkanada@gmail.com', 'Jaydeep Kanada');
        $mail->Subject = 'PHPMailer file sender';
        $mail->msgHTML("My message body");

        $allowedExts = array("doc", "docx", "pdf");
    $extension = end(explode(".", $_FILES["userfile"]["name"]));
        if (in_array($extension, $allowedExts))
        {
            $mail->addAttachment($uploadfile, $_FILES["userfile"]["name"]);
                if (!$mail->send()) {
                    $msg = "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    $msg = "Message sent!";
                }

        }else{
            die("File type not supported. Only PDF or DOC.");
        }
    } else {
        $msg = 'Failed to move file to ' . $uploadfile;
    }
}
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>PHPMailer Upload</title>
</head>
<body>
<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>
<?php } else {
    echo $msg;
} ?>
</body>
</html>
</code>```

I am using PHP mailer for sending mail with attachments and in this code path is correct but it always showing Failed to move path.

答:
Use the right convertion on file size MAX_FILE_SIZE value, something like 10485760

The problem is the value inside the <input type="hidden" name="MAX_FILE_SIZE" value="100000"> tag being in bytes your uploaded file maybe bigger than 97kbytes (100000 bytes => 97.66 kbytes) so causing the system to give an error (if you look at $_FILES["userfile"]['error'] or $_FILES["userfile"]['error'][0] content, you will see that is giving you error 2 that means "The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form".

Body:
<?php
$msg = '';
if (array_key_exists('userfile', $_FILES))
    //$uploadfile = tempnam(sys_get_temp_dir(), sha1($_FILES['userfile']['name']));

        $fileName = $_FILES["userfile"]["name"];
    $fileTmpLoc = $_FILES["userfile"]["tmp_name"];

        $pathAndName = "uploads/".$fileName;
        $moveResult = move_uploaded_file($fileTmpLoc, $pathAndName);

    if ($moveResult == true) {
        // Upload handled successfully
        // Now create a message
        // This should be somewhere in your include_path
        require_once '/home/jaydeepkanada/public_html/phpMailer/PHPMailer-master/PHPMailerAutoload.php';
        $mail = new PHPMailer;
        $mail->setFrom('accounts@newedgesecurity.in', 'Mail From Website');
        $mail->addAddress('jaydeepkanada@gmail.com', 'Jaydeep Kanada');
        $mail->Subject = 'PHPMailer file sender';
        $mail->msgHTML("My message body");

        $allowedExts = array("doc", "docx", "pdf");
    $extension = end(explode(".", $_FILES["userfile"]["name"]));
        if (in_array($extension, $allowedExts))
        {
            $mail->addAttachment($uploadfile, $_FILES["userfile"]["name"]);
                if (!$mail->send()) {
                    $msg = "Mailer Error: " . $mail->ErrorInfo;
                } else {
                    $msg = "Message sent!";
                }

        }else{
            die("File type not supported. Only PDF or DOC.");
        }
    } else {
        $msg = 'Failed to move file to ' . $uploadfile;
    }
}
?>
<!DOCTYPE html>

    <meta charset="utf-8"/>
    <title>PHPMailer Upload</title>

<?php if (empty($msg)) { ?>
    <form method="post" enctype="multipart/form-data">
        <input type="hidden" name="MAX_FILE_SIZE" value="100000"> Send this file: <input name="userfile" type="file">
        <input type="submit" value="Send File">
    </form>
<?php } else {
    echo $msg;
} ?>

I am using PHP mailer for sending mail with attachments and in this code path is correct but it always showing Failed to move path.


问:
How do angular 4 animation transition the routeroutlet properly?
Here is what i trying to achieve, i want an transition that slide to left and right when change my page, but my code it's not working, the event already triggered then when i scroll my page it trigger so many event (i test it with console.log)

here is how my code looks like

app.component.html :

```<code><main [@routerTransition]="getRouterOutletState(o)">
  <router-outlet #o="outlet"></router-outlet>
</main>
</code>```

and here is my app.component.ts :

```<code>animations: [
    trigger('routerTransition', [
      state('in', style({ transform: 'translateX(0)' })),
      transition('out => in', [
        style({ transform: 'translateX(-100%)' }),
        animate(400)
      ]),
      transition('in => out', [
        animate(400, style({ transform: 'translateX(100%)' }))
      ])
    ]),
  ]

})

export class AppComponent {
    fadePageInOut: string = 'in';

  getRouterOutletState(outlet) {
    console.log(outlet + " event triggered outlet");
    this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');
  }

}
</code>```

why it's not working? what i missed here? and console.log of the result of my code is like this :

the event increase when i scroll my page up and down, i must do something wrong for the event triggering and still the transition wont work

答:
You are not returning any value from the getRouterOutletState() function. As a result the animation is not triggered. Add a return statement from the getRouterOutletState() function and return the current value of fadePageInOut.

```<code>getRouterOutletState(outlet) {
  console.log(outlet + " event triggered outlet");
  this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');

  return this.fadePageInOut; // <-- Add this line
}
</code>```

Useful link for Angular Route Animations: https://medium.com/google-developer-experts/angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8

Body:
Here is what i trying to achieve, i want an transition that slide to left and right when change my page, but my code it's not working, the event already triggered then when i scroll my page it trigger so many event (i test it with console.log)

here is how my code looks like

app.component.html :

  <router-outlet #o="outlet"></router-outlet>

and here is my app.component.ts :

animations: [
    trigger('routerTransition', [
      state('in', style({ transform: 'translateX(0)' })),
      transition('out => in', [
        style({ transform: 'translateX(-100%)' }),
        animate(400)
      ]),
      transition('in => out', [
        animate(400, style({ transform: 'translateX(100%)' }))
      ])
    ]),
  ]

})

export class AppComponent {
    fadePageInOut: string = 'in';

  getRouterOutletState(outlet) {
    console.log(outlet + " event triggered outlet");
    this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');
  }

}

why it's not working? what i missed here? and console.log of the result of my code is like this :

the event increase when i scroll my page up and down, i must do something wrong for the event triggering and still the transition wont work

Body:
You are not returning any value from the getRouterOutletState() function. As a result the animation is not triggered. Add a return statement from the getRouterOutletState() function and return the current value of fadePageInOut.

getRouterOutletState(outlet) {
  console.log(outlet + " event triggered outlet");
  this.fadePageInOut = (this.fadePageInOut === 'in' ? 'out' : 'in');

  return this.fadePageInOut; // <-- Add this line
}

Useful link for Angular Route Animations: https://medium.com/google-developer-experts/angular-supercharge-your-router-transitions-using-new-animation-features-v4-3-3eb341ede6c8


问:
RecyclerView scroll to position when a new item is added
I want my RecyclerView to scroll to the bottom when a new item is added to the list. Below is my code:

```<code>RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);

adapter = new RecyclerViewAdapter(data, recyclerView);
recyclerView.setAdapter(adapter);
</code>```

And when I click a button which is below the RecyclerView, data is added to the list:

```<code>public void addNewCard() {
    data.add("New");
    adapter.notifyItemInserted(data.size() - 1);
    recyclerView.scrollToPosition(data.size() - 1);
}
</code>```

Whenever I add an item, it always gets scrolled up to the topmost position. I tried using smoothScrollToPosition() and tried using scrollToPosition() on LinearLayoutManager too. I even tried using ViewTreeObserver. Tried changing the version of RecyclerView in dependencies too. I searched thoroughly on Stack Overflow and none of the solutions work for me.

Any ideas on what could be the problem? I'm using RecyclerView inside a fragment. Could that be a cause of the problem?

My .xml file for the RecyclerView

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_view_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/rel_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp" />

    <Button
        android:id="@+id/button_add_new_card"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/listView"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="8dp"
        android:padding="20dp"
        android:text="+ Add new Item" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>
</code>```

答:
If want to add the data to the bottom of the list you need to use setStackFromEnd() in RecyclerView Layout Manager.

But first, you need to fix your Adapter. You must not pass your RecylerView to your Adapter. So the following code is wrong:

```<code>...
// This is wrong!!
adapter = new RecyclerViewAdapter(data, recyclerView);

recyclerView.setAdapter(adapter);
</code>```

You need to change your Adapter constructor to only receive the data as its parameter. Something like this:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;

  public RecyclerViewAdapter(List<Data> data) {
    this.mData = data;
  }

  ...
}
</code>```

Then you can set the data to always added at the last bottom with the following code:

```<code>LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);

adapter = new RecyclerViewAdapter(data);
recyclerView.setAdapter(adapter);
</code>```

To add the new data, you better to make a new method in the adapter. Something like this:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;
  ...

  public void addItem(Data datum) {
    mData.add(datum);
    notifyItemInserted(mData.size());
  }
}
</code>```

Whenever you have adding a new data, you need to scroll to the bottom with scrollToPosition method. Something like this:

```<code>adapter.addItem(newData);
recyclerView.scrollToPosition(adapter.getItemCount() - 1);
</code>```

Remember that you need to override getItemCount() in your Adapter. It should be something like this:

```<code>public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;
  public RecyclerViewAdapter(List<Data> data) {
    this.mData = data;
  }

  // Return the total count of items
  @Override
  public int getItemCount() {
    return mData.size();
  }

  ...
}
</code>```

Please be aware that I'm using a Data pojo as a sample here. You need to change it according to your data type.

Body:
I want my RecyclerView to scroll to the bottom when a new item is added to the list. Below is my code:

RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);

adapter = new RecyclerViewAdapter(data, recyclerView);
recyclerView.setAdapter(adapter);

And when I click a button which is below the RecyclerView, data is added to the list:

public void addNewCard() {
    data.add("New");
    adapter.notifyItemInserted(data.size() - 1);
    recyclerView.scrollToPosition(data.size() - 1);
}

Whenever I add an item, it always gets scrolled up to the topmost position. I tried using smoothScrollToPosition() and tried using scrollToPosition() on LinearLayoutManager too. I even tried using ViewTreeObserver. Tried changing the version of RecyclerView in dependencies too. I searched thoroughly on Stack Overflow and none of the solutions work for me.

Any ideas on what could be the problem? I'm using RecyclerView inside a fragment. Could that be a cause of the problem?

My .xml file for the RecyclerView

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.NestedScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/scroll_view_recycler"
android:layout_width="match_parent"
android:layout_height="match_parent">

<RelativeLayout
    android:id="@+id/rel_layout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/listView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="6dp" />

    <Button
        android:id="@+id/button_add_new_card"
        style="@style/Widget.AppCompat.Button.Borderless"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/listView"
        android:layout_marginBottom="16dp"
        android:layout_marginTop="8dp"
        android:padding="20dp"
        android:text="+ Add new Item" />
</RelativeLayout>
</android.support.v4.widget.NestedScrollView>

Body:
If want to add the data to the bottom of the list you need to use setStackFromEnd() in RecyclerView Layout Manager.

But first, you need to fix your Adapter. You must not pass your RecylerView to your Adapter. So the following code is wrong:

...
// This is wrong!!
adapter = new RecyclerViewAdapter(data, recyclerView);

recyclerView.setAdapter(adapter);

You need to change your Adapter constructor to only receive the data as its parameter. Something like this:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;

  public RecyclerViewAdapter(List<Data> data) {
    this.mData = data;
  }

  ...
}

Then you can set the data to always added at the last bottom with the following code:

LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setStackFromEnd(true);
recyclerView.setLayoutManager(linearLayoutManager);

adapter = new RecyclerViewAdapter(data);
recyclerView.setAdapter(adapter);

To add the new data, you better to make a new method in the adapter. Something like this:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;
  ...

  public void addItem(Data datum) {
    mData.add(datum);
    notifyItemInserted(mData.size());
  }
}

Whenever you have adding a new data, you need to scroll to the bottom with scrollToPosition method. Something like this:

adapter.addItem(newData);
recyclerView.scrollToPosition(adapter.getItemCount() - 1);

Remember that you need to override getItemCount() in your Adapter. It should be something like this:

public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {

  private List<Data> mData;
  public RecyclerViewAdapter(List<Data> data) {
    this.mData = data;
  }

  // Return the total count of items
  @Override
  public int getItemCount() {
    return mData.size();
  }

  ...
}

Please be aware that I'm using a Data pojo as a sample here. You need to change it according to your data type.


问:
Cognito send confirmation email using custom email
There's a way to send an email other than the one specified in the "Message customisation" tab on Cognito user pool?
I would like to use different email based on some parameters.

E.g.

verification@my-service.com for verification email

welcome@my-service.com for welcome email

答:
You can go to the general settings in Cognito then click on triggers. There you can select Post Confirmation lambda function(this example in node) to send the email. In the lambda function you can make the subject whatever you like and change from email address.

```<code>var aws = require('aws-sdk');
var ses = new aws.SES();

exports.handler = function(event, context) {
  console.log(event);

  if (event.request.userAttributes.email) {
    // Pull another attribute if you want
    sendEmail(event.request.userAttributes.email,
      "Congratulations "+event.userName+", you have been registered!"
      , function(status) {
         context.done(null, event);
      });
    } else {
      // Nothing to do, the user's email ID is unknown
      console.log("Failed");
      context.done(null, event);
    }
  };

  function sendEmail(to, body, completedCallback) {
    var eParams = {
      Destination: {
        ToAddresses: [to]
      },
      Message: {
        Body: {
          Text: {
            Data: body
          }
        },
        Subject: {
          Data: "Welcome to My Service!"
        }
      },
      Source: "welcome@my-service.com"
    };

    var email = ses.sendEmail(eParams, function(err, data){
      if (err) {
        console.log(err);
      } else {
        console.log("===EMAIL SENT===");
      }

      completedCallback('Email sent');
    });

    console.log("EMAIL CODE END");
  };
</code>```

You will also have to set up SES.

Body:
You can go to the general settings in Cognito then click on triggers. There you can select Post Confirmation lambda function(this example in node) to send the email. In the lambda function you can make the subject whatever you like and change from email address.

var aws = require('aws-sdk');
var ses = new aws.SES();

exports.handler = function(event, context) {
  console.log(event);

  if (event.request.userAttributes.email) {
    // Pull another attribute if you want
    sendEmail(event.request.userAttributes.email,
      "Congratulations "+event.userName+", you have been registered!"
      , function(status) {
         context.done(null, event);
      });
    } else {
      // Nothing to do, the user's email ID is unknown
      console.log("Failed");
      context.done(null, event);
    }
  };

  function sendEmail(to, body, completedCallback) {
    var eParams = {
      Destination: {
        ToAddresses: [to]
      },
      Message: {
        Body: {
          Text: {
            Data: body
          }
        },
        Subject: {
          Data: "Welcome to My Service!"
        }
      },
      Source: "welcome@my-service.com"
    };

    var email = ses.sendEmail(eParams, function(err, data){
      if (err) {
        console.log(err);
      } else {
        console.log("===EMAIL SENT===");
      }

      completedCallback('Email sent');
    });

    console.log("EMAIL CODE END");
  };

You will also have to set up SES.


问:
What does DllRegisterServer generated by the VB6 compiler do?
When you compile a VB6 DLL the compiler adds an exported DllRegisterServer() function to the DLL.

What exactly does this function do?

I do understand that its purpose seems to be to add entries to the registry that allow all the COM magic to work... calling it

"Instructs an in-process server to create its registry entries for all
  classes supported in this server module."

But I am interested in a specific, detailed specification for what it does. I haven't found any MSDN documentation on this. Does something like that exist? Has anyone disassembled that code and documented their findings?

Edit: One reason I'm interested in this is that I think there are cases where it doesn't work fully / successfully (even when regsvr32 reports success) and I'd like to understand these potential failure modes better.

答: The function is used to register the DLL with the windows registry.  For example, if you call regsvr32.exe with the DLL name, the DLL will be loaded and then the regsvr32.exe utility will call the DllRegisterServer() function. What the function ought to do from a COM perspective is to make the PROGID, CLSID, and TypeLib entries in the Windows registry so that COM clients can create and use the COM object through CoCreateInstance().</p>


问:
App works in debug mode but crashes with release apk showing java.lang.RuntimeException:Android
I know this has been asked several times before but I am facing an issue.
When I am connecting the device to the system and running my app it is working fine.
Even if I am generating a debug apk and run the app, it works fine.

However, on generating a signed apk for the release of the app I am getting the below error:

```<code>FATAL EXCEPTION: AsyncTask #5
Process: com.xxxx.xxxxx, PID: 8180
java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)
</code>```

I cannot figure out where this exception is occurring and why?

Please, can anyone help?

I have already gone through several links as:

FATAL EXCEPTION : AsyncTask#5

android Fatal Exception: AsyncTask #5

java.lang.RuntimeException: An error occured while executing doInBackground()

I am calling my async task as,

```<code>new BannerAdAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
</code>```

And my async task is,

```<code>// Checking banner ad and displaying the appropriate banner ad
class BannerAdAsyncTask extends AsyncTask<String, Boolean, Boolean> {

    String addUserResponseCode;
    String responseForAdduserRequest;
    String msg;

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Boolean doInBackground(String... params) {

        try {

                String fetchBannerURL = context.getString(R.string.site_url)
                        + "fetchbannerad.cfc?method=fetchbannerad";

                responseForAdduserRequest = fetchContentFromServer(fetchBannerURL);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        try {

            if (responseForAdduserRequest != null) {

            // Parse JSON

            JSONObject pages = new JSONObject(responseForAdduserRequest);

            String d = pages.getString("DATA");

            JSONArray dd = new JSONArray(d);

            int len = dd.length();

            for (int i = 0; i < dd.length(); i++) {

                String p = dd.getString(i);

                JSONArray values = new JSONArray(p);

                adFileName = values.getString(6);
                adLinkLocation = values.getString(7);
            }

            adBanner.setVisibility(View.VISIBLE);

            adBanner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // If the link location contains the companyid field,
                    // fetch the company id and navigate to the app's
                    // companies page with this id
                    if (adLinkLocation.contains("?companyid=")) {

                        int temp = adLinkLocation.indexOf("companyid=");

                        temp = temp + 10;

                        String companyid = adLinkLocation.substring(temp);

                        boolean isNumber = true;

                        try {

                            int id = Integer.parseInt(companyid);

                        } catch (NumberFormatException e) {
                            isNumber = false;
                        }

                        if (isNumber) {

                            Intent intent = new Intent(context,
                                    CompanyProfile.class);
                            intent.putExtra("company_id",
                                    Integer.parseInt(companyid));

                            // Get company branches as a cursor
                            final DataAdapter mDbHelper = new DataAdapter(
                                    context);
                            mDbHelper.createDatabase();
                            mDbHelper.open();

                            intent.putExtra("branch_id", primaryBranchID);
                            intent.putExtra("com_name", name);
                            intent.putExtra("com_tradename", tradename);
                            intent.putExtra("com_desc", "");
                            intent.putExtra("main_branch_id",
                                    primaryBranchID);

                            mDbHelper.close();

                            context.startActivity(intent);
                        }

                    } else {

                        // Otherwise load the link in browser
                        Intent intent = new Intent(
                                "android.intent.action.VIEW", Uri
                                .parse(adLinkLocation));
                        startActivity(intent);
                    }
                }
            });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
</code>```

This is my code for the method that fetched the contents from the server. I suspect that issue is getting the response here,

```<code>    private static String fetchContentFromServer(String request) {

    /* Converting required variables to convert the response */
    String line = "";
    String responseString = "";

    /* Initializing the HTTP client */
    HttpClient httpClient = new DefaultHttpClient();

    try {

        /* Read and write connection timeout */
        HttpParams httpParameters = new BasicHttpParams();

        int timeOutInMillis = 8 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeOutInMillis);

        int socketTimeOutinMillis = 8000;
        HttpConnectionParams.setSoTimeout(httpParameters,
                socketTimeOutinMillis);

        /*
         * Getting the response by giving request and adding it to the
         * buffer reader to read the content
         */
        HttpResponse httpResponse = httpClient
                .execute(new HttpGet(request));
        InputStream inputStream = httpResponse.getEntity().getContent();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));

        /* For all the lines in the response */
        while ((line = bufferedReader.readLine()) != null) {

            /* Appending every line to the result */
            responseString += line;
        }

        /* Closing the input stream and displaying result in text view */
        inputStream.close();

    } catch (Exception e) {

        e.printStackTrace();
    } finally {

        /* Closing the http connection */
        httpClient.getConnectionManager().shutdown();
    }

    return responseString;
}
</code>```

答:
The issue in my case was that I was not getting any kind of server response after generating the release APK whereas all of the server responses were fine in the case of debug APK.

I added the below line in my gradle file,

```<code>    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
</code>```

Body:
I know this has been asked several times before but I am facing an issue.
When I am connecting the device to the system and running my app it is working fine.
Even if I am generating a debug apk and run the app, it works fine.

However, on generating a signed apk for the release of the app I am getting the below error:

FATAL EXCEPTION: AsyncTask #5
Process: com.xxxx.xxxxx, PID: 8180
java.lang.RuntimeException: An error occurred while executing doInBackground() at android.os.AsyncTask$3.done(AsyncTask.java:309)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
at java.lang.Thread.run(Thread.java:818)

I cannot figure out where this exception is occurring and why?

Please, can anyone help?

I have already gone through several links as:

FATAL EXCEPTION : AsyncTask#5

android Fatal Exception: AsyncTask #5

java.lang.RuntimeException: An error occured while executing doInBackground()

I am calling my async task as,

new BannerAdAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

And my async task is,

// Checking banner ad and displaying the appropriate banner ad
class BannerAdAsyncTask extends AsyncTask<String, Boolean, Boolean> {

    String addUserResponseCode;
    String responseForAdduserRequest;
    String msg;

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPreExecute()
     */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected Boolean doInBackground(String... params) {

        try {

                String fetchBannerURL = context.getString(R.string.site_url)
                        + "fetchbannerad.cfc?method=fetchbannerad";

                responseForAdduserRequest = fetchContentFromServer(fetchBannerURL);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /*
     * (non-Javadoc)
     *
     * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
     */
    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);

        try {

            if (responseForAdduserRequest != null) {

            // Parse JSON

            JSONObject pages = new JSONObject(responseForAdduserRequest);

            String d = pages.getString("DATA");

            JSONArray dd = new JSONArray(d);

            int len = dd.length();

            for (int i = 0; i < dd.length(); i++) {

                String p = dd.getString(i);

                JSONArray values = new JSONArray(p);

                adFileName = values.getString(6);
                adLinkLocation = values.getString(7);
            }

            adBanner.setVisibility(View.VISIBLE);

            adBanner.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {

                    // If the link location contains the companyid field,
                    // fetch the company id and navigate to the app's
                    // companies page with this id
                    if (adLinkLocation.contains("?companyid=")) {

                        int temp = adLinkLocation.indexOf("companyid=");

                        temp = temp + 10;

                        String companyid = adLinkLocation.substring(temp);

                        boolean isNumber = true;

                        try {

                            int id = Integer.parseInt(companyid);

                        } catch (NumberFormatException e) {
                            isNumber = false;
                        }

                        if (isNumber) {

                            Intent intent = new Intent(context,
                                    CompanyProfile.class);
                            intent.putExtra("company_id",
                                    Integer.parseInt(companyid));

                            // Get company branches as a cursor
                            final DataAdapter mDbHelper = new DataAdapter(
                                    context);
                            mDbHelper.createDatabase();
                            mDbHelper.open();

                            intent.putExtra("branch_id", primaryBranchID);
                            intent.putExtra("com_name", name);
                            intent.putExtra("com_tradename", tradename);
                            intent.putExtra("com_desc", "");
                            intent.putExtra("main_branch_id",
                                    primaryBranchID);

                            mDbHelper.close();

                            context.startActivity(intent);
                        }

                    } else {

                        // Otherwise load the link in browser
                        Intent intent = new Intent(
                                "android.intent.action.VIEW", Uri
                                .parse(adLinkLocation));
                        startActivity(intent);
                    }
                }
            });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

This is my code for the method that fetched the contents from the server. I suspect that issue is getting the response here,

    private static String fetchContentFromServer(String request) {

    /* Converting required variables to convert the response */
    String line = "";
    String responseString = "";

    /* Initializing the HTTP client */
    HttpClient httpClient = new DefaultHttpClient();

    try {

        /* Read and write connection timeout */
        HttpParams httpParameters = new BasicHttpParams();

        int timeOutInMillis = 8 * 1000;
        HttpConnectionParams.setConnectionTimeout(httpParameters,
                timeOutInMillis);

        int socketTimeOutinMillis = 8000;
        HttpConnectionParams.setSoTimeout(httpParameters,
                socketTimeOutinMillis);

        /*
         * Getting the response by giving request and adding it to the
         * buffer reader to read the content
         */
        HttpResponse httpResponse = httpClient
                .execute(new HttpGet(request));
        InputStream inputStream = httpResponse.getEntity().getContent();
        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(inputStream));

        /* For all the lines in the response */
        while ((line = bufferedReader.readLine()) != null) {

            /* Appending every line to the result */
            responseString += line;
        }

        /* Closing the input stream and displaying result in text view */
        inputStream.close();

    } catch (Exception e) {

        e.printStackTrace();
    } finally {

        /* Closing the http connection */
        httpClient.getConnectionManager().shutdown();
    }

    return responseString;
}

Body:
The issue in my case was that I was not getting any kind of server response after generating the release APK whereas all of the server responses were fine in the case of debug APK.

I added the below line in my gradle file,

    buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }


问:
kivy: why cannot I change the color of my rectangle?
Here is a method that is supposed to draw the canvas of a label:

```<code>def update_canvas(self):
    c = self.canvas.after
    c.clear()
    with c:
        Color([1, 1, 1, 1])
        Line(points=[self.point_from, self.point_to])
        if self.texture:
            Color([1, 0, 0, 1]) # RED RECTANGLE!
            Rectangle(pos=self.pos, size=self.size)
            Color([1, 1, 1, 1])
            Rectangle(pos=self.pos, texture=self.texture, size=self.texture.size)
</code>```

The label used as a tooltip which also has a line pointing to the tooltipped item. The above version produces this output:

If I comment out the Rectangle instruction after the RED COLOR line, this is displayed:

Please note that the text's label is rendered twice, because I have also added a Rectangle(texture=self.texture) instruction, but that is for testing only.

The Label itself is added to the window with this simple call:

```<code>Windows.add_widget(label)
</code>```

The question is this: why is my rectangle not red? (Actually I want it to be half transparent.)

答:
You are passing a list [] to Color(), while Color expects at least 3 parameters rgb, rgba, rgb + mode or rgba + mode

try this:

```<code>def update_canvas(self):
    c = self.canvas.after
    c.clear()
    with c:
        Color(1, 1, 1, 1)
        Line(points=[self.point_from, self.point_to])
        if self.texture:
            Color(1, 0, 0, 1) # RED RECTANGLE!
            Rectangle(pos=self.pos, size=self.size)
            Color(1, 1, 1, 1)
            Rectangle(pos=self.pos, texture=self.texture, size=self.texture.size)
</code>```

If you want a half transparent rectangle change the rgba to 1,0,0,.5

Body:
Here is a method that is supposed to draw the canvas of a label:

def update_canvas(self):
    c = self.canvas.after
    c.clear()
    with c:
        Color([1, 1, 1, 1])
        Line(points=[self.point_from, self.point_to])
        if self.texture:
            Color([1, 0, 0, 1]) # RED RECTANGLE!
            Rectangle(pos=self.pos, size=self.size)
            Color([1, 1, 1, 1])
            Rectangle(pos=self.pos, texture=self.texture, size=self.texture.size)

The label used as a tooltip which also has a line pointing to the tooltipped item. The above version produces this output:

If I comment out the Rectangle instruction after the RED COLOR line, this is displayed:

Please note that the text's label is rendered twice, because I have also added a Rectangle(texture=self.texture) instruction, but that is for testing only.

The Label itself is added to the window with this simple call:

Windows.add_widget(label)

The question is this: why is my rectangle not red? (Actually I want it to be half transparent.)

Body:
You are passing a list [] to Color(), while Color expects at least 3 parameters rgb, rgba, rgb + mode or rgba + mode

try this:

def update_canvas(self):
    c = self.canvas.after
    c.clear()
    with c:
        Color(1, 1, 1, 1)
        Line(points=[self.point_from, self.point_to])
        if self.texture:
            Color(1, 0, 0, 1) # RED RECTANGLE!
            Rectangle(pos=self.pos, size=self.size)
            Color(1, 1, 1, 1)
            Rectangle(pos=self.pos, texture=self.texture, size=self.texture.size)

If you want a half transparent rectangle change the rgba to 1,0,0,.5


问:
Template function which takes lambda with variadic parameters
Educational task: want to write a function which take functional object and its arguments and call it using perfect forwarding:

```<code>auto fun = [](std::string a, std::string const& b) { return a += b; };
std::string s("world!");
s = apply(fun, std::string("Hello, "), s);
</code>```

Had written the function:

```<code>template<typename T, typename ... Args>
T apply(std::function<T(Args...)>&& fun, Args&& ... args)
{
    return fun(std::forward<Args>(args)...);
}
</code>```

However got error:

```<code>error: no matching function for call to ‘apply(main()::<lambda(std::__cxx11::string, const string&)>&, std::__cxx11::string, std::__cxx11::string&)’
    s = apply(fun, std::string("Hello, "), s);
                                            ^
candidate: template<class T, class ... Args> T&& apply(std::function<_Res(_ArgTypes ...)>, Args&& ...)
T apply(std::function<T(Args...)> fun, Args&& ... args)
    ^~~~~

note: template argument deduction/substitution failed:

note: ‘main()::<lambda(std::__cxx11::string, const string&)>’ is not derived from ‘std::function<_Res(_ArgTypes ...)>’

s = apply(fun, std::string("Hello, "), s);
</code>```

What is wrong with syntax? How to fix?

答:
Solution without std::function:

```<code>template<typename F, typename ... Args>
auto apply(F&& fun, Args&&... args) ->
    decltype(std::forward<F>(fun)(std::forward<Args>(args)...))
{
    return std::forward<F>(fun)(std::forward<Args>(args)...);
}
</code>```

Body:
Educational task: want to write a function which take functional object and its arguments and call it using perfect forwarding:

auto fun = [](std::string a, std::string const& b) { return a += b; };
std::string s("world!");
s = apply(fun, std::string("Hello, "), s);

Had written the function:

template<typename T, typename ... Args>
T apply(std::function<T(Args...)>&& fun, Args&& ... args)
{
    return fun(std::forward<Args>(args)...);
}

However got error:

error: no matching function for call to ‘apply(main()::<lambda(std::__cxx11::string, const string&)>&, std::__cxx11::string, std::__cxx11::string&)’
    s = apply(fun, std::string("Hello, "), s);
                                            ^
candidate: template<class T, class ... Args> T&& apply(std::function<_Res(_ArgTypes ...)>, Args&& ...)
T apply(std::function<T(Args...)> fun, Args&& ... args)
    ^~~~~

note: template argument deduction/substitution failed:

note: ‘main()::<lambda(std::__cxx11::string, const string&)>’ is not derived from ‘std::function<_Res(_ArgTypes ...)>’

s = apply(fun, std::string("Hello, "), s);

What is wrong with syntax? How to fix?

Body:
Solution without std::function:

template<typename F, typename ... Args>
auto apply(F&& fun, Args&&... args) ->
    decltype(std::forward<F>(fun)(std::forward<Args>(args)...))
{
    return std::forward<F>(fun)(std::forward<Args>(args)...);
}


问:
what did is difference between java and kotlin about visibility modifiers?

This is what the official document says. But when I do something like this:

```<code>var human : Human? = null
</code>```

and decompile it into java code, I find it actually was

```<code>@Nullable
private Human human;
</code>```

and it's no use to write this

```<code>public var human : Human? = null
</code>```

but when I write this:

```<code>lateinit var human : Human
</code>```

it become public this time

```<code>@NotNull
public Human human;
</code>```

it was a big problem when I use Dagger2

in Dagger2  the property be injected must be public, but if i write var human : Human? = null
it will fail to build.

答:
in Dagger2 i the property be injected must be private

Are you sure? AFAIK the field needs to be public, and lateinit var human: Human should be fine.

Body:
This is what the official document says. But when I do something like this:

var human : Human? = null

and decompile it into java code, I find it actually was

@Nullable
private Human human;

and it's no use to write this

public var human : Human? = null

but when I write this:

lateinit var human : Human

it become public this time

@NotNull
public Human human;

it was a big problem when I use Dagger2

in Dagger2  the property be injected must be public, but if i write var human : Human? = null
it will fail to build.


问:
Refer to a relative cell within a formula set by apps script
I'm attempting to have GAS set formulas into various cells in my spreadsheet.

This works:

```<code>sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M2,'sheet2'!C:O,13,false),\"\")");
</code>```

But I need the row in the formula to be relative (not always M2).

I thought this would work:

```<code>sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M" & rowID & ",'sheet2'!C:O,13,false),\"\")");
</code>```

But it pastes a 0 in the cell.  What's up with that?

答:
Try this:</p>

```<code>getRange(rowID, 14).setValue("=iferror(vlookup(M" + rowID + ",'sheet2'!C:O,13,false),\"\")");
</code>```

Body:
I'm attempting to have GAS set formulas into various cells in my spreadsheet.

This works:

sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M2,'sheet2'!C:O,13,false),\"\")");

But I need the row in the formula to be relative (not always M2).

I thought this would work:

sheet1.getRange(rowID, 14).setValue("=iferror(vlookup(M" & rowID & ",'sheet2'!C:O,13,false),\"\")");

But it pastes a 0 in the cell.  What's up with that?

Body:
Try this:

getRange(rowID, 14).setValue("=iferror(vlookup(M" + rowID + ",'sheet2'!C:O,13,false),\"\")");


问:
What is causing slow login redirect when debugging?
After the user enters a username/password and clicks a button a few steps happen:

Password is encrypted and checked against small database table (customMembershipProvider)

A query returns the users roles (customRoleMembershipProvider)

A query is run that returns about 30 records

FormsAuthentication.RedirectFromLoginPage(userNameTextbox.Text, true); is called

Response.Redirect(@"~/Home.aspx", true); is called

User arrives at simple html page

I have verified that it isn't the queries (1, 2, 3  been cached so it doesn't even hit the database).  The page that the user is redirected to is also cached and has no database logic on it.  In production it is much faster of course, but still not as snappy as I want. What could be causing this issue?  Also, I noticed once I do login, the next time I login (same or different user) the user is redirected instantaneously.

Thanks!

答:
Turned out the slowness was only caused by the following combination:

Windows 7 Ultimate, VS2010 Ultimate, Any CPU configuration

Fixed by adding an x86 debug configuration and using it instead of the Any CPU configuration.


问:
How do I read a large csv file with pandas?
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting a memory error:

```<code>MemoryError                               Traceback (most recent call last)
<ipython-input-58-67a72687871b> in <module>()
----> 1 data=pd.read_csv('aphro.csv',sep=';')

...

MemoryError:
</code>```

Any help on this?

答:
If you use pandas read large file into chunk and then yield row by row, here is what I have done</p>

```<code>import pandas as pd

def chunck_generator(filename, header=False,chunk_size = 10 ** 5):
   for chunk in pd.read_csv(filename,delimiter=',', iterator=True, chunksize=chunk_size, parse_dates=[1] ):
        yield (chunk)

def _generator( filename, header=False,chunk_size = 10 ** 5):
    chunk = chunck_generator(filename, header=False,chunk_size = 10 ** 5)
    for row in chunk:
        yield row

if __name__ == "__main__":
filename = r'file.csv'
        generator = generator(filename=filename)
        while True:
           print(next(generator))
</code>```

Body:
I am trying to read a large csv file (aprox. 6 GB) in pandas and i am getting a memory error:

MemoryError                               Traceback (most recent call last)
<ipython-input-58-67a72687871b> in <module>()
----> 1 data=pd.read_csv('aphro.csv',sep=';')

...

MemoryError:

Any help on this?

Body:
If you use pandas read large file into chunk and then yield row by row, here is what I have done

import pandas as pd

def chunck_generator(filename, header=False,chunk_size = 10 ** 5):
   for chunk in pd.read_csv(filename,delimiter=',', iterator=True, chunksize=chunk_size, parse_dates=[1] ):
        yield (chunk)

def _generator( filename, header=False,chunk_size = 10 ** 5):
    chunk = chunck_generator(filename, header=False,chunk_size = 10 ** 5)
    for row in chunk:
        yield row

if __name__ == "__main__":
filename = r'file.csv'
        generator = generator(filename=filename)
        while True:
           print(next(generator))