问:
elasticsearch mapping for Friend to Friend list
we have started using elasticsearch in our project, we are storing user data and his friend list as nested object, and nested to nested object storing friend's friend list because we required this data when we are doing global search.
Now we are syncing this data in real time with our database, so is this good to syncing done in real time 50-100 TPS or in future it will create problem.

We need to create complex queries for updating the data because we are managing friend list in 2nd level. so how to create advance scripting in painless, I have checked this in Google but not found anything in detail.

If my approach is wrong of doing this, please let me know.

答:
To answer your first question

so is this good to syncing done in real time 50-100 TPS or in future
  it will create problem

As of version ES6.0, Multi level nesting is automatically supported, and detected, resulting in an inner nested query to automatically match the relevant nesting level (and not root) if it exists within another nested query. But there is a caveat, indexing a document with 100 nested fields actually indexes 101 documents as each nested document is indexed as a separate document. To safeguard against ill-defined mappings the number of nested fields that can be defined per index is usually limited to 50 using the index.mapping.nested_fields.limit . This setting allows you to limit the number of field mappings that can be created manually or dynamically, in order to prevent bad documents from causing a mapping explosion. So to answer your question, this is fine, but as your data grows, it becomes more complicated to manage and you risk the danger of a mapping explosion.

To answer your second question

We need to create complex queries for updating the data because we are
  managing friend list in 2nd level. so how to create advance scripting
  in painless, I have checked this in Google but not found anything in
  detail.

You might need to present some context here to be able to understand why your approach is necessary, but basically, in a social profile context, managing a friends list as you are doing is always a bad idea, especially if you anticipate scaling in the future. It may work for smaller use-cases, but it does not work very well when you scale. This is because, the relationships become more sophisticated and you will end up having too many multi nested objects. As mentioned, all factors kept at a constant, you might want to look at a graph database for this kind of a scenario. You could, however, have other reasons to your approach which is why you might want to enumerate your context so we can better advise.

Hope this helps!!


来源: stackexchange

问:
check whether eth0 is up while my active connection is ppp0
I've my eth0connection and I've a ppp0 connection.

keeping alive my ppp0 connection, can I test eth0 connection?

like checking

```<code>ping <ip> <eth0 connection>
</code>```

答:
Have you tried the following (Copying from different question that uses your issue unix.stackexchange)?:

If you look at ping manual man ping, you can read:

```<code>-I interface address
   Set source address to specified interface address. Argument may be numeric IP
   address or name of device.
</code>```

So try, e.g.:

```<code>ping -I eth0 google.com
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I've my eth0connection and I've a ppp0 connection.

keeping alive my ppp0 connection, can I test eth0 connection?

like checking

ping <ip> <eth0 connection>

Body:
Have you tried the following (Copying from different question that uses your issue unix.stackexchange)?:

If you look at ping manual man ping, you can read:

-I interface address
   Set source address to specified interface address. Argument may be numeric IP
   address or name of device.

So try, e.g.:

ping -I eth0 google.com


问:
Swift 3 better way to write this if-statement
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

```<code>if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
</code>```

It seems a little drawn out and not very efficient.

答:
My answer goes a bit further than your question, however I personally feel this code would help clean up your code the best.

You can group if statements (from the looks of your code) like this:

```<code>let noise = round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows))))
let tileGroup1Array = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5]
let tileGroup2Array = [0.4, 0.3, 0.2, 0.1, 0.0]
let tileGroup3Array = [-0.1, -0.2, -0.3, -0.4, -0.5]
let tileGroup4Array = [-0.6, -0.7, -0.8, -0.9, -1.0]
</code>```

Then you can check:

```<code>if(tileGroup1Array.contains(noise)) { ... } else if(tileGroup2Array.contains(noise){ ... })
</code>```

Body:
I am comparing values in a GKNoise field and then setting tiles into a tileMap based on the level of noise

This if-statement is comparing the values by rounding up to the nearest tenth, is there a better way to write it?

if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -1.0 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.9 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.8 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.7 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.6 {
    tileMap.setTileGroup(tileGroup4, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.5 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.4 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.3 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.2 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == -0.1 {
    tileMap.setTileGroup(tileGroup3, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.0 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.1 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.2 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.3 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.4 {
    tileMap.setTileGroup(tileGroup2, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.5 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.6 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.7 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.8 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 0.9 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}
if round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows)))) == 1.0 {
    tileMap.setTileGroup(tileGroup1, forColumn: columns, row: rows)
}

It seems a little drawn out and not very efficient.

Body:
My answer goes a bit further than your question, however I personally feel this code would help clean up your code the best.

You can group if statements (from the looks of your code) like this:

let noise = round(MasterNoise.value(atPosition: vector_float2(Float(columns),Float(rows))))
let tileGroup1Array = [1.0, 0.9, 0.8, 0.7, 0.6, 0.5]
let tileGroup2Array = [0.4, 0.3, 0.2, 0.1, 0.0]
let tileGroup3Array = [-0.1, -0.2, -0.3, -0.4, -0.5]
let tileGroup4Array = [-0.6, -0.7, -0.8, -0.9, -1.0]

Then you can check:

if(tileGroup1Array.contains(noise)) { ... } else if(tileGroup2Array.contains(noise){ ... })


问:
Remove class on outside click
I would like so that when i click outside and the default text loads the previous clicked class should be removed. So for example if i press " Fair Trade " and it becomes color: red; that should fade away when i press outside and load the default text just as it fades away when i click on another title.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}</code>```

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

答:
Add This  $($imgs).removeClass('clicked')

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
        $($imgs).removeClass('clicked')
    })
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}</code>```

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

```

Title: Remove class on outside click

Body:
I would like so that when i click outside and the default text loads the previous clicked class should be removed. So for example if i press " Fair Trade " and it becomes color: red; that should fade away when i press outside and load the default text just as it fades away when i click on another title.

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
    })
  }
})

.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}

    <nobr>FAIR-TRADE</nobr>

TOXICFREE

QUALITY

ORGANIC

VEGAN

Lorem ipsum

"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

 Tap on the symbols if you want to know more.

Body:
Add This  $($imgs).removeClass('clicked')

var $imgs = $(".section-link");

var data = [{
    title: "Fair Trade",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Toxicfree",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Quality",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Organic",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
  {
    title: "Vegan",
    text: "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat."
  },
];

// Get reference to the output area
var $outputDiv = $(".section-display");
var defaulttext = $outputDiv.find(".text1").html()
var defaultTitle = $outputDiv.find(".title1").html();

$imgs.on("click", function() {

  $This = $(this) ;

  $imgs.removeClass("clicked") ;
  $This.addClass("clicked");

  $(".title1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".title1", $outputDiv).html(data[$This.index() - 1].title)
      .animate({
        opacity: 1
      });
  });
  $(".text1", $outputDiv).animate({
    opacity: 0
  }, function() {
    $(".text1", $outputDiv).html(data[$This.index() - 1].text)
      .animate({
        opacity: 1
      });
  })
});

$(document).on("click", function(e) {
  if ($(e.target).closest('.section-display').length != 1 && $(e.target).closest(".section-link").length != 1) {
    $(".title1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".title1", $outputDiv).html(defaultTitle)
        .animate({
          opacity: 1
        });
    });
    $(".text1", $outputDiv).animate({
      opacity: 0
    }, function() {
      $(".text1", $outputDiv).html(defaulttext)
        .animate({
          opacity: 1
        });
        $($imgs).removeClass('clicked')
    })
  }
})

.section-link {
  width: 100px;

  -webkit-transition: all .5s ease-in-out;
  -moz-transition: all .5s ease-in-out;
  -ms-transition: all .5s ease-in-out;
  -o-transition: all .5s ease-in-out;
  transition: all .5s ease-in-out;
}
.section-link.clicked{
  color: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="section-link small-solid-circle-p4 fair-d">
  <h2>
    <nobr>FAIR-TRADE</nobr>
  </h2>
</div>
<div class="section-link small-solid-circle-p4 toxic-d">
  <h2>TOXICFREE</h2>
</div>
<div class="section-link small-solid-circle-p4 quality-d">
  <h2>QUALITY</h2>
</div>
<div class="section-link small-solid-circle-p4 organic-d">
  <h2>ORGANIC</h2>
</div>
<div class="section-link small-solid-circle-p4 vegan-d">
  <h2>VEGAN</h2>
</div>
<div class="section-display active info-p4">
  <h2 class="title1">Lorem ipsum</h2>
  <h2 class="text1">"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<br>
  <br> Tap on the symbols if you want to know more.</h2>
</div>


问:
OSError: [Errno 8] Exec format error
I am having hard time parsing the arguments to subprocess.Popen.  I am trying to execute a script on my Unix server. The script syntax when running on shell prompt is as follows:
/usr/local/bin/script hostname = <hostname> -p LONGLIST. No matter how I try, the script is not running inside subprocess.Popen

The space before and after "=" is mandatory.

```<code>import subprocess
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname = ', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
</code>```

The above does not work.

And when I use shell=False, I get OSError: [Errno 8] Exec format error

答: I will hijack this thread to point out that this error may also happen when target of Popen is not executable. Learnt it hard way when by accident I have had override a perfectly executable binary file with zip file.</p>

Title: OSError: [Errno 8] Exec format error

Body:
I am having hard time parsing the arguments to subprocess.Popen.  I am trying to execute a script on my Unix server. The script syntax when running on shell prompt is as follows:
/usr/local/bin/script hostname = <hostname> -p LONGLIST. No matter how I try, the script is not running inside subprocess.Popen

The space before and after "=" is mandatory.

import subprocess
Out = subprocess.Popen(['/usr/local/bin/script', 'hostname = ', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

The above does not work.

And when I use shell=False, I get OSError: [Errno 8] Exec format error


问:
I need to install Oracle XE 11g on Debian 8, how?
How can I install Oracle on Debian 8, I try a lot of solution but I had an error on
sudo service procps start

please complete the instructions?

答:
Did you set your prerequisites correctly?
Debian isn't a supported linux distribution to run oracle on, so you can get this working, but you will have to put all your prerequisites manually.</p>


问:
How to generate .net modules using Visual Studio 2008
I am writing a c# class library, where each class need to be compiled into different .net modules instead of as a single assembly. Is there any settings to get this done from VS.NET enviornment?</p>

答:
You could use the "Build events" in VS.NET project properties to generate .net assemblies.
Under "Post build" event specify a batch file containing the following code.</p>

```<code>csc /target:module YourClassName1.cs
csc /target:module YourClassName2.cs
</code>```

ContentLicense: CC BY-SA 2.5

Body:
You could use the "Build events" in VS.NET project properties to generate .net assemblies.
Under "Post build" event specify a batch file containing the following code.

csc /target:module YourClassName1.cs
csc /target:module YourClassName2.cs


问:
Enzyme - How to access and set <input> value?
I'm confused about how to access <input> value when using mount. Here's what I've got as my test:

```<code>  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.render().attr('value'));
    input.simulate('focus');
    done();
  });
</code>```

The console prints out undefined. But if I slightly modify the code, it works:

```<code>  it('cancels changes when user presses esc', done => {
    const wrapper = render(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.val());
    input.simulate('focus');
    done();
  });
</code>```

Except, of course, the input.simulate line fails since I'm using render now. I need both to work properly. How do I fix this?

EDIT:

I should mention, <EditableText /> is not a controlled component. But when I pass defaultValue into <input />, it seems to set the value. The second code block above does print out the value, and likewise if I inspect the input element in Chrome and type $0.value in the console, it shows the expected value.

答: So lots of different opinions here. The only thing that worked for me was none of the above, it was using input.props().value. I hope that helps.

Body:
I'm confused about how to access <input> value when using mount. Here's what I've got as my test:

  it('cancels changes when user presses esc', done => {
    const wrapper = mount(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.render().attr('value'));
    input.simulate('focus');
    done();
  });

The console prints out undefined. But if I slightly modify the code, it works:

  it('cancels changes when user presses esc', done => {
    const wrapper = render(<EditableText defaultValue="Hello" />);
    const input = wrapper.find('input');

    console.log(input.val());
    input.simulate('focus');
    done();
  });

Except, of course, the input.simulate line fails since I'm using render now. I need both to work properly. How do I fix this?

EDIT:

I should mention, <EditableText /> is not a controlled component. But when I pass defaultValue into <input />, it seems to set the value. The second code block above does print out the value, and likewise if I inspect the input element in Chrome and type $0.value in the console, it shows the expected value.


问:
I have a issue with npm proxy
I have a problem with proxy services when i need to install any package i get this error:
```
C:\Users\ihab\Desktop\myApp\myApp>npm install -g npm@latest
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to http://registry.npmjs.org/npm failed, reason: getadd
rinfo ENOTFOUND proxy_host proxy_host:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'</p>

<p>npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ihab\AppData\Roaming\npm-cache_logs\2017-11-15T13_49_08_4
73Z-debug.log</p>

<p>C:\Users\ihab\Desktop\myApp\myApp>npm --registry http://registry.cnpmjs.org info
 underscore
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo
npm ERR! network getaddrinfo ENOTFOUND proxy_host proxy_host:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'</p>

<p>npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ihab\AppData\Roaming\npm-cache_logs\2017-11-15T13_51_14_6
81Z-debug.log
```
any solution for this problem please</p>

答:
If there is any proxy issue ask your network team what proxy url they have set . And then set proxy for npm

windows .

```<code>npm config set proxy http://username:password@url-of-proxy
npm config set https-proxy http://username:password@url-of-proxy
</code>```

Title: I have a issue with npm proxy

Body:
I have a problem with proxy services when i need to install any package i get this error:
```
C:\Users\ihab\Desktop\myApp\myApp>npm install -g npm@latest
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! network request to <a href="http://registry.npmjs.org/npm" rel="nofollow noreferrer">http://registry.npmjs.org/npm</a> failed, reason: getadd
rinfo ENOTFOUND proxy_host proxy_host:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'</p>

<p>npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ihab\AppData\Roaming\npm-cache_logs\2017-11-15T13_49_08_4
73Z-debug.log</p>

<p>C:\Users\ihab\Desktop\myApp\myApp>npm --registry <a href="http://registry.cnpmjs.org" rel="nofollow noreferrer">http://registry.cnpmjs.org</a> info
 underscore
npm ERR! code ENOTFOUND
npm ERR! errno ENOTFOUND
npm ERR! syscall getaddrinfo
npm ERR! network getaddrinfo ENOTFOUND proxy_host proxy_host:80
npm ERR! network This is a problem related to network connectivity.
npm ERR! network In most cases you are behind a proxy or have bad network settin
gs.
npm ERR! network
npm ERR! network If you are behind a proxy, please make sure that the
npm ERR! network 'proxy' config is set properly.  See: 'npm help config'</p>

<p>npm ERR! A complete log of this run can be found in:
npm ERR!     C:\Users\ihab\AppData\Roaming\npm-cache_logs\2017-11-15T13_51_14_6
81Z-debug.log
```
any solution for this problem please

Body:
If there is any proxy issue ask your network team what proxy url they have set . And then set proxy for npm

windows .

npm config set proxy http://username:password@url-of-proxy
npm config set https-proxy http://username:password@url-of-proxy


问:
Fatal error: Call to a member function prepare() on null in php
Trying to connect database and fetch details, but it is showing an error:

Fatal error: Call to a member function prepare() on null

I am trying:

```<code><?php
class Database
{

    private $host = "******";
    private $db_name = "******";
    private $username = "******";
    private $password = "******";
    public $conn;

    public function dbConnection()
    {

        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>
</code>```

The prepare code is defined in class.user.php:

```<code><?php
require_once 'lang.php';
require_once 'dbconfig.php';
class USER
{
    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }
//More codes...
}
?>
</code>```

答:
The error occurred due to connecting MySQL database which does not allow external access!

Sorry commentors for troubling you.

Body:
Trying to connect database and fetch details, but it is showing an error:

Fatal error: Call to a member function prepare() on null

I am trying:

<?php
class Database
{

    private $host = "******";
    private $db_name = "******";
    private $username = "******";
    private $password = "******";
    public $conn;

    public function dbConnection()
    {

        $this->conn = null;
        try
        {
            $this->conn = new PDO("mysql:host=" . $this->host . ";dbname=" . $this->db_name, $this->username, $this->password);
            $this->conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        }
        catch(PDOException $exception)
        {
            echo "Connection error: " . $exception->getMessage();
        }

        return $this->conn;
    }
}
?>

The prepare code is defined in class.user.php:

<?php
require_once 'lang.php';
require_once 'dbconfig.php';
class USER
{
    private $conn;

    public function __construct()
    {
        $database = new Database();
        $db = $database->dbConnection();
        $this->conn = $db;
    }

    public function runQuery($sql)
    {
        $stmt = $this->conn->prepare($sql);
        return $stmt;
    }
//More codes...
}
?>


问:
i need a query which returns 1 column 5 rows and 2nd column 10 rows
here is my query

```<code>SELECT
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno1) where sd.tpbp LIKE ('p%')
      )
,0)A,
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno2) where sd.tpbp LIKE ('p%')
      )
,0)b
</code>```

here first select query return 1 row and 2nd returns multiple rows
and am getting a error like

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

so what should i do to make this query work

答:
You can use this instead

```<code>select
    case when exists(
        select subjectshrt from subject_definition sd  join student_subject ss
        on (sd.sdsrno = ss.sdsrno1) where sd.tpbp LIKE ('p%')
    ) then 1 else 0 end as A,
    case when exists(
        select subjectshrt from subject_definition sd  join student_subject ss
        on (sd.sdsrno = ss.sdsrno2) where sd.tpbp LIKE ('p%')
    ) then 1 else 0 end as B
</code>```

but it would probably be much better to write a select statement with joins and get results as appropriate.

```<code>select case when sh.sdrno = ss.sdrno1 then sd.subjectshrt else 0 end as A, ... -- similar for B
from subject_definition sd
    left join student_subject ss
    on ((sh.sdsrno = ss.sdrno1) or (sh.sdsrno = ss.sdrno2))
where sd.tpbp like 'p%'
</code>```

Checking execution plans for comparison reasons strongly advised.

Body:
here is my query

SELECT
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno1) where sd.tpbp LIKE ('p%')
      )
,0)A,
ISNULL(
     (
     select subjectshrt from subject_definition sd  join student_subject ss
     on(sd.sdsrno =ss.sdsrno2) where sd.tpbp LIKE ('p%')
      )
,0)b

here first select query return 1 row and 2nd returns multiple rows
and am getting a error like

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.

so what should i do to make this query work

Body:
You can use this instead

select
    case when exists(
        select subjectshrt from subject_definition sd  join student_subject ss
        on (sd.sdsrno = ss.sdsrno1) where sd.tpbp LIKE ('p%')
    ) then 1 else 0 end as A,
    case when exists(
        select subjectshrt from subject_definition sd  join student_subject ss
        on (sd.sdsrno = ss.sdsrno2) where sd.tpbp LIKE ('p%')
    ) then 1 else 0 end as B

but it would probably be much better to write a select statement with joins and get results as appropriate.

select case when sh.sdrno = ss.sdrno1 then sd.subjectshrt else 0 end as A, ... -- similar for B
from subject_definition sd
    left join student_subject ss
    on ((sh.sdsrno = ss.sdrno1) or (sh.sdsrno = ss.sdrno2))
where sd.tpbp like 'p%'

Checking execution plans for comparison reasons strongly advised.


问:
Material UI component reference does not work
I am building a little chat application.i have used Material UI TextField to input user message. but i can't refer it. I read about this. they said that they do not support for refs.
this is my code. and it works.

```<code>class App extends Component {
  constructor() {
    super();
    this.state = {
      q: "default"
    };

  }
  handleChanges(val) {
    this.setState({ q: val });
  }
  handleSearch(val) {
    this.setState({ q: val });
    console.log(this.state.q);
  }
  render() {
    return (
      <div className="App">
        <h1>  {this.state.q}</h1>
        <Row className="show-grid">
          <Col sm={2} md={4} className="contact"><h5>contact</h5><br /></Col>
          <Col sm={10} md={8} className="chat grid-border"><h5>chat</h5><br />
            <div className="history"></div>
            <div className="message top-border">

              <input type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }} />
              <MuiThemeProvider>
                <FlatButton label="Primary" primary={true} onTouchTap={(e) => { e.preventDefault(); this.handleSearch(this.refs.question.value); }} />
              </MuiThemeProvider>

            </div>
          </Col>
        </Row>{/*show-grid ends here*/}
      </div>
    );
  }
}
export default App;
</code>```

If i used this material UI TextField instead of native HTML input tag it does not get the value from the reference.

```<code><MuiThemeProvider>
       <TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>
</MuiThemeProvider>
</code>```

Is there any workaround or alternative UI library for this ?

答:
You can also use inputRef. This prop is available from material 1.0.

```<code><TextField
   className={classes.textField}
   inputRef={input => (this._my_field = input)}
   label="My field"
   fullWidth
   margin="normal"
   defaultValue={this.props.my_field}
   onChange={this.handleChange("dhis_password")}
/>
</code>```

The on change let’s you update the state when it changes, but if you need to get the value unchanged, then the inputRef is necessary.

Also have a look at You can see this How to get password field value in react's material-ui

Body:
I am building a little chat application.i have used Material UI TextField to input user message. but i can't refer it. I read about this. they said that they do not support for refs.
this is my code. and it works.

class App extends Component {
  constructor() {
    super();
    this.state = {
      q: "default"
    };

  }
  handleChanges(val) {
    this.setState({ q: val });
  }
  handleSearch(val) {
    this.setState({ q: val });
    console.log(this.state.q);
  }
  render() {
    return (

  {this.state.q}

        <Row className="show-grid">
          <Col sm={2} md={4} className="contact">
contact

</Col>
          <Col sm={10} md={8} className="chat grid-border">
chat

              <input type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }} />
              <MuiThemeProvider>
                <FlatButton label="Primary" primary={true} onTouchTap={(e) => { e.preventDefault(); this.handleSearch(this.refs.question.value); }} />
              </MuiThemeProvider>

          </Col>
        </Row>{/*show-grid ends here*/}

    );
  }
}
export default App;

If i used this material UI TextField instead of native HTML input tag it does not get the value from the reference.

<MuiThemeProvider>
       <TextField hintText="Ask your question" fullWidth={true} multiLine={true} rows={2} rowsMax={4} type="text" ref="question" onChange={(e) => { this.handleChanges(this.refs.question.value) }}/>
</MuiThemeProvider>

Is there any workaround or alternative UI library for this ?

Body:
You can also use inputRef. This prop is available from material 1.0.

<TextField
   className={classes.textField}
   inputRef={input => (this._my_field = input)}
   label="My field"
   fullWidth
   margin="normal"
   defaultValue={this.props.my_field}
   onChange={this.handleChange("dhis_password")}
/>

The on change let’s you update the state when it changes, but if you need to get the value unchanged, then the inputRef is necessary.

Also have a look at You can see this How to get password field value in react's material-ui


问:
What is this method doing? (Arrays and random numbers)
My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.

I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.

```<code>int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}

 //This is my code
 public static void main(String[] args) {
    int []a = arrayHist ();
    printArray (a);
}

public static int randomInt (int low, int high) {
    int range = (high - low) +1;
    return (int) (Math.random() * range) + low;

}

public static int[] randomIntArray (int x) {
    int[] random = new int[x];
    for (int i = 0; i< x; i++) {
        random [i] = randomInt (-5, 15);

    }
    return random;
}

public static int[] arrayHist () {
    int[] counts = new int [30];
    int[] hist = randomIntArray (30);
    for (int i = 0; i < 10 && i >= 0; i++) {
        int index = hist[i];
        counts[index]++;
    }
    return hist;
}

public static void printArray (int[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println (a[i]);
    }
}
</code>```

I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?

答:
I'll put some comments in your code, and see if you can spot where it goes wrong:

```<code>//take a histogram of the array. We're only going to count values between 0 and 10
//so 25th to 75 centiles, ignoring values that are lower than 0 or higher than 10
public static int[] arrayHist () {

  //need to make an array of 11 numbers for the counts
  int[] counts = new int [30];

  //get an array of 30 random numbers
  int[] hist = randomIntArray (30);

  //loop over the whole array of 30 numbers
  for (int i = 0; i < 10 && i >= 0; i++) {
    //retrieve the random number into a variable temporarily
    int index = hist[i];

    //if the value is too low or too high, skip it

    //else, store it in the counts array - the value from the random array
    //serves as the index position in the counts array
    counts[index]++;
  }

  //return the counts array
  return hist;
}
</code>```

What I've done with my comments is equivalent to designing the algorithm using the language you think in (English) and then you can translate it into the language you're learning (java). Very few developers think in the programming language they write. As a student I recommend you should ALWAYS write comments to explain your algorithm to yourself before you write code underneath the comments. You get points for writing comments (usually) so if you write them first then a) it helps you write the code and b) you don't have the tedious job of writing comments after you get the code working

Please please, for your own good/learning, try working out what is wrong from the above before looking at the spoilers(answers) below. Roll the mouse over the box to display the spoilers

 ```<code> //loop over the whole array of 30 numbers - YOU ONLY LOOP 10
 for (int i = 0; i < 10 && i >= 0; i++) {
   //if the value is too low or too high, skip it - YOU DIDN'T DO THIS CHECK
   ...
 }
 //return the counts array - YOU RETURNED THE WRONG ARRAY
 return hist;</code>```

Edits in response to comments:

Checking a range

You'll have to check two limits, and hence it will need to be of one of the following forms:

```<code>if(x < 0 || x > 10) then don't do the count

if(!(x >= 0 && x <= 10)) then don't do the count

if(x >= 0 && x <= 10) then do the count

if(!(x < 0 || x > 10)) then do the count
</code>```

Tests that use NOT - the exclamation mark ! - are typically a bit harder to read and understand, so try to avoid them is possible. Tests that are "positive minded" - i.e. they return a positive result rather than a negative that needs to be negated - are easier to read and understand.

A helpful tip for loops and methods, in terms of error checking, is to test for bad values that meet certain conditions, and if a bad value is encountered, then skip processing the rest of the loop (using the continue) keyword, or skip the rest of the method (by returning from it)

Doing this means that your if body (the bit between { and  } ) doesnt get massive. Compare:

```<code>for(...){
  if(test for bad values)
    continue;

  //50 lines long loop body
}
</code>```

Is neater than doing:

```<code>for(...){
  if(test for goodvalues){
    //50 lines long loop body
  }
}
</code>```

If you use the bottom pattern, you can end up after several IFs in a real indented mess, with { and } all over the place and your code is way over to the right hand side of the screen:

```<code>    for(...){
        //code
        if(...){
            //code
            if(...){
                //code
                if(...){
                    //code
                    if(...){
                        //code
                        if(...){
                            //code
                            if(...){
                                //code
                            }
                            //code
                        }
                        //code
                    }
                    //code
                }
                //code
            }
            //code
        }
        //code
    }
</code>```

Keeping indent levels to a minimum helps make your code more readable

Hence, I recommend in your case, that rather than test for the value being inside the range 0 to 10 and doing something with it, you adopt the form "if value is OUTSIDE" the range 0 to 10, skip doing the rest of the loop

Body:
My textbook gave me this code to help count the amount of times a certain number shows up in an array of integers. I tried to apply the code my textbook gave me to my assignment but it doesn't seem to be working. Basically, I have to generate 30 random integers in an array, with the upper bound being 15 and lower bond being -5.

I want to find out how many times a number in the array is equal to 0, 1, 2... all the way until 10. The first code is the one my textbook gave me. They also used a random number generator but instead of finding how many elements is equal to 0, 1, etc, they want to find how many times each number appears. (The scores array is simply the random number generator, and their upper bound is 100). The second code is mine.

int[] counts = new int [100];
for (int i = 0; i < scores.length; i++) {
int index = scores[i];
counts[index]++;
}

 //This is my code
 public static void main(String[] args) {
    int []a = arrayHist ();
    printArray (a);
}

public static int randomInt (int low, int high) {
    int range = (high - low) +1;
    return (int) (Math.random() * range) + low;

}

public static int[] randomIntArray (int x) {
    int[] random = new int[x];
    for (int i = 0; i< x; i++) {
        random [i] = randomInt (-5, 15);

    }
    return random;
}

public static int[] arrayHist () {
    int[] counts = new int [30];
    int[] hist = randomIntArray (30);
    for (int i = 0; i < 10 && i >= 0; i++) {
        int index = hist[i];
        counts[index]++;
    }
    return hist;
}

public static void printArray (int[] a) {
    for (int i = 0; i < a.length; i++) {
        System.out.println (a[i]);
    }
}

I'm supposed to be getting only 11 elements, but instead I get 30 random numbers again. Why is that?

Body:
I'll put some comments in your code, and see if you can spot where it goes wrong:

//take a histogram of the array. We're only going to count values between 0 and 10
//so 25th to 75 centiles, ignoring values that are lower than 0 or higher than 10
public static int[] arrayHist () {

  //need to make an array of 11 numbers for the counts
  int[] counts = new int [30];

  //get an array of 30 random numbers
  int[] hist = randomIntArray (30);

  //loop over the whole array of 30 numbers
  for (int i = 0; i < 10 && i >= 0; i++) {
    //retrieve the random number into a variable temporarily
    int index = hist[i];

    //if the value is too low or too high, skip it

    //else, store it in the counts array - the value from the random array
    //serves as the index position in the counts array
    counts[index]++;
  }

  //return the counts array
  return hist;
}

What I've done with my comments is equivalent to designing the algorithm using the language you think in (English) and then you can translate it into the language you're learning (java). Very few developers think in the programming language they write. As a student I recommend you should ALWAYS write comments to explain your algorithm to yourself before you write code underneath the comments. You get points for writing comments (usually) so if you write them first then a) it helps you write the code and b) you don't have the tedious job of writing comments after you get the code working

Please please, for your own good/learning, try working out what is wrong from the above before looking at the spoilers(answers) below. Roll the mouse over the box to display the spoilers

 //loop over the whole array of 30 numbers - YOU ONLY LOOP 10
 for (int i = 0; i < 10 && i >= 0; i++) {
   //if the value is too low or too high, skip it - YOU DIDN'T DO THIS CHECK
   ...
 }
 //return the counts array - YOU RETURNED THE WRONG ARRAY
 return hist;

Edits in response to comments:

Checking a range

You'll have to check two limits, and hence it will need to be of one of the following forms:

if(x < 0 || x > 10) then don't do the count

if(!(x >= 0 && x <= 10)) then don't do the count

if(x >= 0 && x <= 10) then do the count

if(!(x < 0 || x > 10)) then do the count

Tests that use NOT - the exclamation mark ! - are typically a bit harder to read and understand, so try to avoid them is possible. Tests that are "positive minded" - i.e. they return a positive result rather than a negative that needs to be negated - are easier to read and understand.

A helpful tip for loops and methods, in terms of error checking, is to test for bad values that meet certain conditions, and if a bad value is encountered, then skip processing the rest of the loop (using the continue) keyword, or skip the rest of the method (by returning from it)

Doing this means that your if body (the bit between { and  } ) doesnt get massive. Compare:

for(...){
  if(test for bad values)
    continue;

  //50 lines long loop body
}

Is neater than doing:

for(...){
  if(test for goodvalues){
    //50 lines long loop body
  }
}

If you use the bottom pattern, you can end up after several IFs in a real indented mess, with { and } all over the place and your code is way over to the right hand side of the screen:

    for(...){
        //code
        if(...){
            //code
            if(...){
                //code
                if(...){
                    //code
                    if(...){
                        //code
                        if(...){
                            //code
                            if(...){
                                //code
                            }
                            //code
                        }
                        //code
                    }
                    //code
                }
                //code
            }
            //code
        }
        //code
    }

Keeping indent levels to a minimum helps make your code more readable

Hence, I recommend in your case, that rather than test for the value being inside the range 0 to 10 and doing something with it, you adopt the form "if value is OUTSIDE" the range 0 to 10, skip doing the rest of the loop


问:
Include c++ header in all cpp files from cmake
Is there any way to include a header (.hpp) in all cpp files from a project (automatic)?

The project is compiled using cmake.

答: You can use pre-compiled headers to that. Cross-compile implementation of that for CMake is not very easy, so, I recommend 3rd party module for that, for example CMakePCHCompiler</p>


问:
DialogFlow (API.AI) REST with php
I work on DialogFlow recently and I need to send a POST to my own web services.
It's a Rest services work with Symfony et PHP.

So I tried something and it didn't work.
In the tutorial it worked with Google Cloud, but I don't want to work with it.

I changed the URL of Webhook with my own. I didn't change anything else in DialogFlow because it was good with google. There it is :

```<code>/**
 * @Rest\View()
 * @Rest\Post("/testDialogBot")
 */
public function testDialogBotAction( Request $request )
{
    $re = "Test reponse";
    $response = new Response(json_encode( array( "speech" => $re, "displayText" => $re )));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

}
</code>```

The JSON of DialogFlow return :

```<code>"status": {
  "code": 206,
  "errorType": "partial_content",
  "errorDetails": "Webhook call failed. Error: Request timeout."
},
</code>```

I'm sure it can work, I do something bad probably.

Thank's for help.

答: Ok that's fine, you don't need every parameters. My URL was wrong and It seems that DialogFlow doesn't accept https but only http.</p>

Title: DialogFlow (API.AI) REST with php

Body:
I work on DialogFlow recently and I need to send a POST to my own web services.
It's a Rest services work with Symfony et PHP.

So I tried something and it didn't work.
In the tutorial it worked with Google Cloud, but I don't want to work with it.

I changed the URL of Webhook with my own. I didn't change anything else in DialogFlow because it was good with google. There it is :

/**
 * @Rest\View()
 * @Rest\Post("/testDialogBot")
 */
public function testDialogBotAction( Request $request )
{
    $re = "Test reponse";
    $response = new Response(json_encode( array( "speech" => $re, "displayText" => $re )));
    $response->headers->set('Content-Type', 'application/json');
    return $response;

}

The JSON of DialogFlow return :

"status": {
  "code": 206,
  "errorType": "partial_content",
  "errorDetails": "Webhook call failed. Error: Request timeout."
},

I'm sure it can work, I do something bad probably.

Thank's for help.


问:
SQL Selecting max date by year for 3 unique IDs
I've got a list like this where I need to get the max date per year for each combination of unique IDs.

```<code>Calculated-Date|ID_A | ID_B | ID_C
   2017/11/5   |  AB |  A   |  C
   2017/10/5   |  AB |  A   |  C
   2016/10/5   |  AB |  A   |  C
   2017/10/5   |  AB |  C   |  C
   2016/10/5   |  AB |  C   |  C
   2016/10/30  |  AB |  C   |  C
   2015/10/5   |  AB |  C   |  C
</code>```

What I would like to get is this

```<code>    Calculated-Date|ID_A | ID_B | ID_C
       2017/11/5   |  AB |  A   |  C
       2016/10/5   |  AB |  A   |  C
       2017/10/5   |  AB |  C   |  C
       2016/10/30  |  AB |  C   |  C
       2015/10/5   |  AB |  C   |  C
</code>```

I've tried a variation of subqueries but I am fairly new to SQL and is truly stuck at the moment. Any help is much appreciated!

I've tried this:

```<code>select distinct max(Calculated-Date), ID_A, ID_B, ID_C
    from TABLE_1
    group by Calculated-Date, ID_A, ID_B, ID_C
order by ID_A, ID_B, ID_C
</code>```

答:
You Can Try</p>

```<code>SELECT * FROM TableName ORDER BY Calculated-Date DESC
</code>```

Body:
I've got a list like this where I need to get the max date per year for each combination of unique IDs.

Calculated-Date|ID_A | ID_B | ID_C
   2017/11/5   |  AB |  A   |  C
   2017/10/5   |  AB |  A   |  C
   2016/10/5   |  AB |  A   |  C
   2017/10/5   |  AB |  C   |  C
   2016/10/5   |  AB |  C   |  C
   2016/10/30  |  AB |  C   |  C
   2015/10/5   |  AB |  C   |  C

What I would like to get is this

    Calculated-Date|ID_A | ID_B | ID_C
       2017/11/5   |  AB |  A   |  C
       2016/10/5   |  AB |  A   |  C
       2017/10/5   |  AB |  C   |  C
       2016/10/30  |  AB |  C   |  C
       2015/10/5   |  AB |  C   |  C

I've tried a variation of subqueries but I am fairly new to SQL and is truly stuck at the moment. Any help is much appreciated!

I've tried this:

select distinct max(Calculated-Date), ID_A, ID_B, ID_C
    from TABLE_1
    group by Calculated-Date, ID_A, ID_B, ID_C
order by ID_A, ID_B, ID_C

Body:
You Can Try

SELECT * FROM TableName ORDER BY Calculated-Date DESC


问:
Create a mailto link with Razor
I have a view with a model that has an email address.  How do I create an anchor? to allow the user to simply click on it an open Outlook?  I could create an anchor manually but then how do I include the email address?</p>

```<code><a href="mailto:" + Model.CreatorEmail >Email</a>
</code>```

答:
Just use the @ syntax</p>

```<code><a href="mailto:@(Model.CreatorEmail)">Email</a>
</code>```

Title: Create a mailto link with Razor

Body:
I have a view with a model that has an email address.  How do I create an anchor? to allow the user to simply click on it an open Outlook?  I could create an anchor manually but then how do I include the email address?

Email

Body:
Just use the @ syntax

<a href="mailto:@(Model.CreatorEmail)">Email</a>


答:
```<code>Select * from
(
   Select id_a, id_b, id_c, calculateddate,
          row_number() over ( partition by id_a,id_b,id_c,
              year(calculateddate) order by calculateddate desc) r
From table
) x
Where r=1
</code>```

Title: SQL Selecting max date by year for 3 unique IDs


问:
Visual studio 2015 c++ project error c++11 standard
I have a problem with my project when I'm going to compile it. I use visual studio 2015 and the code where the error appears is :

```<code>template <typename AtomicElement>
class Granule {
public:

typedef spare::Sequence<AtomicElement> RepresentantType;

unsigned int            SymbolID;    // identifier of the symbol
unsigned int                Occurrences; // occurrences of the symbol
spare::RealType                 CompCost;    // compactness cost
spare::RealType                 Cost;        // total cost
spare::RealType                 CardCost;    // cardinality/size cost
spare::RealType             Part;        // index of partition of the symbol
spare::RealType             Clust;       // index of the cluster of the symbol
spare::RealType                 CardClust;   // cardinality of the cluster of the symbol
std::vector<spare::RealType>    ThetaVec;    // vector for theta values

    /*
     * Default constructor
     */
    Granule() {}

    /*
     * Constructor prototype
     */
    Granule(typename spare::Sequence<AtomicElement>& rPrototype,
           spare::RealType  aRecogThreshold,
           spare::RealType  aClusterQuality) {

        if (rPrototype.size()==0) {
            throw std::logic_error("Empty prototype.");
        }

        if ((aRecogThreshold < 0) || (aRecogThreshold > 1)) {
            throw std::logic_error("Invalid DistThreshold.");
        }

        if ((aClusterQuality < 0) || (aClusterQuality > 1)) {
            throw std::logic_error("Invalid ClusterQuality.");
        }

        // Initialization
        mPrototype= rPrototype;
        mRecogThreshold= aRecogThreshold;
        mClusterQuality= aClusterQuality;
    }

    /*
     * Constructor with prototype defined through iterator
     */
    Granule(typename spare::Sequence<AtomicElement>::const_iterator iBegin,
            typename spare::Sequence<AtomicElement>::const_iterator iEnd,
            GdsReal aTheta,
            GdsReal aBeta) {

        if (iBegin >= iEnd) {
            throw std::logic_error("Invalid iterators.");
        }

        if ((aTheta < 0) || (aTheta > 1)) {
            throw std::logic_error("Invalid Theta.");
        }

        if ((aBeta < 0) || (aBeta > 1)) {
            throw std::logic_error("Invalid Beta.");
        }

        // Assign
        mPrototype.assign(iBegin, iEnd);
        mRecogThreshold= aTheta;
        mClusterQuality= aBeta;
    }

    // Prototype definition through iterators
    typename spare::Sequence<AtomicElement>::const_iterator begin() const { return mPrototype.begin(); }

    typename spare::Sequence<AtomicElement>::const_iterator end() const   { return mPrototype.end(); }

    // Prototype size
    typename spare::Sequence<AtomicElement>::size_type  size () const { return mPrototype.size(); }

    // Access to Prototype
    const typename spare::Sequence<AtomicElement>&  Prototype() const       { return mPrototype; }
    // Access to Prototype
    typename spare::Sequence<AtomicElement>&  Prototype()           { return mPrototype; }

    // Access to RecogThreshold
    const spare::RealType&   RecogThreshold() const { return mRecogThreshold; }

    // Access to ClusterQuality
    const spare::RealType&   ClusterQuality() const { return mClusterQuality; }
    // Access to RecogThreshold
    spare::RealType&         RecogThreshold()        { return mRecogThreshold; }

    // Access to ClusterQuality
    spare::RealType&         ClusterQuality()        { return mClusterQuality; }

private:

    // Structure that represents the symbol
    typename spare::Sequence<AtomicElement> mPrototype;

    // Recognition threshold
    spare::RealType                         mRecogThreshold;

    // Symbol quality
    spare::RealType                         mClusterQuality; };

   // Symbols ordering criteria
  template <class StructureType>
  inline bool operator<(const StructureType& S1, const StructureType& S2) {
            return (S1.ClusterQuality() > S2.ClusterQuality());
  }
</code>```

When I compile the error is :

```<code>error C2039: 'ClusterQuality': is not a member of 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Granule<std::vector<spare::RealType,std::allocator<T>>>>>>'
</code>```

But if I compile the same project on Dev c++ and use the flag c++11 I don't have this error.

How can I solve this problem? I have to use visual studio.

答:
You problem is that your operator< is global and too broad. I assume somewhere yo have code that iterates over an vector and compare elements.

```<code>template <class StructureType>
inline bool operator<(const Granule<StructureType>& S1, const Granule<StructureType>& S2) {
    return (S1.ClusterQuality() > S2.ClusterQuality());
}
</code>```

or similar.

I could reproduce it here https://godbolt.org/g/3AR6kd. I just added

```<code>int main()
{
    std::vector<int> t2;

    if (t2.end() < t2.begin())
    {
    }

    return 0;
}
</code>```

Body:
I have a problem with my project when I'm going to compile it. I use visual studio 2015 and the code where the error appears is :

template <typename AtomicElement>
class Granule {
public:

typedef spare::Sequence<AtomicElement> RepresentantType;

unsigned int            SymbolID;    // identifier of the symbol
unsigned int                Occurrences; // occurrences of the symbol
spare::RealType                 CompCost;    // compactness cost
spare::RealType                 Cost;        // total cost
spare::RealType                 CardCost;    // cardinality/size cost
spare::RealType             Part;        // index of partition of the symbol
spare::RealType             Clust;       // index of the cluster of the symbol
spare::RealType                 CardClust;   // cardinality of the cluster of the symbol
std::vector<spare::RealType>    ThetaVec;    // vector for theta values

    /*
     * Default constructor
     */
    Granule() {}

    /*
     * Constructor prototype
     */
    Granule(typename spare::Sequence<AtomicElement>& rPrototype,
           spare::RealType  aRecogThreshold,
           spare::RealType  aClusterQuality) {

        if (rPrototype.size()==0) {
            throw std::logic_error("Empty prototype.");
        }

        if ((aRecogThreshold < 0) || (aRecogThreshold > 1)) {
            throw std::logic_error("Invalid DistThreshold.");
        }

        if ((aClusterQuality < 0) || (aClusterQuality > 1)) {
            throw std::logic_error("Invalid ClusterQuality.");
        }

        // Initialization
        mPrototype= rPrototype;
        mRecogThreshold= aRecogThreshold;
        mClusterQuality= aClusterQuality;
    }

    /*
     * Constructor with prototype defined through iterator
     */
    Granule(typename spare::Sequence<AtomicElement>::const_iterator iBegin,
            typename spare::Sequence<AtomicElement>::const_iterator iEnd,
            GdsReal aTheta,
            GdsReal aBeta) {

        if (iBegin >= iEnd) {
            throw std::logic_error("Invalid iterators.");
        }

        if ((aTheta < 0) || (aTheta > 1)) {
            throw std::logic_error("Invalid Theta.");
        }

        if ((aBeta < 0) || (aBeta > 1)) {
            throw std::logic_error("Invalid Beta.");
        }

        // Assign
        mPrototype.assign(iBegin, iEnd);
        mRecogThreshold= aTheta;
        mClusterQuality= aBeta;
    }

    // Prototype definition through iterators
    typename spare::Sequence<AtomicElement>::const_iterator begin() const { return mPrototype.begin(); }

    typename spare::Sequence<AtomicElement>::const_iterator end() const   { return mPrototype.end(); }

    // Prototype size
    typename spare::Sequence<AtomicElement>::size_type  size () const { return mPrototype.size(); }

    // Access to Prototype
    const typename spare::Sequence<AtomicElement>&  Prototype() const       { return mPrototype; }
    // Access to Prototype
    typename spare::Sequence<AtomicElement>&  Prototype()           { return mPrototype; }

    // Access to RecogThreshold
    const spare::RealType&   RecogThreshold() const { return mRecogThreshold; }

    // Access to ClusterQuality
    const spare::RealType&   ClusterQuality() const { return mClusterQuality; }
    // Access to RecogThreshold
    spare::RealType&         RecogThreshold()        { return mRecogThreshold; }

    // Access to ClusterQuality
    spare::RealType&         ClusterQuality()        { return mClusterQuality; }

private:

    // Structure that represents the symbol
    typename spare::Sequence<AtomicElement> mPrototype;

    // Recognition threshold
    spare::RealType                         mRecogThreshold;

    // Symbol quality
    spare::RealType                         mClusterQuality; };

   // Symbols ordering criteria
  template <class StructureType>
  inline bool operator<(const StructureType& S1, const StructureType& S2) {
            return (S1.ClusterQuality() > S2.ClusterQuality());
  }

When I compile the error is :

error C2039: 'ClusterQuality': is not a member of 'std::_Vector_iterator<std::_Vector_val<std::_Simple_types<Granule<std::vector<spare::RealType,std::allocator<T>>>>>>'

But if I compile the same project on Dev c++ and use the flag c++11 I don't have this error.

How can I solve this problem? I have to use visual studio.

Body:
You problem is that your operator< is global and too broad. I assume somewhere yo have code that iterates over an vector and compare elements.

template <class StructureType>
inline bool operator<(const Granule<StructureType>& S1, const Granule<StructureType>& S2) {
    return (S1.ClusterQuality() > S2.ClusterQuality());
}

or similar.

I could reproduce it here https://godbolt.org/g/3AR6kd. I just added

int main()
{
    std::vector<int> t2;

    if (t2.end() < t2.begin())
    {
    }

    return 0;
}


问:
Test the size of a text on a button with getTextSize()
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

```<code><Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />
</code>```

The test:

```<code>buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );
</code>```

How I should do to recive the ral value of the text size?

答:
```<code>     float oldSize=buttoneql.getTextSize();
</code>```

text size in float

```<code>    Log.d("size in float",""+oldSize);
    float dp= getResources().getDisplayMetrics().scaledDensity;
</code>```

float value of scale density

```<code>    float newSize=oldSize/dp;
</code>```

textsize in sp = new size

```<code>    Log.d("newSize in sp-->",""+newSize);
</code>```

compare float value of text size and new size

```<code>    if(48.0==newSize){
        Log.d("equal size-->","true");
    }
    else{
        Log.d("equal size-->","false");
    }
</code>```

Body:
I need to check if the text size on a button have the size 37sp.
I found a method to get the size with: .getTextSize(), but the size with I receive is: 126.0,  and not 48sp.
The code off button:

<Button
    android:id="@+id/buttoneql"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="="
    android:textColor="@android:color/black"
    android:textSize="48sp" />

The test:

buttoneql = (Button) currentActivity.findViewById(R.id.buttoneql);
assertEquals( 48.0f, buttoneql.getTextSize() );

How I should do to recive the ral value of the text size?

Body:
     float oldSize=buttoneql.getTextSize();

text size in float

    Log.d("size in float",""+oldSize);
    float dp= getResources().getDisplayMetrics().scaledDensity;

float value of scale density

    float newSize=oldSize/dp;

textsize in sp = new size

    Log.d("newSize in sp-->",""+newSize);

compare float value of text size and new size

    if(48.0==newSize){
        Log.d("equal size-->","true");
    }
    else{
        Log.d("equal size-->","false");
    }


问:
Boxing..do I get it right?

Possible Duplicate:

  What is boxing and unboxing and what are the trade offs?

Hi,
From my understanding:
When I assign data of value type to (reference) type object variable, it gets boxed and the result is not actual reference as it points to copy of the value stored on the heap. Is that right?
Thanks

答:
This might help you</p>

```<code>int i = 1;
object o = i;   // boxing on the heap
int j = (int) o;    // unboxing to the stack
</code>```

Title: Boxing..do I get it right?

Body:
This might help you

int i = 1;
object o = i;   // boxing on the heap
int j = (int) o;    // unboxing to the stack


问:
Saving large map in GenServer, is this a valid use case?
Could this be a valid use for GenServer:

If the process_id is the user_id and it is unique. Process contains a query result of a big map of data which is generated via DB. Now if 100's of users log in to the system and ask for their data map they all are saved in their own process referenced by the user_id which is unique

So upon asking for the map I will check to see if there is a process with user_id ( which is process id ) and grab it and feed it to back to the user, if not then I create it and put it in a new state

now if user updated his map, at the update, I make sure to update the sate or create a new one.

Thank you for your guidance

答:
This is perfectly valid unless you have a million users logged in. This is usually handled in Erlang ecosystem with so-called pools.

The main principle is: you limit the size of the pool of processes to, say, 100 (5000, whatever, it mostly depends on your HW capacity) and use any preemptive storage for newcomers (the oldest dies if the capacity is over the limit.)

You might consider serializing these displaced data, or spawn new nodes, or whatever. In general, the process holding the state is the preferable solution in OTP, unless you hit the memory limit. In this case you’d probably opt-in for some persistent storage, like DETS or (better) mnesia.

It worth noting that Elixir provides Agent module for this purpose, but I never use it because plain old good GenServer is IMHO a cleaner concept.


问:
Bash - Adding titles into to a piped table command
I have a simple script to output the content of the file students.txt as a basic table to the print file, which is then displayed.

```<code>#!/bin/bash

cat students.txt | column -t -s',' | sort -u -k3 > print.txt
cat print.txt
</code>```

The output looks like as follows:

```<code>Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200
</code>```

and so on. However I also want to be able to add headings for each column and have them align perfectly, as well as not being sorted. I have tried to use printf and echo but when piped into the command they do not display and I cannot align the columns correctly by printing the heading names outside of the pipe. The desired output I am looking for would look like this:

```<code>Family Name  Initials  Interviewer Initials  Interview Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200
</code>```

How could I achieve this?

答:
May be you can try a simple echo

```<code>cat students.txt | column -t -s',' | sort -u -k3 > print.txt
echo 'Family Name  Initials  Interviewer Initials  Interview Time' && cat print.txt
</code>```

If you need them to be aligned based on your headings then you can use column

```<code>column -t <<< "Family_Name  Initials  Interviewer_Initials  Interview_Time
Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200
"
Family_Name  Initials  Interviewer_Initials  Interview_Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200
</code>```

Note: spaces in column header is not allowed, else it would be treated as separate columns

Body:
I have a simple script to output the content of the file students.txt as a basic table to the print file, which is then displayed.

#!/bin/bash

cat students.txt | column -t -s',' | sort -u -k3 > print.txt
cat print.txt

The output looks like as follows:

Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200

and so on. However I also want to be able to add headings for each column and have them align perfectly, as well as not being sorted. I have tried to use printf and echo but when piped into the command they do not display and I cannot align the columns correctly by printing the heading names outside of the pipe. The desired output I am looking for would look like this:

Family Name  Initials  Interviewer Initials  Interview Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200

How could I achieve this?

Body:
May be you can try a simple echo

cat students.txt | column -t -s',' | sort -u -k3 > print.txt
echo 'Family Name  Initials  Interviewer Initials  Interview Time' && cat print.txt

If you need them to be aligned based on your headings then you can use column

column -t <<< "Family_Name  Initials  Interviewer_Initials  Interview_Time
Consoling  ST  DWC  0900
Scribing   RA  DWC  1000
Gloater    AU  DWC  1100
Crimp      DI  DWC  1200
"
Family_Name  Initials  Interviewer_Initials  Interview_Time
Consoling    ST        DWC                   0900
Scribing     RA        DWC                   1000
Gloater      AU        DWC                   1100
Crimp        DI        DWC                   1200

Note: spaces in column header is not allowed, else it would be treated as separate columns


问:
Illegal string offset 'url'
I am getting this error (Illegal string offset 'url') on 2 webpages of my website.  I am currently on windows plesk hosting of Godaddy. I don't understand much of PHP.

Here is my code, i am getting error in a line.

Here is the code of that line
////

```<code>  .'<img src="'.get_field('image')['url'].'" alt="user-image" />'
</code>```

///

Apologies for the edit.

答:
May be get_field is a function, in that case it must be...

```<code>.'<img src="'.get_field ( $image ) .'" alt="user-image" />'
</code>```

since the parameters of a function must be enclosed by "( )"

Title: Illegal string offset 'url'

Body:
I am getting this error (Illegal string offset 'url') on 2 webpages of my website.  I am currently on windows plesk hosting of Godaddy. I don't understand much of PHP.

Here is my code, i am getting error in a line.

Here is the code of that line
////

  .''

///

Apologies for the edit.

Body:
May be get_field is a function, in that case it must be...

.'<img src="'.get_field ( $image ) .'" alt="user-image" />'

since the parameters of a function must be enclosed by "( )"


问:
How can I format a number into a currency value without php?
I have a value in my mySQL database 13148.70. I want to convert it into a currency format:

```<code>$data = $db->query('SELECT *, ROUND((price), 2) AS price FROM data')->fetchAll(PDO::FETCH_ASSOC);
</code>```

The result is:

```<code>13148.70
</code>```

But I would need 13 148,70 €

答:
Please refer the https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format</p>

```<code>select REPLACE(CONCAT(FORMAT(price,2,'de_DE')," €"),"."," ") from data;
</code>```

Body:
I have a value in my mySQL database 13148.70. I want to convert it into a currency format:

$data = $db->query('SELECT *, ROUND((price), 2) AS price FROM data')->fetchAll(PDO::FETCH_ASSOC);

The result is:

13148.70

But I would need 13 148,70 €

Body:
Please refer the https://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_format

select REPLACE(CONCAT(FORMAT(price,2,'de_DE')," €"),"."," ") from data;


答:
You put the header Family Name, Initials, Interviewer Initials, Interview Time before the contents of students.txt before sending it to the column comand, and I think that should do the trick.

Perhaps something like:

```<code>TEMP=$(mktemp)
TEMP2=$(mktemp)
cat students.txt | sort -u -k3 > $TEMP
echo Family Name, Initials, Interviewer Initials, Interview Time > $TEMP2
cat $TEMP >> $TEMP2
cat $TEMP2 | column -t -s',' > print.txt
rm -f $TEMP $TEMP2
cat print.txt
</code>```

Title: Bash - Adding titles into to a piped table command

Body:
You put the header Family Name, Initials, Interviewer Initials, Interview Time before the contents of students.txt before sending it to the column comand, and I think that should do the trick.

Perhaps something like:

TEMP=$(mktemp)
TEMP2=$(mktemp)
cat students.txt | sort -u -k3 > $TEMP
echo Family Name, Initials, Interviewer Initials, Interview Time > $TEMP2
cat $TEMP >> $TEMP2
cat $TEMP2 | column -t -s',' > print.txt
rm -f $TEMP $TEMP2
cat print.txt


问:
Authentication Oauth on Windows Mobile Emulator Fails with HTTPS
Lets set the stage
Doing a windows phone app, and trying to authenticate using Hammock OAuth library http://hammock.codeplex.com/
Language is C#.

I got to the point where I make the request, get the url with the token, then I am redirected in the WebBrowser control, but as soon as I enter my login and password I am redirected to a HTTPS URL, then that screen with the warning saying "We're having trouble with this site's security certificate", with the option of going back or continuing (Same one we see in windows when there is something unusual with the Certificate).

When I choose to continue, I get a page saying "We can't display this page right now", "Error: Cannot find server or DNS error"

I have tryed this directly on the IE Browser on the emulator and it works fine.

Any ideas?

答:
These are the currently supported certificates for Windows Phone. Without knowledge of the issuer of the certificate on the server you're accessing, I'm thinking it may not be one of these.

SSL Root Certificates for Windows Phone


问:
Change http port in wildfly maven plugin
I would like to change the default HTTP port using the wildfly-maven-plugin to 8380. Usually, I can do that changing the offset, but this is not working, my changes are ignored and HTTP port continues on 8080.

I'm starting wildfly in the same maven project, because this is way more practical (download and start automatically). Just like that:

```<code>mvn wildfly:run -Dwildfly.version=10.1.0.Final
</code>```

My project contains JAR, WAR and EAR. Classic structure.

As I understood from another SO questions, I need to put the plugin entry in each pom.xml that needs to be ignored, putting <skip>true</skip> in pom.xml of the: root, WAR and JAR. Just like that:

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>
</code>```

If I not skip this guys, the Wildfly try to deploy the JAR/WAR/Root, what is not my objective. I would like to deploy only the EAR.

To do that, I use the <skip>false</skip>  only for pom.xml of the EAR:

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
    </configuration>
</plugin>
</code>```

The localhost:8080/app/ works well after that.

But if I try to change the offset or http port, nothing different happens. This is some of the args that I already try on <configuration/> without success:

```<code><server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>

<jvmArgs>-Djboss.socket.binding.port-offset=300</jvmArgs>

<jvmArgs>-Djboss.http.port=8380</jvmArgs>
</code>```

The change that have some effect was:

```<code><serverConfig>standalone.xml</serverConfig>
<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>
<filename>${project.build.finalName}.ear</filename>
</code>```

This also have changed the port (jvmArgs is deprecated):

```<code><javaOpts>-Djboss.socket.binding.port-offset=300</javaOpts>
</code>```

But in both cases the EAR application is not deployed...

Any idea? Thanks!

答:
try not skipping the configuration :D</p>

```<code><plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <port>8380</port>
    </configuration>
</plugin>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I would like to change the default HTTP port using the wildfly-maven-plugin to 8380. Usually, I can do that changing the offset, but this is not working, my changes are ignored and HTTP port continues on 8080.

I'm starting wildfly in the same maven project, because this is way more practical (download and start automatically). Just like that:

mvn wildfly:run -Dwildfly.version=10.1.0.Final

My project contains JAR, WAR and EAR. Classic structure.

As I understood from another SO questions, I need to put the plugin entry in each pom.xml that needs to be ignored, putting <skip>true</skip> in pom.xml of the: root, WAR and JAR. Just like that:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>true</skip>
    </configuration>
</plugin>

If I not skip this guys, the Wildfly try to deploy the JAR/WAR/Root, what is not my objective. I would like to deploy only the EAR.

To do that, I use the <skip>false</skip>  only for pom.xml of the EAR:

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <skip>false</skip>
    </configuration>
</plugin>

The localhost:8080/app/ works well after that.

But if I try to change the offset or http port, nothing different happens. This is some of the args that I already try on <configuration/> without success:

<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>

<jvmArgs>-Djboss.socket.binding.port-offset=300</jvmArgs>

<jvmArgs>-Djboss.http.port=8380</jvmArgs>

The change that have some effect was:

<serverConfig>standalone.xml</serverConfig>
<server-args>
    <server-arg>-Djboss.socket.binding.port-offset=300</server-arg>
</server-args>
<filename>${project.build.finalName}.ear</filename>

This also have changed the port (jvmArgs is deprecated):

<javaOpts>-Djboss.socket.binding.port-offset=300</javaOpts>

But in both cases the EAR application is not deployed...

Any idea? Thanks!

Body:
try not skipping the configuration :D

<plugin>
    <groupId>org.wildfly.plugins</groupId>
    <artifactId>wildfly-maven-plugin</artifactId>
    <version>1.2.1.Final</version>
    <configuration>
        <port>8380</port>
    </configuration>
</plugin>


问:
Container Blobs with metadata
We have created a storage account for images and uploaded many images with the metadata property set. (as given below)

```<code> public async Task<bool> UploadFileToBlob(CustomFile file)
    {
        // Get Blob Container
        CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");
        container.CreateIfNotExists();

        // Get reference to blob (binary content)
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);

        // set its properties
        blockBlob.Properties.ContentType = file.FileMime;
        blockBlob.Metadata["tag"] = "computer";
        :
        :
}
</code>```

There could be multiple images could have uploaded with the same tag name as a meta data property.

Now, I need to just get the list of images from the blob container which are mapped with the same tag name (I saw samples to download all the blobcontent but I want to specifically get the filtered list with the specific tag name which was set in the meta data of the uploaded file)

Thanks

答:
There could be multiple images could have uploaded with the same tag name as a meta data property. Now, I need to just get the list of images from the blob container which are mapped with the same tag name.

As Zhaoxing Lu answered that there is no build-in features for you to achieve your purpose. Per my understanding, you could include path information in your blob names, you could create a virtual directory structure based on the tag category as follows:

```<code>https://{accountname}.blob.core.windows.net/{container-name}/{tag01}/photo1.jpg
https://{accountname}.blob.core.windows.net/{container-name}/{tag01}/photo2.jpg
https://{accountname}.blob.core.windows.net/{container-name}/{tag02}/photo3.jpg
</code>```

Then, you could leverage ListBlobs and specify the prefix parameter as follows to retrieve your blobs:

```<code>var blockBlobs = container.ListBlobs(prefix: "tag01").OfType<CloudBlockBlob>();
</code>```

Title: Container Blobs with metadata

Body:
We have created a storage account for images and uploaded many images with the metadata property set. (as given below)

 public async Task<bool> UploadFileToBlob(CustomFile file)
    {
        // Get Blob Container
        CloudBlobContainer container = BlobUtilities.GetBlobClient.GetContainerReference("documents");
        container.CreateIfNotExists();

        // Get reference to blob (binary content)
        CloudBlockBlob blockBlob = container.GetBlockBlobReference(file.FileName);

        // set its properties
        blockBlob.Properties.ContentType = file.FileMime;
        blockBlob.Metadata["tag"] = "computer";
        :
        :
}

There could be multiple images could have uploaded with the same tag name as a meta data property.

Now, I need to just get the list of images from the blob container which are mapped with the same tag name (I saw samples to download all the blobcontent but I want to specifically get the filtered list with the specific tag name which was set in the meta data of the uploaded file)

Thanks

Body:
There could be multiple images could have uploaded with the same tag name as a meta data property. Now, I need to just get the list of images from the blob container which are mapped with the same tag name.

As Zhaoxing Lu answered that there is no build-in features for you to achieve your purpose. Per my understanding, you could include path information in your blob names, you could create a virtual directory structure based on the tag category as follows:

https://{accountname}.blob.core.windows.net/{container-name}/{tag01}/photo1.jpg
https://{accountname}.blob.core.windows.net/{container-name}/{tag01}/photo2.jpg
https://{accountname}.blob.core.windows.net/{container-name}/{tag02}/photo3.jpg

Then, you could leverage ListBlobs and specify the prefix parameter as follows to retrieve your blobs:

var blockBlobs = container.ListBlobs(prefix: "tag01").OfType<CloudBlockBlob>();