问:
Authentication-Flows: java.lang.StringIndexOutOfBoundsException: String index out of range: -1
I'm refer to project of OhadR, He is using Spring security to login and set new password by email.
this link:

```<code>Authentication-Flows: https://github.com/OhadR/Authentication-Flows
</code>```

I have finished some steps as:

```<code>1. create account
2. confirm account by email
3. login sucess
4. change or set new password (this step happened exception)
</code>```

But when I input new password and confirm new password, I received an exception following as:

```<code>SEVERE: Servlet.service() for servlet [action] in context with path [] threw exception [Request processing failed; nested exception is java.lang.StringIndexOutOfBoundsException: String index out of range: -1] with root cause
 java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at com.ohadR.web.crypto.service.CryptoService.getDecodedStringFromEncodedBased64String(CryptoService.java:244)
at com.ohadR.web.crypto.service.CryptoService.extractStringAndDate(CryptoService.java:107)
at com.ohadR.web.auth_flows.core.AuthenticationFlowsProcessorImpl.handleSetNewPassword(AuthenticationFlowsProcessorImpl.java:279)
at com.ohadR.web.auth_flows.web.UserActionController.setNewPassword(UserActionController.java:239)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
</code>```

This is scope code cause exception:

```<code>@Override
public String handleSetNewPassword(
        String encUserAndTimestamp,
        String password,
        String retypedPassword) throws AuthenticationFlowsException
{
    validateRetypedPassword(password, retypedPassword);

    ImmutablePair<Date, String> stringAndDate =
    cryptoService.extractStringAndDate( encUserAndTimestamp );

    validateExpiration(stringAndDate.getLeft());

    String email = stringAndDate.getRight();

    //after validations, make the work: validate password constraints, and update DB:

    //validate the input:
    AuthenticationPolicy settings = getAuthenticationSettings();

    validatePassword(password, settings);

    String encodedPassword = encodeString(email, password);

    // go to the DB and: (1) update the password, and (2) activate the account:
    setPassword(email, encodedPassword);

    return email;
}
</code>```

Set values to debug: (Updated)

(Updated)

get and set value when debug:
value of link in email:

```<code>http://localhost:9999/rp?uts=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw
</code>```

When click this link, it will redirect to URL(set new password screen):

```<code>http://localhost:9999/login/setNewPassword.jsp?enc=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw
</code>```

and then input value in encUserAndTimestamp parameter in debug

finally, I received an message error:

```<code>Failed to decrypt URL content http://localhost:9999/login/setNewPassword.jsp?enc=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw
</code>```

It seem my URL is wrong !!

How to fix this exception, thank so much!

答:
You are right; indeed it is a bug (since 2014...)

https://github.com/OhadR/Authentication-Flows/issues/13

However though, I've just try to reproduce it (forgot-password flow), and it works fine! Here is a link to YouTube, so you can see exactly what I did...

Body:
I'm refer to project of OhadR, He is using Spring security to login and set new password by email.
this link:

Authentication-Flows: https://github.com/OhadR/Authentication-Flows

I have finished some steps as:

1. create account
2. confirm account by email
3. login sucess
4. change or set new password (this step happened exception)

But when I input new password and confirm new password, I received an exception following as:

SEVERE: Servlet.service() for servlet [action] in context with path [] threw exception [Request processing failed; nested exception is java.lang.StringIndexOutOfBoundsException: String index out of range: -1] with root cause
 java.lang.StringIndexOutOfBoundsException: String index out of range: -1
at java.lang.String.substring(Unknown Source)
at com.ohadR.web.crypto.service.CryptoService.getDecodedStringFromEncodedBased64String(CryptoService.java:244)
at com.ohadR.web.crypto.service.CryptoService.extractStringAndDate(CryptoService.java:107)
at com.ohadR.web.auth_flows.core.AuthenticationFlowsProcessorImpl.handleSetNewPassword(AuthenticationFlowsProcessorImpl.java:279)
at com.ohadR.web.auth_flows.web.UserActionController.setNewPassword(UserActionController.java:239)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:222)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:137)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:814)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:737)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)

This is scope code cause exception:

@Override
public String handleSetNewPassword(
        String encUserAndTimestamp,
        String password,
        String retypedPassword) throws AuthenticationFlowsException
{
    validateRetypedPassword(password, retypedPassword);

    ImmutablePair<Date, String> stringAndDate =
    cryptoService.extractStringAndDate( encUserAndTimestamp );

    validateExpiration(stringAndDate.getLeft());

    String email = stringAndDate.getRight();

    //after validations, make the work: validate password constraints, and update DB:

    //validate the input:
    AuthenticationPolicy settings = getAuthenticationSettings();

    validatePassword(password, settings);

    String encodedPassword = encodeString(email, password);

    // go to the DB and: (1) update the password, and (2) activate the account:
    setPassword(email, encodedPassword);

    return email;
}

Set values to debug: (Updated)

(Updated)

get and set value when debug:
value of link in email:

http://localhost:9999/rp?uts=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw

When click this link, it will redirect to URL(set new password screen):

http://localhost:9999/login/setNewPassword.jsp?enc=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw

and then input value in encUserAndTimestamp parameter in debug

finally, I received an message error:

Failed to decrypt URL content http://localhost:9999/login/setNewPassword.jsp?enc=ap0wGvPL56FiYbMshHLe5Yh5PWEkz/kWEbJA32uJPSxw

It seem my URL is wrong !!

How to fix this exception, thank so much!


来源: stackexchange

问:
finding an element from one list in another list in python
Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

```<code>list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]
</code>```

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

ContentLicense: CC BY-SA 3.0

Body:
Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

Body:
Use .index() on a list:

list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

string = "hello"
positions = [list_one.index(c) for c in string]
print(positions)
# [8, 5, 12, 12, 15]


问:
How can I save an object to a file?
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

```<code>m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]
</code>```

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

答:
You need to serialize the objects before you could save them to a file and deserialize them to retrieve them back. As mentioned by Cory, 2 standard serialization libraries are widely used, Marshal and YAML.

Both Marshal and YAML use the methods dump and load for serializing and deserializing respectively.

Here is how you could use them:

```<code>m = [
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ],
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ]
    ]

# Quick way of opening the file, writing it and closing it
File.open('/path/to/yaml.dump', 'w') { |f| f.write(YAML.dump(m)) }
File.open('/path/to/marshal.dump', 'wb') { |f| f.write(Marshal.dump(m)) }

# Now to read from file and de-serialize it:
YAML.load(File.read('/path/to/yaml.dump'))
Marshal.load(File.read('/path/to/marshal.dump'))
</code>```

You need to be careful about the file size and other quirks associated with File reading / writing.

More info, can of course be found in the API documentation.

ContentLicense: CC BY-SA 2.5

Title: How can I save an object to a file?

Body:
I would like to save an object to a file, and then read it from the file easily. As a simple example, lets say I have the following 3d array:

m = [[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]],
[[0, 0, 0],
 [0, 0, 0],
 [0, 0, 0]]]

Is there an easy Ruby API that I can use to achieve this without programming a parser to interpret the data from the file? In the example I give it is easy, but as the objects become more complicated, it gets annoying to make objects persistent.

Body:
You need to serialize the objects before you could save them to a file and deserialize them to retrieve them back. As mentioned by Cory, 2 standard serialization libraries are widely used, Marshal and YAML.

Both Marshal and YAML use the methods dump and load for serializing and deserializing respectively.

Here is how you could use them:

m = [
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ],
     [
      [0, 0, 0],
      [0, 0, 0],
      [0, 0, 0]
     ]
    ]

# Quick way of opening the file, writing it and closing it
File.open('/path/to/yaml.dump', 'w') { |f| f.write(YAML.dump(m)) }
File.open('/path/to/marshal.dump', 'wb') { |f| f.write(Marshal.dump(m)) }

# Now to read from file and de-serialize it:
YAML.load(File.read('/path/to/yaml.dump'))
Marshal.load(File.read('/path/to/marshal.dump'))

You need to be careful about the file size and other quirks associated with File reading / writing.

More info, can of course be found in the API documentation.


问:
Selenium explicit wait upper limit
I'm using Selenium to do some automated testing in a C# app.  I have a component that's not disappearing after the 90 seconds explicit wait.  Is there an upper limit to the timeout:

```<code>Driver.WaitUntil(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("section > h1 > img")), 90);
</code>```

I haven't found anything indicating there's an upper limit.

答:
WebDriverWait constructor is WebDriverWait(IWebDriver, TimeSpan) TimeSpan has several properties, one of them is Days, witch receives double as parameter. So theoretically you can do

```<code>WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromDays(double.MaxValue));
</code>```

And see what happens first, your explicit wait ends or the sun goes supernova :)

(The script will probably crash much sooner).

Title: Selenium explicit wait upper limit

Body:
I'm using Selenium to do some automated testing in a C# app.  I have a component that's not disappearing after the 90 seconds explicit wait.  Is there an upper limit to the timeout:

Driver.WaitUntil(ExpectedConditions.InvisibilityOfElementLocated(By.CssSelector("section > h1 > img")), 90);

I haven't found anything indicating there's an upper limit.

Body:
WebDriverWait constructor is WebDriverWait(IWebDriver, TimeSpan) TimeSpan has several properties, one of them is Days, witch receives double as parameter. So theoretically you can do

WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromDays(double.MaxValue));

And see what happens first, your explicit wait ends or the sun goes supernova :)

(The script will probably crash much sooner).


答:
you can iterate thought the list :

```<code>>>> for i in range(len(list_two)):
...     for j in range(len(list_one)):
...             if list_two[i]==list_one[j]:
...                     list_3.append(j)
>>> list_3
[8, 5, 12, 12, 15]
</code>```

but wim's answer is more elegant !

Title: finding an element from one list in another list in python

Body:
you can iterate thought the list :

>>> for i in range(len(list_two)):
...     for j in range(len(list_one)):
...             if list_two[i]==list_one[j]:
...                     list_3.append(j)
>>> list_3
[8, 5, 12, 12, 15]

but wim's answer is more elegant !

ContentLicense: CC BY-SA 4.0


问:
How to toggle add/remove when adding html into a textarea?
When I click on the button ADD, it should be adding all the html into the textarea, and works fine. However, If I click again I should be removing that from the text area.
An idea maybe is by pushing the inserted html into an array?

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="container">
  <div class="row">
     <div class="col-xs-12 col-md-6">
      <div class="thumbnail">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/3fJjajItnEQ?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe></div><div class="caption">
          <p>Duration: <span class="video-time">31:54</span></p>
          <button type="button" class="btn btn-danger btn-block btn_video"><strong>ADD</strong></button>
        </div>
      </div>
    </div>
    <div class="col-xs-12 col-md-6">
      <div class="thumbnail">
        <div class="embed-responsive embed-responsive-16by9">
          <iframe class="embed-responsive-item" src="https://www.youtube.com/embed/3fJjajItnEQ?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe></div><div class="caption">
          <p>Duration: <span class="video-time">31:54</span></p>
          <button type="button" class="btn btn-danger btn-block btn_video"><strong>ADD</strong></button>
        </div>
      </div>
    </div>
  </div>
</div>

<textarea name="usp-custom-5" id="usp-custom-5" data-required="false" placeholder="Example Input 5" data-richtext="false" class="usp-input usp-textarea usp-form-16" rows="5" cols="30" style="margin: 0px; height: 266px; width: 996px;"></textarea></code>```

Here it is a Fiddle.

```<code>$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});
</code>```

答:
See if it's what you need:

```<code>return currentValue + $imageSelected
</code>```

replace:

```<code>return $imageSelected
</code>```

If you need to save the information before erasing, paste in an array:

```<code>var arr = [];
    $('body').on('click', '.btn_video', function() {
      var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
      $('#usp-custom-5').val(function(_, currentValue) {
        arr.push($imageSelected);
        return $imageSelected
      });
    });
</code>```

Body:
When I click on the button ADD, it should be adding all the html into the textarea, and works fine. However, If I click again I should be removing that from the text area.
An idea maybe is by pushing the inserted html into an array?

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

Duration: 31:54

          <button type="button" class="btn btn-danger btn-block btn_video">ADD</button>

Duration: 31:54

          <button type="button" class="btn btn-danger btn-block btn_video">ADD</button>

<textarea name="usp-custom-5" id="usp-custom-5" data-required="false" placeholder="Example Input 5" data-richtext="false" class="usp-input usp-textarea usp-form-16" rows="5" cols="30" style="margin: 0px; height: 266px; width: 996px;"></textarea>

Here it is a Fiddle.

$('body').on('click', '.btn_video', function() {
  var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
  $('#usp-custom-5').val(function(_, currentValue) {
    return currentValue + $imageSelected
  });
});

Body:
See if it's what you need:

return currentValue + $imageSelected

replace:

return $imageSelected

If you need to save the information before erasing, paste in an array:

var arr = [];
    $('body').on('click', '.btn_video', function() {
      var $imageSelected = $(this).parent().parent().parent().prop('outerHTML');
      $('#usp-custom-5').val(function(_, currentValue) {
        arr.push($imageSelected);
        return $imageSelected
      });
    });


问:
Webpack Dev Server with NGINX proxy_pass for https domain causes: net::ERR_CONNECTION_CLOSED
I have setup a server which hosts an 'angular2-webpack-starter' project for the front-end and a nodejs back-end. The nginx default has two proxy_pass's to map the connections to the right places on the server.  ALMOST everything works as expected.. BUT there is an issue with the proxy of sockjs-node/info which truly surprised me.

When running I see:

```<code>zone.js:1960 GET https://localhost:3000/sockjs-node/info?t=1490740454197 net::ERR_CONNECTION_CLOSED
</code>```

The two proxies are:

```<code>  location ^~ /server/ {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   Host      $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass https://127.0.0.1:9000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }

  location ^~ / {
    #proxy_buffering    off;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   Host      $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://127.0.0.1:3000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }
</code>```

I have looked over serveral other answers to this issue, to no avail.  I tried adding cors stuff on the front-end which makes no sense and this has no effect.  I tried turning off proxy_buffering to no avail (as I would expect). I even added 'underscored_in_headers on;' in nginx, to no avail.

Others have used the webpack-dev-server to do the proxy, but it seems that nginx should handle this easily and when I move to production without the webpack-dev-server I will have the same issue.

If you have encountered this issue, or have an idea, your help would be greatly appreciated.

答:
It took quite a while, but I figured out the issue.  Others may benefit when attempting to run on a secure site during development.

The issue was proxy_pass to 'http://127.0.0.1:3000/'.  This causes issues.

Changing to:

proxy_pass https://127.0.0.1:3000/;

AND setting devServer in webpack.dev.js to:

```<code>  https: true,
  https: {
    key: fs.readFileSync('/etc/apache2/certwork/xxx.key'),
    cert: fs.readFileSync('/etc/apache2/certwork/xxx.crt'),
    ca: fs.readFileSync('/etc/apache2/certwork/ssl-bundle.crt')
  },
</code>```

solved the issue.  NOTE: https: true is enough, but I wanted to make the connection as accepted as possible, hence I added the key, cert, ca stuff.

YOU will still see:

And in my case:

Since the connection to 'https://localhost:3000' still has a mismatch with the domain name.  IE. localhost !== parke.dynazu.com.  BUT all is working and when I move away from the webpack-dev-server, this will not be an issue.

Body:
I have setup a server which hosts an 'angular2-webpack-starter' project for the front-end and a nodejs back-end. The nginx default has two proxy_pass's to map the connections to the right places on the server.  ALMOST everything works as expected.. BUT there is an issue with the proxy of sockjs-node/info which truly surprised me.

When running I see:

zone.js:1960 GET https://localhost:3000/sockjs-node/info?t=1490740454197 net::ERR_CONNECTION_CLOSED

The two proxies are:

  location ^~ /server/ {
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   Host      $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass https://127.0.0.1:9000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }

  location ^~ / {
    #proxy_buffering    off;
    proxy_set_header   X-Real-IP $remote_addr;
    proxy_set_header   X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header   Host      $host;
    proxy_set_header X-NginX-Proxy true;
    proxy_pass http://127.0.0.1:3000/;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";
  }

I have looked over serveral other answers to this issue, to no avail.  I tried adding cors stuff on the front-end which makes no sense and this has no effect.  I tried turning off proxy_buffering to no avail (as I would expect). I even added 'underscored_in_headers on;' in nginx, to no avail.

Others have used the webpack-dev-server to do the proxy, but it seems that nginx should handle this easily and when I move to production without the webpack-dev-server I will have the same issue.

If you have encountered this issue, or have an idea, your help would be greatly appreciated.

Body:
It took quite a while, but I figured out the issue.  Others may benefit when attempting to run on a secure site during development.

The issue was proxy_pass to 'http://127.0.0.1:3000/'.  This causes issues.

Changing to:

proxy_pass https://127.0.0.1:3000/;

AND setting devServer in webpack.dev.js to:

  https: true,
  https: {
    key: fs.readFileSync('/etc/apache2/certwork/xxx.key'),
    cert: fs.readFileSync('/etc/apache2/certwork/xxx.crt'),
    ca: fs.readFileSync('/etc/apache2/certwork/ssl-bundle.crt')
  },

solved the issue.  NOTE: https: true is enough, but I wanted to make the connection as accepted as possible, hence I added the key, cert, ca stuff.

YOU will still see:

And in my case:

Since the connection to 'https://localhost:3000' still has a mismatch with the domain name.  IE. localhost !== parke.dynazu.com.  BUT all is working and when I move away from the webpack-dev-server, this will not be an issue.


问:
Button's Text Cycle Through String-Array
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

```<code><string-array name="RG_answers">
     <item>text 1</item><!--Of course this is example text-->
     <item>text 2</item>
     <item>text 3</item>
</string-array>
</code>```

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

```<code> mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
</code>```

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.

答:
Something like this.</p>

```<code>private int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String[] btnText = getResources().getStringArray(R.array.RG_answers);
    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTrueButton.setText(btnText[count]);
            if (count < btnText.length - 1) {
                count++;
            } else {
                count = 0;
            }
        }
    });
}
</code>```

Body:
I have a button that when clicked, the text inside changes. I'm trying to accomplish this with an array in my strings.xml, thinking that the onClick will do a for loop through the string-array

<string-array name="RG_answers">
     <item>text 1</item>
     <item>text 2</item>
     <item>text 3</item>
</string-array>

I don't know if I'm just not Googling correctly, or what. Inside my onCreate() my button is basic

 mTrueButton = (Button) findViewById(R.id.true_button);
        mTrueButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

So basic that it's only helpful (if that) by providing the names I called it. Is it possible/feasible? From what I've found I haven't seen anyone ask a question like this.

Body:
Something like this.

private int count = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    final String[] btnText = getResources().getStringArray(R.array.RG_answers);
    mTrueButton = (Button) findViewById(R.id.true_button);
    mTrueButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mTrueButton.setText(btnText[count]);
            if (count < btnText.length - 1) {
                count++;
            } else {
                count = 0;
            }
        }
    });
}


问:
KeystoneJS post request does not work
This is my view

```<code>form.contact-form(method="post").col-md-12
            input(type='hidden', name='action', value='notes.edit' + data.post.id)
            .form-group.col-md-12
            .form-group.col-md-12
                    label.text-center Title
                    input.form-control.input-box(type='text', name='title', value=data.post.title, placeholder='Title' required)
            .form-group.col-md-12
                    label.text-center Content *
                    .row
                        .col-md-6
                            input.form-control.input-box(type='text', name='briefcontent', value=data.post.content.brief, placeholder='brief content')
                        .col-md-6
                            input.form-control.input-box(type='text', name='extendedcontent', value=data.post.content.extended placeholder='extended content')
            button(type='submit').btn.btn-success Edit Notes
            form.contact-form(method="post").col-md-12
</code>```

This is my post route

```<code>view.on('post', { action: 'notes.edit'}, function(next) {
    console.log('edit notes')
    res.redirect('/')

});
</code>```

This is my route bindings

```<code>// Setup Route Bindings
exports = module.exports = function (app) {
// Views
app.all('/', routes.views.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.get('/registration', routes.views.registration);
app.post('/registration', routes.views.registration);
app.all('/signin', routes.views.signin);
app.all('/signout', routes.views.signout);
app.all('/contact', routes.views.contact);
app.all('/addnotes', routes.views.addnotes);
app.all('/editnotes/:post', routes.views.editnotes);
app.all('/editnotes', routes.views.editnotes);
</code>```

The post request does not seem to work at all. I try console.log for the post request but in does not appear in terminal.

答:
You're appending the data.post.id to the value property of your input. Thus, the input value changes to be something that isn't notes.edit. Your POST route is expecting a request with an action value of only notes.edit, therefore the POST request isn't being handled by that route.

In your Pug template:

```<code> input(type='hidden', name='action', value='notes.edit')
</code>```

EDIT:

You have a second form within your form. That may have something to do with it as well. Try removing it.

Title: KeystoneJS post request does not work

Body:
This is my view

form.contact-form(method="post").col-md-12
            input(type='hidden', name='action', value='notes.edit' + data.post.id)
            .form-group.col-md-12
            .form-group.col-md-12
                    label.text-center Title
                    input.form-control.input-box(type='text', name='title', value=data.post.title, placeholder='Title' required)
            .form-group.col-md-12
                    label.text-center Content *
                    .row
                        .col-md-6
                            input.form-control.input-box(type='text', name='briefcontent', value=data.post.content.brief, placeholder='brief content')
                        .col-md-6
                            input.form-control.input-box(type='text', name='extendedcontent', value=data.post.content.extended placeholder='extended content')
            button(type='submit').btn.btn-success Edit Notes
            form.contact-form(method="post").col-md-12

This is my post route

view.on('post', { action: 'notes.edit'}, function(next) {
    console.log('edit notes')
    res.redirect('/')

});

This is my route bindings

// Setup Route Bindings
exports = module.exports = function (app) {
// Views
app.all('/', routes.views.index);
app.get('/blog/:category?', routes.views.blog);
app.get('/blog/post/:post', routes.views.post);
app.get('/gallery', routes.views.gallery);
app.get('/registration', routes.views.registration);
app.post('/registration', routes.views.registration);
app.all('/signin', routes.views.signin);
app.all('/signout', routes.views.signout);
app.all('/contact', routes.views.contact);
app.all('/addnotes', routes.views.addnotes);
app.all('/editnotes/:post', routes.views.editnotes);
app.all('/editnotes', routes.views.editnotes);

The post request does not seem to work at all. I try console.log for the post request but in does not appear in terminal.

Body:
You're appending the data.post.id to the value property of your input. Thus, the input value changes to be something that isn't notes.edit. Your POST route is expecting a request with an action value of only notes.edit, therefore the POST request isn't being handled by that route.

In your Pug template:

 input(type='hidden', name='action', value='notes.edit')

EDIT:

You have a second form within your form. That may have something to do with it as well. Try removing it.


问:
How do you get the index of the current iteration of a foreach loop?
Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, I currently do something like this depending on the circumstances:

```<code>int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}
</code>```

答:
It's only going to work for a List and not any IEnumerable, but in LINQ there's this:

```<code>IList<Object> collection = new List<Object> {
    new Object(),
    new Object(),
    new Object(),
    };

foreach (Object o in collection)
{
    Console.WriteLine(collection.IndexOf(o));
}

Console.ReadLine();
</code>```

@Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)

@Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.

That said, List might keep an index of each object along with the count.

Jonathan seems to have a better idea, if he would elaborate?

It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.

OwnerDisplayName: Graphain

Body:
Is there some rare language construct I haven't encountered (like the few I've learned recently, some on Stack Overflow) in C# to get a value representing the current iteration of a foreach loop?

For instance, I currently do something like this depending on the circumstances:

int i = 0;
foreach (Object o in collection)
{
    // ...
    i++;
}

LastEditorDisplayName: Graphain

Body:
It's only going to work for a List and not any IEnumerable, but in LINQ there's this:

IList<Object> collection = new List<Object> {
    new Object(),
    new Object(),
    new Object(),
    };

foreach (Object o in collection)
{
    Console.WriteLine(collection.IndexOf(o));
}

Console.ReadLine();

@Jonathan I didn't say it was a great answer, I just said it was just showing it was possible to do what he asked :)

@Graphain I wouldn't expect it to be fast - I'm not entirely sure how it works, it could reiterate through the entire list each time to find a matching object, which would be a helluvalot of compares.

That said, List might keep an index of each object along with the count.

Jonathan seems to have a better idea, if he would elaborate?

It would be better to just keep a count of where you're up to in the foreach though, simpler, and more adaptable.

OwnerDisplayName: crucible

LastEditorDisplayName: crucible


问:
DDD repositories as singletons?
Quick question: Would it be a good or a bad idea to implement my domain-driven design style repositories as singletons? Why?

Or should I maybe use a dependency injector container to manage my repositories and decide if they are singletons or not?

I'm still reading DDD Quickly, and would like to see some good repository examples.

答:
I am not sure about this and I have the same problem. I think that you should make a repository a singleton when the objects that it works with are used often. And that it shouldn't be made a singleton if you use objects that it works with rarely, because the repository would take a lot of memory for objects and maybe it would be called only once and never again during usage of the application.
As I said, this may not be correct thinking.</p>

OwnerDisplayName: Torbjørn

Title: DDD repositories as singletons?

OwnerDisplayName: gljivar


问:
Selenium Authentication Popup preventing driver close or quit
I have a selenium automated task setup to login to a website to retrieve some information. It's very basic in the automation. Just logging in and clicking two links. I am running into an issue that is proving to be a problem.

The site in question uses the Authentication Required popup which is not a javascript popup but rather the regular windows auth popup. From what I have read this isn't handled out of the box with selenium.

I am using the "http://Username:Password@url.com" to get to the site but every now and then the site itself has issues on their end where it will prompt me again from username/password randomly. Sometimes I have to enter the username/password twice in a row when navigating there by hand.

Since my task just loops continuously for a few hours picking up the needed info I figured I would just use WebDriverWait to verify an element is present on the page. If the authentication popup appears, the element isn't present. No need to care about this run, so just start over.

The problem I am having is that when the Authentication popup is displayed and I hit my timeout limit I want to close the driver/browser window so that I can start the task over again. However, driver.Close() and driver.Quit() are not doing anything. The browser remains open and the unloaded page is still there with the login popup.

Is there anyway I can force close this? Switch focus to the browser window then force close?

答:
The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box. The below code was tested on Google Chrome in java.

```<code>Alert alert = driver.switchTo().alert();
alert.authenticateUsing(new UserAndPassword(Username, Password));
</code>```

In case it doesn't work and you might want to try this:
https://stackoverflow.com/a/40757504/7071055

Body:
The Alert Method, authenticateUsing() lets you skip the Http Basic Authentication box. The below code was tested on Google Chrome in java.

Alert alert = driver.switchTo().alert();
alert.authenticateUsing(new UserAndPassword(Username, Password));

In case it doesn't work and you might want to try this:
https://stackoverflow.com/a/40757504/7071055


答:
Adding to @wim's answer, could be done with a simple comprehension.</p>

```<code>>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]
</code>```

Body:
Is there a way to have two lists named list1 and list2 and be able to look up the position of one entry in another. i.e.

list_one = ["0", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]

list_two = ["h","e","l","l","o"]

my aim is to allow the user to enter a word which the program will then convert in a set of numbers corresponding to the letters entries in list_one

so if the user did input hello the computer would return 85121215 (being the position of the entries)

is there a possible way to do this

Body:
Adding to @wim's answer, could be done with a simple comprehension.

>>> [list_one.index(x) for x in list_two]
[8, 5, 12, 12, 15]


问:
"Npm ls" shows broken dependencies. How to solve?
I would like a little help from you with this problem that's make me crazy (Maybe it's an Obsessive Compulsive Disorder ¯ \ _ (ツ) _ / ¯ )

I have a project with Nodejs + Angular + Ionic that seems to have dependency problems when checking with the "node ls" command in your own folder i see "unmet peer dependency".

In "npm install" just showing warnings, but in "npm ls" show "unmet peer dependency".
What is the relationship? And how can I do to solve it?

I have already updated nodejs 7.8.0, I have already re-installed the dependencies in the project folder with "npm install", but it still has not solved.

Command output "npm ls" that presents errors ...

Thank you all

答:
These are happening because

let assume there are 4 modules=> a,b,c,d

so, a dependent on b,

b dependent on c

but d version dependent on c (old version).

Now c new version cannot matched with the c of old version hence unmeet dependency.

(solution):=

 remove node_modules and install again

or update d


问:
Google Cloud Functions with ECONNRESET errors until I redeploy
I'm using Google Cloud Functions to:

Watch for a new Firebase entry

Download a file that's referenced in the Firebase entry

Generate a thumbnail based on that file.

Upload the thumbnail to the cloud bucket.

Unfortunately I'm getting ECONNRESET errors repeatedly on step 4, and the only way to fix it seems to be to redeploy the function. Any ideas how to further debug this?

Edit:

It seems like many times when this happens, when I try to deploy the function again, it errors, and I have to run the deploy twice. Is something hanging or something?

答:
You can directly report a bug to the Firebase Support team, or open a support ticket with Firebase to troubleshoot a specific issue. </p>

<p>You may also report a Cloud Functions specific issue in the Google Issue Tracker, which is similar to Stack Overflow in that it is accessible by the public (but specifically used for filing issue reports).   </p>

Body:
You can directly report a bug to the Firebase Support team, or open a support ticket with Firebase to troubleshoot a specific issue.

You may also report a Cloud Functions specific issue in the Google Issue Tracker, which is similar to Stack Overflow in that it is accessible by the public (but specifically used for filing issue reports).


问:
Batch Delete Files From File On Cmd Line
I have a long list of file names in a txt file, which I generated using

```<code>findstr /M "string here" *.* > c:\files.log
</code>```

The file is about 3mb. Now i want to delete all of those files. I tried del < c:\files.log but that doesn't work. What should I use?

答:
You must have %%a and not %a inside the batch file
%a for cmd</p>

Body:
I have a long list of file names in a txt file, which I generated using

findstr /M "string here" *.* > c:\files.log

The file is about 3mb. Now i want to delete all of those files. I tried del < c:\files.log but that doesn't work. What should I use?


问:
WPF: TreeView does not show any children
I've been trying to get my first TreeView to work, at first without the ViewModel. But no matter what I do, it doesn't show any children, even though the binding is correct.

I'm using two Item templates, one for hierarchical and another for data. You can see the important parts for both below:

```<code>class GrupoTag
{
    public string Nome { get; set; }
    public GrupoTag Pai { get; set; }
    public List<Tag> ListaFilhos { get; set; }
    public List<GrupoTag> SubGrupos { get; set; }
    public GrupoTag(string nome)
    {
        Nome = nome;
        ListaFilhos = new List<Tag>();
        SubGrupos = new List<GrupoTag>();
    }
    public List<object> Filhos
    {
        get
        {
            List<object> lista = new List<object>();
            foreach (GrupoTag subGrupo in SubGrupos)
                lista.Add(subGrupo);
            foreach (Tag filho in ListaFilhos)
                lista.Add(filho);
        }
    }
}
</code>```

```<code>class Tag
    {
        public GrupoTag Pai { get; set; }
        public string Nome { get; set; }
        public Tag(string nome)
        {
            Nome = nome;
        }
        public Tag(GrupoTag pai, string nome)
        {
            Pai = pai;
            Nome = nome;
        }
    }
</code>```

The XAML binding to all of this:

```<code><TreeView Name="MenuTags">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="xml2Excel2:GrupoTag" ItemsSource="{Binding Filhos}">
            <TextBlock Text="{Binding Nome}" />
        </HierarchicalDataTemplate>
        <DataTemplate DataType="xml2Excel2:Tag">
            <TextBlock Text="{Binding Nome}" />
        </DataTemplate>
    </TreeView.Resources>
</TreeView>
</code>```

But the property "Filhos" on the GrupoTag class is never accessed. I've tried putting a breakpoint in there, throwing an exception, but it's simply never called. And the TreeView only displays the names of the collection of GrupoTags I assigned to it as its ItemSource in code-behind.

```<code>MenuTags.ItemsSource = arvoreTeste.SubGrupos;
</code>```

I've read all the related questions and corrected the code for the respective errors, but I'm still lost here.

EDIT 1: So I modified the code of the classes to conform to the simple interface below:

```<code>class ITag
{
    public string Nome { get; set; }
    public ObservableCollection<ITag> Filhos { get; set; }
}
</code>```

As per Benin comment, GrupoTag now uses a single property stored in a ObservableCollection to represent its children. And, as per Adnan answer removed the DataType from the XAML TreeView. Now it looks like this:

```<code><TreeView Name="ArvoreTags">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Nome}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
 </TreeView>
</code>```

It works, the TreeViewis functional. But I don't know why.

答:
You need to give your TreeView ItemSource and DataType. And I would agree to Berins comment , you should avoid making new list to each access to Filhos property. TreeView works very good with Polymorphis, I mean with data types.

```<code><TreeView   DockPanel.Dock="Top"
            DataContext="{Binding ProjectNodes_DataContext}"
            ItemsSource="{Binding Nodes}">
  <TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:ProjectNode}" ItemsSource="{Binding SubItems}">
        <StackPanel>
            <TextBlock Text="{Binding Header}"/>
        </StackPanel>
    </HierarchicalDataTemplate>
  </TreeView.Resources>
</code>```

My Property is:

```<code>private ProjectNodesVM mProjectNodes_DataContext;
public ProjectNodesVM ProjectNodes_DataContext
{
    get { return mProjectNodes_DataContext; }
    protected set
    {
        SetProperty(ref mProjectNodes_DataContext, value);
    }
}
</code>```

and class ProjectNodesVM has:

```<code>public ObservableCollection<ProjectNode> Nodes {
    get { return mNodes; }
    protected set { SetProperty(ref mNodes, value); }
}
</code>```

inside ProjectNode class i have:

```<code>private string mHeader;
public string Header
{
    get { return mHeader; }
    set { SetProperty(ref mHeader, value); }
}
</code>```

Body:
I've been trying to get my first TreeView to work, at first without the ViewModel. But no matter what I do, it doesn't show any children, even though the binding is correct.

I'm using two Item templates, one for hierarchical and another for data. You can see the important parts for both below:

class GrupoTag
{
    public string Nome { get; set; }
    public GrupoTag Pai { get; set; }
    public List<Tag> ListaFilhos { get; set; }
    public List<GrupoTag> SubGrupos { get; set; }
    public GrupoTag(string nome)
    {
        Nome = nome;
        ListaFilhos = new List<Tag>();
        SubGrupos = new List<GrupoTag>();
    }
    public List<object> Filhos
    {
        get
        {
            List<object> lista = new List<object>();
            foreach (GrupoTag subGrupo in SubGrupos)
                lista.Add(subGrupo);
            foreach (Tag filho in ListaFilhos)
                lista.Add(filho);
        }
    }
}

class Tag
    {
        public GrupoTag Pai { get; set; }
        public string Nome { get; set; }
        public Tag(string nome)
        {
            Nome = nome;
        }
        public Tag(GrupoTag pai, string nome)
        {
            Pai = pai;
            Nome = nome;
        }
    }

The XAML binding to all of this:

<TreeView Name="MenuTags">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="xml2Excel2:GrupoTag" ItemsSource="{Binding Filhos}">
            <TextBlock Text="{Binding Nome}" />
        </HierarchicalDataTemplate>
        <DataTemplate DataType="xml2Excel2:Tag">
            <TextBlock Text="{Binding Nome}" />
        </DataTemplate>
    </TreeView.Resources>
</TreeView>

But the property "Filhos" on the GrupoTag class is never accessed. I've tried putting a breakpoint in there, throwing an exception, but it's simply never called. And the TreeView only displays the names of the collection of GrupoTags I assigned to it as its ItemSource in code-behind.

MenuTags.ItemsSource = arvoreTeste.SubGrupos;

I've read all the related questions and corrected the code for the respective errors, but I'm still lost here.

EDIT 1: So I modified the code of the classes to conform to the simple interface below:

class ITag
{
    public string Nome { get; set; }
    public ObservableCollection<ITag> Filhos { get; set; }
}

As per Benin comment, GrupoTag now uses a single property stored in a ObservableCollection to represent its children. And, as per Adnan answer removed the DataType from the XAML TreeView. Now it looks like this:

<TreeView Name="ArvoreTags">
    <TreeView.ItemTemplate>
        <HierarchicalDataTemplate ItemsSource="{Binding Children}">
            <TextBlock Text="{Binding Nome}" />
        </HierarchicalDataTemplate>
    </TreeView.ItemTemplate>
 </TreeView>

It works, the TreeViewis functional. But I don't know why.

Body:
You need to give your TreeView ItemSource and DataType. And I would agree to Berins comment , you should avoid making new list to each access to Filhos property. TreeView works very good with Polymorphis, I mean with data types.

<TreeView   DockPanel.Dock="Top"
            DataContext="{Binding ProjectNodes_DataContext}"
            ItemsSource="{Binding Nodes}">
  <TreeView.Resources>
    <HierarchicalDataTemplate DataType="{x:Type local:ProjectNode}" ItemsSource="{Binding SubItems}">
        <StackPanel>
            <TextBlock Text="{Binding Header}"/>
        </StackPanel>
    </HierarchicalDataTemplate>
  </TreeView.Resources>

My Property is:

private ProjectNodesVM mProjectNodes_DataContext;
public ProjectNodesVM ProjectNodes_DataContext
{
    get { return mProjectNodes_DataContext; }
    protected set
    {
        SetProperty(ref mProjectNodes_DataContext, value);
    }
}

and class ProjectNodesVM has:

public ObservableCollection<ProjectNode> Nodes {
    get { return mNodes; }
    protected set { SetProperty(ref mNodes, value); }
}

inside ProjectNode class i have:

private string mHeader;
public string Header
{
    get { return mHeader; }
    set { SetProperty(ref mHeader, value); }
}


问:
Command echo executes before read
I wrote this code:
   read NAME | echo "$NAME"
Unexpectedly, command echo executes before read, in this case it shows an empty line and then waits for me to enter the text. Does anyone know what to do if I want read to execute first?

答:
A pipe is a communication channel between two processes, a writer and a reader.    The writer and reader can execute simultaneously, only needing to depend on each other for the write/read relationship.

For the pipe to do anything useful, the writer (the command on the left) needs to output something to its standard output (stdout), and the reader (the command on the right) needs to read from its standard input (stdin).  If the reader does not actually attempt to read from stdin, it will not block and will execute without waiting for the writer to do anything.

The pipe is an operating system mechanism that connects the writer's stdout with the reader's stdin without you, the programmer, having to bother with any detail regarding file descriptors, synchronization, and other boring and tricky details.  It is great but if you do not understand what happens behind the scene, it may produce results you will consider surprising (but are not).

In your case, the read command does not output anything to stdout (it assigns variable NAME), and the echo command does not read anything from stdin.  Since echo does not read anything, it executes without having to wait for anything, and therefore you see the output of echo right away.  The read command, however, needs to wait for input from its own stdin (which has nothing to do with the pipe, because the pipe is only concerned with stdout from read) ; read has its stdin connected to the terminal, so it waits for keyboard input.

In other words, your commands execute in parallel, and do not communicate with each other at all.

Remember, both commands in a pipe execute simultaneously as much as they can.  A reader that does not actually read will not bother with its writer, and vice-versa.

Title: Command echo executes before read


问:
In Swift, how do I detect a double tap from the spacebar in UITextView?
I'm working on an app that is heavily dependent on a UITextView. The desired behavior is when a user double taps the spacebar, the cursor will indent 5 spaces. How would I do this?</p>

答: Use the UITextViewDelegate and in the textView(UITextView, shouldChangeTextIn: NSRange, replacementText: String) function you keep track of the space inputs and the times. When you receive two space inputs within a short time frame, you manipulate the textfield with the 5 spaces.</p>


问:
SQL Server Group By with Joins
```<code>SELECT
    [CustomerKey] AS 'Cust #',
    CU.[CompanyName] AS 'Company Name',
    ISS.InvoiceDate AS 'Invoice Date',
    ISS.InvoiceTotal AS 'Invoice Total',
    ISNULL(CU.ShopPhone,'') AS 'Company Shop',
    ISNULL(CU.CellPhone,'') AS 'Company Cell',
    ISNULL(CU.OfficePhone,'') AS 'Company Office',
    ISNULL(CF.FirstName, '') AS 'FName',
    ISNULL(CF.LastName,'') AS 'LName',
    ISNULL(CF.WorkPhone,'') AS 'Contact Work',
    ISNULL(CF.CellPhone,'') AS 'Contact Cell',
    ISNULL(CF.HomePhone,'') AS 'Contact Home',
    ISNULL(CF.EMail,'') AS 'Contact Email',
    PSO.OutsidePartsSalespersonName
FROM
    [ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
    [ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
    [ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
    (SELECT
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
     FROM
         [ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
     WHERE
         EntityID IS NOT NULL
         AND FirstName <> ''
         AND EntityTypeID = '3'
         AND SetDefault = '1'
     GROUP BY
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
    CU.Inactive = '0'
    AND ISS.InvoiceType = 'Parts Order'
    AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
    AND CU.CustomerBaseBranchID = '1'
    AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
    CU.CustomerKey, CU.[CompanyName],
    ISS.InvoiceDate, ISS.InvoiceTotal,
    CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
    CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
    CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
    CU.CompanyName, ISS.InvoiceDate
</code>```

How can I group this to SUM ISS.InvoiceTotal grouped by CustomerKey?

I keep getting the "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." error.

Any ideas?

答:
If you SUM() in the ISS table you can't select from it or add it to the GROUP BY.

```<code>SELECT
    [CustomerKey] AS 'Cust #',
    CU.[CompanyName] AS 'Company Name',
    LAST(ISS.InvoiceDate) AS 'Invoice Date',
    SUM(ISS.InvoiceTotal) AS 'Invoice Total',
    ISNULL(CU.ShopPhone,'') AS 'Company Shop',
    ISNULL(CU.CellPhone,'') AS 'Company Cell',
    ISNULL(CU.OfficePhone,'') AS 'Company Office',
    ISNULL(CF.FirstName, '') AS 'FName',
    ISNULL(CF.LastName,'') AS 'LName',
    ISNULL(CF.WorkPhone,'') AS 'Contact Work',
    ISNULL(CF.CellPhone,'') AS 'Contact Cell',
    ISNULL(CF.HomePhone,'') AS 'Contact Home',
    ISNULL(CF.EMail,'') AS 'Contact Email',
    PSO.OutsidePartsSalespersonName
FROM
    [ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
    [ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
    [ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
    (SELECT
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
     FROM
         [ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
     WHERE
         EntityID IS NOT NULL
         AND FirstName <> ''
         AND EntityTypeID = '3'
         AND SetDefault = '1'
     GROUP BY
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
    CU.Inactive = '0'
    AND ISS.InvoiceType = 'Parts Order'
    AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
    AND CU.CustomerBaseBranchID = '1'
    AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
    CU.CustomerKey, CU.[CompanyName],
    CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
    CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
    CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
    CU.CompanyName
</code>```

Title: SQL Server Group By with Joins

Body:
SELECT
    [CustomerKey] AS 'Cust #',
    CU.[CompanyName] AS 'Company Name',
    ISS.InvoiceDate AS 'Invoice Date',
    ISS.InvoiceTotal AS 'Invoice Total',
    ISNULL(CU.ShopPhone,'') AS 'Company Shop',
    ISNULL(CU.CellPhone,'') AS 'Company Cell',
    ISNULL(CU.OfficePhone,'') AS 'Company Office',
    ISNULL(CF.FirstName, '') AS 'FName',
    ISNULL(CF.LastName,'') AS 'LName',
    ISNULL(CF.WorkPhone,'') AS 'Contact Work',
    ISNULL(CF.CellPhone,'') AS 'Contact Cell',
    ISNULL(CF.HomePhone,'') AS 'Contact Home',
    ISNULL(CF.EMail,'') AS 'Contact Email',
    PSO.OutsidePartsSalespersonName
FROM
    [ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
    [ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
    [ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
    (SELECT
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
     FROM
         [ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
     WHERE
         EntityID IS NOT NULL
         AND FirstName <> ''
         AND EntityTypeID = '3'
         AND SetDefault = '1'
     GROUP BY
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
    CU.Inactive = '0'
    AND ISS.InvoiceType = 'Parts Order'
    AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
    AND CU.CustomerBaseBranchID = '1'
    AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
    CU.CustomerKey, CU.[CompanyName],
    ISS.InvoiceDate, ISS.InvoiceTotal,
    CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
    CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
    CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
    CU.CompanyName, ISS.InvoiceDate

How can I group this to SUM ISS.InvoiceTotal grouped by CustomerKey?

I keep getting the "is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause." error.

Any ideas?

Body:
If you SUM() in the ISS table you can't select from it or add it to the GROUP BY.

SELECT
    [CustomerKey] AS 'Cust #',
    CU.[CompanyName] AS 'Company Name',
    LAST(ISS.InvoiceDate) AS 'Invoice Date',
    SUM(ISS.InvoiceTotal) AS 'Invoice Total',
    ISNULL(CU.ShopPhone,'') AS 'Company Shop',
    ISNULL(CU.CellPhone,'') AS 'Company Cell',
    ISNULL(CU.OfficePhone,'') AS 'Company Office',
    ISNULL(CF.FirstName, '') AS 'FName',
    ISNULL(CF.LastName,'') AS 'LName',
    ISNULL(CF.WorkPhone,'') AS 'Contact Work',
    ISNULL(CF.CellPhone,'') AS 'Contact Cell',
    ISNULL(CF.HomePhone,'') AS 'Contact Home',
    ISNULL(CF.EMail,'') AS 'Contact Email',
    PSO.OutsidePartsSalespersonName
FROM
    [ProfitMaster].[dbo].[vwAC_SSR_Customer] CU with (nolock)
LEFT JOIN
    [ProfitMaster].[dbo].[vwAC_SSR_InvoiceSalesSummary] ISS with (nolock) ON CU.CustomerKey = ISS.Customer
JOIN
    [ProfitMaster].[dbo].[vwSV_INV_PartsSalesOrder] PSO with (nolock) ON PSO.PartsSalesOrderInvoiceID = ISS.PartsSalesOrderInvoiceID
LEFT JOIN
    (SELECT
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail
     FROM
         [ProfitMaster].[dbo].[vwGB_CON_ContactFull] with (nolock)
     WHERE
         EntityID IS NOT NULL
         AND FirstName <> ''
         AND EntityTypeID = '3'
         AND SetDefault = '1'
     GROUP BY
         EntityID, FirstName, LastName, WorkPhone, CellPhone, HomePhone, EMail) AS CF ON CU.CustomerID = CF.EntityID
WHERE
    CU.Inactive = '0'
    AND ISS.InvoiceType = 'Parts Order'
    AND ISS.InvoiceDate BETWEEN '2017-02-01 00:00:00.000' AND '2017-03-31 3:59:59.000'
    AND CU.CustomerBaseBranchID = '1'
    AND PSO.OutsidePartsSalespersonName IN ('Dave Freeland', 'Mark Miller', 'Ryan Oaks')
GROUP BY
    CU.CustomerKey, CU.[CompanyName],
    CU.ShopPhone, CU.CellPhone, CU.OfficePhone,
    CF.FirstName, CF.LastName, CF.WorkPhone, CF.CellPhone,
    CF.HomePhone, CF.EMail, PSO.OutsidePartsSalespersonName
ORDER BY
    CU.CompanyName


问:
low-level iOS crash from UIAlertView _performPopup
I've been getting some low level crashes lately, and this one in particular is hard to determine the origin / state of the app. Has anyone seen this or know the problem? Thanks!

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x3dcccccd
Crashed Thread:  0
```<code></p>

<p>Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x3dcccccd
Crashed Thread:  0</p>

<p>Thread 0 Crashed:
0   libobjc.A.dylib                 0x000025fa objc_msgSend + 18
1   UIKit                           0x00162d1c -[UIAlertView(Private) _performPopup:] + 12
2   UIKit                           0x001628de -[UIAlertView(Private) _repopup] + 10
3   UIKit                           0x0016d196 -[UIAlertView(Private) _removeAlertWindowOrShowAnOldAlert] + 70
4   UIKit                           0x00162afa -[UIAlertView(Private) _popoutAnimationDidStop:finished:] + 502
5   UIKit                           0x00050ae4 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 184
6   UIKit                           0x000509ee -[UIViewAnimationState animationDidStop:finished:] + 34
7   QuartzCore                      0x0002ee8c run_animation_callbacks(double, void*) + 284
8   QuartzCore                      0x0002ed2c CA::timer_callback(__CFRunLoopTimer*, void*) + 96
9   CoreFoundation                  0x00022d1c CFRunLoopRunSpecific + 2092
10  CoreFoundation                  0x000224da CFRunLoopRunInMode + 42
11  GraphicsServices                0x000030d4 GSEventRunModal + 108
12  GraphicsServices                0x00003180 GSEventRun + 56
13  UIKit                           0x0000342a -[UIApplication _run] + 374
14  UIKit                           0x00001954 UIApplicationMain + 636
15  iPadDrinkHub.1.0.7              0x00002f24 0x1000 + 7972
16  iPadDrinkHub.1.0.7              0x00002ed8 0x1000 + 7896</p>

<p>```

答:
Weird crashes are sometimes a symptom of memory corruption and/or mismanagement.  I just found and fixed a difficult-to-find bug in one of my apps a few days ago.  The app had been working flawlessly for 6 months on iOS 3.2, but would crash instantly on iOS 4.2.  The crash was happening while adding the main view to the window during applicationDidFinishLaunching.  The stack trace showed 100% iOS code; there wasn't a single function of mine in there anywhere (except for applicationDidFinishLaunching).  It turned out I was over-releasing a UIImage in code that had been called earlier while views were getting loaded.  (I was mistakenly calling release on an autoreleased UIImage).

I haven't seen the specific crash that you're seeing, but here are a few things you can try that may shed some light:

(1) Run the app with NSZombieEnabled.  This is an environment variable you set via Xcode that will often identify places where you may be referencing objects that have already been freed (e.g., like the over-release example I mentioned earlier).  Additional details are here:

http://www.cocoadev.com/index.pl?NSZombieEnabled

(2) You can turn on logging that will log all messages sent to all objects.  The log is a written to a text file in the tmp folder.  If you inspect the log file leading up to the crash, you may gain some insight into what's happening right before the crash.  This is actually the technique I used to solve my bug.  You can either modify your code to enable/disable logging:

```<code>instrumentObjcMessageSends(YES);
// Do stuff...
instrumentObjcMessageSends(NO);
</code>```

Or, you can call the function directly from the debugger.  For example, set a breakpoint right before the crash, then drop into the debugger console and do this:

```<code>(gdb) call (void)instrumentObjcMessageSends(YES)
</code>```

Additional details are here:

http://www.dribin.org/dave/blog/archives/2006/04/22/tracing_objc/

Body:
I've been getting some low level crashes lately, and this one in particular is hard to determine the origin / state of the app. Has anyone seen this or know the problem? Thanks!

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x3dcccccd
Crashed Thread:  0

Exception Type:  EXC_BAD_ACCESS (SIGSEGV)
Exception Codes: KERN_INVALID_ADDRESS at 0x3dcccccd
Crashed Thread:  0

Thread 0 Crashed:
0   libobjc.A.dylib                 0x000025fa objc_msgSend + 18
1   UIKit                           0x00162d1c -[UIAlertView(Private) _performPopup:] + 12
2   UIKit                           0x001628de -[UIAlertView(Private) _repopup] + 10
3   UIKit                           0x0016d196 -[UIAlertView(Private) _removeAlertWindowOrShowAnOldAlert] + 70
4   UIKit                           0x00162afa -[UIAlertView(Private) _popoutAnimationDidStop:finished:] + 502
5   UIKit                           0x00050ae4 -[UIViewAnimationState sendDelegateAnimationDidStop:finished:] + 184
6   UIKit                           0x000509ee -[UIViewAnimationState animationDidStop:finished:] + 34
7   QuartzCore                      0x0002ee8c run_animation_callbacks(double, void*) + 284
8   QuartzCore                      0x0002ed2c CA::timer_callback(__CFRunLoopTimer*, void*) + 96
9   CoreFoundation                  0x00022d1c CFRunLoopRunSpecific + 2092
10  CoreFoundation                  0x000224da CFRunLoopRunInMode + 42
11  GraphicsServices                0x000030d4 GSEventRunModal + 108
12  GraphicsServices                0x00003180 GSEventRun + 56
13  UIKit                           0x0000342a -[UIApplication _run] + 374
14  UIKit                           0x00001954 UIApplicationMain + 636
15  iPadDrinkHub.1.0.7              0x00002f24 0x1000 + 7972
16  iPadDrinkHub.1.0.7              0x00002ed8 0x1000 + 7896

Body:
Weird crashes are sometimes a symptom of memory corruption and/or mismanagement.  I just found and fixed a difficult-to-find bug in one of my apps a few days ago.  The app had been working flawlessly for 6 months on iOS 3.2, but would crash instantly on iOS 4.2.  The crash was happening while adding the main view to the window during applicationDidFinishLaunching.  The stack trace showed 100% iOS code; there wasn't a single function of mine in there anywhere (except for applicationDidFinishLaunching).  It turned out I was over-releasing a UIImage in code that had been called earlier while views were getting loaded.  (I was mistakenly calling release on an autoreleased UIImage).

I haven't seen the specific crash that you're seeing, but here are a few things you can try that may shed some light:

(1) Run the app with NSZombieEnabled.  This is an environment variable you set via Xcode that will often identify places where you may be referencing objects that have already been freed (e.g., like the over-release example I mentioned earlier).  Additional details are here:

http://www.cocoadev.com/index.pl?NSZombieEnabled

(2) You can turn on logging that will log all messages sent to all objects.  The log is a written to a text file in the tmp folder.  If you inspect the log file leading up to the crash, you may gain some insight into what's happening right before the crash.  This is actually the technique I used to solve my bug.  You can either modify your code to enable/disable logging:

instrumentObjcMessageSends(YES);
// Do stuff...
instrumentObjcMessageSends(NO);

Or, you can call the function directly from the debugger.  For example, set a breakpoint right before the crash, then drop into the debugger console and do this:

(gdb) call (void)instrumentObjcMessageSends(YES)

Additional details are here:

http://www.dribin.org/dave/blog/archives/2006/04/22/tracing_objc/


问:
Build action for sql script files in database projects (*.sqlproj)
For a sql script file in a database project, is there anything to be gained by using a Build Action of Build or Compile? I usually just use None, but wonder if Build or Compile do anything for a sql script e.g. perhaps some sort of additional syntax checking?

(We use our own custom deployment for scripts, so deployment options are not required.)

答: If you are building the project, creating a dacpac and then using sqlpackage.exe to deploy the dacpac to the server. Then setting the build action to none on a script will ensure that the script is not included in the update to the server. It give you8 a way to control what updates are carried out thru this tooling. </p>


问:
Updating A Program's Directory
I have a program that uses forms.  The forms are pointing to files in c:\filepath1 as set forth in main.prg (set defa, set path).   I make a test copy of the files, change the path in main.prg, the forms are still referencing the files in the old path.  I don't want to have to recreate all the data environments in all the forms.  How can I avoid doing so?  Any help on this would be kindly appreciated.

Missy.

答:
When Dataenvironment is used AND the path recorded in DataEnvironment tables exist, then that path is used no matter what the current path is. If you don't want to touch Dataenvironment at all (even programmatically) then you must remove that path (rename for example).

As a side note: I have:

```<code>UpdateDE(this)
</code>```

in my DataEnvironment.BeforeOpenTables method. In UpdateDE.prg I have code that loops all the cursors in DE and set their path to the one that I want to use as "current".

EDIT: Here is a sample UpdateDE.prg:

```<code>Lparameters toDE
Do setups && prg keeping common "set" entries
Local Array aDEMembers[1]
Local lnMembers,ix,lcMembers
If !(Type('oApp')='O' And !Isnull(m.oApp))
  Public oApp
  oApp = Createobject('myApp')
Endif
lnMembers = Amembers(aDEMembers,m.toDE,2)
For ix=1 To m.lnMembers
  With Evaluate('toDe.'+aDEMembers[m.ix])
    If Lower(.BaseClass) == 'cursor'
      If Atc(oApp.cAppDBC,.Database) > 0
        .Database = Addbs(oApp.cAppDataPath)+oApp.cAppDBC
      Else
        .CursorSource = Addbs(oApp.cAppDataPath)+Justfname(.CursorSource)
      Endif
    Endif
  Endwith
Endfor

Define Class myApp As Custom
  cAppDBC = 'myDatabase.dbc'
  cAppDataPath=Fullpath('data')
  cCurPath = ''
  Procedure Init
    This.cCurPath = Set('path')
    If File('dbparam.dbf') && a small dbf that holds path to current data folder
      Select dataLoc From dbparam Where locType == 'DATABASE' Into Array arrDataLoc
      If _Tally > 0
        This.cAppDataPath = arrDataLoc
        Set Path To (arrDataLoc[1]+';'+This.cCurPath)
      Endif
      Use In 'dbparam'
    Endif
  Endproc
  Procedure Destroy
    Set Path To (This.cCurPath)
  Endproc
Enddefine
</code>```

Title: Updating A Program's Directory

Body:
When Dataenvironment is used AND the path recorded in DataEnvironment tables exist, then that path is used no matter what the current path is. If you don't want to touch Dataenvironment at all (even programmatically) then you must remove that path (rename for example).

As a side note: I have:

UpdateDE(this)

in my DataEnvironment.BeforeOpenTables method. In UpdateDE.prg I have code that loops all the cursors in DE and set their path to the one that I want to use as "current".

EDIT: Here is a sample UpdateDE.prg:

Lparameters toDE
Do setups && prg keeping common "set" entries
Local Array aDEMembers[1]
Local lnMembers,ix,lcMembers
If !(Type('oApp')='O' And !Isnull(m.oApp))
  Public oApp
  oApp = Createobject('myApp')
Endif
lnMembers = Amembers(aDEMembers,m.toDE,2)
For ix=1 To m.lnMembers
  With Evaluate('toDe.'+aDEMembers[m.ix])
    If Lower(.BaseClass) == 'cursor'
      If Atc(oApp.cAppDBC,.Database) > 0
        .Database = Addbs(oApp.cAppDataPath)+oApp.cAppDBC
      Else
        .CursorSource = Addbs(oApp.cAppDataPath)+Justfname(.CursorSource)
      Endif
    Endif
  Endwith
Endfor

Define Class myApp As Custom
  cAppDBC = 'myDatabase.dbc'
  cAppDataPath=Fullpath('data')
  cCurPath = ''
  Procedure Init
    This.cCurPath = Set('path')
    If File('dbparam.dbf') && a small dbf that holds path to current data folder
      Select dataLoc From dbparam Where locType == 'DATABASE' Into Array arrDataLoc
      If _Tally > 0
        This.cAppDataPath = arrDataLoc
        Set Path To (arrDataLoc[1]+';'+This.cCurPath)
      Endif
      Use In 'dbparam'
    Endif
  Endproc
  Procedure Destroy
    Set Path To (This.cCurPath)
  Endproc
Enddefine


问:
Why is AdMob ad Frequency capping not working?
I set two impressions per minute per user but it doesn't work. Ads keep showing every time.

on AdMob site they say : A change to frequency capping, such as changing the cap from two to three, can take up to a day to take effect.

But it has been more than FIVE days since I applied change to Frequency capping and it is not working? Here is how I request ads :

```<code>private void requestNewInterstitial() {
        AdRequest adRequest = new   AdRequest.Builder().addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").build();
        mInterstitialAd.loadAd(adRequest);
}
</code>```

I use setTestDevice so real ads wont show app because impressions on real ads can get me banned.

答:
Admob puts frequency capping on Real Ads only and not on Test Ads. Try removing your test device and observe real Ads, frequency capping works. I have tried and tested on Emulator and Real device.
Found no docs for reference, this is from my experience.

To Suffice-

Frequency capping works when Not added as Test Device

Frequency capping does not work Added as Test Device

Hope it helps :)

Body:
I set two impressions per minute per user but it doesn't work. Ads keep showing every time.

on AdMob site they say : A change to frequency capping, such as changing the cap from two to three, can take up to a day to take effect.

But it has been more than FIVE days since I applied change to Frequency capping and it is not working? Here is how I request ads :

private void requestNewInterstitial() {
        AdRequest adRequest = new   AdRequest.Builder().addTestDevice("XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX").build();
        mInterstitialAd.loadAd(adRequest);
}

I use setTestDevice so real ads wont show app because impressions on real ads can get me banned.


问:
C Not able to include a format specifier when assign a string
I'd like to be able to use the %d format specifier when assign a value to a string called answer. I tried to do this but I can't get the format specifier replaced by an integer when running the program...
Here's my code:

```<code>#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    const char *answer;
    int year;
    printf("Enter a year: \n");
    scanf("%d", &year);
    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        answer =  "%d does have a bissextus day", year;
    }
    else {
        answer = "%d doesn't have a bissextus day", year;
    }

    printf("%s\n", answer);

    return 0;
}
</code>```

I'd also like to know if in this case it's a good choice to use const char *answer and if it's not, I'd like to know what I should use instead.

答:
You can use snprintf:

```<code>char answer[34];
// ...
snprintf(answer, 34, "%d does have a bissextus day", year);
</code>```

Body:
I'd like to be able to use the %d format specifier when assign a value to a string called answer. I tried to do this but I can't get the format specifier replaced by an integer when running the program...
Here's my code:

#include <stdio.h>
#include <stdlib.h>
int main(void)
{
    const char *answer;
    int year;
    printf("Enter a year: \n");
    scanf("%d", &year);
    if ( (year % 400 == 0) || ( (year % 4 == 0) && !(year % 100 == 0) ) ){
        answer =  "%d does have a bissextus day", year;
    }
    else {
        answer = "%d doesn't have a bissextus day", year;
    }

    printf("%s\n", answer);

    return 0;
}

I'd also like to know if in this case it's a good choice to use const char *answer and if it's not, I'd like to know what I should use instead.

Body:
You can use snprintf:

char answer[34];
// ...
snprintf(answer, 34, "%d does have a bissextus day", year);


问:
How do I "clear" std::promise?
I have a program, which should in cycle launch 8 threads, which will return a value using std::promise. So I think I need to create a vector of 8 promise objects, get their futures, and use these promises to return the values and then join the threads with main. The problem is this: on the next iteration I will create 8 more threads -- can i reuse the same promise objects, or do I need to create 8 more? I haven't found any way to reuse them on the internet, but maybe I'm missing something obvious?

答:
To reuse promises, simply reassign them.</p>

```<code>std::promise<int> my_promise;
//use the promise
my_promise = std::promise<int>(); //now you have a new promise
</code>```

Title: How do I "clear" std::promise?

Body:
To reuse promises, simply reassign them.

std::promise<int> my_promise;
//use the promise
my_promise = std::promise<int>(); //now you have a new promise


问:
Column name or number of supplied values does not match table definition in SQL Server 2014
```<code>DECLARE @query VARCHAR(max)
DECLARE @years VARCHAR(max)

SELECT  @years = STUFF(( SELECT DISTINCT '],[' + ltrim(str(Years)) FROM
                 #Inquires ORDER BY '],[' + ltrim(str(Years)) desc FOR XML
                 PATH('')), 1, 2, '') + ']'

SET @query = 'INSERT INTO Table_Name SELECT *
              FROM (SELECT ReportDate, Company, EventType, Years,Months#,
                    Months,Inquires FROM #Inquires
                    WHERE Company = ''Company_Name'')t PIVOT (SUM(Inquires)
                    FOR Years IN ('+@years+')) AS pvt ORDER BY Company, Months#'

EXECUTE (@query)
</code>```

I am getting this error while executing this code:

Column name or number of supplied values does not match table definition

This code is running fine in SQL Server 2008, but not in SQL Server 2014.

答:
I'm guessing that you now have more years returned from your pivot than you have in your table.

Try specifying your column names for your insert and in your select.

Body:
DECLARE @query VARCHAR(max)
DECLARE @years VARCHAR(max)

SELECT  @years = STUFF(( SELECT DISTINCT '],[' + ltrim(str(Years)) FROM
                 #Inquires ORDER BY '],[' + ltrim(str(Years)) desc FOR XML
                 PATH('')), 1, 2, '') + ']'

SET @query = 'INSERT INTO Table_Name SELECT *
              FROM (SELECT ReportDate, Company, EventType, Years,Months#,
                    Months,Inquires FROM #Inquires
                    WHERE Company = ''Company_Name'')t PIVOT (SUM(Inquires)
                    FOR Years IN ('+@years+')) AS pvt ORDER BY Company, Months#'

EXECUTE (@query)

I am getting this error while executing this code:

Column name or number of supplied values does not match table definition

This code is running fine in SQL Server 2008, but not in SQL Server 2014.


问:
Same GET request to same URL give different Response, strange behavior
I have a very strange bug and I don't know what is going on.

I have an endpoints like this:

```<code> private void init() {
    if (ioConfigurationDAO == null) {
      ioConfigurationDAO = new IOConfigurationDAO();
      ioConfigurationDAO.init();
    }

    property = new AigatewayProperty();
 }

  @GET
  @Path("/{id : \\d+}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getIoConfiguration(@PathParam("id") Integer id) {
    init();
    if (!ChannelName.isValidChannel(id)) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    IOConfiguration ioConfig = ioConfigurationDAO.findIOConfiguration("CH" + id);
    System.out.println(ioConfig.getConversionType());
    // close();
    return Response.status(Response.Status.OK).entity(ioConfig).build();
  }
</code>```

When I am making request to this url: http://localhost:8080/aigateway/rest/ioconfiguration/3

Some time, I get a correct response:

{"ioConfigurationId":"CH3","active":true,"name":"1","conversionType":"Linear","mInfo":0.32,"bInfo":0.55,"voltageDivide":"/4","sampleRange":"24
  Bits","samplePeriod":10,"storeRaw":false,"storeConverted":false,"defaultGraph":"Line","title":"","unit":"","rangeLowerbound":0,"rangeUpperbound":100,"code":"function
  conversion_CH3 (input) {\n\treturn input;\n}"}

Sometimes, I get wrong response with null values:

{"ioConfigurationId":"CH3","active":null,"name":null,"conversionType":null,"mInfo":null,"bInfo":null,"voltageDivide":null,"sampleRange":null,"samplePeriod":null,"storeRaw":null,"storeConverted":null,"defaultGraph":null,"title":null,"unit":null,"rangeLowerbound":null,"rangeUpperbound":null,"code":null}

I don't know what is going on.

One thing to mention is that:

I have to manually initiate my entity manager becuase my EJB annotations doesn't work, and I am not closing my connection to the database since I don't know when the applicaton will end. I don't know if this is the reason that cause this problem.

Someone please help me, if you need more information, I am willing to share.

Thanks!

答: I solved this problem by using EJB properly. The only reason I can think that is causing this problem is because I never close the my entity manager, so the next time when I am trying to create a new one, there is some problem going on and that's why I am getting null values sometimes.</p>

Body:
I have a very strange bug and I don't know what is going on.

I have an endpoints like this:

 private void init() {
    if (ioConfigurationDAO == null) {
      ioConfigurationDAO = new IOConfigurationDAO();
      ioConfigurationDAO.init();
    }

    property = new AigatewayProperty();
 }

  @GET
  @Path("/{id : \\d+}")
  @Produces(MediaType.APPLICATION_JSON)
  public Response getIoConfiguration(@PathParam("id") Integer id) {
    init();
    if (!ChannelName.isValidChannel(id)) {
      return Response.status(Response.Status.NOT_FOUND).build();
    }
    IOConfiguration ioConfig = ioConfigurationDAO.findIOConfiguration("CH" + id);
    System.out.println(ioConfig.getConversionType());
    // close();
    return Response.status(Response.Status.OK).entity(ioConfig).build();
  }

When I am making request to this url: http://localhost:8080/aigateway/rest/ioconfiguration/3

Some time, I get a correct response:

{"ioConfigurationId":"CH3","active":true,"name":"1","conversionType":"Linear","mInfo":0.32,"bInfo":0.55,"voltageDivide":"/4","sampleRange":"24
  Bits","samplePeriod":10,"storeRaw":false,"storeConverted":false,"defaultGraph":"Line","title":"","unit":"","rangeLowerbound":0,"rangeUpperbound":100,"code":"function
  conversion_CH3 (input) {\n\treturn input;\n}"}

Sometimes, I get wrong response with null values:

{"ioConfigurationId":"CH3","active":null,"name":null,"conversionType":null,"mInfo":null,"bInfo":null,"voltageDivide":null,"sampleRange":null,"samplePeriod":null,"storeRaw":null,"storeConverted":null,"defaultGraph":null,"title":null,"unit":null,"rangeLowerbound":null,"rangeUpperbound":null,"code":null}

I don't know what is going on.

One thing to mention is that:

I have to manually initiate my entity manager becuase my EJB annotations doesn't work, and I am not closing my connection to the database since I don't know when the applicaton will end. I don't know if this is the reason that cause this problem.

Someone please help me, if you need more information, I am willing to share.

Thanks!


问:
What is the --release flag in the Java 9 compiler?
Java 9's javac has a new flag --release:

```<code>> javac --help
...

--release <release>
    Compile for a specific VM version. Supported targets: 6, 7, 8, 9
</code>```

How is it different from -source and -target flags? Is it just a shortcut for -source X -target X?

答:
Not exactly.

JEP 247: Compile for Older Platform Versions defines this new command-line option, --release:

We defined a new command-line option, --release, which automatically configures the compiler to produce class files that will link against an implementation of the given platform version. For the platforms predefined in javac, --release N is equivalent to -source N -target N -bootclasspath <bootclasspath-from-N>. (emphasis mine)

So no, it is not equivalent to -source N -target N. The reason for this addition is stated in the "Motivation" section:

javac provides two command line options, -source and -target, which can be used to select the version of the Java language accepted by the compiler and the version of the class files it produces, respectively. By default, however, javac compiles against the most-recent version of the platform APIs. The compiled program can therefore accidentally use APIs only available in the current version of the platform. Such programs cannot run on older versions of the platform, regardless of the values passed to the -source and -target. options. This is a long-term usability pain point, since users expect that by using these options they'll get class files that can run on the specified platform version.

In short, specifying the source and target options are not sufficient for cross-compilation. Because javac, by default, compiles against the most recent of the platform APIs, they can't be guaranteed to run on older versions. You also need to specify the -bootclasspath option corresponding to the older version to cross-compile correctly. This would include the correct API version to compile against and allow for execution on older version. Since it was very often forgotten, it was decided to add one command line option which did all the necessary things to correctly cross-compile.

Further reading in the mailing list and Oracle Docs. The original bug was filed here. Note that since the integration of this option, JDK builds have come bundled with descriptions of the platform APIs of older releases, mentioned under section "Risks and Assumptions". That means you don't need the older version installed on your machine for cross-compilation to work.

Body:
Java 9's javac has a new flag --release:

> javac --help
...

--release <release>
    Compile for a specific VM version. Supported targets: 6, 7, 8, 9

How is it different from -source and -target flags? Is it just a shortcut for -source X -target X?


问:
How to configure Airflow dag to run at specific time on daily basis?
How to configure the Airflow dag to execute at specified time on daily basis no matter what happens, something exactly like crons.

I know that similar behaviour could be obtained using TimeSensor, but in this case it depends upon the sensor tasks and which might conflict with the dag execution time.

Example: With sensor approach if I have sensor to run at 0 hour 15th minutes but if dag is executed at later then my task is delayed, so even for the sensor approach I need to make sure that the Dag is executed on right time.

So how to make sure that Dag is executed at specified time?

答:
To start a DAG for example everyday on 2:30 AM in the morning you can do the following:

```<code>DAG(
   dag_id='dag_id',
   # start date:28-03-2017
   start_date= datetime(year=2017, month=3, day=28),
   # run this dag at 2 hours 30 min interval from 00:00 28-03-2017
   schedule_interval='30 2 * * *')
</code>```

Before configuring the schedule the interpretation of the cron interval can verified and tested here: https://crontab.guru/

Body:
To start a DAG for example everyday on 2:30 AM in the morning you can do the following:

DAG(
   dag_id='dag_id',
   # start date:28-03-2017
   start_date= datetime(year=2017, month=3, day=28),
   # run this dag at 2 hours 30 min interval from 00:00 28-03-2017
   schedule_interval='30 2 * * *')

Before configuring the schedule the interpretation of the cron interval can verified and tested here: https://crontab.guru/


问:
Django view: How to display data from a dictionary
I've got a dictionary like {'a':{'c':2, 'd':4 }, 'b': {'c':'value', 'd': 3}}

How can I display this into a table in view?

答:
Depends on how you want to do it. In Django templates, you access keys the same way you access a method. That is, Python code like

```<code>print my_dict['a']['c']    # Outputs: 2
</code>```

becomes

```<code>{{ my_dict.a.c }}    {# Outputs: 2 #}
</code>```

in Django templates.

Body:
Depends on how you want to do it. In Django templates, you access keys the same way you access a method. That is, Python code like

print my_dict['a']['c']    # Outputs: 2

becomes

{{ my_dict.a.c }}    {# Outputs: 2 #}

in Django templates.


问:
Insert from one table into another with commit Intervals
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

```<code>INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)
</code>```

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

```<code>create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;
</code>```

答:
The increment of uncommitted needs to be
    uncommitted := uncommitted + sql%rowcount ; </p>

<p>Not as in post
    uncommitted :+ uncommitted + sql%rowcount ; </p>

Body:
I have written a procedure to insert data from one table into another table. There is a huge amount of data - a total of 106 millions rows. So I want to put a commit interval on the query.

I have found this script that normally will work and will not take time to get the job done but I don't know why I get an error on

INSERT INTO dlc_pr_activity_remise
VALUES (add all values using ga_array(i).<value in select>)

Errors:

Error(51,1): PL/SQL: SQL Statement ignored

  Error(51,47): PL/SQL: ORA-00917: missing comma

My procedure :

create or replace
PROCEDURE ACTIVITY1 AS
BEGIN
DECLARE
commit_interval pls_integer := 250000 ;
uncommitted pls_integer := 0;
fetch_size  pls_integer := 2500 ;
cursor g1 is SELECT prr.EVT_DECLENCHEUR ,
                    prr.BQ_CDF ,
                    prr.BQ_DOM ,
                    prr.NUM_COMMERCANT ,
                    prr.TYPE_CONTRAT_COM ,
                    prr.COMMERCANT_SIRET ,
                    prr.TYPE_PRE_COMP ,
                    prr.BQ_CDF_ID_EBF ,
                    prr.BQ_DOM_ID_EBF ,
                    prr.DAT_TRAITEMENT ,
                    prr.EVT_TYPE_OPERATION ,
                    prr.DEV_MT_CRE ,
                    prr.NBR_DECI_MT_CRE ,
                    prr.REF_FICHIER_TRAITE ,
                    prr.NUM_CTC ,
                    prr.REF_FICHIER_ORIGINE ,
                    prr.ORIGINE_FLUX ,
                    prr.NUM_EST_REMISE ,
                    prr.NUM_REMISE_ORIGINE ,
                    prr.NUM_MACHINE ,
                    prr.REF_ARCHIVAGE_REM ,
                    prr.DAT_REMISE ,
                    prr.SUPPORT_REMISE ,
                    prr.DAT_REMISE_CALCULEE ,
                    prr.DAT_VALEUR_REMISE ,
                    prr.COD_APPLI ,
                    to_date(SYSDATE,'DD/MM/YYYY')
                    FROM dlc_pr_remise prr
                    WHERE NOT EXISTS
                      (SELECT *
                      FROM DLC_PR_ACTIVITY_REMISE prao
                      WHERE prao.num_est_remise = prr.num_est_remise
                      );
TYPE GL_T is table of gl%rowtype ;
gl_array GL_T;
begin
open gl ;
loop
fetch gl
bulk collect
into gl_array
limit fetch_size ;
forall i in 1 .. gl_arary.count
INSERT INTO dlc_pr_activity_remise values(add all values using ga_array(i).<value in select>)
uncommitted :+ uncommitted + sql%rowcount ;
exit when gl_arary.count < fetch_size ;
if uncommitted >= commit_interval
then
commit ;
uncommitted := 0;
end if ;
end loop ;
commit ;
close gl;
END ;
END ACTIVITY1;

Body:
The increment of uncommitted needs to be
    uncommitted := uncommitted + sql%rowcount ;

Not as in post
    uncommitted :+ uncommitted + sql%rowcount ;


答:
You should use a timer which checks for short time intervals and the shouldChangeTextInRange delegate method for UITextView and write a condition for space strings. After that, you can use the insertText method of UITextInput, one of UITextView's protocols:

```<code>func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " {
        if isSecondSpace {
            (textView as UIKeyInput).insertText("     ") //5 spaces
        } else {
            isSecondSpace = true

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                self.isSecondSpace = false
            }
        }

        return false
    }

    return true
}
</code>```

Title: In Swift, how do I detect a double tap from the spacebar in UITextView?

Body: I'm working on an app that is heavily dependent on a UITextView. The desired behavior is when a user double taps the spacebar, the cursor will indent 5 spaces. How would I do this?

Body:
You should use a timer which checks for short time intervals and the shouldChangeTextInRange delegate method for UITextView and write a condition for space strings. After that, you can use the insertText method of UITextInput, one of UITextView's protocols:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    if text == " " {
        if isSecondSpace {
            (textView as UIKeyInput).insertText("     ") //5 spaces
        } else {
            isSecondSpace = true

            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.2) {
                self.isSecondSpace = false
            }
        }

        return false
    }

    return true
}


问:
Force Scrollbars Images CSS
How would I accomplish the following without the use of tables?

If I don't wrap the imgs in tds the scroll bars aren't forced.

The imgs are pushed down like regular text with out the tds.

I have tried setting the imgs to display:block, inline-block and a couple other ideas but I'm clueless.

http://jsfiddle.net/zjews/

Edit: I could apply inline-table to the wrapped "a" links but unfortunately internet explorer doesn't support this property.  Does anyone know of a way to emulate inline-table in internet explorer.

答:
You could wrap all the images in a container div and give that a fixed width.  Then force the x axis to overflow.

something like this: http://jsfiddle.net/3n6nm/1/

Title: Force Scrollbars Images CSS