问:
Alpine container not able to resolve hostname
I have a StatefulSet Kubernetes deployment with 2 worker nodes. I was able to bring the containers up on those 2 nodes using a headless service hence the nodes have hostname as

abc-0.abc.default.svc.cluster.local

abc-1.abc.default.svc.cluster.local

The problem is that I am not able to ping abc-0 from abc-1 and in the opposite direction using the hostname. If I use IP addresses then everything works fine.

There were issues related the DNS resolution with Alpine Linux at some point(https://github.com/gliderlabs/docker-alpine/issues/8#issuecomment-172594887) but seems it was fixed in Alpine Linux 3.4.

What would be the good way to verify that the problem I am facing is not because of the Linux but instead some misconfiguration in Kube-DNS or something?

答:
I assume you mean ping abc-0, did you try ping abc-0.abc ?
The resolv.conf is not enriched with all the statefull service entries search domains, just the namespace one, so when you try to access by only abc-0 it actually resolves to abc-0.default.svc.cluster.local


来源: stackexchange

问:
navigator.online show iframe and when offline show image
Need help to display a cached image (service worker) when no internet connection, in place of my iframe - herewith my not working attempt in fiddle

```<code><https://jsfiddle.net/hrax5doq/10/>
</code>```

In fiddle I used an external image location just as an example but how do I use a cached imaged url in my code

答:
Like this :

if (window.navigator.onLine) {
d.innerHTML = '';
} else {
 d.innerHTML = '';
}```
<pre class="snippet-code-css lang-css prettyprint-override"><code>iframe {
  width: 100%;
  height: 600px;
  scrolling: no;
  marginheight: 0;
  marginwidth: 0;
  frameborder: 0;
  border: 0;
}</code>```

```

ContentLicense: CC BY-SA 3.0

Body:
Need help to display a cached image (service worker) when no internet connection, in place of my iframe - herewith my not working attempt in fiddle

<https://jsfiddle.net/hrax5doq/10/>

In fiddle I used an external image location just as an example but how do I use a cached imaged url in my code

Body:
Like this :

if (window.navigator.onLine) {
d.innerHTML = '<iframe id="iframe" src="https://maps.google.it/maps?q=Inprint Printers,25+Watermeyer+st,eMalahleni,Mpumalanga,1035&output=embed" allowfullscreen></iframe>';
} else {
 d.innerHTML = '<img scr="https://upload.wikimedia.org/wikipedia/commons/2/23/User-Chaza93-Offline.png">';
}

iframe {
  width: 100%;
  height: 600px;
  scrolling: no;
  marginheight: 0;
  marginwidth: 0;
  frameborder: 0;
  border: 0;
}

<div id="d"></div>


问:
Geocoding gem for Mongoid
Is there a geocoding gem similar to acts_as_geocodable for Mongoid? So far as I can tell all geocoding gems seem to be built for ActiveRecord. </p>

答:
Just use something like GCoder https://github.com/heycarsten/gcoder if you are using google.

If you want callbacks like acts_as_geocodable you can extend your model to use this lib.

ContentLicense: CC BY-SA 2.5

Title: Geocoding gem for Mongoid


问:
is there a way to export bash shell options to subshell?
I set bash options (e.g. shopt -e autocd) in current shell & want to export/copy this options to a newly created subshell. Is there a way to do this?

Bash Version is: GNU bash, Version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Example:

```<code>$shopt -s autocd
$shopt autocd
autocd          on
$bash
$shopt autocd
autocd          off
</code>```

答:
You can export many shell options analogous to shell variables by using the corresponding shell variable BASHOPTS which stores the shell options:

```<code>export BASHOPTS
</code>```

Here is some information of the Bash man page:

BASHOPTS:
  A colon-separated list of enabled shell options.  Each word in the list is a valid argument for the -s option to the shopt builtin command (see SHELL BUILTIN COMMANDS below).  The options appearing in BASHOPTS are those reported as on by shopt.  If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files.  This variable is read-only.

There is a closely related variable SHELLOPTS, but this only seems to work well if bash is invoked directly (e.g. via bash) rather than via sh because sh enables the POSIX mode of Bash. Here is more information on this issue.

Body:
I set bash options (e.g. shopt -e autocd) in current shell & want to export/copy this options to a newly created subshell. Is there a way to do this?

Bash Version is: GNU bash, Version 4.3.11(1)-release (x86_64-pc-linux-gnu)

Example:

$shopt -s autocd
$shopt autocd
autocd          on
$bash
$shopt autocd
autocd          off

Body:
You can export many shell options analogous to shell variables by using the corresponding shell variable BASHOPTS which stores the shell options:

export BASHOPTS

Here is some information of the Bash man page:

BASHOPTS:
  A colon-separated list of enabled shell options.  Each word in the list is a valid argument for the -s option to the shopt builtin command (see SHELL BUILTIN COMMANDS below).  The options appearing in BASHOPTS are those reported as on by shopt.  If this variable is in the environment when bash starts up, each shell option in the list will be enabled before reading any startup files.  This variable is read-only.

There is a closely related variable SHELLOPTS, but this only seems to work well if bash is invoked directly (e.g. via bash) rather than via sh because sh enables the POSIX mode of Bash. Here is more information on this issue.


问:
How to access the control directly by its formGroupName
In This form I have to access the control of formControlName="last" to show errors of it.

        <input formControlName="first" placeholder="First name">

        <input formControlName="last" placeholder="Last name">

        invalid

    <input formControlName="email" placeholder="Email">

    <button type="submit">Submit</button>

This code has thrown an error 'controls' of undefined(Bold Formatted line).
control could be accessible by form['controls'].name['controls'].last.invalid , but is there any way I could access the control directly by its formGroupName ?

Thanks in Advance

答:
Try this</p>

```<code><div *ngIf="!form.controls.name.controls.last.valid">
       Invalid last name !!
    </div>
</code>```

Body:
Try this

<div *ngIf="!form.controls.name.controls.last.valid">
       Invalid last name !!
    </div>


问:
Get the value of label corresponding to the checked value of checkbox in a row
I have been having some issues with fetching the value of label for a corresponding checked value. Now i tried with closest attribute but it didnt work and as i dont have tr and cant use it as well. Issue is i am having the checkbox and its value inside a li tag. On click of button i call a function which needs to provide me with the checked values. So i am not sure how will i be able to fetch it. Below is my code and what i have tried.

function test() {
  $('.chkName').each(function() {
    if ($(this).is(':checked')) {
      //How do i fetch the coorresponding val?
    }
  });
}
```

<pre class="lang-html prettyprint-override"><code><li class="listRow" style=" max-width:314px; min-width:314px;">
  <label>
    <input id="id1" type="checkbox" name="" checked="checked" class="chkName">
    <label>test</label>
  </label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
  <label>
    <input id="id2" type="checkbox" name="" checked="checked" class="chkName">
    <label>test1</label>
  </label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
  <label>
    <input id="id3" type="checkbox" name="" class="chkName">
    <label>test2</label>
  </label>
</li>
</code>```

答:
I would recommend to set a value on the checkbox itself.

```<code><li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test" id="id1" type="checkbox" name="" checked="checked" class="chkName">
          <label>test</label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test1" id="id2" type="checkbox" name="" checked="checked" class="chkName">
          <label>test1</label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test2" id="id3" type="checkbox" name="" class="chkName">
          <label>test2</label>
</li>
</code>```

JS:

```<code> function test()
    {
         $('.chkName').each(function()
        {
            if($(this).is(':checked'))
            {
                //How do i fetch the coorresponding val?
                console.log($(this).val())
            }
        });

    }
</code>```

Otherwise, if you really want the value of the label, use "next":

```<code> function test()
    {
         $('.chkName').each(function()
        {
            if($(this).is(':checked'))
            {
                //How do i fetch the coorresponding val?
                console.log($(this).next().text())
            }
        });

    }
</code>```

Body:
I have been having some issues with fetching the value of label for a corresponding checked value. Now i tried with closest attribute but it didnt work and as i dont have tr and cant use it as well. Issue is i am having the checkbox and its value inside a li tag. On click of button i call a function which needs to provide me with the checked values. So i am not sure how will i be able to fetch it. Below is my code and what i have tried.

function test() {
  $('.chkName').each(function() {
    if ($(this).is(':checked')) {
      //How do i fetch the coorresponding val?
    }
  });
}

    <input id="id1" type="checkbox" name="" checked="checked" class="chkName">
    test

    <input id="id2" type="checkbox" name="" checked="checked" class="chkName">
    test1

    <input id="id3" type="checkbox" name="" class="chkName">
    test2

Body:
I would recommend to set a value on the checkbox itself.

<li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test" id="id1" type="checkbox" name="" checked="checked" class="chkName">
          <label>test</label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test1" id="id2" type="checkbox" name="" checked="checked" class="chkName">
          <label>test1</label>
</li>
<li class="listRow" style=" max-width:314px; min-width:314px;">
        <input value="test2" id="id3" type="checkbox" name="" class="chkName">
          <label>test2</label>
</li>

JS:

 function test()
    {
         $('.chkName').each(function()
        {
            if($(this).is(':checked'))
            {
                //How do i fetch the coorresponding val?
                console.log($(this).val())
            }
        });

    }

Otherwise, if you really want the value of the label, use "next":

 function test()
    {
         $('.chkName').each(function()
        {
            if($(this).is(':checked'))
            {
                //How do i fetch the coorresponding val?
                console.log($(this).next().text())
            }
        });

    }


问:
Make input type file required based on condition in AngularJS
I am receiving a JSON data from backend like these

```<code>{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}
</code>```

And in the html i am populating a form by ng-repeat

```<code><tr data-ng-repeat="choice in choices track  by $index">
    <td>{{choice.number}}</td>
    <td><p>{{choice.short_text}}</p></td>
    <td><input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required></td>
    <td><input type="checkbox"  ng-model="choice.include"></td>
    <td><input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">
    </td>
</tr>
</code>```

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

答:
You can use ng-required property. ref ng-required

```<code><input type="file" id="abc{{$index}}" class="photo-upload"
       file-model="pic{{$index}}" accept="image/*"
       ng-required="choice.is_photo == true" />
</code>```

Body:
I am receiving a JSON data from backend like these

{
  "data":{
    "xyz":[
      {
        "number":"1",
        "short_text":"Vertrag unterzeichnen",
        "long_text":"Nach Vertrabsunterzeichnung Namen eintragen",
        "is_photo":false
      },
      {
        "number":"2",
        "short_text":"HR unterrichten",
        "long_text":"HR hat eigene Workflows",
        "is_photo":true
      }
    ]
  }
}

And in the html i am populating a form by ng-repeat

    {{choice.number}}

{{choice.short_text}}

    <input type="textbox" size="50" class="des-textinput" ng-model="choice.desc" required>
    <input type="checkbox"  ng-model="choice.include">
    <input type="file" id="abc{{$index}}" class="photo-upload"
               file-model="pic{{$index}}" accept="image/*">

Now I want to make the input type file required if the value of is_photo is true in the JSON I am receiving. For each row if the value if is_photo is false then it will be not required.

From the given JSON the condition will be the first input type file will be not required as first row is_photo is false, but the second one will be required as the value of is_photo is true.

How will I do that?

Body:
You can use ng-required property. ref ng-required

<input type="file" id="abc{{$index}}" class="photo-upload"
       file-model="pic{{$index}}" accept="image/*"
       ng-required="choice.is_photo == true" />


问:
Show overlay on image on mobile devices using pure JavaScript
I have a requirement where I need to show overlay on image on mobile devices whenever user touches the image. I am doing it with the code shown below:

document.getElementsByTagName('img')[0].addEventListener('touchstart', function(event){

    let elementExists = document.getElementById('wrapper');
    let Center = document.createElement('div');

    if (!elementExists) {
      let Wrapper = document.createElement('div');
      let parentElement = event.currentTarget.parentElement;
      Wrapper.classList.add('Wrapper');
      Wrapper.id = 'wrapper';

     Center.classList.add('Center');

     parentElement.appendChild(Wrapper);
     Wrapper.appendChild(Center);

      Wrapper.addEventListener('touchend', function(event){
        if (document.getElementById('wrapper')) {
            document.getElementById('wrapper').remove();
        }
      });
    }
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.col-md-6 {
        width: 375px;
        height: 211px;
        margin: 20px;
        position: relative;
    }

        .Wrapper {
        display: table;
        position: absolute;
        background-color: rgba(0, 0, 0, 0.5);
        height: 100% !important;
        width: 100%;
        text-align: center;
        z-index: 1000;
        font-family: arial;
        color: #fff;
        top: 0;
    }

    .Center {
        display: table-cell;
        vertical-align: middle;
    }</code>```

```

The above code works fine, but I have image wrapped in a tag so by default it showing me screen when user touches an image as shown below:

And because of it overlay is not displaying on mobile screen. I would require help how can I fix it.

EDIT:

I am thinking of adding touch swipe event using plain JavaScript but I am not able to do it exactly.
Please let me know if I can get any help!

答: Why not just leave out the link and just add the event listener directly to the image?</p>

Body:
I have a requirement where I need to show overlay on image on mobile devices whenever user touches the image. I am doing it with the code shown below:

document.getElementsByTagName('img')[0].addEventListener('touchstart', function(event){

    let elementExists = document.getElementById('wrapper');
    let Center = document.createElement('div');

    if (!elementExists) {
      let Wrapper = document.createElement('div');
      let parentElement = event.currentTarget.parentElement;
      Wrapper.classList.add('Wrapper');
      Wrapper.id = 'wrapper';

     Center.classList.add('Center');

     parentElement.appendChild(Wrapper);
     Wrapper.appendChild(Center);

      Wrapper.addEventListener('touchend', function(event){
        if (document.getElementById('wrapper')) {
            document.getElementById('wrapper').remove();
        }
      });
    }
});

.col-md-6 {
        width: 375px;
        height: 211px;
        margin: 20px;
        position: relative;
    }

        .Wrapper {
        display: table;
        position: absolute;
        background-color: rgba(0, 0, 0, 0.5);
        height: 100% !important;
        width: 100%;
        text-align: center;
        z-index: 1000;
        font-family: arial;
        color: #fff;
        top: 0;
    }

    .Center {
        display: table-cell;
        vertical-align: middle;
    }

The above code works fine, but I have image wrapped in a tag so by default it showing me screen when user touches an image as shown below:

And because of it overlay is not displaying on mobile screen. I would require help how can I fix it.

EDIT:

I am thinking of adding touch swipe event using plain JavaScript but I am not able to do it exactly.
Please let me know if I can get any help!


问:
How to extract apple's 1 billion countdown?
I've been trying to figure it out for hours and i didn't success, This Counter from Apple 1 billion downloads prize. doesn't use flash at all, only javascript and 0-9 images, which makes it really cool. Now after stackoverflow successed to extract google's pacman, can we do that?

P.S I can't even know if this is using prototype or scriptaculous since they're both included.

答:
There's a file stored on the apple server which contains a count and a timestamp:

http://www.apple.com/autopush/us/itunes/includes/countdown.inc

That should give you a rough count.


答:
Before we get to your question there's several issues which should be addressed. Firstly, your HTML is invalid as you have nested  elements. I'd suggets you remove the outer one and give the inner a for attribute to relate it to the sibling checkbox. Also, you shouldn't use inline style (or JS). The .listRow elements already have classes, so you can easily place the styles in a stylesheet.

As for the issue, you can use the :checked selector to find only the checked elements. Then, in the each() loop, you can use the this keyword to refer to the current element in the iteration. From there you can use next() to get the sibling label element. Try this:

function test() {
  $('.chkName:checked').each(function() {
    var $label = $(this).next('label');
    console.log($label.text());
  });
}

test();```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.listRow {
  width: 314px;
}</code>```

    <input id="id1" type="checkbox" name="" checked="checked" class="chkName">
    test

    <input id="id2" type="checkbox" name="" checked="checked" class="chkName">
    test1

    <input id="id3" type="checkbox" name="" class="chkName">
    test2

```

Title: Get the value of label corresponding to the checked value of checkbox in a row

Body:
Before we get to your question there's several issues which should be addressed. Firstly, your HTML is invalid as you have nested <label> elements. I'd suggets you remove the outer one and give the inner a for attribute to relate it to the sibling checkbox. Also, you shouldn't use inline style (or JS). The .listRow elements already have classes, so you can easily place the styles in a stylesheet.

As for the issue, you can use the :checked selector to find only the checked elements. Then, in the each() loop, you can use the this keyword to refer to the current element in the iteration. From there you can use next() to get the sibling label element. Try this:

function test() {
  $('.chkName:checked').each(function() {
    var $label = $(this).next('label');
    console.log($label.text());
  });
}

test();

.listRow {
  width: 314px;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="listRow">
    <input id="id1" type="checkbox" name="" checked="checked" class="chkName">
    <label for="id1">test</label>
  </li>
  <li class="listRow">
    <input id="id2" type="checkbox" name="" checked="checked" class="chkName">
    <label for="id2">test1</label>
  </li>
  <li class="listRow">
    <input id="id3" type="checkbox" name="" class="chkName">
    <label for="id3">test2</label>
  </li>
</ul>


问:
Why does this type cast in Java with a fraction work?
```<code> double frac = (double) 3/2
</code>```

For the longest time I thought this would only cast the result of the int division to double, but frac has the intended value of 1.5. Why does this work?

答:
```<code>double frac = (double) 3/2;
</code>```

is equivalent to

```<code>double frac = ((double) 3)/2;
</code>```

first 3 is cast to double (and becomes 3.0), and then floating point division is performed, returning 1.5.

If the division was performed prior to the casting as in

```<code>double frac = (double) (3/2);
</code>```

the result would be 1.0, since integer division would have been performed prior to the casting.

Body:
 double frac = (double) 3/2

For the longest time I thought this would only cast the result of the int division to double, but frac has the intended value of 1.5. Why does this work?

Body:
double frac = (double) 3/2;

is equivalent to

double frac = ((double) 3)/2;

first 3 is cast to double (and becomes 3.0), and then floating point division is performed, returning 1.5.

If the division was performed prior to the casting as in

double frac = (double) (3/2);

the result would be 1.0, since integer division would have been performed prior to the casting.


问:
modifying columns of pandas data-frame on different conditions
This is my data-frame and I want to convert the values in column c and d into KB.
Here M stands for Mega-byte and G stands for Gigabyte. How it can be done.</p>

```<code>               b         c         d
              abc      12.8G     12.6G
              def      2.67M      3.4G
              ghi      12.5G     34.5M
              jkl      12.1G      1.2G
</code>```

答:
Dict mapping with .str accessor will help i.e

```<code>di = {'M':10**3,'G':10**6 }

df[['c','d']] = df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(str) + 'KB'
</code>```

```
     b             c             d
0  abc  12800000.0KB  12600000.0KB
1  def      2670.0KB   3400000.0KB
2  ghi  12500000.0KB     34500.0KB
3  jkl  12100000.0KB   1200000.0KB
```

If you need just the integer then use

```<code>df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(int)
</code>```

Body:
This is my data-frame and I want to convert the values in column c and d into KB.
Here M stands for Mega-byte and G stands for Gigabyte. How it can be done.

               b         c         d
              abc      12.8G     12.6G
              def      2.67M      3.4G
              ghi      12.5G     34.5M
              jkl      12.1G      1.2G

Body:
Dict mapping with .str accessor will help i.e

di = {'M':10**3,'G':10**6 }

df[['c','d']] = df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(str) + 'KB'

     b             c             d
0  abc  12800000.0KB  12600000.0KB
1  def      2670.0KB   3400000.0KB
2  ghi  12500000.0KB     34500.0KB
3  jkl  12100000.0KB   1200000.0KB

If you need just the integer then use

df[['c','d']].apply(lambda x : pd.to_numeric(x.str[:-1]) * x.str[-1].map(di)).astype(int)


问:
Redirect HTTP to HTTPS or deny usage of HTTP?
Configuring on Apache HTTPD server, many articles on the web advise to enforce HTTPS protocol by redirecting (permanently) all HTTP request to HTTPS.

Below is what I understand is happening when a user tries to reach a server supporting both HTTP and HTTPS :

Client's user agent (web browser for example, but not only) sends a request to http://my.domain.com.

Server receives request on port 80, and sends a permanent redirection (code 301) to https://my.domain.com.

Client's user agent receives the response. Given the status code, it sends the same request to https://my.domain.com.

Server receives request on port 443 and sends back the wanted content.

So, if the request contains sensitive data, between steps 1 and 2, a man-in-the-middle could recover it, non-ciphered, in the request.

If the client uses a web browser, this browser keeps in cache the 301 redirection, and the next time the client send a request using HTTP, it will automatically send it using HTTPS instead.

But, what if the client clears the cache often ? Or use another user agent than a web browser, which does not store the permanent redirection ? Don't we lose the benefit of HTTPS here ?

A concrete example : a REST API, and the requests contain sensitive data. This API can be called from any HTTP client (online, embed in a software or website, standalone).

In this case, could it be better to just disable HTTP support on server level in order to enforce the use of HTTPS ?

Edit 2017-11-14:

sys0dm1n told me about HSTS below. But the security provided by this mechanism depends entirely on the user agent's compliance to the specification.

Edit 2017-11-15:

I edit my post after the first answers I receive, to precise my concern.

答:
"Would disabling http entirely help?"

It probably would. I'm updating and changing my answer from 2017, because as user kamilz points out in the comments below, I was clearly to hasty, and drew the wrong conclusion. To quote Kamilz:

If the destination server is known but it doesn't listen on port 80 (or port 80 is blocked), TCP handshake should fail and still no HTTP data would be sent over the wire. If it listens on 80, it will accept TCP connection and data would be send over the wire in the plaintext.

That makes sense, of course. So why could I see the sensitive data in the pictures below? Kamilz explains that too:

Fiddler acts as a web proxy and that's why it is able to see original request.

That data is simply not sent yet - it was still on my machine, and no DNS lookup had yet been performed. At some point after having passed through Fiddler, the DNS lookup would have been performed, but no valid IP address would have been found1, and since there would be no valid IP, there would be no place to send the content at all.

(1. That is, assuming nobody registers the address http://somefakeurlthatdoesnotexistanywhare.com, with my silly spelling error and all).

Previous, incorrect answer

For context, here's my original answer (who knows, it might even be enlightening, and help others avoid drawing the same false conclusion):

No, I don't think it would, and here`s why: Presumably, your client / browser does not know if a site running http exists before a request is sent. Sure, it will receive an error code like 404 or something similar, but at that point, the original request will already have been sent over the wire, and any "man in the middle" may well have been able to observe that request.

As a simple illustration of the problem, here's a call to a fake http-url, made from Postman, an caught in Fiddler. As you can see, a 502 error is returned, but the original request still contained the sensitive data.

Now just for a comparison, if I do the same, but just change the url to https instead, I get a different result in Fiddler:

This tries to set up a tunnel, and does not reveal any of the post-data.

So in conclusion, your best option is probably to enable HSTS and get your site on the HSTS preload list, which should stop any HTTP-request from being sent to begin with (at least for recent versions of most major browsers).

ContentLicense: CC BY-SA 4.0


问:
How to write SQL query into code-igniter formate
How to write below SQL query in to code-igniter </p>

```<code>SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )
</code>```

答:
You can do like this query</p>

```<code>$query = $this->db
    ->select('pm.id, pm.region, pm.port_name, tbl_port_annual_throughput.YEAR, tbl_port_annual_throughput.TOTAL_THROUGHPUT, tbl_port_annual_throughput.status')
    ->from('tbl_port_annual_throughput')
    ->join('port_master pm', 'pm.id = tbl_port_annual_throughput.PORT_ID')
    ->where('pm.country','100@Kenya')
    ->group_start()
        ->group_start()
            ->where('tbl_port_annual_throughput.YEAR','2014')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
    ->group_end()
    ->get();
</code>```

Body:
How to write below SQL query in to code-igniter

SELECT
    `pm`.`id`,
    `pm`.`region`,
    `pm`.`port_name`,
    `pm`.`country`,
    `tbl_port_annual_throughput`.`YEAR`,
    `tbl_port_annual_throughput`.`TOTAL_THROUGHPUT`,
    `tbl_port_annual_throughput`.`status`
    FROM (`tbl_port_annual_throughput`)
    JOIN `port_master` pm
      ON `pm`.`id` = `tbl_port_annual_throughput`.`PORT_ID`
    WHERE `pm`.`country` = "100@Kenya"
    AND (
        (`tbl_port_annual_throughput`.`YEAR` =  '2014' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2015' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
        OR (`tbl_port_annual_throughput`.`YEAR` =  '2016' AND `tbl_port_annual_throughput`.`status` =  'Confirmed')
    )

Body:
You can do like this query

$query = $this->db
    ->select('pm.id, pm.region, pm.port_name, tbl_port_annual_throughput.YEAR, tbl_port_annual_throughput.TOTAL_THROUGHPUT, tbl_port_annual_throughput.status')
    ->from('tbl_port_annual_throughput')
    ->join('port_master pm', 'pm.id = tbl_port_annual_throughput.PORT_ID')
    ->where('pm.country','100@Kenya')
    ->group_start()
        ->group_start()
            ->where('tbl_port_annual_throughput.YEAR','2014')
            ->where('tbl_port_annual_throughput.status','Confirmed')
        ->group_end()
    ->group_end()
    ->get();


问:
DynamoDB partition key choice for notes app
I want to create a DynamoDB table that allows me to save notes from users.

The attributes I have:

user_id

note_id (uuid)

type

text

The main queries I will need:

Get all notes of a certain user

Get a specific note

Get all notes of a certain type (the less used query)

I know that in terms of performance and DynamoDB partitions note_id would be the right choice because they are unique and would be distributed equally over the partitions but on the other hand is much harder to get all notes of a user without scanning all items or using a GSI. And if they are unique I suppose it doesn't make any sense to have a sort key.

The other option would be to use user_id as partition key and note_id as sort key, but if I have certain users that are a much larger number of notes than others wouldn't that impact my performance?

Is it better to have a partition key unique (like note_id) to scale well with DynamoDB partitions and use GSIs to create my queries or to use instead a partition key for my main query (user_id)?

Thanks

答:
I would use user_id as your primary partition(hash) key and note_id as your primary range(sort) key.

You have already noted that in an ideal situation, each partition key is accessed with equal regularity to optimise performance see Design For Uniform Data Access Across Items In Your Tables. The use of user_id is perfectly fine as long as you have a good spread of users who regularly log in. Indeed AWS specifically encourage this option (see 'Choosing a Partition Key' table in the link above).

This approach will also make your application code much simpler than your alternative approach.

You then have a second choice which is whether to apply a Global Secondary Index for your get notes by type query. A GSI key, unlike a primary key, does not need to be unique (see AWS GSI guide, therefore I suggest you would simply use type as your GSI partition key without a range key.

The obvious plus side to using a GSI is a faster result when you perform the note type query. However you should be aware of the downsides also. A GSI has a separate throughput allowance than your table, so you need to provision this in addition to your table throughput (at extra cost). If you dont provision your GSI with enough read units it could end up slower than a scan on your table. If you dont provision enough write units, your table writes could be throttled, even if your table had enough write units.

Also, AWS warn that GSIs are updated asynchronously (usually within a fraction of a second but it can be longer). This means queries on your GSI might return the 'wrong' result if you have table writes and index reads very close together. If this was a problem you would need to handle it in your application code.


问:
How would one implement a variable sized cache object to reduce memory allocations in C++?
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

```<code>//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};
</code>```

Is my general concept sound here? Is there are better way of accomplishing this?

答:
The key issue I see is returning an

auto_ptr

for memory allocated in a non-default fashion. You could solve this by defining a suitable overloaded delete, but its better to define your own destroy function as part of the factory. If you do this, you also localise the memory management in the Cache class, allowing you more freedom to improve performance local to that class.
If course, using a smart pointer to control memory management is a good idea; what you would need to do is define your own allocator and define a smart_ptr to use it.

For reference, another approach to managing custom allocation is to define a custom new operator. I.e. This sort of thing:

```<code>struct Cache
{
    void* allocate(size_t size)
    {
        size_t blockSize = sizeof(size_t) + size;
        // Placeholder: do what ever appropriate to blocks of size 'blockSize'
        return malloc(blockSize);
    }
    void destroy(void* p)
    {
        size_t* block = reinterpret_cast<size_t*>(p);
        size_t blockSize = *block;
        // Placeholder: do what ever appropriate to blocks of size 'blockSize'
        free(p);
    }

};
Cache cache;

void* operator new (size_t size, Cache& cache )
{
    return cache.allocate(size);
}

struct CacheObject
{
    void operator delete(void* p)
    {
        cache.destroy(p);
    }
};

CacheObject* co = new (cache) CacheObject;
</code>```

Body:
Before the performance people tear my head off: yes, I have done profiling before asking this :)

I'm once again looking at my one of a type container, and while I have a solution that works, the performance is poor because each type of item that's cached results in a separate allocation on the heap (which is of course expensive).

Based on static analysis of my program's input, I have figured out a way to know the total size required by all of the objects that might be put in my cache object that's getting passed around. Basically, I have a list of objects that may be constructed in a given cache object, so I know what the size of what I might have to cache is in advance, but not at compile time -- runtime only.

Basically, what I'd like to do is what boost::make_shared does -- gets a single memory block, and constructs the shared_ptr bits as well as the controlled object in the same memory block.

I don't have to worry about preserving copying behavior as the cache object is noncopyable and passed around by pointer by clients (it's usually stored in something like a ptr_vector or a std::auto_ptr).

I'm not familiar however with how exactly one would implement such a container however, namely how one follows alignment restrictions and such.

In pseudocode, what I'd like to do:

//I know a lot of what's in here is not portable -- I need to run only on x86
//and x64 machines. Yes, this couple of classes looks hacky, but I'd rather
//have one hacky class than a whole programfull :)

class CacheRegistrar
{
    //Blah blah
public:
    //Figures out what objects will be in the cache, etc
    const std::vector<std::size_t>& GetRequiredObjectSizes() const;
    //Other stuff...
    template <typename T>
    void RegisterCacheObject();
    template <typename T>
    std::size_t GetObjectIndex() const;
    // etc.
};

class CacheObject;

std::auto_ptr<CacheObject> CacheObjectFactory(const CacheRegistrar& registrar)
{
    //Pretend this is in a CPP file and therefore CacheObject is defined...
    const std::vector<size_t>& sizes(registrar.GetRequiredObjectSizes());
    std::size_t sumOfCache = std::accumulate(sizes.begin(), sizes.end());
    sumOfCache += sizeof(CacheObject);
    boost::scoped_array<char> buffer(new char[] sumOfCache);
    CacheObject *obj = new (reinterpret_cast<void *>(buffer.get())) CacheObject;
    buffer.release(); //PSEUDOCODE (boost::scoped_array has no release member);
    return std::auto_ptr<CacheObject>(obj); //Nothrow
}

class CacheObject
{
    CacheRegistrar *registrar; //Set by my constructor
public:
    template<typename T>
    T& Get()
    {
        char * startOfCache = reinterpret_cast<char *>(this) +
            sizeof(CacheObject);
        char * cacheItem = startOfCache + registrar->GetObjectIndex<T>();
        return *reinterpret_cast<T*>(cacheItem);
    }
};

Is my general concept sound here? Is there are better way of accomplishing this?

Body:
The key issue I see is returning an

auto_ptr

for memory allocated in a non-default fashion. You could solve this by defining a suitable overloaded delete, but its better to define your own destroy function as part of the factory. If you do this, you also localise the memory management in the Cache class, allowing you more freedom to improve performance local to that class.
If course, using a smart pointer to control memory management is a good idea; what you would need to do is define your own allocator and define a smart_ptr to use it.

For reference, another approach to managing custom allocation is to define a custom new operator. I.e. This sort of thing:

struct Cache
{
    void* allocate(size_t size)
    {
        size_t blockSize = sizeof(size_t) + size;
        // Placeholder: do what ever appropriate to blocks of size 'blockSize'
        return malloc(blockSize);
    }
    void destroy(void* p)
    {
        size_t* block = reinterpret_cast<size_t*>(p);
        size_t blockSize = *block;
        // Placeholder: do what ever appropriate to blocks of size 'blockSize'
        free(p);
    }

};
Cache cache;

void* operator new (size_t size, Cache& cache )
{
    return cache.allocate(size);
}

struct CacheObject
{
    void operator delete(void* p)
    {
        cache.destroy(p);
    }
};

CacheObject* co = new (cache) CacheObject;


问:
How to insert sql query in java
I connected the sql server to intellij idea. I want to execute the inserting query (the code is written below). But with the following code , I'm not able to insert data into the database. I am creating address book n java using intellij idea and MySQL server and taking input from user with insert query:</p>

```<code>B.addActionListener( new ActionListener( ) {
    @Override
    public void actionPerformed(ActionEvent e) {
    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        DriverManager.registerDriver( DriverManager.getDriver( "jdbc:mysql://localhost:3306/mysql" ) );

        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");

        Statement st = con.createStatement();
       String rs = "insert into mysql57.addressbook" +"(fname,lname,addr,phonenum,id,email)" +"values(?,?,?,?,?,?)";

        System.out.println(532 );
        PreparedStatement preparedStatement = con.prepareStatement(rs);
        preparedStatement.setString(1, TUID.getText());
        preparedStatement.setString(2, tfn.getText());
        preparedStatement.setString(3, tln.getText());
        preparedStatement.setString(4, tpn.getText());
        preparedStatement.setString(5, tad.getText());
        preparedStatement.setString(6, tmail.getText());
        System.out.println(88 );
      preparedStatement.executeUpdate(rs);
      }
    catch (Exception ex){}
</code>```

答:
```<code>B.addActionListener( new ActionListener( ) {
@Override
public void actionPerformed(ActionEvent e) {
try
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    DriverManager.registerDriver( DriverManager.getDriver( "jdbc:mysql://localhost:3306/mysql" ) );

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");

    Statement st = con.createStatement();
   String rs = "insert into mysql57.addressbook" +"(fname,lname,addr,phonenum,id,email)" +"values(?,?,?,?,?,?)";

    System.out.println(532 );
    PreparedStatement preparedStatement = con.prepareStatement(rs);
    preparedStatement.setString(1, TUID.getText());
    preparedStatement.setString(2, tfn.getText());
    preparedStatement.setString(3, tln.getText());
    preparedStatement.setString(4, tpn.getText());
    preparedStatement.setString(5, tad.getText());
    preparedStatement.setString(6, tmail.getText());
    System.out.println(88 );
  preparedStatement.executeUpdate(rs);
  }
catch (Exception ex){
//Any exception caught will be logged here.
ex.printStackTrace();
}
</code>```

<p>Your catch block is empty, probably there is an exception but its being swallowed. </p>

Title: How to insert sql query in java

Body:
I connected the sql server to intellij idea. I want to execute the inserting query (the code is written below). But with the following code , I'm not able to insert data into the database. I am creating address book n java using intellij idea and MySQL server and taking input from user with insert query:

B.addActionListener( new ActionListener( ) {
    @Override
    public void actionPerformed(ActionEvent e) {
    try
    {
        Class.forName("com.mysql.jdbc.Driver").newInstance();
        DriverManager.registerDriver( DriverManager.getDriver( "jdbc:mysql://localhost:3306/mysql" ) );

        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");

        Statement st = con.createStatement();
       String rs = "insert into mysql57.addressbook" +"(fname,lname,addr,phonenum,id,email)" +"values(?,?,?,?,?,?)";

        System.out.println(532 );
        PreparedStatement preparedStatement = con.prepareStatement(rs);
        preparedStatement.setString(1, TUID.getText());
        preparedStatement.setString(2, tfn.getText());
        preparedStatement.setString(3, tln.getText());
        preparedStatement.setString(4, tpn.getText());
        preparedStatement.setString(5, tad.getText());
        preparedStatement.setString(6, tmail.getText());
        System.out.println(88 );
      preparedStatement.executeUpdate(rs);
      }
    catch (Exception ex){}

Body:
B.addActionListener( new ActionListener( ) {
@Override
public void actionPerformed(ActionEvent e) {
try
{
    Class.forName("com.mysql.jdbc.Driver").newInstance();
    DriverManager.registerDriver( DriverManager.getDriver( "jdbc:mysql://localhost:3306/mysql" ) );

    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql", "root", "root");

    Statement st = con.createStatement();
   String rs = "insert into mysql57.addressbook" +"(fname,lname,addr,phonenum,id,email)" +"values(?,?,?,?,?,?)";

    System.out.println(532 );
    PreparedStatement preparedStatement = con.prepareStatement(rs);
    preparedStatement.setString(1, TUID.getText());
    preparedStatement.setString(2, tfn.getText());
    preparedStatement.setString(3, tln.getText());
    preparedStatement.setString(4, tpn.getText());
    preparedStatement.setString(5, tad.getText());
    preparedStatement.setString(6, tmail.getText());
    System.out.println(88 );
  preparedStatement.executeUpdate(rs);
  }
catch (Exception ex){
//Any exception caught will be logged here.
ex.printStackTrace();
}

Your catch block is empty, probably there is an exception but its being swallowed.


问:
VS2015 application crashes when calling C++ function with delegates
I am using ABBYY's FineReader engine, and when trying to initialize, my application crashes (while debugging). If I run the .exe it works fine.

Declarations:

```<code><DllImport("kernel32.dll")>
Private Shared Function LoadLibrary(dllToLoad As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function GetProcAddress(hModule As IntPtr, procedureName As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function FreeLibrary(hModule As IntPtr) As Boolean
End Function

' FREngine.dll functions
<UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Unicode)>
Private Delegate Function GetEngineObject(devSN As String, reserved1 As String, reserved2 As String, ByRef engine As FREngine.IEngine) As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DeinitializeEngine() As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DllCanUnloadNow() As Integer
</code>```

and to initialize:

```<code> ' Load the FREngine.dll library
    dllHandle = LoadLibrary(enginePath)

    Try
        If dllHandle = IntPtr.Zero Then
            Throw New Exception("Can't load " + enginePath)
        End If

        Dim getEngineObjectPtr As IntPtr = GetProcAddress(dllHandle, "GetEngineObject")
        If getEngineObjectPtr = IntPtr.Zero Then
            Throw New Exception("Can't find GetEngineObject function")
        End If
        Dim deinitializeEnginePtr As IntPtr = GetProcAddress(dllHandle, "DeinitializeEngine")
        If deinitializeEnginePtr = IntPtr.Zero Then
            Throw New Exception("Can't find DeinitializeEngine function")
        End If
        Dim dllCanUnloadNowPtr As IntPtr = GetProcAddress(dllHandle, "DllCanUnloadNow")
        If dllCanUnloadNowPtr = IntPtr.Zero Then
            Throw New Exception("Can't find DllCanUnloadNow function")
        End If

        ' Convert pointers to delegates
        _getEngineObject = DirectCast(Marshal.GetDelegateForFunctionPointer(getEngineObjectPtr, GetType(GetEngineObject)), GetEngineObject)
        _deinitializeEngine = DirectCast(Marshal.GetDelegateForFunctionPointer(deinitializeEnginePtr, GetType(DeinitializeEngine)), DeinitializeEngine)
        _dllCanUnloadNow = DirectCast(Marshal.GetDelegateForFunctionPointer(dllCanUnloadNowPtr, GetType(DllCanUnloadNow)), DllCanUnloadNow)

        ' Call the GetEngineObject function
        Dim hresult As Integer = _getEngineObject(developerSN, Nothing, Nothing, m_engine)
</code>```

The last line is the one that causes the crash (no errors or output). The same code works fine in VS2010, but not in VS2015. What am I missing here?

答:
The reason it crashes is because you're using a non-developer license to debug ABBYY in Visual Studio, unfortunately it crashes without providing a meaningful exception and there's no information about this on their support site.

Ensure you're using a developer license whilst debugging and a run-time license if running it via the exe.

Body:
I am using ABBYY's FineReader engine, and when trying to initialize, my application crashes (while debugging). If I run the .exe it works fine.

Declarations:

<DllImport("kernel32.dll")>
Private Shared Function LoadLibrary(dllToLoad As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function GetProcAddress(hModule As IntPtr, procedureName As String) As IntPtr
End Function
<DllImport("kernel32.dll")>
Private Shared Function FreeLibrary(hModule As IntPtr) As Boolean
End Function

' FREngine.dll functions
<UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet:=CharSet.Unicode)>
Private Delegate Function GetEngineObject(devSN As String, reserved1 As String, reserved2 As String, ByRef engine As FREngine.IEngine) As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DeinitializeEngine() As Integer
<UnmanagedFunctionPointer(CallingConvention.StdCall)>
Private Delegate Function DllCanUnloadNow() As Integer

and to initialize:

 ' Load the FREngine.dll library
    dllHandle = LoadLibrary(enginePath)

    Try
        If dllHandle = IntPtr.Zero Then
            Throw New Exception("Can't load " + enginePath)
        End If

        Dim getEngineObjectPtr As IntPtr = GetProcAddress(dllHandle, "GetEngineObject")
        If getEngineObjectPtr = IntPtr.Zero Then
            Throw New Exception("Can't find GetEngineObject function")
        End If
        Dim deinitializeEnginePtr As IntPtr = GetProcAddress(dllHandle, "DeinitializeEngine")
        If deinitializeEnginePtr = IntPtr.Zero Then
            Throw New Exception("Can't find DeinitializeEngine function")
        End If
        Dim dllCanUnloadNowPtr As IntPtr = GetProcAddress(dllHandle, "DllCanUnloadNow")
        If dllCanUnloadNowPtr = IntPtr.Zero Then
            Throw New Exception("Can't find DllCanUnloadNow function")
        End If

        ' Convert pointers to delegates
        _getEngineObject = DirectCast(Marshal.GetDelegateForFunctionPointer(getEngineObjectPtr, GetType(GetEngineObject)), GetEngineObject)
        _deinitializeEngine = DirectCast(Marshal.GetDelegateForFunctionPointer(deinitializeEnginePtr, GetType(DeinitializeEngine)), DeinitializeEngine)
        _dllCanUnloadNow = DirectCast(Marshal.GetDelegateForFunctionPointer(dllCanUnloadNowPtr, GetType(DllCanUnloadNow)), DllCanUnloadNow)

        ' Call the GetEngineObject function
        Dim hresult As Integer = _getEngineObject(developerSN, Nothing, Nothing, m_engine)

The last line is the one that causes the crash (no errors or output). The same code works fine in VS2010, but not in VS2015. What am I missing here?


问:
TextInputLayout shared element transition issue
Here we go: two Activities with a shared element transition (Button). The second Activity has a TextInputLayout with a hint:

```<code><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:focusable="true"
              android:focusableInTouchMode="true"
              android:gravity="center_horizontal"
              android:orientation="vertical">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="GO"
            android:transitionName="test"/>

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent"
                                                   android:layout_height="wrap_content"
                                                   android:hint="WTF?!">
        <android.support.design.widget.TextInputEditText android:layout_width="match_parent"
                                                         android:layout_height="wrap_content"/>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>
</code>```

The enter transition of the second Activity is delayed for clarifying the problem: The hint of the TextInputLayout ignores the transition animation and displayed immediately after the transition is started. At the end of the animation you can see the correctly animated EditText background (horizontal line) below the hint. Is this a bug or am I missing something? Here is the second Activity:

```<code>public class SecondActivity extends AppCompatActivity {

    public static void launch(Activity activity, View sharedElement) {
        Intent intent = new Intent(activity, SecondActivity.class);

        ActivityOptionsCompat options = ActivityOptionsCompat.
                makeSceneTransitionAnimation(activity, sharedElement, "test");
        activity.startActivity(intent, options.toBundle());
    }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setEnterTransition(new Slide().setDuration(5000));
        }
    }
}
</code>```

EDIT: This bug can be "fixed" by adding a background the the second Activity's layout.

答:
Seems to be a bug. I submitted a new issue.

You can avoid this by defining an android:background for the second activity.

Body:
Here we go: two Activities with a shared element transition (Button). The second Activity has a TextInputLayout with a hint:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:app="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:focusable="true"
              android:focusableInTouchMode="true"
              android:gravity="center_horizontal"
              android:orientation="vertical">

    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:text="GO"
            android:transitionName="test"/>

    <android.support.design.widget.TextInputLayout android:layout_width="match_parent"
                                                   android:layout_height="wrap_content"
                                                   android:hint="WTF?!">
        <android.support.design.widget.TextInputEditText android:layout_width="match_parent"
                                                         android:layout_height="wrap_content"/>
    </android.support.design.widget.TextInputLayout>
</LinearLayout>

The enter transition of the second Activity is delayed for clarifying the problem: The hint of the TextInputLayout ignores the transition animation and displayed immediately after the transition is started. At the end of the animation you can see the correctly animated EditText background (horizontal line) below the hint. Is this a bug or am I missing something? Here is the second Activity:

public class SecondActivity extends AppCompatActivity {

    public static void launch(Activity activity, View sharedElement) {
        Intent intent = new Intent(activity, SecondActivity.class);

        ActivityOptionsCompat options = ActivityOptionsCompat.
                makeSceneTransitionAnimation(activity, sharedElement, "test");
        activity.startActivity(intent, options.toBundle());
    }

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

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().setEnterTransition(new Slide().setDuration(5000));
        }
    }
}

EDIT: This bug can be "fixed" by adding a background the the second Activity's layout.


问:
how to get payment response if my server stop working when callback url call by payment getway
I am working on stripe payment getaway one question is arising in my mind.this question in few steps i have defined below.

customer generate a payment request on my server

after input successful details customer request submitted on stripe.

stripe payment getaway done their process and  they send me  response either success or failure.

now what happen when stripe send me success or failure that time my server stopped working. then obviously i am not able to save stripe response in my tables. even i don't have record what my customer paid to my website.

so how would we know the stripe response even after my server stopped working on stripe callback.

i am using PHP for this.

答:
I note that you originally tagged this question with PayPal. You should understand that Stripe works differently how a conventional PayPal checkout flow would work.

With PayPal the shopper arrives at the end of your checkout flow, they click a link to get transferred to PayPal, they login/register, confirm their card details and then PayPal sends a callback to your server. This is where your point about your server being down is relevant.

With Stripe Checkout the flow is different. You add the Stripe javascript code to the final page of your checkout, this triggers a panel (like a modal window) where the shopper enters their card details. Upon submission Stripe generates a token for the card and then adds this as a hidden fields to the form on your site.

You set the form action to point to some code on your server. Upon submission your PHP script then takes the token and processes a payment.

At no point is there a callback between Stripe and your site. Instead you take the payment in a single call from your server. Once you get a response from this API call then you can log the order in your database, send confirmation emails, etc.

Hope this helps.


问:
How to get items into array from string with comma separated values in type script and any item has comma it will be in double quotes
I've been struggling to get all items of below string into an array.

abc,"de,f",hi,"hello","te,st&" items into an array in Typescript.

If any string has  comma (,) or ampersand (&) in it,It will be placed in double quotes.

Tried split function but it fails as my strings can have comma as well.

Any help in this regard is highly appreciated.

Thank you.

答:
RegEx /(?:^|,)(\"(?:[^\"])\"|[^,])/ has helped me get the required values.

var test = '"abc,123",test,123,456,"def:get"';

test.split(/(\"(?:[^\"])\"|[^,])/);

Its returning the below array.

["", ""abc,123"", ",", "test", ",", "123", ",", "456", ",", ""def:get"", ""]

And when a particular values in side double quotes,I just trimmed them to get the actual values and have ignore empty items of array..


问:
read from a formatted test file using fscanf() in c
Here is the text file

```<code>Username:user1  Password:pass1
Username:user2  Password:pass2
</code>```

I want to read the username and password from the text. the problem is there is not way to change the format of the text. i tried to read but as there is not space between colon(:), it gives whole username:user1 as string but i want only user1. i referred to this question but it did not help as there is no space between colon.

I tried :

```<code> while ((fscanf(fp,"Username:%s Password:%s",username,password))!=EOF)
</code>```

but it gives many undefined characters after user1 and loop never ends.

答:
Try the following code:</p>

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

int main (int argc, char *argv[])
{
    char username[128];
    char password[128];
    FILE *fp;
    int ret;

    fp = fopen("read.txt", "r");
    if (!fp) {
        printf("Failed to open a file\n");
        return 1;
    }

    while (1) {
        ret = fscanf(fp, "Username:%s Password:%s\n",username,password);
        if (ret == EOF)
            break;
        if (ret == 2)
            printf("%s %s\n", username, password);
        else {
            printf("%d\n", ret);
            perror("fscanf:");
            break;
        }
    }

    fclose(fp);
    return 0;
}
</code>```

Body:
Here is the text file

Username:user1  Password:pass1
Username:user2  Password:pass2

I want to read the username and password from the text. the problem is there is not way to change the format of the text. i tried to read but as there is not space between colon(:), it gives whole username:user1 as string but i want only user1. i referred to this question but it did not help as there is no space between colon.

I tried :

 while ((fscanf(fp,"Username:%s Password:%s",username,password))!=EOF)

but it gives many undefined characters after user1 and loop never ends.

Body:
Try the following code:

#include <stdio.h>
#include <string.h>

int main (int argc, char *argv[])
{
    char username[128];
    char password[128];
    FILE *fp;
    int ret;

    fp = fopen("read.txt", "r");
    if (!fp) {
        printf("Failed to open a file\n");
        return 1;
    }

    while (1) {
        ret = fscanf(fp, "Username:%s Password:%s\n",username,password);
        if (ret == EOF)
            break;
        if (ret == 2)
            printf("%s %s\n", username, password);
        else {
            printf("%d\n", ret);
            perror("fscanf:");
            break;
        }
    }

    fclose(fp);
    return 0;
}


问:
How to run all the scenarios of one feature file in single browser instance with selenium,serenity & cucumber
I am not able to execute selenium,cucumber & serenity scenarios of one feature file in single browser instance and currently each scenario is running in new browser instance

Below are my configurations:

Serenity and Cucumber version:

serenity.version=1.2.2-rc.1

serenity.cucumber.version=1.1.16

serenity.properties details:

serenity.use.unique.browser=true

restart.browser.each.scenario=false

Please let me know what other configuration i need to do to run all scenarios in one browser instance

答:
```<code>serenity.use.unique.browser=true
serenity.restart.browser.for.each=STORY
</code>```

(there can be also NEVER - for not closing browser even between Stories)

I've managed to add above and the SCENARIOS in one STORY would run without closing browser.

Check also if you have any Step that includes CLOSING the browser.
Take into account also what you have in @AfterStories and @AfterScenarios.

Body:
serenity.use.unique.browser=true
serenity.restart.browser.for.each=STORY

(there can be also NEVER - for not closing browser even between Stories)

I've managed to add above and the SCENARIOS in one STORY would run without closing browser.

Check also if you have any Step that includes CLOSING the browser.
Take into account also what you have in @AfterStories and @AfterScenarios.


问:
Better Performance with single thread
I'm doing a tree search for a class assignment. I understand the tree search part, but as I have some extra time, I wanted to speed it up by adding more threads.

The final task is to take in a set of constraints, classes and time-slots, and output a schedule with all those classes, and which satisfies all the constraints. An empty or partial assignment goes in, a complete class assignment comes out.

Our search is designed like a tree, with the input being the root node. The function div(n) is as follows: for a node n, find an unused class C, and for each unused slot S, produce a child node with C in S. To make the search more efficient, we use a search control which ranks the quality of nodes, so that the best candidates are selected first, and we don't waste time on bad candidates

A node implements Comparable, with compareTo() implemented using the search control. I use a priority queue to store nodes awaiting processing, so the 'best' nodes are always next in line. A worker removes an node, applies div() and adds the children to the priority queue.

My first approach was using a shared priority queue, specifically PriorityBlockingQueue. The performance was abysmal, since the queue was almost always blocking.

I tried to fix it by adding a background worker and a ConcurrentLinkedQueue buffer. workers would add to the buffer, and the the worker would periodically move elements from the buffer to the priority queue. This didn't work either.

The best performance I have found is to give each worker it's own priority queue. I'm guessing that this is as good as it gets, as now threads aren't connected to the actions of others. with this config, on an 4C/8T machine, I get a speedup  of ~2.5. I think the bottleneck here is the allocation of memory for all these nodes, but I could be wrong here.

From Searcher:

```<code>private PriorityQueue<Schedule> workQueue;
private static volatile boolean shutdownSignal = false;
private Schedule best;

public Searcher(List<Schedule> instances) {
    workQueue = new PriorityQueue<>(instances);
}

public static void stop() {
    shutdownSignal = true;
}

/**
 * Run the search control starting with the first node in the workQueue
 */
@Override
public void run() {

    while (!shutdownSignal) {
        try {
            Schedule next = workQueue.remove();
            List<Schedule> children = next.div(checkBest);
            workQueue.addAll(children);
        } catch (Exception e) {
            //TODO: handle exception
        }
    }
    //For testing
    System.out.println("Shutting down: " + workQueue.size());
}

//passing a function as a parameter
Consumer<Schedule> checkBest = new Consumer<Schedule>() {
    public void accept(Schedule sched) {
        if (best == null || sched.betterThan(best)) {
            best = sched;
            Model.checkBest.accept(sched);
        }
    }
};
</code>```

From Schedule:

```<code>public List<Schedule> div(Consumer<Schedule> completion) {
    List<Schedule> n = new ArrayList<>();

    int selected = 0;
    List<Slot> available = Model.getSlots();
    List<Slot> allocated = getAssigned();

    while (allocated.get(selected) != null) {
        selected++;
    } // find first available slot to fill.
      // Iterate through all available slots
    for (Slot t : available) {
        //Prepare a fresh copy
        List<Slot> newAssignment = new ArrayList<>(allocated.size());
        Collections.copy(newAssignment, allocated);

        //assign the course to the timeslot
        newAssignment.set(selected, t);
        Schedule next = new Schedule(this, newAssignment);
        n.add(next);
    }

    /**
     * Filter out nodes which violate the hard constraints and which are solved,
     * and check if they are the best in a calling thread
     */

    List<Schedule> unsolvedNodes = new ArrayList<>();

    for (Schedule schedule: n) {
        if (schedule.constr() && !schedule.solved()){
            unsolvedNodes.add(schedule);
            completion.accept(schedule);
        }
    }
    return unsolvedNodes;
}
</code>```

答:
I would say that fork-join framework is an appropriate tool for your task. You need to extend your task from either ResursiveTask or ResursiveAction and submit it to ForkJoinPool. Here is a pseudo-code sample. Also your shutdown flag must be volatile.

```<code>public class Task extends RecursiveAction {
    private final Node<Integer> node;

    public Task(Node<Integer> node) {
      this.node = node;
    }

    @Override
    protected void compute() {
      // check result and stop recursion if needed

      List<Task> subTasks = new ArrayList<>();

      List<Node<Integer>> nodes = div(this.node);
      for (Node<Integer> node : nodes) {
        Task task = new Task(node);
        task.fork();
        subTasks.add(task);
      }

      for(Task task : subTasks) {
        task.join();
      }
    }

    public static void main(String[] args) {
        Node root = getRootNode();
        new ForkJoinPool().invoke(new Task(root));
    }
</code>```

Title: Better Performance with single thread

Body:
I'm doing a tree search for a class assignment. I understand the tree search part, but as I have some extra time, I wanted to speed it up by adding more threads.

The final task is to take in a set of constraints, classes and time-slots, and output a schedule with all those classes, and which satisfies all the constraints. An empty or partial assignment goes in, a complete class assignment comes out.

Our search is designed like a tree, with the input being the root node. The function div(n) is as follows: for a node n, find an unused class C, and for each unused slot S, produce a child node with C in S. To make the search more efficient, we use a search control which ranks the quality of nodes, so that the best candidates are selected first, and we don't waste time on bad candidates

A node implements Comparable, with compareTo() implemented using the search control. I use a priority queue to store nodes awaiting processing, so the 'best' nodes are always next in line. A worker removes an node, applies div() and adds the children to the priority queue.

My first approach was using a shared priority queue, specifically PriorityBlockingQueue. The performance was abysmal, since the queue was almost always blocking.

I tried to fix it by adding a background worker and a ConcurrentLinkedQueue buffer. workers would add to the buffer, and the the worker would periodically move elements from the buffer to the priority queue. This didn't work either.

The best performance I have found is to give each worker it's own priority queue. I'm guessing that this is as good as it gets, as now threads aren't connected to the actions of others. with this config, on an 4C/8T machine, I get a speedup  of ~2.5. I think the bottleneck here is the allocation of memory for all these nodes, but I could be wrong here.

From Searcher:

private PriorityQueue<Schedule> workQueue;
private static volatile boolean shutdownSignal = false;
private Schedule best;

public Searcher(List<Schedule> instances) {
    workQueue = new PriorityQueue<>(instances);
}

public static void stop() {
    shutdownSignal = true;
}

/**
 * Run the search control starting with the first node in the workQueue
 */
@Override
public void run() {

    while (!shutdownSignal) {
        try {
            Schedule next = workQueue.remove();
            List<Schedule> children = next.div(checkBest);
            workQueue.addAll(children);
        } catch (Exception e) {
            //TODO: handle exception
        }
    }
    //For testing
    System.out.println("Shutting down: " + workQueue.size());
}

//passing a function as a parameter
Consumer<Schedule> checkBest = new Consumer<Schedule>() {
    public void accept(Schedule sched) {
        if (best == null || sched.betterThan(best)) {
            best = sched;
            Model.checkBest.accept(sched);
        }
    }
};

From Schedule:

public List<Schedule> div(Consumer<Schedule> completion) {
    List<Schedule> n = new ArrayList<>();

    int selected = 0;
    List<Slot> available = Model.getSlots();
    List<Slot> allocated = getAssigned();

    while (allocated.get(selected) != null) {
        selected++;
    } // find first available slot to fill.
      // Iterate through all available slots
    for (Slot t : available) {
        //Prepare a fresh copy
        List<Slot> newAssignment = new ArrayList<>(allocated.size());
        Collections.copy(newAssignment, allocated);

        //assign the course to the timeslot
        newAssignment.set(selected, t);
        Schedule next = new Schedule(this, newAssignment);
        n.add(next);
    }

    /**
     * Filter out nodes which violate the hard constraints and which are solved,
     * and check if they are the best in a calling thread
     */

    List<Schedule> unsolvedNodes = new ArrayList<>();

    for (Schedule schedule: n) {
        if (schedule.constr() && !schedule.solved()){
            unsolvedNodes.add(schedule);
            completion.accept(schedule);
        }
    }
    return unsolvedNodes;
}

Body:
I would say that fork-join framework is an appropriate tool for your task. You need to extend your task from either ResursiveTask or ResursiveAction and submit it to ForkJoinPool. Here is a pseudo-code sample. Also your shutdown flag must be volatile.

public class Task extends RecursiveAction {
    private final Node<Integer> node;

    public Task(Node<Integer> node) {
      this.node = node;
    }

    @Override
    protected void compute() {
      // check result and stop recursion if needed

      List<Task> subTasks = new ArrayList<>();

      List<Node<Integer>> nodes = div(this.node);
      for (Node<Integer> node : nodes) {
        Task task = new Task(node);
        task.fork();
        subTasks.add(task);
      }

      for(Task task : subTasks) {
        task.join();
      }
    }

    public static void main(String[] args) {
        Node root = getRootNode();
        new ForkJoinPool().invoke(new Task(root));
    }


问:
Unable to add custom claim in Tymon JWT
I'm using Tymon JWT to generate my token in Laravel. I have followed the guide in Tymon's github site carefully to add my custom claims like so:

```<code>$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);
</code>```

I managed to generate a token after authenticating the user, but when I decode the token with JWT decoder, I only see the default claims, but not  my custom claim.

答:
You are using Tymon JWT version 1.0.0 maybe?

From Github Tymon JWT

For version 0.5.* See the WIKI for documentation.

Documentation for 1.0.0 is coming soon, but there is an unfinished guide here

Use

```<code>JWTAuth::customClaims(['foo' => 'bar'])->attempt(['login' => '', 'password' => '']);
</code>```

Title: Unable to add custom claim in Tymon JWT

Body:
I'm using Tymon JWT to generate my token in Laravel. I have followed the guide in Tymon's github site carefully to add my custom claims like so:

$customClaims = ['foo' => 'bar', 'baz' => 'bob'];
JWTAuth::attempt($credentials, $customClaims);

I managed to generate a token after authenticating the user, but when I decode the token with JWT decoder, I only see the default claims, but not  my custom claim.

Body:
You are using Tymon JWT version 1.0.0 maybe?

From Github Tymon JWT

For version 0.5.* See the WIKI for documentation.

Documentation for 1.0.0 is coming soon, but there is an unfinished guide here

Use

JWTAuth::customClaims(['foo' => 'bar'])->attempt(['login' => '', 'password' => '']);


问:
Apollo Graphql Schema Stitching Conflict
I have a problem regarding GraphQL Schema stitching.
I have two Graphql Schemas:

```<code>type Name {
   firstname: String!
   lastname: String!
}

type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
}

type Query {
   user(userId: String!): User
}
</code>```

and

```<code>type User {
   age: String!
}

type Query {
   user(userId: String!): User
}
</code>```

I now tried to merge the schemas using graphql-tools's mergeSchemas Function:

```<code>const schema = mergeSchemas({
   schemas: [schema1, schema2]
});
</code>```

But instead of what I'm trying to achieve (an extended User Type):

```<code>type Name {
   firstname: String!
   lastname: String!
}

type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
   age: String!
}

type Query {
   user(userId: String!): User
}
</code>```

it resulted in this:
    type Name {
       firstname: String!
       lastname: String!
    }

```<code>type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
}

type Query {
   user(userId: String!): User
}
</code>```

Only one of the UserTypes is displayed in the final schema.
I tried using the onTypeConflict API in mergeSchemas to extend the Type but I haven't made any results.

Is there a way to merge Schemas by extending Types on Conflict?

答:
This should help</p>

```<code>extend type User {
   age: String!
}
</code>```

Body:
I have a problem regarding GraphQL Schema stitching.
I have two Graphql Schemas:

type Name {
   firstname: String!
   lastname: String!
}

type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
}

type Query {
   user(userId: String!): User
}

and

type User {
   age: String!
}

type Query {
   user(userId: String!): User
}

I now tried to merge the schemas using graphql-tools's mergeSchemas Function:

const schema = mergeSchemas({
   schemas: [schema1, schema2]
});

But instead of what I'm trying to achieve (an extended User Type):

type Name {
   firstname: String!
   lastname: String!
}

type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
   age: String!
}

type Query {
   user(userId: String!): User
}

it resulted in this:
    type Name {
       firstname: String!
       lastname: String!
    }

type Address {
   street: String!
   number: Int!
}

type User {
   name: Name!
   address: Address!
}

type Query {
   user(userId: String!): User
}

Only one of the UserTypes is displayed in the final schema.
I tried using the onTypeConflict API in mergeSchemas to extend the Type but I haven't made any results.

Is there a way to merge Schemas by extending Types on Conflict?

Body:
This should help

extend type User {
   age: String!
}


问:
When exactly is the HttpSession expired (starts being eligible for destroying - not necessarily destroyed yet)?
I would like to know when exactly an HttpSession would be expired (not the same as destroyed)?

I am trying to figure out if session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000) will give me the exact time in milliseconds of session expiry each time a request comes with the same session id!

From the javadocs:

long getLastAccessedTime()

```<code>  Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.
</code>```

int  getMaxInactiveInterval()

```<code>  Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.
</code>```

Lets say we have the following:

Treq1 - the time the container received the 1st request  (HttpSession.lastAccessedTime)

Tresp1 - the time the container sends the 1st response

Preq1 - the time period between Treq1 and Tresp1 (the time period that the server processes the 1st request

Treq2 - the time the container received the 2nd request  (HttpSession.lastAccessedTime)

Preq1req2 - the time period between Treq1 and Treq2 (the time between requests entering the container)

Presp1req2 - the time period between Tresp1 and Treq2 (the time between the 1st response exiting the container and the 2nd request entering the container)

So now, when does the server calculate the session as expired? When:

1. Treq1 + maxInactiveInterval < Treq1 + Preq1req2 => maxInactiveInterval < Preq1req2

2. Tresp1 + maxInactiveInterval < Tresp1 + Presp1req2 => maxInactiveInterval < Presp1req2

This part, the servlet container will keep this session open between client accesses is a bit confusing. Does it mean between requests entering the container or between response exiting and requests entering?

On a side note, I know that the session might not be destroyed at the exact time of expiry, but I don't know yet if it is destroyed before any request processing logic occurs in the container. I am referring to the request that holds an expired session id.

Kind Regards,

Despot

答:
source?

I traced requests twice using "org.springframework.boot:spring-boot-starter-web:1.5.6.RELEASE" spring and concluded:

In your service handler (doGet, doXX, or Controller methods), the expiration time is going to be session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000) (2. case)

```<code>Duration:        |<---------- Preq1req2 ---------->|
Duration:        |           |<---- Presp1req2 --->|
Time    :      Treq1       Tresp1                Treq2      Tresp2
Action  : req1-->|--service--|-->resp1 ...  req2-->|--service--|-->resp2
Duration:        |<- Preq1 ->|                     |<- Preq2 ->|
                 |           |                                 |
Set :       creationTime     |                                 |
          lastAccessedTime   |                                 |
                      lastAccessedTime                  lastAccessedTime
</code>```

When lastAccessedTime is updated after service:

Code snippet from C:/Users/ssfang/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.16/tomcat-embed-core-8.5.16-sources.jar

```<code>package org.apache.catalina.session;
public class StandardSession implements HttpSession, Session, Serializable {
    /** The time this session was created, in milliseconds since midnight, January 1, 1970 GMT. */
    protected long creationTime = 0L;

    /**
     * We are currently processing a session expiration, so bypass
     * certain IllegalStateException tests.  NOTE:  This value is not
     * included in the serialized version of this object.
     */
    protected transient volatile boolean expiring = false;

    /** The last accessed time for this Session. */
    protected volatile long lastAccessedTime = creationTime;

    /** The session event listeners for this Session. */
    protected transient ArrayList<SessionListener> listeners = new ArrayList<>();

    /** Flag indicating whether this session is valid or not. */
    protected volatile boolean isValid = false;

    /** The current accessed time for this session. */
    protected volatile long thisAccessedTime = creationTime;

    /** The access count for this session. */
    protected transient AtomicInteger accessCount = null;

    /**
     * The maximum time interval, in seconds, between client requests before the servlet container may
     * invalidate this session.  A negative time indicates that the session should never time out.
     */
    protected volatile int maxInactiveInterval = -1;

    /**
     * Return the idle time from last client access time without invalidation check
     * @see #getIdleTime()
     */
    @Override
    public long getIdleTimeInternal() {
        long timeNow = System.currentTimeMillis();
        long timeIdle;
        if (LAST_ACCESS_AT_START) {
            timeIdle = timeNow - lastAccessedTime;
        } else {
            timeIdle = timeNow - thisAccessedTime;
        }
        return timeIdle;
    }

    /**
     * Set the creation time for this session.  This method is called by the
     * Manager when an existing Session instance is reused.
     *
     * @param time The new creation time
     */
    @Override
    public void setCreationTime(long time) {
        this.creationTime = time;
        this.lastAccessedTime = time;
        this.thisAccessedTime = time;
    }

    /** Return the <code>isValid</code> flag for this session. */
    @Override
    public boolean isValid() {
        if (!this.isValid) {
            return false;
        }
        if (this.expiring) {
            return true;
        }
        if (ACTIVITY_CHECK && accessCount.get() > 0) {
            return true;
        }
        if (maxInactiveInterval > 0) {
            int timeIdle = (int) (getIdleTimeInternal() / 1000L);
            if (timeIdle >= maxInactiveInterval) {
                expire(true);
            }
        }
        return this.isValid;
    }
}
</code>```

Check whether the session is valid before getting the session

A background thread to scan all sessions whether have expired.

Body:
I would like to know when exactly an HttpSession would be expired (not the same as destroyed)?

I am trying to figure out if session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000) will give me the exact time in milliseconds of session expiry each time a request comes with the same session id!

From the javadocs:

long getLastAccessedTime()

  Returns the last time the client sent a request associated with this session, as the number of milliseconds since midnight January 1, 1970 GMT, and marked by the time the container received the request.

int  getMaxInactiveInterval()

  Returns the maximum time interval, in seconds, that the servlet container will keep this session open between client accesses.

Lets say we have the following:

Treq1 - the time the container received the 1st request  (HttpSession.lastAccessedTime)

Tresp1 - the time the container sends the 1st response

Preq1 - the time period between Treq1 and Tresp1 (the time period that the server processes the 1st request

Treq2 - the time the container received the 2nd request  (HttpSession.lastAccessedTime)

Preq1req2 - the time period between Treq1 and Treq2 (the time between requests entering the container)

Presp1req2 - the time period between Tresp1 and Treq2 (the time between the 1st response exiting the container and the 2nd request entering the container)

So now, when does the server calculate the session as expired? When:

1. Treq1 + maxInactiveInterval < Treq1 + Preq1req2 => maxInactiveInterval < Preq1req2

2. Tresp1 + maxInactiveInterval < Tresp1 + Presp1req2 => maxInactiveInterval < Presp1req2

This part, the servlet container will keep this session open between client accesses is a bit confusing. Does it mean between requests entering the container or between response exiting and requests entering?

On a side note, I know that the session might not be destroyed at the exact time of expiry, but I don't know yet if it is destroyed before any request processing logic occurs in the container. I am referring to the request that holds an expired session id.

Kind Regards,

Despot

Body:
source?

I traced requests twice using "org.springframework.boot:spring-boot-starter-web:1.5.6.RELEASE" spring and concluded:

In your service handler (doGet, doXX, or Controller methods), the expiration time is going to be session.getLastAccessedTime() + (session.getMaxInactiveInterval() * 1000) (2. case)

Duration:        |<---------- Preq1req2 ---------->|
Duration:        |           |<---- Presp1req2 --->|
Time    :      Treq1       Tresp1                Treq2      Tresp2
Action  : req1-->|--service--|-->resp1 ...  req2-->|--service--|-->resp2
Duration:        |<- Preq1 ->|                     |<- Preq2 ->|
                 |           |                                 |
Set :       creationTime     |                                 |
          lastAccessedTime   |                                 |
                      lastAccessedTime                  lastAccessedTime

When lastAccessedTime is updated after service:

Code snippet from C:/Users/ssfang/.m2/repository/org/apache/tomcat/embed/tomcat-embed-core/8.5.16/tomcat-embed-core-8.5.16-sources.jar

package org.apache.catalina.session;
public class StandardSession implements HttpSession, Session, Serializable {
    /** The time this session was created, in milliseconds since midnight, January 1, 1970 GMT. */
    protected long creationTime = 0L;

    /**
     * We are currently processing a session expiration, so bypass
     * certain IllegalStateException tests.  NOTE:  This value is not
     * included in the serialized version of this object.
     */
    protected transient volatile boolean expiring = false;

    /** The last accessed time for this Session. */
    protected volatile long lastAccessedTime = creationTime;

    /** The session event listeners for this Session. */
    protected transient ArrayList<SessionListener> listeners = new ArrayList<>();

    /** Flag indicating whether this session is valid or not. */
    protected volatile boolean isValid = false;

    /** The current accessed time for this session. */
    protected volatile long thisAccessedTime = creationTime;

    /** The access count for this session. */
    protected transient AtomicInteger accessCount = null;

    /**
     * The maximum time interval, in seconds, between client requests before the servlet container may
     * invalidate this session.  A negative time indicates that the session should never time out.
     */
    protected volatile int maxInactiveInterval = -1;

    /**
     * Return the idle time from last client access time without invalidation check
     * @see #getIdleTime()
     */
    @Override
    public long getIdleTimeInternal() {
        long timeNow = System.currentTimeMillis();
        long timeIdle;
        if (LAST_ACCESS_AT_START) {
            timeIdle = timeNow - lastAccessedTime;
        } else {
            timeIdle = timeNow - thisAccessedTime;
        }
        return timeIdle;
    }

    /**
     * Set the creation time for this session.  This method is called by the
     * Manager when an existing Session instance is reused.
     *
     * @param time The new creation time
     */
    @Override
    public void setCreationTime(long time) {
        this.creationTime = time;
        this.lastAccessedTime = time;
        this.thisAccessedTime = time;
    }

    /** Return the <code>isValid</code> flag for this session. */
    @Override
    public boolean isValid() {
        if (!this.isValid) {
            return false;
        }
        if (this.expiring) {
            return true;
        }
        if (ACTIVITY_CHECK && accessCount.get() > 0) {
            return true;
        }
        if (maxInactiveInterval > 0) {
            int timeIdle = (int) (getIdleTimeInternal() / 1000L);
            if (timeIdle >= maxInactiveInterval) {
                expire(true);
            }
        }
        return this.isValid;
    }
}

Check whether the session is valid before getting the session

A background thread to scan all sessions whether have expired.


问:
CSS position type change (absolute to relative) on child div causes odd effect on parent div. Why is that?
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

```<code>html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}
</code>```

...and in the HTML page I used:

```<code><body>
<div id=container>
 <div id=childDiv>
  test
    </div>
</div>

</body>
</code>```

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo

答:
When something is absolutely positioned, it is taken out of normal flow so its size, margins, etc. do not affect the things around it.

When something is relatively positioned, it is placed in normal flow (so its size, margins, etc. do affect the things around it) and layout is initially handled as if it were position: static, then it is moved according to the left, right, top and bottom properties.

Body:
I'm trying to understand CSS positioning and I'm having trouble figuring out why a simple change that apparently should have no effect on the layout is causing a very disruptive change. I'm obviously missing something.

The initial objective was to place an inner div
 vertically and horizontally within another div. That was fairly simple:

html, body {
 margin:0;
 padding:0;
 height:100%;
}

div#container {
 position:relative;
 background:#4444ff;
 margin: 0 auto; /* center, not in IE5 */

 height:80%;
 min-height:80%;
}

div#childDiv {
 position:absolute;
 background:#ff5555;

 /* next we center it vertically and horizontally */
 width:900px;
 height:600px;
 top:50%;
 margin-top:-300px;
 left:50%;
 margin-left:-450px;
}

...and in the HTML page I used:

  test

which worked fine.

The curious part is what happens when I change the position attribute of the #childDiv div from absolute to relative.

My understanding is that first is should not affect the #container div at all since I'm changing only the position of the child element, and second that it should not change the layout since it is the only child element, its parent uses relative position and third I have not specified any offsets (tp, left, etc).

Instead, when I make this change, the parent #container is messed up (shows only up to the half of the viewport instead of 80% height as previously), and the position of #childDiv changes accordingly (also upwards, half outside the viewport).

My questions is: why does that happen? What concepts I'm not taking into account and why was the parent div affected by a change in the children's position setting?

If I remove #childDiv from within #container and place it inside body, then #container is no longer affected by that change so it seems something is propagating up in the DOM, which is odd to me. I've seen the same in firefox, opera, IE and chrome.

I have read W3C's spec on this topic but I haven't been able to figure this one out so far...

UPDATE: I created examples in JS fiddle to show the problem. You can see the original is here: jsfiddle.net/7Pr9y/1 and the affected one is here: jsfiddle.net/7Pr9y/3

Thank you!
Eduardo


问:
Unable to resize column in chrome dev tools Resources
So I have an android project in which I am using realm. The issue being that my design has a lot of columns listed in one particular table. Sadly I can't seem to see all of them and I can't resize it is there a horizontal scroll I can use I'm not sure how to handle this?

答:
There's no horizontal bar, but you can use these two options to help read the db data (if you don't have an extra screen):

Zoom out using Cmd+-

You can perform SQL queries to select a subset of columns by clicking on the database icon and writing the query on the right panel.