问:
Center div with equal margins. Margin-bottom not working with height 100vh?
No matter what I try to do, I can't get my div to have equal margins all the way around.

I assume margin-bottom/padding-bottom doesn't work when you set the height to 100vh or 100%?

I need it to be responsive so px values are no use here.

I've created a fiddle: https://jsfiddle.net/uLmkyqpf/

Code:

HTML:

```<code> <div class="mySec header">
   <div class="info">
      <ul id="headList">
        <li>
            <a data-section="top-left" id="link" href="#">ABOUT</a>
        </li>
        <li>
            <a data-section="getInvolved" id="link" href="#">CLASSES</a>
        </li>
          <li>
            <a data-section="footer" id="link" href="#">CONTACT</a>
        </li>
      </ul>
        <h1 class="title">Niki Gibbs Modern Pilates</h1>
        <p class="title2">Working From The Inside Out.</p>
        <img id="pilLogo" src="pilatesLog.png">
    </div>
</div>
</code>```

CSS:

```<code>body {
 margin: 0;
 padding: 0;
 font-family: 'Josefin Sans', sans-serif;
 background-color: #EFEFEF;
 text-align: center;
 overflow: hidden;
 height: 100%;
 width: 100%;
}
.mySec {
  position: relative;
  height: 100%;
  margin-right: 4%;
  margin-left: 4%;
  margin-top: 4%;
  padding-bottom: 4%;
  overflow: hidden;
}
.header {
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(#FFC0CB, #9370DB); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(#FFC0CB, #9370DB ); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(#FFC0CB, #9370DB); /* For Firefox 3.6 to 15 */
}
#headList {
  list-style: none;
  font-family: 'Josefin Sans', sans-serif;
  position: relative;
  left: -1vw;
}
#headList li {
    display: inline;
}
#headList li a {
    color: #000;
    font-size: 1.4vw;
    padding: 2vw;
    text-decoration: none;
    letter-spacing: 2px;
    font-weight: 200;
}
.title {
  font-family: 'Amatic SC', cursive;
  font-size:8vw;
  position: relative;
  bottom: 8.3vh;
  color: #000;
}

.title2 {
  color: #000;
  position: relative;
  font-size: 2vw;
  bottom: 14vh;
}
#pilLogo {
    position: relative;
    left: 25vw;
    bottom: 41vh;
}
.info {
    position: relative;
    top: 25vh;
}
</code>```

答:
Using the same percentage values for a margin will always make the top/bottom appear different then for left/right.

The percentage is calculated with respect to the width of the
  generated box's containing block. Note that this is true for
  'margin-top' and 'margin-bottom' as well.

https://www.w3.org/TR/CSS2/box.html#propdef-margin

If you still want to use a dynamic value for your margin, I would suggest either vh or vw.

Your example updated: https://jsfiddle.net/uLmkyqpf/2/

Body:
No matter what I try to do, I can't get my div to have equal margins all the way around.

I assume margin-bottom/padding-bottom doesn't work when you set the height to 100vh or 100%?

I need it to be responsive so px values are no use here.

I've created a fiddle: https://jsfiddle.net/uLmkyqpf/

Code:

HTML:

            ABOUT

            CLASSES

            CONTACT

Niki Gibbs Modern Pilates

Working From The Inside Out.

CSS:

body {
 margin: 0;
 padding: 0;
 font-family: 'Josefin Sans', sans-serif;
 background-color: #EFEFEF;
 text-align: center;
 overflow: hidden;
 height: 100%;
 width: 100%;
}
.mySec {
  position: relative;
  height: 100%;
  margin-right: 4%;
  margin-left: 4%;
  margin-top: 4%;
  padding-bottom: 4%;
  overflow: hidden;
}
.header {
    background: red; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(#FFC0CB, #9370DB); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(#FFC0CB, #9370DB ); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(#FFC0CB, #9370DB); /* For Firefox 3.6 to 15 */
}
#headList {
  list-style: none;
  font-family: 'Josefin Sans', sans-serif;
  position: relative;
  left: -1vw;
}
#headList li {
    display: inline;
}
#headList li a {
    color: #000;
    font-size: 1.4vw;
    padding: 2vw;
    text-decoration: none;
    letter-spacing: 2px;
    font-weight: 200;
}
.title {
  font-family: 'Amatic SC', cursive;
  font-size:8vw;
  position: relative;
  bottom: 8.3vh;
  color: #000;
}

.title2 {
  color: #000;
  position: relative;
  font-size: 2vw;
  bottom: 14vh;
}
#pilLogo {
    position: relative;
    left: 25vw;
    bottom: 41vh;
}
.info {
    position: relative;
    top: 25vh;
}


来源: stackexchange

问:
Remove single br in paragraph but not double br?
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

```<code>p br {display:none}
</code>```

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

```<code>p br { content: ' '; }
</code>```

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

```<code><p> oremipsum lorem<br/>
orem blalgr<br/><br/>
loremg grthrt
</p>
</code>```

答:
This jQuery will remove any single
, but still keep

:

$(".container br").filter(function() {
  var $item = $(this);
  return !$item.next().is("br") && !$item.prev().is("br");
}).remove();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>p {margin: 0;}</code>```

Hello. One BR below.

Hello. Two BR below.

Hello. One BR below.

Hello. Two BR below.

Hello. No BR below.

```

ContentLicense: CC BY-SA 3.0

Body:
I have a paragraph with some single
 and double
.

I'd like to add all the single
, but not the double
.

How is that possible?

If I use

p br {display:none}

It hides all the br tags. However, when I have two br, I would like them to still display . . ..  How can we make this work? It seems I can not find any relevant information.

I also tried the following without success:

p br { content: ' '; }

Thanks a lot for your time !

-- edit --

my paragraph is formatted like that:

 oremipsum lorem

orem blalgr

loremg grthrt

Body:
This jQuery will remove any single <br/>, but still keep <br/><br/>:

$(".container br").filter(function() {
  var $item = $(this);
  return !$item.next().is("br") && !$item.prev().is("br");
}).remove();

p {margin: 0;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <p>Hello. One BR below.</p>
  <br />
  <p>Hello. Two BR below.</p>
  <br /><br />
  <p>Hello. One BR below.</p>
  <br />
  <p>Hello. Two BR below.</p>
  <br /><br />
  <p>Hello. No BR below.</p>
</div>


问:
How to add class to all rows
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

```<code>$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});
</code>```

Demo Here (Fiddle)

答:
https://fiddle.jshell.net/w9zkwb1f/5/

$(document).ready(function () {

  $("#selectAll").click(function(){
    if($(this).is(':checked')){
      $("input[type='checkbox']").prop("checked",true);
      $("table tr").addClass("warning");
    }
    else{
      $("input[type='checkbox']").prop("checked",false);
      $("table tr").removeClass("warning");
    }
  });

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
            $("#selectAll").prop("checked",false).removeClass("warning");
        }
    });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-striped table-hover table-condensed">
    <tr>
        <th><input type="checkbox" id="selectAll"/></th>
        <th>Title</th>
        <th>Title</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
</table></code>```

Title: How to add class to all rows

Body:
In given example, I can select/deselect each row on clicking on checkbox from td, but how to select/deselect all rows on click  id="selectAll" from th

JS :

$(document).ready(function () {

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
        }
    });
});

Demo Here (Fiddle)

Body:
https://fiddle.jshell.net/w9zkwb1f/5/

$(document).ready(function () {

  $("#selectAll").click(function(){
    if($(this).is(':checked')){
      $("input[type='checkbox']").prop("checked",true);
      $("table tr").addClass("warning");
    }
    else{
      $("input[type='checkbox']").prop("checked",false);
      $("table tr").removeClass("warning");
    }
  });

    $("input[type='checkbox']").change(function (e) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').addClass("warning");
        } else {
            $(this).closest('tr').removeClass("warning");
            $("#selectAll").prop("checked",false).removeClass("warning");
        }
    });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered table-striped table-hover table-condensed">
    <tr>
        <th><input type="checkbox" id="selectAll"/></th>
        <th>Title</th>
        <th>Title</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>Hello</td>
        <td>Hello</td>
    </tr>
</table>


问:
Angular 4 sequential Http.post calls
How to make sequential (synchronous) http POST calls (wait the response from each call)

```<code>generateDoc(project, Item, language, isDOCXFormat) : Observable<any> {
        return this.http.post(this.sessionStorageService.retrieve('backendApi').baseUri + '/export/document/' + project.projectId + '/' + Item.id,
                     {language:language, isDOCXFormat:isPDFFormat}, option);
    }
</code>```

Thank you.

答:
If you want synchronous calls, you can use concatMap:

```<code>http.post(url1, data1).concatMap(t=> http.post(url2, data2);
</code>```

Title: Angular 4 sequential Http.post calls

Body:
How to make sequential (synchronous) http POST calls (wait the response from each call)

generateDoc(project, Item, language, isDOCXFormat) : Observable<any> {
        return this.http.post(this.sessionStorageService.retrieve('backendApi').baseUri + '/export/document/' + project.projectId + '/' + Item.id,
                     {language:language, isDOCXFormat:isPDFFormat}, option);
    }

Thank you.

Body:
If you want synchronous calls, you can use concatMap:

http.post(url1, data1).concatMap(t=> http.post(url2, data2);


问:
Vehicles are missing in default CryEngine 5 installation
I installed CryEngine 5 from an official site. Now I want to add a vehicle to a level.

As described in Beginners manual, I need to

open the Create Object tool, go to Entity and expand Vehicles in the list that appears in the bottom of the tool.

However, there is no Vehicles item:

How to add DefaultVehicle into my level?

答: It turns out that in CryEngine 5 you need to download GameSDK, because engine does not have this editor by default.</p>


问:
What does different arguments of model.sumary() in keras python mean?
When I write model.summary() I get something like

How can I get "connected to" argument? Also, can someone tell me the meaning of None in output shape argument?

答:
None means that the number of samples that you feed into your network is not yet defined. This in general is a hyperparameter that you choose before training and is independent of your models architecture.

model.summary() is documented here

You might want to look into model.get_weights() or model.get_config() (which are methods though).

Useful attributes of class Model are (per Keras documentation):

model.layers: flattened list of the layers comprising the model graph

model.inputs: list of input tensors

model.outputs: list of output tensors


问:
Python - appended character gets lost
Hey I´m quite new to python and i´m writing a script to sort through a file in for some keywords, and everything works fine except a small reading/printing miss that i don´t understand... This is my problem code and the file im scanning through:

```<code>File:
    SEND TEST
    Tester -> 1FFF 19 02 0F :\user\log
    SEND TEST
    Tester -> 1FFF 18 00 0F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 12 11 5F :\user\log
    SEND TEST
    Tester -> 1FFF 12 55 1F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 19 03 2F :\user\log
code:
      if line.startswith('Tester ->'):
         start = 'Tester -> '  # take string from
         end = ':\ ' # end at
         data.append(line[line.find(start) + 9 :line.find(end)].strip('[Channel 1]'))
</code>```

this prints

```<code>1FFF 19 02 0F
1FFF 18 00 0F [Channel 1]
1FFF 12 11 5F
1FFF 12 55 1F [Channel 1]
1FFF 19 03 2F
</code>```

The data.append string has the problem, as shown in the print i works, but i want to extract the code ex 1FFF 12 55 1F but not [Channel 1] aslo... so i used .strip to remove it, but then i get this print:

```<code>1FFF 19 02 0F
FFF 18 00 0F
1FFF 12 11 5F
FFF 12 55 1F
1FFF 19 03 2F
</code>```

All strings that has [Channel 1] loses the first character and if i put a 8 instead of a 9 in data.apped it prints:

```<code>1FFF 19 02 0F
> 1FFF 18 00 0F
1FFF 12 11 5F
> 1FFF 12 55 1F
1FFF 19 03 2F
</code>```

Then it takes the > from the Tester -> and I don´t understand why? it skips the character in between for some reason? It´s like when I have a 9 it counts every character including spaces and when I have a 8 it counts characters but not including spaces... how is that possible? someone who knows how to fix this, thanks!

```<code># Sending Request: Tester -> 1631 11 33 F5 :\ APP_3130 \ Read Identifier \
Tester -> 1631 22 F1 2E :\ APP_3138 \ Read Identifier \
Tester -> 1FFF 19 02 0F [Channel 1]
</code>```

答:
this is a version using regex:

```<code>import re

rgx = re.compile('Tester\ ->\ ([0-9a-fA-F\ ]{13})')

for line in file:
    match = rgx.match(line)
    if match:
        data.append(match.group(1))

print(data)
# ['1FFF 19 02 0F', '1FFF 18 00 0F', '1FFF 12 11 5F',
#  '1FFF 12 55 1F', '1FFF 19 03 2F']
</code>```

the regular expression matches the string 'Tester -> ' followed by a string of length 13 containing hexadecimal characters or spaces.

that is assuming that you iterate over your file line per line.

Title: Python - appended character gets lost

Body:
Hey I´m quite new to python and i´m writing a script to sort through a file in for some keywords, and everything works fine except a small reading/printing miss that i don´t understand... This is my problem code and the file im scanning through:

File:
    SEND TEST
    Tester -> 1FFF 19 02 0F :\user\log
    SEND TEST
    Tester -> 1FFF 18 00 0F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 12 11 5F :\user\log
    SEND TEST
    Tester -> 1FFF 12 55 1F [Channel 1] :\user\log
    SEND TEST
    Tester -> 1FFF 19 03 2F :\user\log
code:
      if line.startswith('Tester ->'):
         start = 'Tester -> '  # take string from
         end = ':\ ' # end at
         data.append(line[line.find(start) + 9 :line.find(end)].strip('[Channel 1]'))

this prints

1FFF 19 02 0F
1FFF 18 00 0F [Channel 1]
1FFF 12 11 5F
1FFF 12 55 1F [Channel 1]
1FFF 19 03 2F

The data.append string has the problem, as shown in the print i works, but i want to extract the code ex 1FFF 12 55 1F but not [Channel 1] aslo... so i used .strip to remove it, but then i get this print:

1FFF 19 02 0F
FFF 18 00 0F
1FFF 12 11 5F
FFF 12 55 1F
1FFF 19 03 2F

All strings that has [Channel 1] loses the first character and if i put a 8 instead of a 9 in data.apped it prints:

1FFF 19 02 0F
> 1FFF 18 00 0F
1FFF 12 11 5F
> 1FFF 12 55 1F
1FFF 19 03 2F

Then it takes the > from the Tester -> and I don´t understand why? it skips the character in between for some reason? It´s like when I have a 9 it counts every character including spaces and when I have a 8 it counts characters but not including spaces... how is that possible? someone who knows how to fix this, thanks!

# Sending Request: Tester -> 1631 11 33 F5 :\ APP_3130 \ Read Identifier \
Tester -> 1631 22 F1 2E :\ APP_3138 \ Read Identifier \
Tester -> 1FFF 19 02 0F [Channel 1]

Body:
this is a version using regex:

import re

rgx = re.compile('Tester\ ->\ ([0-9a-fA-F\ ]{13})')

for line in file:
    match = rgx.match(line)
    if match:
        data.append(match.group(1))

print(data)
# ['1FFF 19 02 0F', '1FFF 18 00 0F', '1FFF 12 11 5F',
#  '1FFF 12 55 1F', '1FFF 19 03 2F']

the regular expression matches the string 'Tester -> ' followed by a string of length 13 containing hexadecimal characters or spaces.

that is assuming that you iterate over your file line per line.


问:
Average Memory Access Time for 25% memory instructions
*An I-cache has a 0.95 hit rate, hit rate time 3 cycles and a D-cache has a 0.85 hit rate (3 cycles). Miss penalty of both is 40 cycles. What is the AMAT for 0.25 Memory instructions?

I successfully calculated:
AMAT_I = 3 + 0.05 * 40 = 5
AMAT_D = 3 + 0.15 * 40 = 9

The solutions tells me:
AMAT_Total = 1/1.25 * AMAT_I + 0.25/1.25 * AMAT_D but I don't understand why. Can someone please explain me the logic behind it? I thought: AMAT_Total = 0.25 * (AMAT_I + AMAT_D)

答:
If you were only accessing I-cache and D-cache on memory access instructions, your answer would be correct. However, all of your instructions go through I-cache, hence the name instruction-cache. To put it in a different way:

When you are executing any instruction = you access I-Cache

When you are execution memory instructions = you access both I-Cache to fetch the instruction and you access D-Cache for the data.


问:
Define correctly height for UIScrollView
I'm creating a application using Swift3, and i have difficult to define correctly height for UIScrollView, i'm using autolayout and create this structure:

UIScrollView

UIView // The container view

UIImageView // Constraint Top Edges  = 20 in relation to UIView

UITextView // Constraint Top Edges = 40 in relation to UIImageView

UITextView // Constraint Top Edges = 20 in relation to UITextView

UIButton // Constraint Top Edges 30 in relation to UITextView

Currently, i'm using this logic to calculate UIScrollView height

```<code>override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize.height = scrollHeight

}
</code>```

But, i can only get the views height, and them not consider the Constraints "margins", i would like know any way to calculate correct height for UIScrollView, adjusted according their content.

Body:
I'm creating a application using Swift3, and i have difficult to define correctly height for UIScrollView, i'm using autolayout and create this structure:

UIScrollView

UIView // The container view

UIImageView // Constraint Top Edges  = 20 in relation to UIView

UITextView // Constraint Top Edges = 40 in relation to UIImageView

UITextView // Constraint Top Edges = 20 in relation to UITextView

UIButton // Constraint Top Edges 30 in relation to UITextView

Currently, i'm using this logic to calculate UIScrollView height

override func viewDidLayoutSubviews() {
    var scrollHeight : CGFloat = 0.0

    for view in self.containerView.subviews {
        view.layoutIfNeeded()
        scrollHeight += view.frame.size.height
    }

    // Adding height for scrollview, according to the sum of all child views
    self.scrollView.contentSize.height = scrollHeight

}

But, i can only get the views height, and them not consider the Constraints "margins", i would like know any way to calculate correct height for UIScrollView, adjusted according their content.

Body: self.scrollview.contentsize.height = containerview.height;


问:
Jsoup: How to select direct parents until the root without their siblings?
I'm trying to get all direct parents of element, but also I get their siblings.

For example, I have this DOM structure...

```<code><div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2>
    <a href="google.com">google</a>
    <p>
      <img class="first">
    </p>
    <img class="second">
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>
</code>```

So I want get all direct parents of img element with class first until a div with class html.

I've tried using the following code

```<code>Element element = document.select("img").first();
Node root = element.root();
</code>```

But in the root var I get whole DOM structure also with all siblings.

UPDATE

After this in root var I have the whole DOM structure again:

```<code><div class="html">
  <div class="head"></div>
  <div class="body">
    <a href="seznam.cz">seznam</a>
    <h2>Foo</h2>
    <a href="google.com">google</a>
    <p>
      <img class="first">
    </p>
    <img class="second">
    <ol>
      <li>1</li>
      <li>2</li>
    </ol>
  </div>
</div>
</code>```

But I want something like this:

```<code><div class="html">
  <div class="body">
    <p>
      <img class="first">
    </p>
  </div>
</div>
</code>```

答:
First of all get all elements with class name 'first' using,

```<code>Elements childs = document.getElementsByClass("first");
</code>```

Now, iterate all child elements to get their parent elements using,

```<code>    for( Element child : childs){
      Elements parents = child.parents();
      for(Element parent: parents){
        System.out.println(parent.tagName());
      }
    }
</code>```

Try this, Hope it will work for you ;)

Body:
I'm trying to get all direct parents of element, but also I get their siblings.

For example, I have this DOM structure...

    seznam

Foo

    google

1

2

So I want get all direct parents of img element with class first until a div with class html.

I've tried using the following code

Element element = document.select("img").first();
Node root = element.root();

But in the root var I get whole DOM structure also with all siblings.

UPDATE

After this in root var I have the whole DOM structure again:

    seznam

Foo

    google

1

2

But I want something like this:

Body:
First of all get all elements with class name 'first' using,

Elements childs = document.getElementsByClass("first");

Now, iterate all child elements to get their parent elements using,

    for( Element child : childs){
      Elements parents = child.parents();
      for(Element parent: parents){
        System.out.println(parent.tagName());
      }
    }

Try this, Hope it will work for you ;)


问:
Looking for the next "Daylight Saving Time" using the Windows registery
Looking for the next "Daylight Saving Time" using the Windows registry.

I have to use an old version of Borland C++.

Idea from Daylight Saving Time change with an absolute date

The "W. Europe Standard Time" in the registry says that the "Daylight Saving Time" occurs in the 5th occurrence of the Sunday of March which is false because it is the 4th occurrence. MSDN doc.

So when I am doing :

```<code>void findDate(int year, SYSTEMTIME systemTime)
{
    struct tm timestr;
    int occ = 0;
    bool found = false;

    timestr.tm_year = year - 1900;
    timestr.tm_mon = systemTime.wMonth - 1;
    timestr.tm_mday = 0;
    timestr.tm_hour = systemTime.wHour;
    timestr.tm_min = systemTime.wMinute;
    timestr.tm_sec = systemTime.wSecond;
    timestr.tm_isdst = 0;

    while((timestr.tm_mday <= 31 && !found)) {
        timestr.tm_mday += 1;
        time_t standard = mktime(&timestr);
        struct tm * temp = localtime(&standard);
        if(temp->tm_wday == systemTime.wDayOfWeek) {
           occ++;
        }

        if(occ >= sysemTime.wDay) {
             found = true;
             printf("\n\nFound: %s", asctime( &timestr ));
        }
    }
}

int main(int argc, char* argv[])
{
 // Get the timezone info.
 TIME_ZONE_INFORMATION TimeZoneInfo;
 GetTimeZoneInformation( &TimeZoneInfo );
 DYNAMIC_TIME_ZONE_INFORMATION TimeZoneInfoDyn;

 printf("\n\nStandardDate %d wDay%d wDayOfWeek%d %d %d %d", TimeZoneInfo.StandardDate.wMonth, TimeZoneInfo.StandardDate.wDay, TimeZoneInfo.StandardDate.wDayOfWeek, TimeZoneInfo.StandardDate.wHour, TimeZoneInfo.StandardDate.wMinute, TimeZoneInfo.StandardDate.wSecond);
 printf("\nDaylightDate %d wDay%d wDayOfWeek%d %d %d %d", TimeZoneInfo.DaylightDate.wMonth, TimeZoneInfo.DaylightDate.wDay, TimeZoneInfo.DaylightDate.wDayOfWeek, TimeZoneInfo.DaylightDate.wHour, TimeZoneInfo.DaylightDate.wMinute, TimeZoneInfo.DaylightDate.wSecond);

 findDate(2017, TimeZoneInfo.StandardDate);
 findDate(2018, TimeZoneInfo.DaylightDate);
 getchar();
 return 0;

}
</code>```

It displays :

```<code>Found: Sun Oct 29 03:00:00 2017
Found: Sun Apr 01 03:00:00 2018
</code>```

Instead of :

```<code>Found: Sun Oct 29 03:00:00 2017
Found: Sun Mar 25 03:00:00 2018
</code>```

What am I doing wrong?

答:
The "W. Europe Standard Time" in the registery says that the "Daylight Saving Time" occurs in the 5th occurance of the sunday of March which is false because it is the 4th occurance.

From the documentation quoted in the linked answer:

(1 to 5, where 5 indicates the final occurrence during the month if that day of the week does not occur 5 times).

So it is not false.

Furthermore, in your loop you increment tm_mday and occ before checking whether you've already reached the desired day. If you were on it to start with, you'll overshoot.

By the way, sysemTime is misspelt.

Body:
Looking for the next "Daylight Saving Time" using the Windows registry.

I have to use an old version of Borland C++.

Idea from Daylight Saving Time change with an absolute date

The "W. Europe Standard Time" in the registry says that the "Daylight Saving Time" occurs in the 5th occurrence of the Sunday of March which is false because it is the 4th occurrence. MSDN doc.

So when I am doing :

void findDate(int year, SYSTEMTIME systemTime)
{
    struct tm timestr;
    int occ = 0;
    bool found = false;

    timestr.tm_year = year - 1900;
    timestr.tm_mon = systemTime.wMonth - 1;
    timestr.tm_mday = 0;
    timestr.tm_hour = systemTime.wHour;
    timestr.tm_min = systemTime.wMinute;
    timestr.tm_sec = systemTime.wSecond;
    timestr.tm_isdst = 0;

    while((timestr.tm_mday <= 31 && !found)) {
        timestr.tm_mday += 1;
        time_t standard = mktime(&timestr);
        struct tm * temp = localtime(&standard);
        if(temp->tm_wday == systemTime.wDayOfWeek) {
           occ++;
        }

        if(occ >= sysemTime.wDay) {
             found = true;
             printf("\n\nFound: %s", asctime( &timestr ));
        }
    }
}

int main(int argc, char* argv[])
{
 // Get the timezone info.
 TIME_ZONE_INFORMATION TimeZoneInfo;
 GetTimeZoneInformation( &TimeZoneInfo );
 DYNAMIC_TIME_ZONE_INFORMATION TimeZoneInfoDyn;

 printf("\n\nStandardDate %d wDay%d wDayOfWeek%d %d %d %d", TimeZoneInfo.StandardDate.wMonth, TimeZoneInfo.StandardDate.wDay, TimeZoneInfo.StandardDate.wDayOfWeek, TimeZoneInfo.StandardDate.wHour, TimeZoneInfo.StandardDate.wMinute, TimeZoneInfo.StandardDate.wSecond);
 printf("\nDaylightDate %d wDay%d wDayOfWeek%d %d %d %d", TimeZoneInfo.DaylightDate.wMonth, TimeZoneInfo.DaylightDate.wDay, TimeZoneInfo.DaylightDate.wDayOfWeek, TimeZoneInfo.DaylightDate.wHour, TimeZoneInfo.DaylightDate.wMinute, TimeZoneInfo.DaylightDate.wSecond);

 findDate(2017, TimeZoneInfo.StandardDate);
 findDate(2018, TimeZoneInfo.DaylightDate);
 getchar();
 return 0;

}

It displays :

Found: Sun Oct 29 03:00:00 2017
Found: Sun Apr 01 03:00:00 2018

Instead of :

Found: Sun Oct 29 03:00:00 2017
Found: Sun Mar 25 03:00:00 2018

What am I doing wrong?


问:
how to integrate material icons into opencart
Can anyone explain how to integrate Google material icons into Opencart or into any other website?
Here is the link to Google material icons.

Thank you...

答:
You can try to use a CSS framework like this: http://materializecss.com/icons.html

it is really close to the material design of Google


问:
Using pngcrush with git export filter
I’d like to optimize png files when I export them (using git archive) from the repository, using a smudge filter. However, if I understand it correctly, these filters work only via STDIN and STDOUT, while pngcrush needs a “real” file.

Is there any workaround?

答:
Use temporary files. eg:</p>

```<code>IN=$(mktemp)
OUT=$(mktemp)

# save stdin to temp file
cat > "$IN"

# Crush the image and ignore regular output.
# Die if pngcrush fails.
pngcrush "$IN" "$OUT" > /dev/null || exit $?

# write temp file to stdout
cat "$OUT"

# clean up
rm "$IN" "$OUT" &
</code>```

ContentLicense: CC BY-SA 2.5

Title: Using pngcrush with git export filter

Body:
Use temporary files. eg:

IN=$(mktemp)
OUT=$(mktemp)

# save stdin to temp file
cat > "$IN"

# Crush the image and ignore regular output.
# Die if pngcrush fails.
pngcrush "$IN" "$OUT" > /dev/null || exit $?

# write temp file to stdout
cat "$OUT"

# clean up
rm "$IN" "$OUT" &


问:
And Condition with join is similar to where condition after join
Is it similar to have and condition with join and where condition after join?

for example

will it give me same result for below two queries

```<code>1) SELECT COUNT(*)
FROM language_message_mapping lm
 LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
  AND lm.user_profile_id_fk IS NOT NULL

2) SELECT COUNT(*)
FROM language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
where lm.user_profile_id_fk IS NOT NULL
</code>```

I want to update rows which I get from above query
please tell me below update query is correct or not

```<code>UPDATE language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
SET lm.user_account_id_fk=up.user_account_id_fk
AND lm.user_profile_id_fk IS NOT NULL;
</code>```

答:
NO, they are not same at all. your first query will give a proper effect of a OUTER JOIN whereas the second query will be eventually same as INNER JOIN

For an INNER JOIN this wouldn't make any difference though

Body:
Is it similar to have and condition with join and where condition after join?

for example

will it give me same result for below two queries

1) SELECT COUNT(*)
FROM language_message_mapping lm
 LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
  AND lm.user_profile_id_fk IS NOT NULL

2) SELECT COUNT(*)
FROM language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
where lm.user_profile_id_fk IS NOT NULL

I want to update rows which I get from above query
please tell me below update query is correct or not

UPDATE language_message_mapping lm
LEFT JOIN user_profiles up ON lm.user_profile_id_fk=user_profile_id_pk
SET lm.user_account_id_fk=up.user_account_id_fk
AND lm.user_profile_id_fk IS NOT NULL;


问:
If JazzSm is installed in a virtual directory, DWC installation fails on Win 10
Dynamic Workload Console installation fails on Windows 10 if JazzSm is installed in a virtual directory (i.e. C:\Program Files). A pop up appears asking for the credential.</p>

答: to circumvent the problem, insert the JazzSm credentials or install both Dynamic Workload Console and JazzSm in a non-virtual directory.</p>


问:
Application logs not getting updated
Am facing similar issue in my application.
Updated with new log4j properties.

Redirect log messages to a log file, support file rolling.

```<code>log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=tmp\applicatione2e.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
</code>```

Whereas after running the application , not able to find the updated log file in the given path. Can anyone help me how to fix it?`

答:
Please try with this.

log4j.rootLogger=INFO, file

log4j.appender.file=org.apache.log4j.RollingFileAppender

log4j.appender.file.File=tmp\applicatione2e.log

log4j.appender.file.MaxFileSize=10MB

log4j.appender.file.MaxBackupIndex=10

log4j.appender.file.layout=org.apache.log4j.PatternLayout

log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Title: Application logs not getting updated

Body:
Am facing similar issue in my application.
Updated with new log4j properties.

Redirect log messages to a log file, support file rolling.

log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=tmp\applicatione2e.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout

Whereas after running the application , not able to find the updated log file in the given path. Can anyone help me how to fix it?`


问:
How to properly apply a CSS hack for IE11+
I am creating a loading spinner for my web application. It is working perfectly fine in chrome but in IE11 the CSS styles are not working.

Below is the sample code for loading spinner that i am using from https://codepen.io/creotip/pen/dfaIh?editors=1100#0:

* {
  padding: 0px;
  margin: 0px;
}

body {
  overflow: hidden;
}

.page-bg {
  position: absolute;
  top: -20px;
  left: -20px;
  right: -20px;
  bottom: -20px;
  background: url('https://i.imgur.com/BlihuYt.jpg') center;
  -webkit-filter: blur(0px);
  z-index: 10;
}

.preloader {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background: -webkit-radial-gradient(rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.8));
  z-index: 10;
}

.preloader>.preloader-box {
  position: absolute;
  width: 345px;
  height: 30px;
  top: 50%;
  left: 50%;
  margin: -15px 0 0 -150px;
  -webkit-perspective: 200px;
}

.preloader .preloader-box>div {
  position: relative;
  width: 30px;
  height: 30px;
  background: #CCC;
  float: left;
  text-align: center;
  line-height: 30px;
  font-family: Verdana;
  font-size: 20px;
  color: #FFF;
}

.preloader .preloader-box>div:nth-child(1) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 0ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(2) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 75ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(3) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 150ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(4) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 225ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(5) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 300ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(6) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 375ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(7) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 450ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(8) {
  background: #3366FF;
  -webkit-animation: movement 600ms ease 525ms infinite alternate;
}

@-webkit-keyframes movement {
  from {
    -webkit-transform: scale(1.0) translateY(0px) rotateX(0deg);
    box-shadow: 0 0 0 rgba(0, 0, 0, 0);
  }
  to {
    -webkit-transform: scale(1.5) translateY(-25px) rotateX(45deg);
    box-shadow: 0 25px 40px rgba(0, 0, 0, 0.4);
    background: #3399FF;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page-bg"></div>

<div class="preloader">
  <div class="preloader-box">
    <div>L</div>
    <div>O</div>
    <div>A</div>
    <div>D</div>
    <div>I</div>
    <div>N</div>
    <div>G</div>
  </div>
</div></code>```

How can I resolve this problem and fix this for IE11?

答:
Your code had vendor prefixes

The prefix -webkit limits the property to browsers powered by the webkit engine

I removed the prefixes from your code and this is working for me on IE 11

* {
  padding: 0px;
  margin: 0px;
}

body {
  overflow: hidden;
}

.page-bg {
  position: absolute;
  top: -20px;
  left: -20px;
  right: -20px;
  bottom: -20px;
  background: url('https://i.imgur.com/BlihuYt.jpg') center;
  -webkit-filter: blur(0px);
  z-index: 10;
}

.preloader {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background: radial-gradient(rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.8));
  z-index: 10;
}

.preloader>.preloader-box {
  position: absolute;
  width: 345px;
  height: 30px;
  top: 50%;
  left: 50%;
  margin: -15px 0 0 -150px;
  perspective: 200px;
}

.preloader .preloader-box>div {
  position: relative;
  width: 30px;
  height: 30px;
  background: #CCC;
  float: left;
  text-align: center;
  line-height: 30px;
  font-family: Verdana;
  font-size: 20px;
  color: #FFF;
}

.preloader .preloader-box>div:nth-child(1) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 0ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(2) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 75ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(3) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 150ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(4) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 225ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(5) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 300ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(6) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 375ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(7) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 450ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(8) {
  background: #3366FF;
  animation: movement 600ms ease 525ms infinite alternate;
}

@keyframes movement {
  from {
    transform: scale(1.0) translateY(0px) rotateX(0deg);
    box-shadow: 0 0 0 rgba(0, 0, 0, 0);
  }
  to {
    transform: scale(1.5) translateY(-25px) rotateX(45deg);
    box-shadow: 0 25px 40px rgba(0, 0, 0, 0.4);
    background: #3399FF;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page-bg"></div>

<div class="preloader">
  <div class="preloader-box">
    <div>L</div>
    <div>O</div>
    <div>A</div>
    <div>D</div>
    <div>I</div>
    <div>N</div>
    <div>G</div>
  </div>
</div></code>```

Body:
I am creating a loading spinner for my web application. It is working perfectly fine in chrome but in IE11 the CSS styles are not working.

Below is the sample code for loading spinner that i am using from https://codepen.io/creotip/pen/dfaIh?editors=1100#0:

* {
  padding: 0px;
  margin: 0px;
}

body {
  overflow: hidden;
}

.page-bg {
  position: absolute;
  top: -20px;
  left: -20px;
  right: -20px;
  bottom: -20px;
  background: url('https://i.imgur.com/BlihuYt.jpg') center;
  -webkit-filter: blur(0px);
  z-index: 10;
}

.preloader {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background: -webkit-radial-gradient(rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.8));
  z-index: 10;
}

.preloader>.preloader-box {
  position: absolute;
  width: 345px;
  height: 30px;
  top: 50%;
  left: 50%;
  margin: -15px 0 0 -150px;
  -webkit-perspective: 200px;
}

.preloader .preloader-box>div {
  position: relative;
  width: 30px;
  height: 30px;
  background: #CCC;
  float: left;
  text-align: center;
  line-height: 30px;
  font-family: Verdana;
  font-size: 20px;
  color: #FFF;
}

.preloader .preloader-box>div:nth-child(1) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 0ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(2) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 75ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(3) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 150ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(4) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 225ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(5) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 300ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(6) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 375ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(7) {
  background: #3366FF;
  margin-right: 15px;
  -webkit-animation: movement 600ms ease 450ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(8) {
  background: #3366FF;
  -webkit-animation: movement 600ms ease 525ms infinite alternate;
}

@-webkit-keyframes movement {
  from {
    -webkit-transform: scale(1.0) translateY(0px) rotateX(0deg);
    box-shadow: 0 0 0 rgba(0, 0, 0, 0);
  }
  to {
    -webkit-transform: scale(1.5) translateY(-25px) rotateX(45deg);
    box-shadow: 0 25px 40px rgba(0, 0, 0, 0.4);
    background: #3399FF;
  }
}

L

O

A

D

I

N

G

How can I resolve this problem and fix this for IE11?

Body:
Your code had vendor prefixes

The prefix -webkit limits the property to browsers powered by the webkit engine

I removed the prefixes from your code and this is working for me on IE 11

* {
  padding: 0px;
  margin: 0px;
}

body {
  overflow: hidden;
}

.page-bg {
  position: absolute;
  top: -20px;
  left: -20px;
  right: -20px;
  bottom: -20px;
  background: url('https://i.imgur.com/BlihuYt.jpg') center;
  -webkit-filter: blur(0px);
  z-index: 10;
}

.preloader {
  position: absolute;
  top: 0px;
  left: 0px;
  right: 0px;
  bottom: 0px;
  background: radial-gradient(rgba(0, 0, 0, 0) 50%, rgba(0, 0, 0, 0.8));
  z-index: 10;
}

.preloader>.preloader-box {
  position: absolute;
  width: 345px;
  height: 30px;
  top: 50%;
  left: 50%;
  margin: -15px 0 0 -150px;
  perspective: 200px;
}

.preloader .preloader-box>div {
  position: relative;
  width: 30px;
  height: 30px;
  background: #CCC;
  float: left;
  text-align: center;
  line-height: 30px;
  font-family: Verdana;
  font-size: 20px;
  color: #FFF;
}

.preloader .preloader-box>div:nth-child(1) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 0ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(2) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 75ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(3) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 150ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(4) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 225ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(5) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 300ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(6) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 375ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(7) {
  background: #3366FF;
  margin-right: 15px;
  animation: movement 600ms ease 450ms infinite alternate;
}

.preloader .preloader-box>div:nth-child(8) {
  background: #3366FF;
  animation: movement 600ms ease 525ms infinite alternate;
}

@keyframes movement {
  from {
    transform: scale(1.0) translateY(0px) rotateX(0deg);
    box-shadow: 0 0 0 rgba(0, 0, 0, 0);
  }
  to {
    transform: scale(1.5) translateY(-25px) rotateX(45deg);
    box-shadow: 0 25px 40px rgba(0, 0, 0, 0.4);
    background: #3399FF;
  }
}

<div class="page-bg"></div>

<div class="preloader">
  <div class="preloader-box">
    <div>L</div>
    <div>O</div>
    <div>A</div>
    <div>D</div>
    <div>I</div>
    <div>N</div>
    <div>G</div>
  </div>
</div>


问:
ASP .Net Core Model Binding To A Collection
I'm new to ASP .Net Core 1.0 and I'm trying to bind a view to a model that contains a collection of same object. The main model is a questionnaire and may contain any count of questions with different types. But my problem is inside the ActionResult method, my List property is always null during post.

This is the form:

```<code><form id="mainForm" asp-controller="Default" asp-action="PersonalDetails" asp-route-sectionTypeCode="@Model.SectionTypeCode" asp-route-sectionNumber="@Model.SectionNumber" method="post" asp-anti-forgery="false">
        @{
            for (Int32 i = 0; i < Model.Questions.Count; i++)
            {
                string spacerValue = "";
                if (i == Model.Questions.Count - 1)
                {
                    spacerValue = "extraLargeSpacerBottom";
                }
                <div class="form-group @spacerValue">
                    <label>@Model.Questions[i].QuestionTitle</label>
                    @{
                        switch (Model.Questions[i].QuestionTypeCode)
                        {
                            case 1:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="text">
                                break;

                            case 2:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;

                            case 3:
                                <select asp-for="Questions[i].Value" class="form-control appInput" asp-items="Model.Questions[i].QuestionOptions"></select>
                                break;

                            case 4:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="date">
                                break;

                            case 5:
                                <div>
                                    <label class="radio-inline">
                                        <input asp-for="Questions[i].Value" value="true" type="radio"><span class="radioSpace">Yes</span>
                                    </label>
                                    <label class="radio-inline">
                                        <input asp-for="Questions[i].Value" value="false" type="radio"><span class="radioSpace">No</span>
                                    </label>
                                </div>
                                break;

                            case 6:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;
                        }
                    }
                </div>
            }
        }
    </form>
</code>```

And this is the _Question class:

```<code>public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }

    public dynamic Value { get; set; }
    #endregion

    public _Question() { }

    public _Question(Int32 questionTypeCode, string questionTitle, string questionHelp, List<SelectListItem> options = null)
    {
        QuestionTypeCode = questionTypeCode;
        QuestionTitle = questionTitle;
        QuestionHelp = questionHelp;
        QuestionOptions = options;

        switch (questionTypeCode)
        {
            case 1:
                ValidationMessage = "Please enter a text value";
                break;

            case 2:
                ValidationMessage = "Please enter a numeric value";
                break;

            case 4:
                ValidationMessage = "Please enter a date value";
                break;

            case 6:
                ValidationMessage = "Please enter a currency value";
                break;
        }
    }
}
</code>```

The main model contains a list of _Question objects that are being generated at runtime from a database.

Can anybody please help me about my null result?

答:
Model binding does not work with private set. Setter must be public so that MVC can set the values in the postback

```<code>public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }
    //...
}
</code>```

You can find more details about the model binding here

Body:
I'm new to ASP .Net Core 1.0 and I'm trying to bind a view to a model that contains a collection of same object. The main model is a questionnaire and may contain any count of questions with different types. But my problem is inside the ActionResult method, my List property is always null during post.

This is the form:

<form id="mainForm" asp-controller="Default" asp-action="PersonalDetails" asp-route-sectionTypeCode="@Model.SectionTypeCode" asp-route-sectionNumber="@Model.SectionNumber" method="post" asp-anti-forgery="false">
        @{
            for (Int32 i = 0; i < Model.Questions.Count; i++)
            {
                string spacerValue = "";
                if (i == Model.Questions.Count - 1)
                {
                    spacerValue = "extraLargeSpacerBottom";
                }

                    @Model.Questions[i].QuestionTitle
                    @{
                        switch (Model.Questions[i].QuestionTypeCode)
                        {
                            case 1:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="text">
                                break;

                            case 2:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;

                            case 3:
                                <select asp-for="Questions[i].Value" class="form-control appInput" asp-items="Model.Questions[i].QuestionOptions"></select>
                                break;

                            case 4:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="date">
                                break;

                            case 5:

                                        <input asp-for="Questions[i].Value" value="true" type="radio">Yes

                                        <input asp-for="Questions[i].Value" value="false" type="radio">No

                                break;

                            case 6:
                                <input asp-for="Questions[i].Value" class="form-control appInput" type="number">
                                break;
                        }
                    }

            }
        }
    </form>

And this is the _Question class:

public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }

    public dynamic Value { get; set; }
    #endregion

    public _Question() { }

    public _Question(Int32 questionTypeCode, string questionTitle, string questionHelp, List<SelectListItem> options = null)
    {
        QuestionTypeCode = questionTypeCode;
        QuestionTitle = questionTitle;
        QuestionHelp = questionHelp;
        QuestionOptions = options;

        switch (questionTypeCode)
        {
            case 1:
                ValidationMessage = "Please enter a text value";
                break;

            case 2:
                ValidationMessage = "Please enter a numeric value";
                break;

            case 4:
                ValidationMessage = "Please enter a date value";
                break;

            case 6:
                ValidationMessage = "Please enter a currency value";
                break;
        }
    }
}

The main model contains a list of _Question objects that are being generated at runtime from a database.

Can anybody please help me about my null result?

Body:
Model binding does not work with private set. Setter must be public so that MVC can set the values in the postback

public class _Question
{
    #region Properties
    public string QuestionTitle { get; private set; }
    public string QuestionHelp { get; private set; }
    public Int32 QuestionTypeCode { get; private set; }
    public string ValidationMessage { get; private set; }
    public List<SelectListItem> QuestionOptions { get; private set; }
    //...
}

You can find more details about the model binding here


问:
If condition inside of map() React
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

```<code>{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}
</code>```

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

```<code>render() {
  return (
    <div>
      <div className="box">
        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (
              <h1>hejsan</h1>
            )}
          )}
      </div>
    </div>
  )
}
</code>```

But it doesn't work..! Here's the error:

I appreciate all the help I can get!

答:
There are two syntax errors in your ternary conditional:

remove the keyword if. Check the correct syntax here.

You are missing a parenthesis in your code. If you format it like this:

```<code>{(this.props.schema.collectionName.length < 0 ?
   (<Expandable></Expandable>)
   : (<h1>hejsan</h1>)
)}
</code>```

Hope this works!

Title: If condition inside of map() React

Body:
I have a map()function that needs to display views based on a condition. I've looked at the React documentation on how to write conditions and this is how you can write a condition:

{if (loggedIn) ? (
  // Hello!
) : (
  // ByeBye!
)}

Here's the link: https://facebook.github.io/react/docs/conditional-rendering.html#inline-if-else-with-conditional-operator

So, I tried to take that knowledge and implemant it in my React app. And it turned out like this:

render() {
  return (

        {this.props.collection.ids
          .filter(
            id =>
              // note: this is only passed when in top level of document
              this.props.collection.documents[id][
                this.props.schema.foreignKey
              ] === this.props.parentDocumentId
          )
          .map(id =>
            {if (this.props.schema.collectionName.length < 0 ? (

              <Expandable>
                <ObjectDisplay
                  key={id}
                  parentDocumentId={id}
                  schema={schema[this.props.schema.collectionName]}
                  value={this.props.collection.documents[id]}
                />
              </Expandable>

            ) : (

hejsan

            )}
          )}

  )
}

But it doesn't work..! Here's the error:

I appreciate all the help I can get!

Body:
There are two syntax errors in your ternary conditional:

remove the keyword if. Check the correct syntax here.

You are missing a parenthesis in your code. If you format it like this:

{(this.props.schema.collectionName.length < 0 ?
   (<Expandable></Expandable>)
   : (<h1>hejsan</h1>)
)}

Hope this works!


问:
Django string to date format
I want to convert my string date to django date format. I tried a method. but did not work.

```<code>date = datetime.datetime.strptime(request.POST.get('date'),"Y-mm-dd").date()
</code>```

I got this error.

```<code>time data '2014-04-07' does not match format 'Y-mm-dd'
</code>```

what 's wrong in my code.

答:
django.utils.dateparse.parse_date function will return None if given date not in %Y-%m-%d format

I have not found a function in django source code to parse string by DATE_INPUT_FORMATS. So I wrote a custom helper function for that and
 I have added to here for help others.

```<code>from datetime import datetime
from django.utils.formats import get_format

def parse_date(date_str):
    """Parse date from string by DATE_INPUT_FORMATS of current language"""
    for item in get_format('DATE_INPUT_FORMATS'):
        try:
            return datetime.strptime(date_str, item).date()
        except (ValueError, TypeError):
            continue

    return None
</code>```

Title: Django string to date format

Body:
I want to convert my string date to django date format. I tried a method. but did not work.

date = datetime.datetime.strptime(request.POST.get('date'),"Y-mm-dd").date()

I got this error.

time data '2014-04-07' does not match format 'Y-mm-dd'

what 's wrong in my code.

Body:
django.utils.dateparse.parse_date function will return None if given date not in %Y-%m-%d format

I have not found a function in django source code to parse string by DATE_INPUT_FORMATS. So I wrote a custom helper function for that and
 I have added to here for help others.

from datetime import datetime
from django.utils.formats import get_format

def parse_date(date_str):
    """Parse date from string by DATE_INPUT_FORMATS of current language"""
    for item in get_format('DATE_INPUT_FORMATS'):
        try:
            return datetime.strptime(date_str, item).date()
        except (ValueError, TypeError):
            continue

    return None


问:
foreign table, foreign sever and foreign data wrapper: how they communicate
When the postgreSQL database server gets the query, how does it find the related foreign data wrapper to resolve the query? What does exactly foreign server do?

I want to know the sequence of messages that happens when database server gets a query on foreign table?

答:
Let's clarify the terminology.

A foreign data wrapper is an object that wraps code for communication with an external data source.

A foreign server is an object that specifies how to locate a certain external data source. It belongs to a foreign data wrapper.

A user mapping is an object that contains credentials to authenticate with an external data source. It belongs to a foreign server and a database user.

A foreign table is an object that describes an object containing data in an external data source. It belongs to a foreign server.

So when a user tries to access a foreign table, PostgreSQL knows how to reach the data source (via the foreign server that belongs to the table), how to authenticate (via the user mapping) and what functions to use to perform this connection and exchange data (via the foreign data wrapper).

Most foreign data wrappers don't require a connection to the remote data souce for query planning, but when data are fetched or sent, a connection will be established.

Depending on the foreign data wrapper, such a connection is closed when the query is done or cached for the lifetime of the database session.


问:
Need to implement bulk PDF extraction using Tesseract API
I have large numbers PDF document, from which I need to extract text. The extracted text I use for further processing. I did this for a small subset of documents using Tesseract API in a linear approach and I get the required output. However, this takes a very long time when I have a large number of documents.

I tried to use the Hadoop environment processing capabilities (Map-Reduce) and storage (HDFS) for solving this issue. However, I am facing problem to implement Tesseract API into the Hadoop (Map-Reduce) approach. As Teserract converts the files into intermediate image files, I am confused as to how intermediate result Image files of Tesseract-API-process can be handled inside HDFS.

I have searched and unsuccesfully tried a few options earlier like:

I have extracted text from PDF by extending FileInputFormat class into my own PdfInputFormat class using Hadoop-Map-Reduce, for this i used Apache PDFBox to extract text from pdf, but when it comes to scanned-pdf's which contains image, this solution does not give me the required results.

I found few answers on the same topic stating to use -Fuse and that will help or one should generate image files locally and than upload those into hdfs for further processing. Not sure if this is the correct approach.

Would like to know approaches around this.

答:
This is an approach found to process multiple pdf's to extract text using the power of the Hadoop Framework, and then use this text for further processing:

Put all the PDFs to be converted to text in one folder.

Create one text file per pdf to contain the path to the pdf. e.g. if I have 10 pdfs to convert, then I have 10 text files generated, each containing the unique path to the respective pdf.

These text files are given as input in the map-reduce program

Because input file size is very small only 1 input split is generated by framework for 1 input. e.g if I have 10 pdfs as input, then framework will generate 10 input-split.

From each Input-split one line(record) is read by Record-Reader and  passed to one mapper as a value. So if there are 10 records(line==File  Path) in input text file , 10 times mapper will run. As I have one  record per input-split so one mapper-reducer is assigned to do task for that input-split.

As I have 10 input-split 10 mapper will run, parallel.

Inside the Mapper ghost-script generates images, passing the file name from Mapper value attribute. The image is converted to text using Tesseract inside the mapper itself to get the text of each pdf. This is the output.

This is passed to the reducer to do other analytics work as required.

This is the current solution. Would like feedback on this.


问:
SugarmCRM REST API always returns "null"
I'm trying to test out the SugarCRM REST API, running latest version of CE (6.0.1). It seems that whenever I do a query, the API returns "null", nothing else. If I omit the parameters, then the API returns the API description (which the documentation says it should).

I'm trying to perform a login, passing as parameter the method (login), input_type and response_type (json) and rest_data (JSON encoded parameters). The following code does the query:

```<code> $api_target = "http://example.com/sugarcrm/service/v2/rest.php";

 $parameters = json_encode(array(
    "user_auth" => array(
        "user_name" => "admin",
        "password" => md5("adminpassword"),
    ),
    "application_name" => "Test",
    "name_value_list" => array(),
 ));
 $postData = http_build_query(array(
    "method" => "login",
    "input_type" => "json",
    "response_type" => "json",
    "rest_data" => $parameters
 ));
 echo $parameters . "\n";
 echo $postData . "\n";

 echo file_get_contents($api_target, false,
    stream_context_create(array(
        "http" => array(
            "method" => "POST",
            "header" => "Content-Type: application/x-www-form-urlencoded\r\n",
            "content" => $postData
        )
    ))) . "\n";
</code>```

I've tried different variations of parameters and using username instead of user_name, and all provide the same result, just a response "null" and that's it.

答: Try setting input_type and response_type to JSON (capitals). If it doesn't work, go to Sugar installation, edit config.php entry under logger => level and make it debug instead of fatal and see if it says about any errors.

Body:
I'm trying to test out the SugarCRM REST API, running latest version of CE (6.0.1). It seems that whenever I do a query, the API returns "null", nothing else. If I omit the parameters, then the API returns the API description (which the documentation says it should).

I'm trying to perform a login, passing as parameter the method (login), input_type and response_type (json) and rest_data (JSON encoded parameters). The following code does the query:

 $api_target = "http://example.com/sugarcrm/service/v2/rest.php";

 $parameters = json_encode(array(
    "user_auth" => array(
        "user_name" => "admin",
        "password" => md5("adminpassword"),
    ),
    "application_name" => "Test",
    "name_value_list" => array(),
 ));
 $postData = http_build_query(array(
    "method" => "login",
    "input_type" => "json",
    "response_type" => "json",
    "rest_data" => $parameters
 ));
 echo $parameters . "\n";
 echo $postData . "\n";

 echo file_get_contents($api_target, false,
    stream_context_create(array(
        "http" => array(
            "method" => "POST",
            "header" => "Content-Type: application/x-www-form-urlencoded\r\n",
            "content" => $postData
        )
    ))) . "\n";

I've tried different variations of parameters and using username instead of user_name, and all provide the same result, just a response "null" and that's it.


问:
How to get rid of V677: custom declaration of a standard type warning
We are using a PVS Studio (free variant for opensource projects) in conjunction with travis-ci and it for some reason spawns errors for files located in /usr/local/clang-3.5.0/lib/clang/3.5.0/include:

```
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:58:1: warning: V677 Custom declaration of a standard 'size_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:86:1: warning: V677 Custom declaration of a standard 'wchar_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stdarg.h:30:1: warning: V677 Custom declaration of a standard 'va_list' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:47:1: warning: V677 Custom declaration of a standard 'ptrdiff_t' type. The declaration from system header files should be used instead.
```

This location looks like an example of “system” headers for non-standard compiler and is far away from the project root (which AFAIR is somewhere in /home: standard travis location). Script run uses latest version from https://www.viva64.com/en/pvs-studio-download-linux/, latest run at “Mon Jul 3 20:13:42 UTC 2017” (unfortunately, used version is not saved).

答:
If the compiler is located in some unusual place, it is recommended to add a new path to the analyzer exceptions, so that you can see in the report only the warnings for the code of your own projects.

pvs-studio-analyzer analyze ... -e /path/to/exclude-path ...

or

pvs-studio ... --exclude-path /path/to/exclude-path ...

Body:
We are using a PVS Studio (free variant for opensource projects) in conjunction with travis-ci and it for some reason spawns errors for files located in /usr/local/clang-3.5.0/lib/clang/3.5.0/include:

/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:58:1: warning: V677 Custom declaration of a standard 'size_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:86:1: warning: V677 Custom declaration of a standard 'wchar_t' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stdarg.h:30:1: warning: V677 Custom declaration of a standard 'va_list' type. The declaration from system header files should be used instead.
/usr/local/clang-3.5.0/lib/clang/3.5.0/include/stddef.h:47:1: warning: V677 Custom declaration of a standard 'ptrdiff_t' type. The declaration from system header files should be used instead.

This location looks like an example of “system” headers for non-standard compiler and is far away from the project root (which AFAIR is somewhere in /home: standard travis location). Script run uses latest version from https://www.viva64.com/en/pvs-studio-download-linux/, latest run at “Mon Jul 3 20:13:42 UTC 2017” (unfortunately, used version is not saved).


问:
swift: setting back button image in nav bar
I'm trying to set the back button image in nav bar in my controller, here's my code in viewDidLoad():

```<code>        var backImg: UIImage? = UIImage(named: "back_btn.png")
    println(backImg)
    if var back_img = backImg  {
        println("GET IT")
        println(back_img)
        println(UIControlState.Normal)
        println(UIBarMetrics.Default)
    self.navigationController.navigationBar.backItem.backBarButtonItem.setBackButtonBackgroundImage(back_img, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
    }
</code>```

I tried to put them to viewWillLoad, but getting the same error

Console with error message:

```<code><UIImage: 0x7ff37bd85750>
GET IT
<UIImage: 0x7ff37bd85750>
VSC14UIControlState (has 1 child)
(Enum Value)
fatal error: unexpectedly found nil while unwrapping an Optional value
</code>```

I don't know which part went wrong. Seems like the back_img is not nil, but I got error saying it's nil

Thanks!

答:
In Swift 3.0 + put below code in appdelegate didFinishLaunchingWithOptions method, it will work perfectly

```<code>let backImage = UIImage(named: "BackNavigation")?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)
</code>```

Or for Swift 4.0 +

```<code>let backImage = UIImage(named: "back-icon").withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -80.0), for: .default)
</code>```

The last line will remove the title of Navigation Back Button if you don't want to remove title then just remove last line

Body:
I'm trying to set the back button image in nav bar in my controller, here's my code in viewDidLoad():

        var backImg: UIImage? = UIImage(named: "back_btn.png")
    println(backImg)
    if var back_img = backImg  {
        println("GET IT")
        println(back_img)
        println(UIControlState.Normal)
        println(UIBarMetrics.Default)
    self.navigationController.navigationBar.backItem.backBarButtonItem.setBackButtonBackgroundImage(back_img, forState: UIControlState.Normal, barMetrics: UIBarMetrics.Default)
    }

I tried to put them to viewWillLoad, but getting the same error

Console with error message:

<UIImage: 0x7ff37bd85750>
GET IT
<UIImage: 0x7ff37bd85750>
VSC14UIControlState (has 1 child)
(Enum Value)
fatal error: unexpectedly found nil while unwrapping an Optional value

I don't know which part went wrong. Seems like the back_img is not nil, but I got error saying it's nil

Thanks!

Body:
In Swift 3.0 + put below code in appdelegate didFinishLaunchingWithOptions method, it will work perfectly

let backImage = UIImage(named: "BackNavigation")?.withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)

Or for Swift 4.0 +

let backImage = UIImage(named: "back-icon").withRenderingMode(.alwaysOriginal)
UINavigationBar.appearance().backIndicatorImage = backImage
UINavigationBar.appearance().backIndicatorTransitionMaskImage = backImage
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffset(horizontal: 0, vertical: -80.0), for: .default)

The last line will remove the title of Navigation Back Button if you don't want to remove title then just remove last line

ContentLicense: CC BY-SA 4.0


问:
How can i edit my code so that the exceptions while decryption can end
Exception Occuring:

System.Security.Cryptography.CryptographicException' occurred in
  mscorlib.dll Additional details:: Length of the data to decrypt is
  invalid.

```<code>public string Encrypt(string toEncrypt, bool useHashing)
    {
        toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new System.Configuration.AppSettingsReader();
        // Get the key from config file

        //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        //string key = UTF8Encoding.UTF8.GetString(keyArray);
        ////System.Windows.Forms.MessageBox.Show(key);
        ////If hashing use get hashcode regards to your key

        //keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        try
        {
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;
            iv = tdes.IV;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            //transform the specified region of bytes array to resultArray
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();

            //Return the encrypted data into unreadable string format
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        catch (Exception  ae)
        {
            MessageBox.Show(ae.Message);
            return ae.Message;
        }

        }
public string Decrypt(string cipherString, bool useHashing)
    {
        //get the byte code of the string

        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(cipherString);

        System.Configuration.AppSettingsReader settingsReader = new System.Configuration.AppSettingsReader();
        //Get your key from config file to open the lock!
        //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        string key = UTF8Encoding.UTF8.GetString(keyArray);
        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        tdes.IV=iv;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor

        //string s=resultArray.ToString("X2");

        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }
</code>```

答:
Your Encrypt() method returns the encrypted bytes converted to a Base64 string.  Your Decrypt() method tries to decrypt the Base64 string directly:

```<code>byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(cipherString);
</code>```

Instead you need to convert the Base64 string back to bytes using a Base64 conversion:

```<code>byte[] toEncryptArray = Convert.FromBase64String(cipherString);
</code>```

Body:
Exception Occuring:

System.Security.Cryptography.CryptographicException' occurred in
  mscorlib.dll Additional details:: Length of the data to decrypt is
  invalid.

public string Encrypt(string toEncrypt, bool useHashing)
    {
        toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);

        System.Configuration.AppSettingsReader settingsReader = new System.Configuration.AppSettingsReader();
        // Get the key from config file

        //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        //string key = UTF8Encoding.UTF8.GetString(keyArray);
        ////System.Windows.Forms.MessageBox.Show(key);
        ////If hashing use get hashcode regards to your key

        //keyArray = UTF8Encoding.UTF8.GetBytes(key);

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        try
        {
            tdes.Key = keyArray;
            //mode of operation. there are other 4 modes. We choose ECB(Electronic code Book)
            tdes.Mode = CipherMode.ECB;
            //padding mode(if any extra byte added)
            tdes.Padding = PaddingMode.PKCS7;
            iv = tdes.IV;
            ICryptoTransform cTransform = tdes.CreateEncryptor();
            //transform the specified region of bytes array to resultArray
            byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
            //Release resources held by TripleDes Encryptor
            tdes.Clear();

            //Return the encrypted data into unreadable string format
            return Convert.ToBase64String(resultArray, 0, resultArray.Length);
        }
        catch (Exception  ae)
        {
            MessageBox.Show(ae.Message);
            return ae.Message;
        }

        }
public string Decrypt(string cipherString, bool useHashing)
    {
        //get the byte code of the string

        byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(cipherString);

        System.Configuration.AppSettingsReader settingsReader = new System.Configuration.AppSettingsReader();
        //Get your key from config file to open the lock!
        //string key = (string)settingsReader.GetValue("SecurityKey", typeof(String));
        string key = UTF8Encoding.UTF8.GetString(keyArray);
        if (useHashing)
        {
            //if hashing was used get the hash code with regards to your key
            MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
            keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
            //release any resource held by the MD5CryptoServiceProvider

            hashmd5.Clear();
        }
        else
        {
            //if hashing was not implemented get the byte code of the key
            keyArray = UTF8Encoding.UTF8.GetBytes(key);
        }

        TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
        //set the secret key for the tripleDES algorithm
        tdes.Key = keyArray;
        tdes.IV=iv;
        //mode of operation. there are other 4 modes.
        //We choose ECB(Electronic code Book)

        tdes.Mode = CipherMode.ECB;
        //padding mode(if any extra byte added)
        tdes.Padding = PaddingMode.PKCS7;

        ICryptoTransform cTransform = tdes.CreateDecryptor();
        byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
        //Release resources held by TripleDes Encryptor

        //string s=resultArray.ToString("X2");

        tdes.Clear();
        //return the Clear decrypted TEXT
        return UTF8Encoding.UTF8.GetString(resultArray);
    }

Body:
Your Encrypt() method returns the encrypted bytes converted to a Base64 string.  Your Decrypt() method tries to decrypt the Base64 string directly:

byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(cipherString);

Instead you need to convert the Base64 string back to bytes using a Base64 conversion:

byte[] toEncryptArray = Convert.FromBase64String(cipherString);


问:
How do you deploy Angular apps?
How do you deploy Angular apps once they reach the production phase?

All the guides I've seen so far (even on angular.io) are counting on a lite-server for serving and browserSync to reflect changes - but when you finish with development, how can you publish the app?

Do I import all the compiled .js files on the index.html page or do I minify them using gulp? Will they work? Do I need SystemJS at all in the production version?

答:
Deploying Angular 2 in azure is easy

Run ng build --prod , which will generate a dist folder with everything bundled inside few files including index.html.

Create a resource group and a web app inside it.

Place your dist folders files using FTP. In azure it will look for index.html to the run the application.

That's it. Your app is running !

Title: How do you deploy Angular apps?


问:
MMORPG protocol encryption
Anyone know what the trend is with MMORPG developers encryption their client/server protocols these days?

The pro's and con's are as follows.

Encrypting protocol:

protects trade secrets regarding client/server protocol to a degree?

Botting isn't stopped, it is only changed because people will create bots which read screen states and trigger mouse+keyboard events will then be developed, merely mitigating the development of bots as opposed to stopping them in anyway. Still though bot development is less in supply somewhat, but the demand is still there, they merely get higher bids on rentacoder.com

Regular plain text:

more advanced bots since the developers are able to inject their own datagrams into the client/server protocol. (ie: running through walls, teleporting... which the server side has to now check, which in turn leads to a development contest between out patching exploits via injection (time consuming)

答:
It's pretty irrelevant. I imagine the encrypt the metadata such as the login information, and session information, but then send the gameplay mechanics data in the clear. After all, the server cannot trust the client anyway (not to have been hacked).

Most hack bots will hook into the running game process and poke around with its memory anyway, which is utterly undetectable - they often put in some signature recognition which attempts to detect known hackbots running in memory, but this is essentially useless otherwise.

Another possible technique for spotting hackbots is to spot gameplay patterns from known ones.

Encrypting the data does nothing, as hackbots attack the client, in-memory.

OwnerDisplayName: Zombies

Title: MMORPG protocol encryption

OwnerDisplayName: MarkR


问:
Grid of Checkboxes in WPF
I have a WPF UserControl's datacontext tied to a class like this:

```<code>public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}
</code>```

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

答:
It's not clear if you're expecting each inner List to be the same size but if they are you can use a simple setup. Using nested ItemsControls with single row/column UniformGrids will give you an even distribution and automatically handle collections of any size without needing to setup Row and Column Definitions like with Grid:</p>

```<code><ItemsControl ItemsSource="{Binding Checkboxes}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <ItemsControl ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding}"/>
          </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsPanelTemplate>
          <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
      </ItemsControl>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <UniformGrid Columns="1"/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>
</code>```

Title: Grid of Checkboxes in WPF

Body:
I have a WPF UserControl's datacontext tied to a class like this:

public class CheckBoxGridViewModel
{
  public List<List<bool>> Checkboxes {get; set;}
}

I want it to display a grid of checkboxes. I'm assuming I can use an Itemscontrol, but don't know exactly how to do it with a dynamic set of columns for each row.

This question seems to answer mine, except the answer didn't give the example and I can't figure how to write it out.

So the question is, how would I write the xaml to display the checkboxes of the Checkboxes property so that they are lined up in a nice grid?

The outer list would be each row and the inner list would be each column of the row.

Body:
It's not clear if you're expecting each inner List to be the same size but if they are you can use a simple setup. Using nested ItemsControls with single row/column UniformGrids will give you an even distribution and automatically handle collections of any size without needing to setup Row and Column Definitions like with Grid:

<ItemsControl ItemsSource="{Binding Checkboxes}">
  <ItemsControl.ItemTemplate>
    <DataTemplate>
      <ItemsControl ItemsSource="{Binding}">
        <ItemsControl.ItemTemplate>
          <DataTemplate>
            <CheckBox IsChecked="{Binding}"/>
          </DataTemplate>
        </ItemsControl.ItemTemplate>
        <ItemsPanelTemplate>
          <UniformGrid Rows="1"/>
        </ItemsPanelTemplate>
      </ItemsControl>
    </DataTemplate>
  </ItemsControl.ItemTemplate>
  <ItemsControl.ItemsPanel>
    <ItemsPanelTemplate>
      <UniformGrid Columns="1"/>
    </ItemsPanelTemplate>
  </ItemsControl.ItemsPanel>
</ItemsControl>


问:
NFC tag not detected on iOS11 iphone 7
I have downloaded sample app from WWDC and tried all the steps including provisioning profile and setting up NFC capabilities and adding to project entitlements file. I can successfully ran the app and the sheet successfully appear

But When I tapped on one of my NFC tag. Nothing happens. How can i go further testing for NFC and may I know which one tag do I need to use to be detectable.
Please see my attached NFC tag which I am using currently.

答: I use Sony Xperia NFC Xperia SmartTags, it reads without problems:

Title: NFC tag not detected on iOS11 iphone 7


问:
jQuery and jinja2 .data("") returning undefined
the no of items are displayed along with an edit button with each item on clicking edit button the data of button is retrieved in jQuery function but I am getting undefined not the data-id

```<code><div>
{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id  btn_id="btn"|concatenate:stock.id %}
    <div id="{{ id }}">
    {{ stock.entry_date}}
    {{ stock.supplier }}
    {{ stock.amount }}
    {{ stock.remaining }}
        <button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>
    <hr>
    </div>
    <br>
    {% endwith %}
{% endfor %}
</div>
</code>```

instead of {{stock.id}} I also tried passing other string  but still got undefined

```<code><script type="text/javascript">
     function display_popup() {
         var name = $(this).data("id");
            window.alert(name);
    }

</script>
</code>```

instead of .data() also tried other like .text() .Val but got nothing

答:
As of current code; this in the display_popup function refers to window object thus its not returning the desired value.

Pass current element context this in the inline click handler

```<code><button onclick="display_popup(this)">
</code>```

Script, Accept it as parameter and use it to get data

```<code> function display_popup(elem) {
     var name = $(elem).data("id");
     window.alert(name);
}
</code>```

However, I would recommend you to use unobtrusive event handler. Assign a common class to button.

```<code><button class="edit" data-id="{{stock.id}}"  >edit</button>
</code>```

script

```<code>$(function(){
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work
});
</code>```

$(function() {
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work

  function display_popup() {
    var name = $(this).data("id");
    window.alert(name);
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="edit" type="submit" data-id="1">edit</button></code>```

Set the context of function with current element using .bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

function display_popup() {
  var name = $(this).data("id");
  window.alert(name);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="submit" data-id="1" onclick="display_popup.bind(this)()">edit</button></code>```

Body:
the no of items are displayed along with an edit button with each item on clicking edit button the data of button is retrieved in jQuery function but I am getting undefined not the data-id

{% for stock in part_temp.part_stock_set.all %}
    {% with id="list"|concatenate:stock.id  btn_id="btn"|concatenate:stock.id %}

    {{ stock.entry_date}}
    {{ stock.supplier }}
    {{ stock.amount }}
    {{ stock.remaining }}
        <button id="{{ btn_id }}" type="submit" data-id="{{stock.id}}" onclick="display_popup()" style="position: absolute; right:0;" >edit</button>

    {% endwith %}
{% endfor %}

instead of {{stock.id}} I also tried passing other string  but still got undefined

instead of .data() also tried other like .text() .Val but got nothing

Body:
As of current code; this in the display_popup function refers to window object thus its not returning the desired value.

Pass current element context this in the inline click handler

<button onclick="display_popup(this)">

Script, Accept it as parameter and use it to get data

 function display_popup(elem) {
     var name = $(elem).data("id");
     window.alert(name);
}

However, I would recommend you to use unobtrusive event handler. Assign a common class to button.

<button class="edit" data-id="{{stock.id}}"  >edit</button>

script

$(function(){
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work
});

$(function() {
  $('.edit').on('click', display_popup); //this will set as context so you existing method will work

  function display_popup() {
    var name = $(this).data("id");
    window.alert(name);
  }

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="edit" type="submit" data-id="1">edit</button>

Set the context of function with current element using .bind()

The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

function display_popup() {
  var name = $(this).data("id");
  window.alert(name);
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<button type="submit" data-id="1" onclick="display_popup.bind(this)()">edit</button>


问:
Get top(N) or single value using Bql
How is it possible to use a PXSelect statement so that it retrieves the Top(N) or the first value for a particular DAC.

Let's say that I have a table with a sequence number and I want to obtain the record with the largest sequence number. How can I do that?

Of course, I would like that for performance reasons, SQL just sends 1 record.

答:
You can use SelectWindowed in place of Select on your PXSelect to get the top N records. In the example below it will get the Top 1. If you change the totalRows value of 1 to 5 it would get the top 5 (except you would have to loop or get the PXResultSet to use all 5 records retrieved.)

Top 1 Example:

```<code>DiscountSequence firstRow = PXSelect<DiscountSequence,
    Where<DiscountSequence.discountID, Equal<Required<DiscountSequence.discountID>>>
        >.SelectWindowed(this, 0, 1, someDiscountID);
</code>```

Top 5 Example:

```<code>foreach (DiscountSequence row in PXSelect<DiscountSequence,
    Where<DiscountSequence.discountID, Equal<Required<DiscountSequence.discountID>>>
        >.SelectWindowed(this, 0, 5, someDiscountID))
{
    //5 rows returned
}
</code>```

Title: Get top(N) or single value using Bql

Body:
You can use SelectWindowed in place of Select on your PXSelect to get the top N records. In the example below it will get the Top 1. If you change the totalRows value of 1 to 5 it would get the top 5 (except you would have to loop or get the PXResultSet to use all 5 records retrieved.)

Top 1 Example:

DiscountSequence firstRow = PXSelect<DiscountSequence,
    Where<DiscountSequence.discountID, Equal<Required<DiscountSequence.discountID>>>
        >.SelectWindowed(this, 0, 1, someDiscountID);

Top 5 Example:

foreach (DiscountSequence row in PXSelect<DiscountSequence,
    Where<DiscountSequence.discountID, Equal<Required<DiscountSequence.discountID>>>
        >.SelectWindowed(this, 0, 5, someDiscountID))
{
    //5 rows returned
}


问:
Exporting aws management console settings
When using the aws web management console it's very handy to add favourite services and switch between different roles. However when using a different browser or different computer with the same login it's not showing up.

How to export these settings so they can be imported or synced between computers?

答: What you are asking is not natively supported by AWS. I use GreaseMonkey for a similar need. It also has Chrome extension.</p>