问:
not able to get rid of white gap below and after a div in html
I am working on designing a webpage. Here is my jsfiddle.

In my jsfiddle if you see there is a white gap just above INSURANCE black image and there is a white gap just below that INSURANCE as well. I am not able to figure out how I can get rid of that. I tried so many things but no luck so far. What is the issue here?

Here is my HTML and CSS:

@font-face {
 font-family: AvantGarde Demi;
 src: url(AvantGarde Demi.woff);
}
@font-face {
 font-family: AvantGarde;
 src: url(AvantGarde.woff);
}
@font-face {
 font-family: ITC Avant Garde Gothic;
 src: url(ITC Avant Garde Gothic.woff);
}
/******************For Top Nav****************************/

.topnav {
 position: relative;
 top: -902px;
 background-color: rgba(0, 0, 0, 0.5);
 height: 89px;
 border-bottom: 3px solid #EF7440;
 /*overflow: hidden;*/
}
.topnav ul>li {
 float: left;
 display: block;
 text-align: center;
 padding: 14px 16px;
 width: 15%;
}
.topnav a {
 text-decoration: none;
 font-size: 17px;
 color: white;
 display: block;
}
/* dropdown menus hidden initially */

.topnav ul>li>ul {
 display: none;
 margin-top: 30px;
 width: 200px;
 padding: 0;
 position: absolute;
 background-color: #f76c38;
}
.topnav ul>li>ul>li {
 float: left;
 clear: left;
 display: block;
 text-align: left;
}
body {
 border: 0;
 margin: 0;
 height: 100%;
 min-height: 100%;
 overflow-x: hidden;
}
.header {
 position: relative;
 height: 769px;
}
.header-background {
 height: 769px;
 width: 100%;
}
.orange-bar {
 position: relative;
 padding-left: 150px;
 top: -430px;
 left: -160px;
}
.header h1 {
 padding-left: 110px;
 color: white;
 font-family: AvantGarde;
 text-align: center;
 font-size: 35px;
 left: -420px;
 letter-spacing: .24em;
 position: relative;
 top: -615px;
 font-family: "AvantGarde";
 text-transform: uppercase;
}
.header p {
 padding-left: 290px;
 text-align: center;
 padding-right: 210px;
 font-size: 22px;
 letter-spacing: .12em;
 font-family: "Adelle PE";
 color: white;
 position: relative;
 top: -700px;
}
.header h2 {
 font-family: "Adelle PE";
 font-style: italic;
 text-transform: uppercase;
 top: -490px;
 font-weight: normal;
 font-size: 21px;
 position: relative;
 margin-left: 630px;
 color: white;
 letter-spacing: 0.24em;
}
.header a {
 color: white;
 text-decoration: none;
}
#worldofnorthman {
 background-size: cover;
 background-image: url("our_story.png");
 /*width: 404px;*/

 height: 768px !important;
}
.login {
 display: inline;
 padding-left: 15px;
 letter-spacing: .25em;
 color: white;
 font-size: 11.433px;
 font-family: AvantGarde;
}
.login a {
 color: white;
 text-decoration: none;
}
.login a:hover {
 color: #fe5b1f;
 text-decoration: none;
}
.container {
 width: 100% !important;
}
li.insurance {
 padding-top: 30px !important;
}
li.our-story {
 padding-top: 30px !important;
}
li.login-signup {
 padding-top: 30px !important;
}
li.get-covered {
 margin-top: 15px;
 padding-bottom: 10px !important;
 padding-top: 10px !important;
}
li.our-story {
 /*margin-right: 200px !important;*/
 font-family: AvantGarde;
 letter-spacing: .30em;
 color: white;
}
li.login-signup {
 font-style: italic;
 font-size: 12px;
 font-family: Adelle PE;
 letter-spacing: .30em;
 color: white;
}
li.get-covered {
 border-color: #EF7440;
 border-style: solid;
 color: white;
 letter-spacing: .30em;
 font-family: Adelle PE;
}
li.get-covered:hover {
 background-color: #EF7440;
}
li.insurance {
 margin-right: 80px;
 margin-left: 80px;
 color: white;
 font-family: AvantGarde;
 letter-spacing: .30em;
}
#adventure {p
 background-size: cover;
 background-image: url("https://s15.postimg.org/57rlzm6ij/insurance.png");
 /* width: 404px; */
 height: 768px !important;
}

#worldofnorthman {
 background-size: cover;
 background-image: url("https://s9.postimg.org/3vae4upan/our_story.png");
 /*width: 404px;*/
 height: 768px !important;
}
.container {
 width: 100% !important;
}
.catagories h3 {
 position: relative;
 top: 135px;
 font-size: 25px;
 font-weight: bold;
 color: #fe5b1f;
 letter-spacing: .24em;
 line-height: 1.187;
 text-align: center;
}
.catagories h3:after {
 content: "";
 height: 5px;
 width: 12%;
 background-color: #fe5b1f;
 position: absolute;
 bottom: -.8em;
 left: 50%;
 transform: translate(-50%);
}
#no-line {
 position: relative;
 top: 405px;
 font-family: AvantGarde;
 font-size: 25px;
 font-weight: bold;
 color: #fe5b1f;
 letter-spacing: .24em;
 text-align: center;
}
.catagories a {
 text-decoration: none;
 color: #fe5b1f;
 font-family: AvantGarde;
}

.catagories a:hover {
 text-decoration: none;
 color: #fe5b1f;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><html>
<head>
 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <meta name="robots" content="noindex, nofollow">
 <meta name="googlebot" content="noindex, nofollow">
 <script type="text/javascript" src="/js/lib/dummy.js"></script>
 <link rel="stylesheet" type="text/css" href="/css/result-light.css">
 <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

 <script type="text/javascript" src="https://ajax.googleapis.com;
 color: white;
 font-family: AvantGarde;
 letter-spacing: .30em;
}
  </style>

<script type=" text/javascript ">//<![CDATA[
window.onload=function(){
$(document).ready(function() {
  $(".dropdown>
  a ").click(function() {
  var $dropdownContent = $(this).siblings('.dropdown-content');

  $(this)
   .closest("ul")
   .find("li.dropdown ul.dropdown-content")
   .not($dropdownContent)
   .slideUp(200);

  $dropdownContent.slideToggle(200);
  });
  });

  } //]]>
 </script>

</head>

<body>
 <div class="header"> <img class="header-background" src="https://s30.postimg.org/3q4ox3s81/background-image-chrisdavenport.png">
  <div class="orange-bar">
   <img class="orange-bar-image" src="https://s9.postimg.org/sdrolfjan/orange-bar.png">
  </div>
  <div class="topnav">
   <ul>
    <li class="home"><img src="https://s2.postimg.org/nhr4xxqcp/northman_wordmark_CMYK.png"></li>
    <li class="dropdown" style="margin-left: 10%;margin-top: 1.7%;">
     <b>INSURANCE</b> <i class="fa fa-angle-down" aria-hidden="true"></i>
     <ul class="dropdown-content" style="display: none;">
      <li><i>INDIVIDUAL</i>
      </li>
      <li><i>CORPORATE</i>
      </li>
     </ul>
    </li>
    <li class="our-story">OUR STORY</li>
    <li class="login-signup">Log In | Sign up</li>
    <li class="get-covered" style="width: 10%;">GET <strong style="font-style:italic">COVERED</strong>
    </li>
   </ul>
  </div>
  <h1 class="text-inside-orange">INSURANCE FOR THE WILD</h1>
 </div>

 <div class="catagories" id="catagories">
  <div class="container">
   <div class="row">
    <div id="adventure" class="col-lg-6">
     <h3 id="no-line">INSURANCE </h3>
    </div>
    <div id="worldofnorthman" class="col-lg-6">
     <h3 id="no-line">OUR STORY </h3>
    </div>
   </div>
  </div>
 </div>

 <script>
  // tell the embed parent frame the height of the content
  if (window.parent && window.parent.parent) {
   window.parent.parent.postMessage(["resultsFrame", {
    height: document.body.getBoundingClientRect().height,
    slug: "tne4zh8h"
   }], "*")
  }
 </script>

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

Any thoughts what I did wrong?

答:
I'm not really sure, but the quickest possible fix would be to simple give the categories div the following css:

```<code>top: -25px;
</code>```

edit: Michael has the superior answer to your question. After reading up on margin collapse I found a really helpful link that I wanted to share for everyone who's interested in knowing why the margins collapsed: margin collapse

Body:
I am working on designing a webpage. Here is my jsfiddle.

In my jsfiddle if you see there is a white gap just above INSURANCE black image and there is a white gap just below that INSURANCE as well. I am not able to figure out how I can get rid of that. I tried so many things but no luck so far. What is the issue here?

Here is my HTML and CSS:

@font-face {
 font-family: AvantGarde Demi;
 src: url(AvantGarde Demi.woff);
}
@font-face {
 font-family: AvantGarde;
 src: url(AvantGarde.woff);
}
@font-face {
 font-family: ITC Avant Garde Gothic;
 src: url(ITC Avant Garde Gothic.woff);
}
/******************For Top Nav****************************/

.topnav {
 position: relative;
 top: -902px;
 background-color: rgba(0, 0, 0, 0.5);
 height: 89px;
 border-bottom: 3px solid #EF7440;
 /*overflow: hidden;*/
}
.topnav ul>li {
 float: left;
 display: block;
 text-align: center;
 padding: 14px 16px;
 width: 15%;
}
.topnav a {
 text-decoration: none;
 font-size: 17px;
 color: white;
 display: block;
}
/* dropdown menus hidden initially */

.topnav ul>li>ul {
 display: none;
 margin-top: 30px;
 width: 200px;
 padding: 0;
 position: absolute;
 background-color: #f76c38;
}
.topnav ul>li>ul>li {
 float: left;
 clear: left;
 display: block;
 text-align: left;
}
body {
 border: 0;
 margin: 0;
 height: 100%;
 min-height: 100%;
 overflow-x: hidden;
}
.header {
 position: relative;
 height: 769px;
}
.header-background {
 height: 769px;
 width: 100%;
}
.orange-bar {
 position: relative;
 padding-left: 150px;
 top: -430px;
 left: -160px;
}
.header h1 {
 padding-left: 110px;
 color: white;
 font-family: AvantGarde;
 text-align: center;
 font-size: 35px;
 left: -420px;
 letter-spacing: .24em;
 position: relative;
 top: -615px;
 font-family: "AvantGarde";
 text-transform: uppercase;
}
.header p {
 padding-left: 290px;
 text-align: center;
 padding-right: 210px;
 font-size: 22px;
 letter-spacing: .12em;
 font-family: "Adelle PE";
 color: white;
 position: relative;
 top: -700px;
}
.header h2 {
 font-family: "Adelle PE";
 font-style: italic;
 text-transform: uppercase;
 top: -490px;
 font-weight: normal;
 font-size: 21px;
 position: relative;
 margin-left: 630px;
 color: white;
 letter-spacing: 0.24em;
}
.header a {
 color: white;
 text-decoration: none;
}
#worldofnorthman {
 background-size: cover;
 background-image: url("our_story.png");
 /*width: 404px;*/

 height: 768px !important;
}
.login {
 display: inline;
 padding-left: 15px;
 letter-spacing: .25em;
 color: white;
 font-size: 11.433px;
 font-family: AvantGarde;
}
.login a {
 color: white;
 text-decoration: none;
}
.login a:hover {
 color: #fe5b1f;
 text-decoration: none;
}
.container {
 width: 100% !important;
}
li.insurance {
 padding-top: 30px !important;
}
li.our-story {
 padding-top: 30px !important;
}
li.login-signup {
 padding-top: 30px !important;
}
li.get-covered {
 margin-top: 15px;
 padding-bottom: 10px !important;
 padding-top: 10px !important;
}
li.our-story {
 /*margin-right: 200px !important;*/
 font-family: AvantGarde;
 letter-spacing: .30em;
 color: white;
}
li.login-signup {
 font-style: italic;
 font-size: 12px;
 font-family: Adelle PE;
 letter-spacing: .30em;
 color: white;
}
li.get-covered {
 border-color: #EF7440;
 border-style: solid;
 color: white;
 letter-spacing: .30em;
 font-family: Adelle PE;
}
li.get-covered:hover {
 background-color: #EF7440;
}
li.insurance {
 margin-right: 80px;
 margin-left: 80px;
 color: white;
 font-family: AvantGarde;
 letter-spacing: .30em;
}
#adventure {p
 background-size: cover;
 background-image: url("https://s15.postimg.org/57rlzm6ij/insurance.png");
 /* width: 404px; */
 height: 768px !important;
}

#worldofnorthman {
 background-size: cover;
 background-image: url("https://s9.postimg.org/3vae4upan/our_story.png");
 /*width: 404px;*/
 height: 768px !important;
}
.container {
 width: 100% !important;
}
.catagories h3 {
 position: relative;
 top: 135px;
 font-size: 25px;
 font-weight: bold;
 color: #fe5b1f;
 letter-spacing: .24em;
 line-height: 1.187;
 text-align: center;
}
.catagories h3:after {
 content: "";
 height: 5px;
 width: 12%;
 background-color: #fe5b1f;
 position: absolute;
 bottom: -.8em;
 left: 50%;
 transform: translate(-50%);
}
#no-line {
 position: relative;
 top: 405px;
 font-family: AvantGarde;
 font-size: 25px;
 font-weight: bold;
 color: #fe5b1f;
 letter-spacing: .24em;
 text-align: center;
}
.catagories a {
 text-decoration: none;
 color: #fe5b1f;
 font-family: AvantGarde;
}

.catagories a:hover {
 text-decoration: none;
 color: #fe5b1f;
}

 <meta http-equiv="content-type" content="text/html; charset=UTF-8">
 <meta name="robots" content="noindex, nofollow">
 <meta name="googlebot" content="noindex, nofollow">

 <link rel="stylesheet" type="text/css" href="/css/result-light.css">

 <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">

     INSURANCE

INDIVIDUAL

CORPORATE

OUR STORY

Log In | Sign up

GET COVERED

INSURANCE FOR THE WILD

INSURANCE

OUR STORY

Any thoughts what I did wrong?

Body:
I'm not really sure, but the quickest possible fix would be to simple give the categories div the following css:

top: -25px;

edit: Michael has the superior answer to your question. After reading up on margin collapse I found a really helpful link that I wanted to share for everyone who's interested in knowing why the margins collapsed: margin collapse


来源: stackexchange

问:
After Effects: Move a layer after Position keyframes have been added
I'm not sure how to word this question.

So here's an example.
The animation on a layer slides into view, and bounces back slightly.
Easy peasy.

The Position Keyframes look something like this:

Keyframe 0: (-100,200)
Keyframe 10: (100,200)
Keyframe 15: (125,200)
Keyframe 20: (100,200)

Let's say I want to move this layer, because I don't like where it's vertically positioned. So, I've been selecting each Keyframe (0,10,15,20) and manually changing the Y-axis to whatever number.

Is there an easier way to do this?
I'd like to be able to highlight the layer in the timeline, [press some button] + drag to where I would like it to be on the Y-axis, and the keyframes update themselves

答:
Two ways to do this;

Create a null object (new layer - null object), and attach the animated layer to the null object (click and drag the swirly icon on the animated layer - drag it to the null layer and it should parent to the null layer). Now you can move the position of the null layer and it will move the animated layer, preserving your keyframes.

If you make sure the playhead is over one of the keyframes, and highlight ALL your keyframes, then when you move the position of the layer (e.g move Y up 150) it will apply the same move to all keyframes.

ContentLicense: CC BY-SA 3.0


问:
CSS: Profile Picture Align
I have a problem aligning the profile picture in a chat. The profile picture should always be right beside the username like demonstrated in the picture below.

How can I fix this? Been sitting hours trying to fix this, I know there are some smart people out there that can solve this in no time.

Im not the best at css. Code below:

```<code>jsfiddle.net/cefes3au/2/
</code>```

答:
Your CSS as-is doesn't tell the image to go to the top. Depending on your needs, you may be able to use absolute and relative positioning. One simple method is by adding the following CSS:</p>

```<code>.chat-content {
  position: relative;
}
.responsive-img {
  position: absolute;
  top: 2px;
}
.chat-message {
  margin-left: 40px;
}
</code>```

Title: CSS: Profile Picture Align

Body:
I have a problem aligning the profile picture in a chat. The profile picture should always be right beside the username like demonstrated in the picture below.

How can I fix this? Been sitting hours trying to fix this, I know there are some smart people out there that can solve this in no time.

Im not the best at css. Code below:

jsfiddle.net/cefes3au/2/

Body:
Your CSS as-is doesn't tell the image to go to the top. Depending on your needs, you may be able to use absolute and relative positioning. One simple method is by adding the following CSS:

.chat-content {
  position: relative;
}
.responsive-img {
  position: absolute;
  top: 2px;
}
.chat-message {
  margin-left: 40px;
}


答:
In the div class="col s12 chat-content" element, you had align-items: center, which, while a great default for most things where you need a flexbox, it does what it says on the tin can: it aligns everything within the flexbox to be centered on the cross-axis, whereas you want things aligned to the top.

There are three ways you can fix this:

Switch align-items to stretch: this will take up the full height, if you need further decoration or backgrounds within the elements to be aligned properly

Switch align-items to flex-start: this will solve your problem by aligning the profile picture to the top, as you asked though it will not take up the full height

Remove align-items entirely, because it defaults to flex-start. Clean code is usually seen as better than not, I'd argue.

Here's a great resource on flex-boxes: https://css-tricks.com/snippets/css/a-guide-to-flexbox/

Title: CSS: Profile Picture Align


问:
Jquery toggle(), hide() not working as expected
I'm just starting out with JQuery in a Drupal environment.

I have some thumbnails, and I want it so that when you click one, the bigger picture appears in the "viewport" (a hidden div appears). There might be better ways to accomplish what I am doing, but I need to do it this way.

This is what I have :

```<code>$(document).ready(function() {
  //$('#bigpic1').hide(); //show the first big picture always on page load
  $('#bigpic2').hide();
  $('#bigpic3').hide();

 $('a#thumb1').click(function() {
    $('#bigpic2').hide(); $('#bigpic3').hide();
    $('#bigpic3').toggle(200);
     return false;
  });
 $('a#thumb2').click(function() {
    $('#bigpic1').hide(); $('#bigpic3').hide();
    $('#bigpic2').toggle(200);
    return false;
  });
  $('a#thumb3').click(function() {
    $('#bigpic1').hide(); $('#bigpic2').hide();
    $('#bigpic3').toggle(200);
    return false;
  });

});
</code>```

Besides being some ugly code, it doesn't work right. The first big picture doesn't appear when the page does, and clicking on more thumbnails shows the right div - but never hides any (only one big picture is supposed to be visible at a time in the "viewport").

My HTML looks like this

```<code><table><tr>
  <td><a href="#" mce_href="#" id="thumb1">...thumb1...</td>
  <td><a href="#" mce_href="#" id="thumb2">...thumb2...</td>
  <td><a href="#" mce_href="#" id="thumb3">...thumb3...</td>
</tr>
<tr><td colspan="3">
  <!-- my "viewport" cell -->
  <!-- the big picture displays here -->
  <div  id="bigpic1">... </div>
  <div  id="bigpic2">...</div>
  <div  id="bigpic3">...</div>
</td></tr></table>
</code>```

答:
First, it would be convenient to identify your "viewport cell" by ID or class. I don't know how the rest of your document is set up, but for example:

```<code><td id="viewport-cell" colspan="3">
  <div id="bigpic1">...1... </div>
   ...etc...
</td>
</code>```

Likewise, perhaps you can add a class to your thumbnail links to make things easier:

```<code><a class="thumb" href="#" mce_href="#" name="thumb1" id="thumb1"></a>
</code>```

Set the default style for your "bigpics" to be hidden:

```<code>td#viewport-cell div { /* hide all bigpics */
  display: none;
}
td#viewport-cell div#bigpic1 { /* but show the first one */
  display: block;
}
</code>```

Finally, with jQuery:

```<code>$(document).ready( function(){
  $('table#mytable').find('a.thumb').click( function(e){
    e.preventDefault(); // suppress native click
    var bigpicid = '#bigpic'+ this.id.replace(/^thumb/i,'');
    $(bigpicid).siblings().hide().end().fadeIn('slow');
  });
});
</code>```

Here's an example: http://jsfiddle.net/redler/SDxwF/

ContentLicense: CC BY-SA 2.5

Body:
I'm just starting out with JQuery in a Drupal environment.

I have some thumbnails, and I want it so that when you click one, the bigger picture appears in the "viewport" (a hidden div appears). There might be better ways to accomplish what I am doing, but I need to do it this way.

This is what I have :

$(document).ready(function() {
  //$('#bigpic1').hide(); //show the first big picture always on page load
  $('#bigpic2').hide();
  $('#bigpic3').hide();

 $('a#thumb1').click(function() {
    $('#bigpic2').hide(); $('#bigpic3').hide();
    $('#bigpic3').toggle(200);
     return false;
  });
 $('a#thumb2').click(function() {
    $('#bigpic1').hide(); $('#bigpic3').hide();
    $('#bigpic2').toggle(200);
    return false;
  });
  $('a#thumb3').click(function() {
    $('#bigpic1').hide(); $('#bigpic2').hide();
    $('#bigpic3').toggle(200);
    return false;
  });

});

Besides being some ugly code, it doesn't work right. The first big picture doesn't appear when the page does, and clicking on more thumbnails shows the right div - but never hides any (only one big picture is supposed to be visible at a time in the "viewport").

My HTML looks like this

  ...thumb1...
  ...thumb2...
  ...thumb3...

...

...

...

Body:
First, it would be convenient to identify your "viewport cell" by ID or class. I don't know how the rest of your document is set up, but for example:

<td id="viewport-cell" colspan="3">
  <div id="bigpic1">...1... </div>
   ...etc...
</td>

Likewise, perhaps you can add a class to your thumbnail links to make things easier:

<a class="thumb" href="#" mce_href="#" name="thumb1" id="thumb1"></a>

Set the default style for your "bigpics" to be hidden:

td#viewport-cell div { /* hide all bigpics */
  display: none;
}
td#viewport-cell div#bigpic1 { /* but show the first one */
  display: block;
}

Finally, with jQuery:

$(document).ready( function(){
  $('table#mytable').find('a.thumb').click( function(e){
    e.preventDefault(); // suppress native click
    var bigpicid = '#bigpic'+ this.id.replace(/^thumb/i,'');
    $(bigpicid).siblings().hide().end().fadeIn('slow');
  });
});

Here's an example: http://jsfiddle.net/redler/SDxwF/


问:
How do i pass the fixed value with the input value into an array list using the constructor?
I'm trying to pass two values for an object to be passed into an ArrayList from a constructor, I'm stuck trying to figure out how to pass the rate value which has a fixed value in the constructor which another class is also inheriting from. The obj requires an int, double (int is via input).

```<code>public static HotelRoom roomNormal()
    {
        int room1to299;
        double rate;
        HotelRoom obj = null;

        room1to299 = Integer.parseInt(JOptionPane.showInputDialog("Enter room number"));
        rate = obj.getRate();
        obj = new HotelRoom(room1to299, rate);
        JOptionPane.showMessageDialog(null,"--Rooms Booked out--\n\n\n"
                + "Room No. " + room1to299
                + "Nightly Rate $" + obj.getRate());
        return obj;
    }
</code>```

This is the HotelRoom class

```<code>public class HotelRoom
{
    private int roomNo;
    private double rate;

    public HotelRoom(int roomNo, double rate)
    {
        this.roomNo = roomNo;
        this.rate = rate;
        if(roomNo < 300)
            this.rate = 69.95;
        else
            this.rate = 89.95;
    }

    public int getRoomNo()
    {
        return roomNo;
    }

    public void setRoomNo(int roomNo)
    {
        this.roomNo = roomNo;
    }

    public double getRate()
    {
        return rate;
    }

    public void setRate(double rate)
    {
        this.rate = rate;
    }

    @Override
    public String toString()
    {
        return "Room No.: " + roomNo + ", Rate: " + rate + '\n';
    }

    public double increaseRate(double surcharge)
    {
        return (this.rate + surcharge);
    }
}
</code>```

this is the class inheriting from HotelRoom

```<code>public class Suite extends HotelRoom
{
    private double surcharge = 40.00;

    public Suite(double surcharge, int roomNo, double rate)
    {
        super(roomNo, rate);
        this.surcharge = surcharge;
    }

    public double getSurcharge()
    {
        return surcharge;
    }

    public void setSurcharge(double surcharge)
    {
        this.surcharge = surcharge;
    }

    @Override
    public String toString()
    {
        return super.toString() + "Surcharge: " + surcharge + 'n';
    }
}
</code>```

This is the main method so far

```<code>public static void main(String[] args)
    {
       ArrayList<HotelRoom> hrs = new ArrayList<>();
       int userSelect = menu();
       while(userSelect != 4)
       {
           switch(userSelect)
           {
               case 1:
                   subMenu();
                   break;
               case 2:
                   roomBooked();
                   break;
               case 3:
                   roomBookedAll();
                   break;
               default:
                   JOptionPane.showMessageDialog(null, "Invalid input");
           }
       }

    }
    public static int menu()
    {
        String selectMenu = "--HOTEL RENTAL SYSTEM--\n\n"
                + "1. Choose a room type\n"
                + "2. Room rates information\n"
                + "3. Rooms currently booked\n\n"
                + "4. Exit";
        int select = Integer.parseInt(JOptionPane.showInputDialog(selectMenu));
        return select;
    }
    public static void subMenu()
    {
        String subMenu = "1. Normal Hotel room\n"
                + "2. Suite\n\n"
                + "Choose room type";
        int select = Integer.parseInt(JOptionPane.showInputDialog(subMenu));
        switch(select)
        {
            case 1:
                roomNormal();
                break;
            case 2:
                roomSuite();
                break;
            default:
                break;
        }
    }

    public static HotelRoom roomNormal()
    {
        int room1to299;
        double rate;
        HotelRoom obj = null;

        room1to299 = Integer.parseInt(JOptionPane.showInputDialog("Enter room number"));
        rate = obj.getRate();
        obj = new HotelRoom(room1to299, rate);
        JOptionPane.showMessageDialog(null,"--Rooms Booked out--\n\n\n"
                + "Room No. " + room1to299
                + "Nightly Rate $" + obj.getRate());
        return obj;
    }
</code>```

答:
Your question is a little vague, so I assume the error is in the first block of code you've provided, which is the roomNormal() method. That being said, your HotelRoom object obj needs to be initialized first before it can access the getRate() method. Otherwise, it will throw a null pointer exception.

Solution: rate = 4.5 instead of rate = obj.getRate()

Body:
I'm trying to pass two values for an object to be passed into an ArrayList from a constructor, I'm stuck trying to figure out how to pass the rate value which has a fixed value in the constructor which another class is also inheriting from. The obj requires an int, double (int is via input).

public static HotelRoom roomNormal()
    {
        int room1to299;
        double rate;
        HotelRoom obj = null;

        room1to299 = Integer.parseInt(JOptionPane.showInputDialog("Enter room number"));
        rate = obj.getRate();
        obj = new HotelRoom(room1to299, rate);
        JOptionPane.showMessageDialog(null,"--Rooms Booked out--\n\n\n"
                + "Room No. " + room1to299
                + "Nightly Rate $" + obj.getRate());
        return obj;
    }

This is the HotelRoom class

public class HotelRoom
{
    private int roomNo;
    private double rate;

    public HotelRoom(int roomNo, double rate)
    {
        this.roomNo = roomNo;
        this.rate = rate;
        if(roomNo < 300)
            this.rate = 69.95;
        else
            this.rate = 89.95;
    }

    public int getRoomNo()
    {
        return roomNo;
    }

    public void setRoomNo(int roomNo)
    {
        this.roomNo = roomNo;
    }

    public double getRate()
    {
        return rate;
    }

    public void setRate(double rate)
    {
        this.rate = rate;
    }

    @Override
    public String toString()
    {
        return "Room No.: " + roomNo + ", Rate: " + rate + '\n';
    }

    public double increaseRate(double surcharge)
    {
        return (this.rate + surcharge);
    }
}

this is the class inheriting from HotelRoom

public class Suite extends HotelRoom
{
    private double surcharge = 40.00;

    public Suite(double surcharge, int roomNo, double rate)
    {
        super(roomNo, rate);
        this.surcharge = surcharge;
    }

    public double getSurcharge()
    {
        return surcharge;
    }

    public void setSurcharge(double surcharge)
    {
        this.surcharge = surcharge;
    }

    @Override
    public String toString()
    {
        return super.toString() + "Surcharge: " + surcharge + 'n';
    }
}

This is the main method so far

public static void main(String[] args)
    {
       ArrayList<HotelRoom> hrs = new ArrayList<>();
       int userSelect = menu();
       while(userSelect != 4)
       {
           switch(userSelect)
           {
               case 1:
                   subMenu();
                   break;
               case 2:
                   roomBooked();
                   break;
               case 3:
                   roomBookedAll();
                   break;
               default:
                   JOptionPane.showMessageDialog(null, "Invalid input");
           }
       }

    }
    public static int menu()
    {
        String selectMenu = "--HOTEL RENTAL SYSTEM--\n\n"
                + "1. Choose a room type\n"
                + "2. Room rates information\n"
                + "3. Rooms currently booked\n\n"
                + "4. Exit";
        int select = Integer.parseInt(JOptionPane.showInputDialog(selectMenu));
        return select;
    }
    public static void subMenu()
    {
        String subMenu = "1. Normal Hotel room\n"
                + "2. Suite\n\n"
                + "Choose room type";
        int select = Integer.parseInt(JOptionPane.showInputDialog(subMenu));
        switch(select)
        {
            case 1:
                roomNormal();
                break;
            case 2:
                roomSuite();
                break;
            default:
                break;
        }
    }

    public static HotelRoom roomNormal()
    {
        int room1to299;
        double rate;
        HotelRoom obj = null;

        room1to299 = Integer.parseInt(JOptionPane.showInputDialog("Enter room number"));
        rate = obj.getRate();
        obj = new HotelRoom(room1to299, rate);
        JOptionPane.showMessageDialog(null,"--Rooms Booked out--\n\n\n"
                + "Room No. " + room1to299
                + "Nightly Rate $" + obj.getRate());
        return obj;
    }


问:
Automation testing based on API services level instead of web UI
I start to test new project, and the developer send API services to me to test it because frontend(UI) implementation is not ready.
I have to write Automation scripts for features after stabilizing them

Is it possible to automate API services functionalities, and how plz?

or I have to wait untill frontend is ready so I can locate elements and automate through UI.

Can you please explain to me difference between
Automate through WEB UI vs through Automate API

答:
It's definitely possible to automate API service testing without a UI, and in many cases it's actually preferred.

Is it possible to automate API services functionalities, and how plz?
  or I have to wait untill frontend is ready so I can locate elements and automate through UI.

You can test the API separately from the frontend UI. Remember, all the frontend UI does is make requests to the backend API.  So instead of using the UI to make API requests, you can use a tool like Assertible, which allows you to send HTTP requests to the API and make assertions on the response.

When you're testing an API, you'll want to validate things like status code (eg, 200), and the response body to sure you get the expected response.

Basically:

1) Send API requests (eg, GET /users)

2) Receive API response (eg, [{id: user1}, {id: user2}])

3) Assert the response status code equals 200. Or, assert that 2 users are returned from the API.

Can you please explain to me difference between Automate through WEB UI vs through Automate API

The big difference is like i mentioned above: when you automate testing through the web UI, you are simply using the UI to make API requests. To test the API by itself, you just send requests directly to the backend.

There's many different tools and services you can use to accomplish this. If you want to use a hosted service that doesn't require much code, Assertible and Postman are both great. If you want to write code, you can use pretty much language/library that allows you to make HTTP requests. In JavaScript, for example, Chakram and Frisby.js are both popular choices.

Hope this helps!

As a side note - testing an API separately from the UI has a lot of advantages. Namely, keeping tests small and isolated so that tests aren't flaky and can easily be traced back to a root cause.


问:
Making push notifications with websockets
I've set up an app to send motion data from one device to another using websockets (Starscream library). Now I need to send push notifications when a critical event happens (when app is minimized), does it have anything to do with websockets or I just need to use something like Pusher?</p>

答:
As you said, I think you should use Pusher or any other external service (Pushwoosh, Onesignal, among others) to send push notifications to the users. You can't do this with websockets.

I recommend you to use OneSignal (it is free and some big companies like Uber or Zillow are using it)

EDIT:

I think you can't send a push notification from one device to the other one. One device (let's say Kid.app) should notify the server of an event, and then the server will send the push notification to the other (Parent.app).

Check this link, it will be useful for you.


问:
Could not load file or assembly 'Microsoft.ReportViewer.WebForms'
I am trying to use the report viewer in asp.net and have uploaded my site. However, when my page containing the report viewer is loaded, it shows the following error:

Could not load file or assembly 'Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This is my first time deploying an ASP.NET website, so I'm not sure what the problem is.

答: I had the same error for a different package. My problem was that a dependent project was referencing a different version. I changed them to be the same version and all was good.</p>


问:
make file fails with unknown type error?
I am attempting to run a make file for a third party piece of software but I am getting an error when I run it:

```<code>$ make
gcc -Iinclude/ -Isrc/ -Wall -Wfatal-errors  -Ofast -c ./src/gemm.c -o obj/gemm.o
In file included from ./src/gemm.c:2:
In file included from src/utils.h:5:
In file included from src/list.h:3:
include/darknet.h:491:1: fatal error: unknown type name 'pthread_t'
pthread_t load_data(load_args args);
^
1 error generated.
make: *** [obj/gemm.o] Error 1
</code>```

I'm not very familiar with C, but from what I can tell pthread_t is a datatype that is similar to an int.  I looked at the line that is causing the error:

```<code>pthread_t load_data(load_args args);
</code>```

but don't see anything that would be an obvious cause of the problem.

I looked in my make file and I see this line:

```<code>LDFLAGS= -lm -pthread
</code>```

Could this be part of the problem?

Does anyone know what I might need to do in order to get the pthread_t type recognized so I can run the make file?

I apologize if the answer is obvious - I tried googling the specific error message I was getting but didn't turn much up.  Please let me know if I need to post any other other code than what I have already included.

答:
Your error comes from not including the pthread library (assuming you are compiling this for a posix compliant system, if you are on windows pthreads are unlikely to work).

See were the pthread library is installed in your machine and include it in the command line.

Body:
I am attempting to run a make file for a third party piece of software but I am getting an error when I run it:

$ make
gcc -Iinclude/ -Isrc/ -Wall -Wfatal-errors  -Ofast -c ./src/gemm.c -o obj/gemm.o
In file included from ./src/gemm.c:2:
In file included from src/utils.h:5:
In file included from src/list.h:3:
include/darknet.h:491:1: fatal error: unknown type name 'pthread_t'
pthread_t load_data(load_args args);
^
1 error generated.
make: *** [obj/gemm.o] Error 1

I'm not very familiar with C, but from what I can tell pthread_t is a datatype that is similar to an int.  I looked at the line that is causing the error:

pthread_t load_data(load_args args);

but don't see anything that would be an obvious cause of the problem.

I looked in my make file and I see this line:

LDFLAGS= -lm -pthread

Could this be part of the problem?

Does anyone know what I might need to do in order to get the pthread_t type recognized so I can run the make file?

I apologize if the answer is obvious - I tried googling the specific error message I was getting but didn't turn much up.  Please let me know if I need to post any other other code than what I have already included.


问:
Where can I find a bit shifting guide for C?
I have looked at What are bitwise shift (bit-shift) operators and how do they work?, but I still find the concept of bit shifting difficult to understand.

Can someone point me in the direction of a more basic guide to bit shifting in C? I expect it will be something really long since it will need to cover the whole subject.

I am learning the The C Programming Language (AKA K&R), and that is what this is for, so I can do the exercises. I understand the basics, but I still cannot do correct bit shift operations.

Here are the exercises from K&R that have stumped me

Exercise 2-6: Write a function setbits(x, p, n, y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged.

Exercise 2-7: Write a function invert(x, p, n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged.

Exercise 2-8: Write a function rightrot(x, n) that returns the value of the integer x rotated to the right by n bit positions

Exercise 2-9: In a two's complement number system, x &= (x-1) deletes the rightmost 1-bit in x. Explain why, and use this observation to write a faster version of bitcount.

These are exercises from the k&R (the C programming language) book. It's the best C book there is, but I am having trouble understanding bit shifting, so I am having problems with these exercises.

答:
You're going to need more tools in your toolkit to answer those questions than shifting.

I think you'll need to start very basic about how numbers are represented in binary. Then you'll want to think about how to set and clear specific bits in that number, or a group of bits at the same time. You'll need to know how to test to see if a certain group of bits is set and about masking. You'll have to be able to do all the above with the bitwise operators and, or, xor, inversion, etc. operators.

Then you'll want to know about shifting -- moving bits left and right by a specific number of spaces. You'll want to know what happens to the bits left "empty". Is it filled with a 1 or a 0? When is it filled with a 1 or 0?

Googling "bitwise operations tutorial" seems to have come up with some promising results to begin with. But here are some basics to test yourself against to make sure you understand

```<code>// 1234 in hexadecimal. Do you understand this is not 1234 in decimal? Do you understand
// how specifying in hex makes it easier to think about the binary representation?
unsigned short i = 0x1234;
// Flip all the bits in 0x1234
printf("%04x", ~i);

// Test - Is the most significant bit set?
// mask is a binary number with the most significant bit set. Do
// you understand why this is so?
unsigned short mask = 0x8000;
if ((mask & i) == mask)
{
    printf("bit set!");
}
else
{
    printf("bit cleared!");
}

// Set the most significant bit
i = i | mask;
printf("Set the MSB of i, check it out: %i\n", i)

// Set the second most significant bit
// Do you see how by shifting mask right one it becomes the next most significant bit?
i = i | (mask >> 1);
</code>```

Good Luck!

OwnerDisplayName: angie

LastEditorDisplayName: Rich B

ContentLicense: CC BY-SA 4.0

Body:
You're going to need more tools in your toolkit to answer those questions than shifting.

I think you'll need to start very basic about how numbers are represented in binary. Then you'll want to think about how to set and clear specific bits in that number, or a group of bits at the same time. You'll need to know how to test to see if a certain group of bits is set and about masking. You'll have to be able to do all the above with the bitwise operators and, or, xor, inversion, etc. operators.

Then you'll want to know about shifting -- moving bits left and right by a specific number of spaces. You'll want to know what happens to the bits left "empty". Is it filled with a 1 or a 0? When is it filled with a 1 or 0?

Googling "bitwise operations tutorial" seems to have come up with some promising results to begin with. But here are some basics to test yourself against to make sure you understand

// 1234 in hexadecimal. Do you understand this is not 1234 in decimal? Do you understand
// how specifying in hex makes it easier to think about the binary representation?
unsigned short i = 0x1234;
// Flip all the bits in 0x1234
printf("%04x", ~i);

// Test - Is the most significant bit set?
// mask is a binary number with the most significant bit set. Do
// you understand why this is so?
unsigned short mask = 0x8000;
if ((mask & i) == mask)
{
    printf("bit set!");
}
else
{
    printf("bit cleared!");
}

// Set the most significant bit
i = i | mask;
printf("Set the MSB of i, check it out: %i\n", i)

// Set the second most significant bit
// Do you see how by shifting mask right one it becomes the next most significant bit?
i = i | (mask >> 1);

Good Luck!

OwnerDisplayName: Doug T.


问:
Tips on making custom, reuesable components in Android
I want to create a component that will appear as a navigation menu for an Android application. Basically, the custom component is a rectangular "Div" (to use HTML terms) that contains six buttons. Each button provides a link to another part of the application. I want to use this on every "page", so I want to make it easy to maintain.

What is the recommended class to extend for creating custom components like this? (I've seen the "Widget" class, but not sure If this should only be used for widget that appear outside the app (like Google search))

And

Is the process as simple as creating the custom "Widget" class with it's own XML layout and then adding it to each Activity class?

答:
The class to extend is View, the Widget class is for widgets in the homescreen. This is a nice doc to read: Building Custom Components, I suggest to look at the Compound Controls section, that seems suitable for your problem.

Is the process as simple as creating the custom "Widget" class with it's own XML layout and then adding it to each Activity class?

Yes, once you have written your own view, you just have to add it to your layouts in the XML (just like you do with the android views), something like this:

```<code><com.your.package.YourNiceView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>
</code>```

Body:
The class to extend is View, the Widget class is for widgets in the homescreen. This is a nice doc to read: Building Custom Components, I suggest to look at the Compound Controls section, that seems suitable for your problem.

Is the process as simple as creating the custom "Widget" class with it's own XML layout and then adding it to each Activity class?

Yes, once you have written your own view, you just have to add it to your layouts in the XML (just like you do with the android views), something like this:

<com.your.package.YourNiceView
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"/>


问:
Read a file one line at a time in node.js?
I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I'm missing some connections to make the whole thing fit together.

```<code> var Lazy=require("lazy");
 new Lazy(process.stdin)
     .lines
     .forEach(
          function(line) {
              console.log(line.toString());
          }
 );
 process.stdin.resume();
</code>```

The bit that I'd like to figure out is how I might read one line at a time from a file instead of STDIN as in this sample.

I tried:

```<code> fs.open('./VeryBigFile.csv', 'r', '0666', Process);

 function Process(err, fd) {
    if (err) throw err;
    // DO lazy read
 }
</code>```

but it's not working.  I know that in a pinch I could fall back to using something like PHP, but I would like to figure this out.

I don't think the other answer would work as the file is much larger than the server I'm running it on has memory for.

答:
Another solution is to run logic via sequential executor nsynjs. It reads file line-by-line using node readline module, and it doesn't use promises or recursion, therefore not going to fail on large files. Here is how the code will looks like:

```<code>var nsynjs = require('nsynjs');
var textFile = require('./wrappers/nodeReadline').textFile; // this file is part of nsynjs

function process(textFile) {

    var fh = new textFile();
    fh.open('path/to/file');
    var s;
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        console.log(s);
    fh.close();
}

var ctx = nsynjs.run(process,{},textFile,function () {
    console.log('done');
});
</code>```

Code above is based on this exampe: https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js

Body:
I am trying to read a large file one line at a time. I found a question on Quora that dealt with the subject but I'm missing some connections to make the whole thing fit together.

 var Lazy=require("lazy");
 new Lazy(process.stdin)
     .lines
     .forEach(
          function(line) {
              console.log(line.toString());
          }
 );
 process.stdin.resume();

The bit that I'd like to figure out is how I might read one line at a time from a file instead of STDIN as in this sample.

I tried:

 fs.open('./VeryBigFile.csv', 'r', '0666', Process);

 function Process(err, fd) {
    if (err) throw err;
    // DO lazy read
 }

but it's not working.  I know that in a pinch I could fall back to using something like PHP, but I would like to figure this out.

I don't think the other answer would work as the file is much larger than the server I'm running it on has memory for.

Body:
Another solution is to run logic via sequential executor nsynjs. It reads file line-by-line using node readline module, and it doesn't use promises or recursion, therefore not going to fail on large files. Here is how the code will looks like:

var nsynjs = require('nsynjs');
var textFile = require('./wrappers/nodeReadline').textFile; // this file is part of nsynjs

function process(textFile) {

    var fh = new textFile();
    fh.open('path/to/file');
    var s;
    while (typeof(s = fh.readLine(nsynjsCtx).data) != 'undefined')
        console.log(s);
    fh.close();
}

var ctx = nsynjs.run(process,{},textFile,function () {
    console.log('done');
});

Code above is based on this exampe: https://github.com/amaksr/nsynjs/blob/master/examples/node-readline/index.js


问:
500 (Internal Server Error) ajax and laravel
Hey everyone i'm having an issue editing comments with ajax in laravel 5.4

This works in a modal "press edit and modal opens" so the problem is when y click on edit "editar" i get the 500 (Internal Server Error)

First of all i will show you my js code:

$(document).ready(function(){

var commentId = 0;
    var divcomment = null;

    $('.edit-comment').click(function(event){
      event.preventDefault();
      var divcomment = this.parentNode.parentNode;
      commentId = event.target.parentNode.parentNode.dataset['commentid'];
      var commentBody = $(divcomment).find('#display-comment').text();
      $('#comment-body').val(commentBody);
      $('#edit-comment').modal();
    });

    $('#modal-save').click(function(){
        $.ajax({
            method: 'PUT',
            url: urlEdit,
            data: {comment: $('#comment-body').val(), commentId: commentId, _token: token}
        })
        .done(function (msg){
            $(divcomment).text(msg['new_comment']);
            $('#edit-comment').modal('hide');
        });
    });

});```
</div>
</div>
</p>

<p>My comments controller, update function:</p>

```    public function update(Request $request)
{

    $this->validate($request, [
        'comment' => 'required'
    ]);
    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }
    $comment->comment = $request['comment'];
    $comment->update();
    return response()->json(['new_comment' => $comment->comment], 200);

}
```

<p>I make a var for url: urlEdit, on my view so here's my view:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><article class="row">
                        <div class="col-md-3 col-sm-3 hidden-xs">
                          <figure class="thumbnail">
                            <img class="img-responsive" src="/uploads/avatars/{{ $comment->user->profilepic  }}" />
                            <figcaption class="text-center">{{ $comment->user->name }}</figcaption>
                          </figure>
                        </div>
                        <div class="col-md-8 col-sm-8">
                          <div class="panel panel-default arrow left">
                            <div class="panel-body">
                              <header class="text-left">
                                <div class="comment-user"><i class="fa fa-user"></i> {{ $comment->user->name }}</div>
                                <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"><i class="fa fa-clock-o"></i> {{ $comment->created_at->diffForHumans() }}</time>
                              </header>
                              <div id="comment-post" data-commentid="{{ $comment->id }}">
                                  <p id="display-comment">{{ $comment->comment }}</p>
                              </div>
                            </div>

                            <div class="panel-footer list-inline comment-footer">
                              @if(Auth::guest())

                              No puedes responder ningún comentario si no has ingresado.

                              @else

                              @if(Auth::user() == $comment->user)
                                Editar Eliminar
                              @endif

                              @if(Auth::user() != $comment->user)
                                Responder
                              @endif

                              @endif
                            </div>

                          </div>
                        </div>
                      </article></code>```

This is the modal:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Editar Comentario

        <form>

            Editar comentario
            <textarea class="form-control" name="comment" id="comment"></textarea>

        </form>

        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"> Editar</button>

```
</div>
</div>
</p>

<p>of course that is inside of a foreach loop.</p>

<p>I made 2 vars on my view:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>    <script>
    $(document).ready(function(){
     var token = '{{ Session::token() }}';
     var urlEdit = '{{ url('comments/update') }}';
    });
    </script></code>```

And finally a screenshot:

Thank you in advance.

答:
There are several problems with your code.  Firstly; your variable commentId does not exist at the time of your ajax request, thus is it is not present when the controller is called on the php-side of things.  Since you are using jQuery, this can be easily fixed.

The main difference between your js and the js below, is that I have replaced your

```<code>commentId = event.target.parentNode.parentNode.dataset['commentid'];
</code>```

with

```<code>commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
</code>```

since you are using jQuery.

The above line is equivalent to $(event.target.parentNode.parentNode).find('#comment-post').data('commentId');

Of note, I have commented out the ajax request; the main issue was that commentId did not exist; with the above change, it now does.

$(document).ready(function() {

  var commentId = 0;
  var divcomment = null;

  $('.edit-comment').click(function(event) {
    event.preventDefault();
    var divcomment = this.parentNode.parentNode;
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment-body').val(commentBody);
    $('#edit-comment').modal();
  });

  $('#modal-save').click(function() {
    /*$.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
          comment: $('#comment').val(),
          commentId: commentId,
          _token: token
        }
      })
      .done(function(msg) {
        $(divcomment).text(msg['new_comment']);
        $('#edit-comment').modal('hide');
      });*/
    console.log("comment id: " + commentId + " comment: " + $('#comment-body').val());
  });

});```
<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>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>
<article class="row">
  <div class="col-md-3 col-sm-3 hidden-xs">
    <figure class="thumbnail">
      <img class="img-responsive" src="http://placehold.it/200x200" />
      <figcaption class="text-center">User1</figcaption>
    </figure>
  </div>
  <div class="col-md-8 col-sm-8">
    <div class="panel panel-default arrow left">
      <div class="panel-body">
        <header class="text-left">
          <div class="comment-user"><i class="fa fa-user"></i>User1</div>
          <time class="comment-date" datetime="1 hour ago"><i class="fa fa-clock-o"></i>1 hour ago</time>
        </header>
        <div id="comment-post" data-commentid="1">
          <p id="display-comment">blah blah</p>
        </div>
      </div>

      <div class="panel-footer list-inline comment-footer">
        Editar Eliminar
      </div>
    </div>
  </div>
</article></code>```

Now, aside from that, I am not entirely sure if browsers support the PUT method yet, thus, it may be necessary to add it as a property to your data array that you're sending in your ajax request, as well as change the ajax method to POST, like so:

$.ajax({
  method: 'POST',
  url: urlEdit,
  data: {
    comment: $('#comment').val(),
    commentId: commentId,
    _token: token,
    _method: 'PUT'
  }
})
.done(function(msg) {
  $(divcomment).text(msg['new_comment']);
  $('#edit-comment').modal('hide');
});
```

<p>Finally, on the Laravel side of things, your code looks fine, though you may need a better method of comparing the authenticated user with the logged in user.</p>

<p>Of note; you are validating the existence of the <code>comment</code> request variable in your controller's update method.  So if the variable is empty or an empty string, an error will be thrown by the validator.  I'd have to check specifically how the validator works before I'd be able to provide any code in that regard.</p>

<p><strong>Update</strong>:
As it turns out, in your ajax you have the following:</p>

```comment: $('#comment-body').val(),
```

<p>And that is not the id you gave for that textarea.  The id you gave was <code>comment</code>, or in other words, your code should be this:</p>

```comment: $('#comment').val(),
```

I've thus updated the above examples to reflect this change.

Body:
Hey everyone i'm having an issue editing comments with ajax in laravel 5.4

This works in a modal "press edit and modal opens" so the problem is when y click on edit "editar" i get the 500 (Internal Server Error)

First of all i will show you my js code:

$(document).ready(function(){

var commentId = 0;
    var divcomment = null;

    $('.edit-comment').click(function(event){
      event.preventDefault();
      var divcomment = this.parentNode.parentNode;
      commentId = event.target.parentNode.parentNode.dataset['commentid'];
      var commentBody = $(divcomment).find('#display-comment').text();
      $('#comment-body').val(commentBody);
      $('#edit-comment').modal();
    });

    $('#modal-save').click(function(){
        $.ajax({
            method: 'PUT',
            url: urlEdit,
            data: {comment: $('#comment-body').val(), commentId: commentId, _token: token}
        })
        .done(function (msg){
            $(divcomment).text(msg['new_comment']);
            $('#edit-comment').modal('hide');
        });
    });

});

My comments controller, update function:

    public function update(Request $request)
{

    $this->validate($request, [
        'comment' => 'required'
    ]);
    $comment = Comment::find($request['commentId']);
    if (Auth::user() != $comment->user) {
        return redirect()->back();
    }
    $comment->comment = $request['comment'];
    $comment->update();
    return response()->json(['new_comment' => $comment->comment], 200);

}

I make a var for url: urlEdit, on my view so here's my view:

                            user->profilepic  }}" />

{{ $comment->user->name }}

 {{ $comment->user->name }}

                                <time class="comment-date" datetime="{{ $comment->created_at->diffForHumans() }}"> {{ $comment->created_at->diffForHumans() }}</time>

id }}">

{{ $comment->comment }}

                              @if(Auth::guest())

                              No puedes responder ningún comentario si no has ingresado.

                              @else

                              @if(Auth::user() == $comment->user)
                                Editar Eliminar
                              @endif

                              @if(Auth::user() != $comment->user)
                                Responder
                              @endif

                              @endif

This is the modal:

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Editar Comentario

        <form>

            Editar comentario
            <textarea class="form-control" name="comment" id="comment"></textarea>

        </form>

        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"> Editar</button>

of course that is inside of a foreach loop.

I made 2 vars on my view:

And finally a screenshot:

Thank you in advance.

Body:
There are several problems with your code.  Firstly; your variable commentId does not exist at the time of your ajax request, thus is it is not present when the controller is called on the php-side of things.  Since you are using jQuery, this can be easily fixed.

The main difference between your js and the js below, is that I have replaced your

commentId = event.target.parentNode.parentNode.dataset['commentid'];

with

commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');

since you are using jQuery.

The above line is equivalent to $(event.target.parentNode.parentNode).find('#comment-post').data('commentId');

Of note, I have commented out the ajax request; the main issue was that commentId did not exist; with the above change, it now does.

$(document).ready(function() {

  var commentId = 0;
  var divcomment = null;

  $('.edit-comment').click(function(event) {
    event.preventDefault();
    var divcomment = this.parentNode.parentNode;
    commentId = $("#comment-post", event.target.parentNode.parentNode).data('commentid');
    var commentBody = $(divcomment).find('#display-comment').text();
    $('#comment-body').val(commentBody);
    $('#edit-comment').modal();
  });

  $('#modal-save').click(function() {
    /*$.ajax({
        method: 'PUT',
        url: urlEdit,
        data: {
          comment: $('#comment').val(),
          commentId: commentId,
          _token: token
        }
      })
      .done(function(msg) {
        $(divcomment).text(msg['new_comment']);
        $('#edit-comment').modal('hide');
      });*/
    console.log("comment id: " + commentId + " comment: " + $('#comment-body').val());
  });

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="modal fade" id="edit-comment" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
        <h4 class="modal-title" style="color:#000;">Editar Comentario</h4>
      </div>
      <div class="modal-body">
        <form>
          <div class="form-group">
            <label for="comment">Editar comentario</label>
            <textarea class="form-control" name="comment" id="comment"></textarea>
          </div>
        </form>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn-comment-dismiss btn-comment-modal" data-dismiss="modal"><span class="glyphicon glyphicon-remove"></span> Cerrar</button>
        <button type="button" class="btn-comment-edit btn-comment-modal" id="modal-save"><span class="glyphicon glyphicon-ok"></span> Editar</button>
      </div>
    </div>
  </div>
</div>
<article class="row">
  <div class="col-md-3 col-sm-3 hidden-xs">
    <figure class="thumbnail">
      <img class="img-responsive" src="http://placehold.it/200x200" />
      <figcaption class="text-center">User1</figcaption>
    </figure>
  </div>
  <div class="col-md-8 col-sm-8">
    <div class="panel panel-default arrow left">
      <div class="panel-body">
        <header class="text-left">
          <div class="comment-user"><i class="fa fa-user"></i>User1</div>
          <time class="comment-date" datetime="1 hour ago"><i class="fa fa-clock-o"></i>1 hour ago</time>
        </header>
        <div id="comment-post" data-commentid="1">
          <p id="display-comment">blah blah</p>
        </div>
      </div>

      <div class="panel-footer list-inline comment-footer">
        <a href="#" data-toggle="modal" data-target="edit-comment" class="edit-comment">Editar</a> <a href="#" data-toggle="modal" data-target="delete-comment" class="delete-comment">Eliminar</a>
      </div>
    </div>
  </div>
</article>

Now, aside from that, I am not entirely sure if browsers support the PUT method yet, thus, it may be necessary to add it as a property to your data array that you're sending in your ajax request, as well as change the ajax method to POST, like so:

$.ajax({
  method: 'POST',
  url: urlEdit,
  data: {
    comment: $('#comment').val(),
    commentId: commentId,
    _token: token,
    _method: 'PUT'
  }
})
.done(function(msg) {
  $(divcomment).text(msg['new_comment']);
  $('#edit-comment').modal('hide');
});

Finally, on the Laravel side of things, your code looks fine, though you may need a better method of comparing the authenticated user with the logged in user.

Of note; you are validating the existence of the comment request variable in your controller's update method.  So if the variable is empty or an empty string, an error will be thrown by the validator.  I'd have to check specifically how the validator works before I'd be able to provide any code in that regard.

Update:
As it turns out, in your ajax you have the following:

comment: $('#comment-body').val(),

And that is not the id you gave for that textarea.  The id you gave was comment, or in other words, your code should be this:

comment: $('#comment').val(),

I've thus updated the above examples to reflect this change.


问:
How to make CORS Request
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

```<code>var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}
</code>```

Screenshot of the app:
localhost:3000/weather page

答:
Here is a simple react component which calls the api with query params and get 's the desired result.</p>

```<code>import React, { Component } from 'react'
import axios from 'axios';

export default class App extends Component {

    componentDidMount() {
        axios.get('http://autocomplete.wunderground.com/aq?query=tehran')
            .then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error);
            })
    }
    render () {
        return (
            <div>React simple starter</div>
        )
    }
}
</code>```

Title: How to make CORS Request

Body:
I'm making a weather app with React.js and I want to make a CORS request for fetching data from weather underground website.
What I want is getting a city name, use autocomplete API for finding the city and fetch data for that city.

The problem is, everytime I give a city name (for example: tehran), the xhr.onerror event handler runs and I get this error:

XMLHttpRequest cannot load http://autocomplete.wunderground.com/aq?query=tehran. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

This is my code for fetching data:

var axios = require('axios');

function createCORSRequest(method, url) {
    var xhr = new XMLHttpRequest();
    if ("withCredentials" in xhr) {
        xhr.open(method, url, true);
    }
    else if (typeof XDomainRequest != "undefined") {
        xhr = new XDomainRequest();
        xhr.open(method, url);
    }
    else {
        xhr = null;
    }
    return xhr;
}

function makeCorsRequest(url) {
    var autoCompleteText;
    var xhr = createCORSRequest('GET', url);
    if (!xhr) {
        alert('CORS not supported');
        return;
    }

    xhr.onload = function() {
        var text = xhr.responseText;
        autoCompleteText = text;
    }
    xhr.onerror = function() {
        alert('Woops, there was an error making the request.');
    }
    xhr.send();
    return autoCompleteText;
}

const WEATHER_UNDERGROUND_AUTOCOMPLETE = 'http://autocomplete.wunderground.com/aq?query=';
const WEATHER_UNDERGROUND_URL = 'http://api.wunderground.com/api/eda52d06d32d71e9/conditions/q/';

module.exports = {
    getTemp: function(city) {
        var encodedCity = encodeURIComponent(city);
        var requestAutoComplete = `${WEATHER_UNDERGROUND_AUTOCOMPLETE}${encodedCity}`;

        var autoCompleteText = makeCorsRequest(requestAutoComplete);
        var foundCity = autoCompleteText.RESULTS[0].name.split(', ');
        var requestUrl = `${WEATHER_UNDERGROUND_URL}${foundCity[1]}/${foundcity[0]}.json`;
        return axios.get(requestUrl).then(function(res) {
            return res.data.current_observation.temp_c;
        }, function(err) {
            throw new Error(res.data.error);
        });
    }
}

Screenshot of the app:
localhost:3000/weather page

Body:
Here is a simple react component which calls the api with query params and get 's the desired result.

import React, { Component } from 'react'
import axios from 'axios';

export default class App extends Component {

    componentDidMount() {
        axios.get('http://autocomplete.wunderground.com/aq?query=tehran')
            .then((response) => {
                console.log(response);
            })
            .catch((error) => {
                console.log(error);
            })
    }
    render () {
        return (
            <div>React simple starter</div>
        )
    }
}


问:
Splitting time column into start time / end time columns
I have a table that contains information regarding what they've done throughout the day.  I need to get the start time/end time for each task.

Currently I am able to pull the timestamp of each task, but I am hoping to create Start Times and End Times columns.  Start time would be the timestamp from the previous row, and end time would be the timestamp from the current row.

Is there any simple way to do this?  Here is the query that I am currently using.

```<code>select
Timestamp,
Sku,
Station,
Username,
ActionType
from OverallLogs

where
and ActionType = 'Put'
and Username = 'Name'
and timestamp < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND timestamp >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

Order by timestamp desc
</code>```

Body:
I have a table that contains information regarding what they've done throughout the day.  I need to get the start time/end time for each task.

Currently I am able to pull the timestamp of each task, but I am hoping to create Start Times and End Times columns.  Start time would be the timestamp from the previous row, and end time would be the timestamp from the current row.

Is there any simple way to do this?  Here is the query that I am currently using.

select
Timestamp,
Sku,
Station,
Username,
ActionType
from OverallLogs

where
and ActionType = 'Put'
and Username = 'Name'
and timestamp < DateAdd(Day, DateDiff(Day, 0, GetDate())+1, 0)
AND timestamp >= DateAdd(Day, DateDiff(Day, 0, GetDate()), 0)

Order by timestamp desc

Body:
If you want to get the value of last line ,you can use LAG function.
Example

;WITH sampledata(ID, t) AS(
  SELECT 1 ,DATEADD(HOUR,-12,GETDATE()) UNION
  SELECT 2 ,DATEADD(HOUR,-8,GETDATE()) UNION
  SELECT 3 ,DATEADD(HOUR,-4,GETDATE()) UNION
  SELECT 4 ,DATEADD(HOUR,-2,GETDATE()) UNION
  SELECT 5 ,DATEADD(HOUR,-1,GETDATE())

)
SELECT *,LAG(t)OVER(ORDER BY t ) AS start_t FROM sampledata

ID          t                       start_t
----------- ----------------------- -----------------------
1           2017-06-03 06:48:59.447 NULL
2           2017-06-03 10:48:59.447 2017-06-03 06:48:59.447
3           2017-06-03 14:48:59.447 2017-06-03 10:48:59.447
4           2017-06-03 16:48:59.447 2017-06-03 14:48:59.447
5           2017-06-03 17:48:59.447 2017-06-03 16:48:59.447


问:
Multiple Machines -- Process Many Files Concurrently?
I need to concurrently process a large amount of files (thousands of different files, with avg. size of 2MB per file).

All the information is stored on one (1.5TB) network hard drive, and will be accessed (read) by about 30 different machines. For efficiency, each machine will be reading (and processing) different files (there are thousands of files that need to be processed).

Every machine -- following its reading of a file from the 'incoming' folder on the 1.5TB hard drive -- will be processing the information and be ready to output the processed information back to the 'processed' folder on the 1.5TB drive. the processed information for every file is of roughly the same average size as the input files (about ~2MB per file).

Are there any 'do' and 'donts' when one is building such an operation? is it a problem to have 30 machines or so read (or write) information to the same network drive, at the same time?
(note: existing files will only be read, not appended/written; new files will be created from scratch, so there are no issues of multiple access to the same file...).
Are there any bottlenecks that I should expect?

(I am use Linux, Ubuntu 10.04 LTS on all machines if it all matters)

答:
Things you should think about:

If the processing to be done for each file is simple, then your real bottleneck isn't the amount of parallel files you read, but the capabilities of the hard disk drive.

Unless processing takes a long time (say, some seconds per file) you'll go past a point in which adding more processes will only slow down matters to a crawl, since every process is reading and writing results, and the disk can only do so much.

Try to minimize disk access: for example, download files and produce results locally while other processes are downloading, and send the results back when the load on the disk goes down.

The more I write the more it boils down to how much processing needs to be done for each file. If it's simple parsing, something that takes milliseconds, 1 machine or 30 will make little difference.


问:
Load JPG,BMP, GIF and PNG using CImage under Windows CE6?
I am trying to load JPG images using CImage under windows CE6. I have searched online but most of them use a function as described below (but the function itself is disabled for CE users):

```<code>CImage myImage;

myImage.Load(_T("C:\Image.jpg"));// Not available in windows CE
</code>```

Because in atlimage.h:

```<code>#ifndef _WIN32_WCE

inline HRESULT CImage::Load( IStream* pStream ) throw()
{
    if( !InitGDIPlus() )
    {
        return( E_FAIL );
    }

    Gdiplus::Bitmap bmSrc( pStream );
    if( bmSrc.GetLastStatus() != Gdiplus::Ok )
    {
        return( E_FAIL );
    }

    return( CreateFromGdiplusBitmap( bmSrc ) );
}

inline HRESULT CImage::Load( LPCTSTR pszFileName ) throw()
{
    if( !InitGDIPlus() )
    {
        return( E_FAIL );
    }

    Gdiplus::Bitmap bmSrc( (CT2W)pszFileName );
    if( bmSrc.GetLastStatus() != Gdiplus::Ok )
    {
        return( E_FAIL );
    }

    return( CreateFromGdiplusBitmap( bmSrc ) );
}
</code>```

Is there any other alternative method of loading jpg/bmp/gif/png files using CImage or anything else?

答:
Even though this is an old post, I was looking for this also recently so figured I'd update it.

Windows Ce 6 supports IImagingFactory.  It's a pain in the but to use, but it works, you can load png's or bitmaps from disk or memory.

Microsoft Documentation for CE 5.0

Microsoft Blog example

Body:
I am trying to load JPG images using CImage under windows CE6. I have searched online but most of them use a function as described below (but the function itself is disabled for CE users):

CImage myImage;

myImage.Load(_T("C:\Image.jpg"));// Not available in windows CE

Because in atlimage.h:

#ifndef _WIN32_WCE

inline HRESULT CImage::Load( IStream* pStream ) throw()
{
    if( !InitGDIPlus() )
    {
        return( E_FAIL );
    }

    Gdiplus::Bitmap bmSrc( pStream );
    if( bmSrc.GetLastStatus() != Gdiplus::Ok )
    {
        return( E_FAIL );
    }

    return( CreateFromGdiplusBitmap( bmSrc ) );
}

inline HRESULT CImage::Load( LPCTSTR pszFileName ) throw()
{
    if( !InitGDIPlus() )
    {
        return( E_FAIL );
    }

    Gdiplus::Bitmap bmSrc( (CT2W)pszFileName );
    if( bmSrc.GetLastStatus() != Gdiplus::Ok )
    {
        return( E_FAIL );
    }

    return( CreateFromGdiplusBitmap( bmSrc ) );
}

Is there any other alternative method of loading jpg/bmp/gif/png files using CImage or anything else?


问:
Creating a CI Build for in premise TFS 2015
I create a new build definition using the Visual Studio template. In the part where I have to Save and Queue the build, I see this window below but I cannot see anything in Queue drop-down to select. How should I set this up? Looks like I am missing a step.

答:
You have to setup up build agent, pool and queue.

Here is a Microsoft introduction "How to configure Agents, Pools and Queues"

https://microsoft.github.io/almvm/labs/tfs/build/


问:
Are Numbers As Validated Password Reset Is It Safe?
I have a table like the following:

```<code>|-------|-----------|-------------------|---------------|-----------|
|   id  |   name    |       email       |   password    |   code    |
|_______|___________|___________________|_______________|___________|
|       |           |                   |               |           |
|   1   |   user1   |   user1@gmail.com |   PASSWORD    |   8989    |
|_______|___________|___________________|_______________|___________|
|       |           |                   |               |           |
|   2   |   user2   |   user2@gmail.com |   PASSWORD    |   7676    |
|_______|___________|___________________|_______________|___________|
</code>```

As you can see, there is a column of code that I fill with random. Why the column exists, and what is the purpose?
Initially, I had trouble creating a password reset page, then I created a unique code as the validation of each user.

REGISTER

```<code><?php
include_once 'MySQLiConnect.php';

if(isset($_POST['signup'])) {

    $username = $Connection->real_escape_string($_POST['username']);
    $email = $Connection->real_escape_string($_POST['email']);
    $password = $Connection->real_escape_string($_POST['password']);
    $code = (rand(1111,9999));
    $hashed_pwd = password_hash($password, PASSWORD_DEFAULT);

    $query = "INSERT INTO users(name,email,password,code) VALUES('$username','$email','$hashed_pwd','$code')";

        if ($Connection->query($query)) {
            echo "Success";
            }
}
$Connection->close();
?>

<html>
<body>

<form method="post">
    <input type='text' name='username'/>
    <input type='email' name='email'/>
    <input type='password' name='password'/>
    <button type='submit' name='signup'>Register</button>
</form>

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

After entering the data, and registering, the user has randomly generated code. Let's just say the code is 8989. Users will not know the code, and only know after requesting a password reset.

If the user forgets the password, then the user can reset it by entering the code into the field field that was previously received by email message.

RESET PASSWORD

```<code><?php
include_once 'MySQLiConnect.php';
    $inputmail = $Connection->real_escape_string($_POST['email']);
    $inputcode = $Connection->real_escape_string($_POST['code']);
    $newcode = (rand(1111,9999));
    $newpass = $Connection->real_escape_string($_POST['password']);
    $hashed_pwd = password_hash($newpass, PASSWORD_DEFAULT);

if(isset($_POST['savepass'])) {

    $check_email = $Connection->query("SELECT * FROM users WHERE email='".$inputmail."'");
    $user_check = $check_email->fetch_array();

if ($inputcode == $user_check['code']) {
    $query = "UPDATE users SET password='".$hashed_pwd."', code='".$newcode."' WHERE email='".$inputmail."'";

        if ($Connection->query($query)) {
            echo "Password updated";
        }
    } else {
        echo "Code wrong!";
    }
}
$Connection->close();
?>

<html>
<body>

<form method="post">
    <input type='email' name='email'/>
    <input type='text' name='code'/>
    <input type='password' name='password'/>
    <button type='submit' name='savepass'> Update </button>
</form>

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

The codes above I cut a lot and I took the important part only. Sorry if there might be something wrong. But for the original, work with no problems.

But why do I make this question?
I need your opinion on this trick, because I am not so sure whether the code is safe or potentially broken into by hackers. Because the code is written with plain text without encrypt.

Awaiting your suggestion. thanks.

答:
No it's not.

If someone (somehow) gets a database dump from your site, they can login with each account using the in plain text stored code. Furthermore you are highly vulnerable to anyone attacking you using this angle: They only need to test the numbers 1000-9999 with each email combination. There is also no code in place to protect yourself against such mass login attempts.

Jeff Atwood recently blogged about hash security. If you are concerned about your user password protection, read it :)

If this is a publicly facing website, I would suggest allowing your users to login with their Facebook, Github, Google, ... accounts - whichever are appropriate for your target audience. This way you do not have to implement password reset at all. Let those companies worry how to do this securely for you...

Body:
I have a table like the following:

|-------|-----------|-------------------|---------------|-----------|
|   id  |   name    |       email       |   password    |   code    |
|_______|___________|___________________|_______________|___________|
|       |           |                   |               |           |
|   1   |   user1   |   user1@gmail.com |   PASSWORD    |   8989    |
|_______|___________|___________________|_______________|___________|
|       |           |                   |               |           |
|   2   |   user2   |   user2@gmail.com |   PASSWORD    |   7676    |
|_______|___________|___________________|_______________|___________|

As you can see, there is a column of code that I fill with random. Why the column exists, and what is the purpose?
Initially, I had trouble creating a password reset page, then I created a unique code as the validation of each user.

REGISTER

<?php
include_once 'MySQLiConnect.php';

if(isset($_POST['signup'])) {

    $username = $Connection->real_escape_string($_POST['username']);
    $email = $Connection->real_escape_string($_POST['email']);
    $password = $Connection->real_escape_string($_POST['password']);
    $code = (rand(1111,9999));
    $hashed_pwd = password_hash($password, PASSWORD_DEFAULT);

    $query = "INSERT INTO users(name,email,password,code) VALUES('$username','$email','$hashed_pwd','$code')";

        if ($Connection->query($query)) {
            echo "Success";
            }
}
$Connection->close();
?>

<form method="post">
    <input type='text' name='username'/>
    <input type='email' name='email'/>
    <input type='password' name='password'/>
    <button type='submit' name='signup'>Register</button>
</form>

After entering the data, and registering, the user has randomly generated code. Let's just say the code is 8989. Users will not know the code, and only know after requesting a password reset.

If the user forgets the password, then the user can reset it by entering the code into the field field that was previously received by email message.

RESET PASSWORD

<?php
include_once 'MySQLiConnect.php';
    $inputmail = $Connection->real_escape_string($_POST['email']);
    $inputcode = $Connection->real_escape_string($_POST['code']);
    $newcode = (rand(1111,9999));
    $newpass = $Connection->real_escape_string($_POST['password']);
    $hashed_pwd = password_hash($newpass, PASSWORD_DEFAULT);

if(isset($_POST['savepass'])) {

    $check_email = $Connection->query("SELECT * FROM users WHERE email='".$inputmail."'");
    $user_check = $check_email->fetch_array();

if ($inputcode == $user_check['code']) {
    $query = "UPDATE users SET password='".$hashed_pwd."', code='".$newcode."' WHERE email='".$inputmail."'";

        if ($Connection->query($query)) {
            echo "Password updated";
        }
    } else {
        echo "Code wrong!";
    }
}
$Connection->close();
?>

<form method="post">
    <input type='email' name='email'/>
    <input type='text' name='code'/>
    <input type='password' name='password'/>
    <button type='submit' name='savepass'> Update </button>
</form>

The codes above I cut a lot and I took the important part only. Sorry if there might be something wrong. But for the original, work with no problems.

But why do I make this question?
I need your opinion on this trick, because I am not so sure whether the code is safe or potentially broken into by hackers. Because the code is written with plain text without encrypt.

Awaiting your suggestion. thanks.


问:
Clearing Thread Safe Collections while in parallel.foreach loop after insert to sql
I have a long running process that uses a parallel.foreach loop.  While in that loop, I'm creating instance of two different classes based on what is passed, performing minor tasks, then adding to thread safe collections.  When complete, all data needs to be inserted to sql.

The problem I have is the amount of work done is too large to keep in the collections until all processing is done.  I have to push what is retained to SQL occasionally then remove what was pushed from the collection so more processing can continue without running out of memory and I don't know the best way to do that.  I can easily do it if it wasn't multi-threaded by checking the count of the collections and if it is over a certain amount, call a function that would push the contents to SQL through a bulk insert or valued table then clear that collection on the next statement.   What is the best way to accomplish this within a parallel.foreach?

I'm open to using any collection that is thread safe.  So far I'm been using the ConcurrentQueue and thought about switching to BlockingCollection because I didn't see a way to clear the Concurrent Queue.  I don't care what order the contents are inserted, but I do need to be able to at least remove what is pushed to sql.

My best solution is to use BlockingCollection.GetConsumingEnumerable().  This way, once over x amount, I can copy the contents of that collection to another thread safe collection, perform my insert, then use that list to remove from the original using BlockingCollection.GetConsumingEnumerable().  Once that's done, dispose of the temp list.  I just thought there was a better way because if I have to iterate one at a time to remove, it kind of defeats the purpose of have it multi threaded.

I have seen the use of pulse and wait used but I couldn't find a good use case that seems safe.  I could have something come through after I tested the collection to be over a certain amount and get cleared before it was inserted to sql.

I'm using the 4.5 Framework and I'm managing two different collections that need to be pushed but not necessarily at the same time.

答:
I wouldn't recommend clearing a concurrent collection. Instead, I would 'replace' it with a new one - and process the content from the old one while the other threads push their content to the new one.

Interlocked.Exchange is the technique I would use to accomplish this.


问:
How to rearrange a two dimensional array
I want to assign the values in one array to another, but in a different
order. For example the original array would be:

```<code>1  2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21
</code>```

And the desired array is:

```<code>8  11 14 3 6  16 19
9  12 1  4 7  17 20
10 13 2  5 15 18 21
</code>```

How would I do this? In the code below I moved a selected row to the center, then assigned each array individually. I can't figure out a better way.

```<code>int main()
{
int decide, i, j, k;
int save[3][7];
int shuffle[3][7];
int arr[3][7] = {
                {1, 2, 3, 4, 5, 6, 7},
                {8, 9, 10, 11, 12, 13, 14},
                {15, 16, 17, 18, 19, 20, 21}
            };

printf("Select a number between 1 and 21\n\n0-GroupA (1 - 7))\n1-GroupB ( 8 - 14)\n2-GroupC (15 - 21)\n\n");

for(k = 0 ; k < 1 ; ++k)
{
    printf("Select which group the number falls into:");
    scanf("%d", &decide);

    for(j = 0 ; j < 7 ; ++j)
    {/*moves selected row to middle row of array*/
        save[0][j] = arr[1][j];
        arr[1][j] = arr[decide][j];
        arr[decide][j] = save[0][j];
    }

    /*this is a horrible method*/
    shuffle[0][0] = arr[0][0];
    shuffle[1][0] = arr[0][1];
    shuffle[2][0] = arr[0][2];
    shuffle[0][1] = arr[0][3];
    shuffle[1][1] = arr[0][4];
    shuffle[2][1] = arr[0][5];
    shuffle[0][2] = arr[0][6];
    shuffle[1][2] = arr[1][0];
    shuffle[2][2] = arr[1][1];
    shuffle[0][3] = arr[1][2];
    shuffle[1][3] = arr[1][3];
    shuffle[2][3] = arr[1][4];
    shuffle[0][4] = arr[1][5];
    shuffle[1][4] = arr[1][6];
    shuffle[2][4] = arr[2][0];
    shuffle[0][5] = arr[2][1];
    shuffle[1][5] = arr[2][2];
    shuffle[2][5] = arr[2][3];
    shuffle[0][6] = arr[2][4];
    shuffle[1][6] = arr[2][5];
    shuffle[2][6] = arr[2][6];

}
</code>```

答:
like this ?</p>

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

#define ROWS 3
#define COLS 7

int main(void){
    int arr[ROWS][COLS] = {
        {1, 2, 3, 4, 5, 6, 7},
        {8, 9, 10, 11, 12, 13, 14},
        {15, 16, 17, 18, 19, 20, 21}
    };
    int result[ROWS][COLS];
    int order[ROWS] = {1, 0, 2};
    int n = sizeof(arr)/sizeof(**arr);//number of elements
    int r = 0, c = 0, i = 0, j = 0;

    while(n--){
        result[r++][c] = arr[order[i]][j++];
        if(r == ROWS){
            r = 0;
            c += 1;
        }
        if(j == COLS){
            j = 0;
            i += 1;
        }
    }
    //check print
    for(r = 0; r < ROWS; ++r){
        for(c = 0; c < COLS; ++c)
            printf("%-2d ", result[r][c]);
        puts("");
    }
}
</code>```

Body:
I want to assign the values in one array to another, but in a different
order. For example the original array would be:

1  2  3  4  5  6  7
8  9  10 11 12 13 14
15 16 17 18 19 20 21

And the desired array is:

8  11 14 3 6  16 19
9  12 1  4 7  17 20
10 13 2  5 15 18 21

How would I do this? In the code below I moved a selected row to the center, then assigned each array individually. I can't figure out a better way.

int main()
{
int decide, i, j, k;
int save[3][7];
int shuffle[3][7];
int arr[3][7] = {
                {1, 2, 3, 4, 5, 6, 7},
                {8, 9, 10, 11, 12, 13, 14},
                {15, 16, 17, 18, 19, 20, 21}
            };

printf("Select a number between 1 and 21\n\n0-GroupA (1 - 7))\n1-GroupB ( 8 - 14)\n2-GroupC (15 - 21)\n\n");

for(k = 0 ; k < 1 ; ++k)
{
    printf("Select which group the number falls into:");
    scanf("%d", &decide);

    for(j = 0 ; j < 7 ; ++j)
    {/*moves selected row to middle row of array*/
        save[0][j] = arr[1][j];
        arr[1][j] = arr[decide][j];
        arr[decide][j] = save[0][j];
    }

    /*this is a horrible method*/
    shuffle[0][0] = arr[0][0];
    shuffle[1][0] = arr[0][1];
    shuffle[2][0] = arr[0][2];
    shuffle[0][1] = arr[0][3];
    shuffle[1][1] = arr[0][4];
    shuffle[2][1] = arr[0][5];
    shuffle[0][2] = arr[0][6];
    shuffle[1][2] = arr[1][0];
    shuffle[2][2] = arr[1][1];
    shuffle[0][3] = arr[1][2];
    shuffle[1][3] = arr[1][3];
    shuffle[2][3] = arr[1][4];
    shuffle[0][4] = arr[1][5];
    shuffle[1][4] = arr[1][6];
    shuffle[2][4] = arr[2][0];
    shuffle[0][5] = arr[2][1];
    shuffle[1][5] = arr[2][2];
    shuffle[2][5] = arr[2][3];
    shuffle[0][6] = arr[2][4];
    shuffle[1][6] = arr[2][5];
    shuffle[2][6] = arr[2][6];

}

Body:
like this ?

#include <stdio.h>

#define ROWS 3
#define COLS 7

int main(void){
    int arr[ROWS][COLS] = {
        {1, 2, 3, 4, 5, 6, 7},
        {8, 9, 10, 11, 12, 13, 14},
        {15, 16, 17, 18, 19, 20, 21}
    };
    int result[ROWS][COLS];
    int order[ROWS] = {1, 0, 2};
    int n = sizeof(arr)/sizeof(**arr);//number of elements
    int r = 0, c = 0, i = 0, j = 0;

    while(n--){
        result[r++][c] = arr[order[i]][j++];
        if(r == ROWS){
            r = 0;
            c += 1;
        }
        if(j == COLS){
            j = 0;
            i += 1;
        }
    }
    //check print
    for(r = 0; r < ROWS; ++r){
        for(c = 0; c < COLS; ++c)
            printf("%-2d ", result[r][c]);
        puts("");
    }
}


问:
How do you increase the length of a line in Adobe After Effects?
How do you increase the length of a line after creating one? I have tried trim paths and stroke, but I don't know how to do it. Please help!</p>

答: You created the line with a path inside a shape layer? You can select one of the points and drag it to the new position. (use the pen tool and you should be able to select either points)</p>


问:
Postgres complicated sql query
Have a bit of a complicated query I am trying to work out.  And I'm not really sure how to query google on it to get some help...

I have a table something like this:

```<code> Date      | period | meter   | value
2017-01-01 |    1   | meter01 | 1.12
2017-01-01 |    2   | meter01 | 2.12
.
.
2017-01-01 |    1   | meter02 | 0.12
2017-01-01 |    2   | meter02 | 7.12
.
.
2017-01-02 |    1   | meter01 | 2.12
2017-01-02 |    2   | meter01 | 4.12
.
.
</code>```

There are 48 periods for any given date.  There could be hundreds of meters for any given date also.

I wish to return a result that looks something like this:

```<code> Date       |  Meter    |  Period 1 | Period 2 | Period 3 | Period 4
2017-01-01  |  meter01  |    1.24   |   2.12
2017-01-01  |  meter02  |    2.24   |   3.12
</code>```

The result would give me the totals for each meter, date and period where the period columns are the sum of all readings for the given meter, period and date.

答:
One method is conditional aggregation:</p>

```<code>select date, meter,
       sum(case when period = 1 then value end) as period_01,
       sum(case when period = 2 then value end) as period_02,
       sum(case when period = 3 then value end) as period_03,
       sum(case when period = 4 then value end) as period_04
from t
group by date, meter
order by date, meter;
</code>```

Title: Postgres complicated sql query

Body:
Have a bit of a complicated query I am trying to work out.  And I'm not really sure how to query google on it to get some help...

I have a table something like this:

 Date      | period | meter   | value
2017-01-01 |    1   | meter01 | 1.12
2017-01-01 |    2   | meter01 | 2.12
.
.
2017-01-01 |    1   | meter02 | 0.12
2017-01-01 |    2   | meter02 | 7.12
.
.
2017-01-02 |    1   | meter01 | 2.12
2017-01-02 |    2   | meter01 | 4.12
.
.

There are 48 periods for any given date.  There could be hundreds of meters for any given date also.

I wish to return a result that looks something like this:

 Date       |  Meter    |  Period 1 | Period 2 | Period 3 | Period 4
2017-01-01  |  meter01  |    1.24   |   2.12
2017-01-01  |  meter02  |    2.24   |   3.12

The result would give me the totals for each meter, date and period where the period columns are the sum of all readings for the given meter, period and date.

Body:
One method is conditional aggregation:

select date, meter,
       sum(case when period = 1 then value end) as period_01,
       sum(case when period = 2 then value end) as period_02,
       sum(case when period = 3 then value end) as period_03,
       sum(case when period = 4 then value end) as period_04
from t
group by date, meter
order by date, meter;