答:
i see 2 errors in your falling code. In getLtcPrice function, you should check for errors before resolving, so.

```<code>function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url, function (error, response, body) {
      if (error) { // check for errors immediatly
        reject(ltc_price)
        return
      }
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
        resolve(ltc_price)
      });
    })
  }
</code>```

in saveLtcPrice function, you are always resolving passing a call to an async function. This make no sense. You should do exactly like you did in getLtcPrice function, so:

```<code>function saveLtcPrice (ltc_price) {
      return new Promise(function(resolve, reject) {
        db_name.insert({ _id: nonce, currency:"Litecoin", price:
          ltc_price},function(err, document) { //changed variable name "body" to "document". it's just a convention, this is not the body of an http request, this is an object inside a database
             if (err) {
               reject(err)
               return
             }

             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
             resolve(document)
          })
          )
      });
    }
</code>```

Finally, you should catch errors inside your setInterval function

Title: NodeJS - infinite call on promise functions

Body:
i see 2 errors in your falling code. In getLtcPrice function, you should check for errors before resolving, so.

function getLtcPrice(){
  return new Promise(function(resolve, reject){
    request.get(ltc_url, function (error, response, body) {
      if (error) { // check for errors immediatly
        reject(ltc_price)
        return
      }
        var rep = JSON.parse(body);
        var ltc_price = rep.ask;
        resolve(ltc_price)
      });
    })
  }

in saveLtcPrice function, you are always resolving passing a call to an async function. This make no sense. You should do exactly like you did in getLtcPrice function, so:

function saveLtcPrice (ltc_price) {
      return new Promise(function(resolve, reject) {
        db_name.insert({ _id: nonce, currency:"Litecoin", price:
          ltc_price},function(err, document) { //changed variable name "body" to "document". it's just a convention, this is not the body of an http request, this is an object inside a database
             if (err) {
               reject(err)
               return
             }

             console.log(" ltc price : "+ ltc_price +", uploaded to the database ");
             resolve(document)
          })
          )
      });
    }

Finally, you should catch errors inside your setInterval function


来源: stackexchange

问:
How to find if a string contains any objects in an array?
Say if I have the following code

```<code>String sum = "(5+5)/2*6";
char[] bodmasChars = {'+','-','*','/','.'.'(',')'};
</code>```

Is there a way to check whether the string contains any of the elements in my char[]?

答:
You can try it with Regex or with Simple as :</p>

```<code>String s="(5+5)/2*6";
        if((s.contains("+")||(s.contains("-")||(s.contains("-"))||....))
                {
            System.out.println("yes");
                }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Say if I have the following code

String sum = "(5+5)/2*6";
char[] bodmasChars = {'+','-','*','/','.'.'(',')'};

Is there a way to check whether the string contains any of the elements in my char[]?

Body:
You can try it with Regex or with Simple as :

String s="(5+5)/2*6";
        if((s.contains("+")||(s.contains("-")||(s.contains("-"))||....))
                {
            System.out.println("yes");
                }


问:
Meld error when setting up a new cluster
I am evaluating the DataStax OpsCenter on a virtual machine to start managing/monitoring cassandra. I am following the online docs to create cluster topology models via OpsCenter LCM, but the error message doesn't provide much information for me to continue. The jobs status are,

```<code>error- MeldError, 400 Client Error: Bad Request for url: http://[ip_address]:8888/api/v1/lcm/internal/nodes/6185c776-9034-45b4-a54f-6eb9511274a2/package_information
Meld failed on name="testnode1" ssh-management-address=[ip_address]" node-id="6185c776-9034-45b4-a54f-6eb9511274a2" node-name="testnode1" job-id="1b792c69-bcca-489f-ad12-a6285ba84d59" stdout=" Meld has started... " stderr=""
</code>```

My question is what might be wrong and any hint how to resolve that?

I am new to the cassandra and DataStax communities, please forgive me if any silly question asked!

Q: I used to be a buildbot user and DataStax agent looks like a Buildbot's slave. Why we don't need agent setup on the remote machine to work with opscenter? The working directory of agent is configured in opscenter?

The opscenterd.log, https://pastebin.com/TJsvmr6t

答:
According to the compatibility of the tools set mentioned in https://docs.datastax.com/en/landing_page/doc/landing_page/compatibility.html#compatibilityDocument__opsc-compatibility , I actually use the OpsCenter v5.2 for monitoring and basic db operations. After trial-and-error of .yaml of Agent and .conf of Cassandra 2.2, the Dashboard works!

Knowledge gained,

The OpsCenter 5.2 actually works with Cassandra 2.2 which is not listed in the compatibility table

For beginner, if not sure where to start, try to install all the components on one machine to get idea of the least viable working setup. And from there to configure the actual dev/test/production environment.

Body:
I am evaluating the DataStax OpsCenter on a virtual machine to start managing/monitoring cassandra. I am following the online docs to create cluster topology models via OpsCenter LCM, but the error message doesn't provide much information for me to continue. The jobs status are,

error- MeldError, 400 Client Error: Bad Request for url: http://[ip_address]:8888/api/v1/lcm/internal/nodes/6185c776-9034-45b4-a54f-6eb9511274a2/package_information
Meld failed on name="testnode1" ssh-management-address=[ip_address]" node-id="6185c776-9034-45b4-a54f-6eb9511274a2" node-name="testnode1" job-id="1b792c69-bcca-489f-ad12-a6285ba84d59" stdout=" Meld has started... " stderr=""

My question is what might be wrong and any hint how to resolve that?

I am new to the cassandra and DataStax communities, please forgive me if any silly question asked!

Q: I used to be a buildbot user and DataStax agent looks like a Buildbot's slave. Why we don't need agent setup on the remote machine to work with opscenter? The working directory of agent is configured in opscenter?

The opscenterd.log, https://pastebin.com/TJsvmr6t


问:
UnicodeDecodeError while using gzip and pickle
I am using the practising code of mnist data for deep learning in Python 3.4

The original code is

```<code>import _pickle as cPickle
def load_data():
    f = gzip.open('../data/mnist.pkl.gz', 'rb')
    training_data, validation_data, test_data = cPickle.load(f)
    f.close()
    return (training_data, validation_data, test_data)
def load_data_wrapper():
    tr_d, va_d, te_d = load_data()
    ....
</code>```

However, it causes the UnicodeDecodeError, according to the suggestions on the Internet, I change it cPickle.load(f) to pickle.load(f, encoding='latin1')

And the same error occurs when I run in the shell

>>> training_data, validation_data, test_data = \
... mnist_loader.load_data_wrapper() \
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\E\Deep Learning Tutorial\neural-networks-and-deep-learning-master\src\mnist_loader.py", line 68, in load_data_wrapper
tr_d, va_d, te_d = load_data()
  File "C:\E\Deep Learning Tutorial\neural-networks-and-deep-learning-master\src\mnist_loader.py", line 43, in load_data
```

<p>And the error line traces back to:</p>

```f = gzip.open('../data/mnist.pkl.gz', 'rb')
```

<p>With the same error as before, but only occurs in different line</p>

<pre class="lang-none prettyprint-override"><code>UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)
</code>```

How to fix this problem?

答:
First of all, I was able to reproduce the problem using the mnist.pkl.gz data file extracted from the https://github.com/mnielsen/neural-networks-and-deep-learning/archive/master.zip archive I downloaded. The following exception is raised from the pickle.load(f) call:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)

However the error went away when I added the encoding='bytes' argument to the pickle.load() call as I suggested in a comment under your question.

Another change was to replace the import _pickle as cPickle with just import pickle, however I don't think that's significant (see What difference between pickle and _pickle in python 3?).

Other differences that might be significant, however, are the fact that I'm using Python 3.6.3 on Windows.

```<code>import gzip
import pickle

def load_data():
    f = gzip.open('mnist.pkl.gz', 'rb')
    training_data, validation_data, test_data = \
        pickle.load(f, encoding='bytes')  # Note encoding argument value.
    f.close()
    return (training_data, validation_data, test_data)

def load_data_wrapper():
    tr_d, va_d, te_d = load_data()
    print('gzipped pickled data loaded successfully')

load_data_wrapper()
</code>```

A digression:
The load_data() function could be written a little more succinctly like this:

```<code>def load_data():
    with gzip.open('mnist.pkl.gz', 'rb') as f:
        training_data, validation_data, test_data = \
            pickle.load(f, encoding='bytes')
    return training_data, validation_data, test_data
</code>```

Body:
I am using the practising code of mnist data for deep learning in Python 3.4

The original code is

import _pickle as cPickle
def load_data():
    f = gzip.open('../data/mnist.pkl.gz', 'rb')
    training_data, validation_data, test_data = cPickle.load(f)
    f.close()
    return (training_data, validation_data, test_data)
def load_data_wrapper():
    tr_d, va_d, te_d = load_data()
    ....

However, it causes the UnicodeDecodeError, according to the suggestions on the Internet, I change it cPickle.load(f) to pickle.load(f, encoding='latin1')

And the same error occurs when I run in the shell

>>> training_data, validation_data, test_data = \
... mnist_loader.load_data_wrapper() \
...
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "C:\E\Deep Learning Tutorial\neural-networks-and-deep-learning-master\src\mnist_loader.py", line 68, in load_data_wrapper
tr_d, va_d, te_d = load_data()
  File "C:\E\Deep Learning Tutorial\neural-networks-and-deep-learning-master\src\mnist_loader.py", line 43, in load_data

And the error line traces back to:

f = gzip.open('../data/mnist.pkl.gz', 'rb')

With the same error as before, but only occurs in different line

UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)

How to fix this problem?

Body:
First of all, I was able to reproduce the problem using the mnist.pkl.gz data file extracted from the https://github.com/mnielsen/neural-networks-and-deep-learning/archive/master.zip archive I downloaded. The following exception is raised from the pickle.load(f) call:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x90 in position 614: ordinal not in range(128)

However the error went away when I added the encoding='bytes' argument to the pickle.load() call as I suggested in a comment under your question.

Another change was to replace the import _pickle as cPickle with just import pickle, however I don't think that's significant (see What difference between pickle and _pickle in python 3?).

Other differences that might be significant, however, are the fact that I'm using Python 3.6.3 on Windows.

import gzip
import pickle

def load_data():
    f = gzip.open('mnist.pkl.gz', 'rb')
    training_data, validation_data, test_data = \
        pickle.load(f, encoding='bytes')  # Note encoding argument value.
    f.close()
    return (training_data, validation_data, test_data)

def load_data_wrapper():
    tr_d, va_d, te_d = load_data()
    print('gzipped pickled data loaded successfully')

load_data_wrapper()

A digression:
The load_data() function could be written a little more succinctly like this:

def load_data():
    with gzip.open('mnist.pkl.gz', 'rb') as f:
        training_data, validation_data, test_data = \
            pickle.load(f, encoding='bytes')
    return training_data, validation_data, test_data


问:
Confused about the depth-first-search result when using Golang
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

```<code>import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}
</code>```

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

答:
The line

```<code>helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
</code>```

may not perform as expected. It is called within the loop, and you are probably assuming that in the each iteration the  append will always add the new member to the existing slice. If has more complex behavior that you seem not caring about enough:

If the new value fits into the current capacity of the backing array withing the slice, it is added to the current backing array. All variables assigned to that slice now report the updated content with the added new value present.

If the value does not fit, a new array is allocated. In this case further modifications of the returned slice will not change the content of the initial slice if that old value is also retained.

I am under impression that you may not expect value/content disagreement between the value returned by append and the parameter list you pass to it.

This behavior is described here (scroll to "gotcha").

Body:
I tried to solve the 'Combination Sum' on leetcode, and the result is wrong when using test case:

[7,3,2] 18

I used C++ with the same logic and passed, but when using Golang, my result is:

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,7,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

and the correct one should be

[[2,2,2,2,2,2,2,2,2],[2,2,2,2,2,2,3,3],[2,2,2,2,3,7],[2,2,2,3,3,3,3],[2,2,7,7],[2,3,3,3,7],[3,3,3,3,3,3]]

the code is shown below:

import "sort"
func combinationSum(candidates []int, target int) [][]int {
    result := make([][]int, 0, 0)
    resultp := &result
    sort.Ints(candidates)
    helper(candidates, 0, target, make([]int, 0, 0), resultp, len(candidates))
    return *resultp
}

func helper(nums []int, index int, target int, list []int, resultp *[][]int, length int) {
    if target == 0 {
        *resultp = append(*resultp, list)
        return
    }
    for i := index; i < length; i++ {
        if i != index && nums[i] == nums[i - 1] {
            continue
        }
        if (nums[i] > target) {
            break
        }
        helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)
    }
}

Can anyone tell me why the result is incorrect, I am just confused about the [2,2,2,2,2,7,3,3] in my answer, why the 7 is before the 3 since the array has been sorted? Or anyone can tell me what mistake I have made in my code

Body:
The line

helper(nums, i, target - nums[i], append(list, nums[i]), resultp, length)

may not perform as expected. It is called within the loop, and you are probably assuming that in the each iteration the  append will always add the new member to the existing slice. If has more complex behavior that you seem not caring about enough:

If the new value fits into the current capacity of the backing array withing the slice, it is added to the current backing array. All variables assigned to that slice now report the updated content with the added new value present.

If the value does not fit, a new array is allocated. In this case further modifications of the returned slice will not change the content of the initial slice if that old value is also retained.

I am under impression that you may not expect value/content disagreement between the value returned by append and the parameter list you pass to it.

This behavior is described here (scroll to "gotcha").


问:
Margin-Bottom from outer DIV does not work
I'd like to create an outer DIV, which contains several inner DIVs. At the moment, this works perfect.
But I have some troubles with the margin of the outer div. If the outer DIV has a fixed height (f.ex. height: 100px;), there will be a margin at the bottom. But if I set the height to auto (it should have only the height of all inner DIVs), the margin-bottom disappears.

Example:

Here, the margin-bottom applies normaly. The height of the outer-box is set to a fixed height:
https://jsfiddle.net/v81mehc5/3/

But changing the height of the outer DIV from a fixed height (75px) to auto, the margin-bottom of 40px disappears.
https://jsfiddle.net/v81mehc5/2/

What's missing in the second case? What's wrong overthere?

HTML

```<code>text before

<div class="outer-box">
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
  <div class="innerbox-left">left</div>
  <div class="innerbox-right">right</div>
</div>

text after
</code>```

CSS

```<code>.outer-box
{
  width: 200px;
  height: 75px; /*if height: auto > no margin-bottom will be applied*/
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}
</code>```

Thank you very much for your help.

答:
Floating elements collapse their container. You'll see that if you apply a border to it:

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

<p>You can use a clearing technique to get around this as a possible solution that works in IE8 and up:</p>

```.clearfix:after {
    content: "";
    display: table;
    clear: both;
}
```

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-css lang-css prettyprint-override"><code>  .clearfix:after {
      content: "";
      display: table;
      clear: both;
  }</code>```

Text```

Body:
I'd like to create an outer DIV, which contains several inner DIVs. At the moment, this works perfect.
But I have some troubles with the margin of the outer div. If the outer DIV has a fixed height (f.ex. height: 100px;), there will be a margin at the bottom. But if I set the height to auto (it should have only the height of all inner DIVs), the margin-bottom disappears.

Example:

Here, the margin-bottom applies normaly. The height of the outer-box is set to a fixed height:
https://jsfiddle.net/v81mehc5/3/

But changing the height of the outer DIV from a fixed height (75px) to auto, the margin-bottom of 40px disappears.
https://jsfiddle.net/v81mehc5/2/

What's missing in the second case? What's wrong overthere?

HTML

text before

left

right

left

right

text after

CSS

.outer-box
{
  width: 200px;
  height: 75px; /*if height: auto > no margin-bottom will be applied*/
  background-color: #f1f1f1;
  border: thin dotted #ccc;
  margin-bottom: 40px;
}
.innerbox-left
{
  width: 100px;
  background-color: blue;
  float: left;
}
.innerbox-right
{
  width: 100px;
  background-color: blue;
  float: right;
}

Thank you very much for your help.

Body:
Floating elements collapse their container. You'll see that if you apply a border to it:

<div style="border: 1px solid #666; margin-bottom: 40px;">
<div style="float: left; height: 100px; border: 1px solid #999; width: 49%;"></div>
<div style="float: right; height: 100px; border: 1px solid #999; width: 49%;"></div>
</div>
Text

You can use a clearing technique to get around this as a possible solution that works in IE8 and up:

.clearfix:after {
    content: "";
    display: table;
    clear: both;
}

  .clearfix:after {
      content: "";
      display: table;
      clear: both;
  }

<div style="border: 1px solid #666; margin-bottom: 40px;" class="clearfix">
<div style="float: left; height: 100px; border: 1px solid #999; width: 49%;"></div>
<div style="float: right; height: 100px; border: 1px solid #999; width: 49%;"></div>
</div>
Text


问:
How can I create a motion-blur effect with CSS?
I've got this working nicely on objects with a solid background colour, by applying multiple box-shadows:

jsFiddle

html:

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

css:

```<code>div{width: 50px;
    height: 50px;
    margin: 100px;
    border-radius: 25px;
    background: rgb(0,150,0);
    box-shadow: -15px 0 12px rgba(0,150,0,0.2)
              , -11px 0 10px rgba(0,150,0,0.4)
              ,  -8px 0  8px rgba(0,150,0,0.6)
              ,  -6px 0  6px rgba(0,150,0,0.8)}
</code>```

This isn't ideal as you get shadow bleeding up and down from the element instead of just to the left, but it kinda does the job.

But what I really want is for it to work nicely with a background image, e.g. in this jsFiddle I'd like the colours on the edge of the div (or the edge of the background image at least) to be stretched out.

How can I do that?  Can I?

Thank you

答:
You could add a ::before then duplicate your element and blur it.

div{
  position: relative;
  width: 50px;
        height: 50px;
        margin: 100px;
        border-radius: 25px;
        background: url(https://i.imgur.com/pDj7wo9.png);
        background-size: cover;
        background-position: left center;
}

div::before {
    background: url(https://i.imgur.com/pDj7wo9.png);
    background-size: cover;
    background-position: left center;
    position: absolute;
    width: 55px;
    height: 55px;
    overflow: hidden;
    z-index: -1;
    filter: blur(5px);
    content: "";
    border-radius: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div></div></code>```

Body:
I've got this working nicely on objects with a solid background colour, by applying multiple box-shadows:

jsFiddle

html:

css:

div{width: 50px;
    height: 50px;
    margin: 100px;
    border-radius: 25px;
    background: rgb(0,150,0);
    box-shadow: -15px 0 12px rgba(0,150,0,0.2)
              , -11px 0 10px rgba(0,150,0,0.4)
              ,  -8px 0  8px rgba(0,150,0,0.6)
              ,  -6px 0  6px rgba(0,150,0,0.8)}

This isn't ideal as you get shadow bleeding up and down from the element instead of just to the left, but it kinda does the job.

But what I really want is for it to work nicely with a background image, e.g. in this jsFiddle I'd like the colours on the edge of the div (or the edge of the background image at least) to be stretched out.

How can I do that?  Can I?

Thank you

Body:
You could add a ::before then duplicate your element and blur it.

div{
  position: relative;
  width: 50px;
        height: 50px;
        margin: 100px;
        border-radius: 25px;
        background: url(https://i.imgur.com/pDj7wo9.png);
        background-size: cover;
        background-position: left center;
}

div::before {
    background: url(https://i.imgur.com/pDj7wo9.png);
    background-size: cover;
    background-position: left center;
    position: absolute;
    width: 55px;
    height: 55px;
    overflow: hidden;
    z-index: -1;
    filter: blur(5px);
    content: "";
    border-radius: 100%;
}

<div></div>


问:
Access QML root object from C++ QML type
I have a custom QML type written in C++, the classname is MyCustomType and it's located in the files mycustomtype.h and mycustomtype.cpp.

In the main.cpp file the QML type is made available:

```<code>qmlRegisterType<MyCustomType>("MyCustomType", 1, 0, "MyCustomType");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("../qml/main.qml")));
</code>```

In the main.cpp file I can get access to the engine's root object like this:

```<code>rootObject = static_cast<QQuickWindow *> (engine.rootObjects().first());
</code>```

My issue is that I need access to that rootObject from within the MyCustomType class in the mycustomtype.cpp file. Is that possible?

The only way I could think of was to pass the rootObject to the constructor. But since the MyCustomType is instatiated in the QML document, and not in C++ code, this solution won't work.

Any ideas?

答:
I found a solution based on GrecKo's comment.

Instead of making MyCustomType extend QObject, I made it extend QQuickItem. Then it's possible to call window() from anywhere in that class and get the root object. This is simple and it works.

mycustomtype.h:

```<code>class MyCustomType : public QQuickItem
{
    Q_OBJECT

public:
    explicit MyCustomType(QQuickItem *parent = 0);

}
</code>```

mycustomtype.cpp

```<code>MyCustomType::MyCustomType(QQuickItem *parent) : QQuickItem(parent)
{
    QQuickWindow *rootObject = window();
}
</code>```

Body:
I have a custom QML type written in C++, the classname is MyCustomType and it's located in the files mycustomtype.h and mycustomtype.cpp.

In the main.cpp file the QML type is made available:

qmlRegisterType<MyCustomType>("MyCustomType", 1, 0, "MyCustomType");

QQmlApplicationEngine engine;
engine.load(QUrl(QStringLiteral("../qml/main.qml")));

In the main.cpp file I can get access to the engine's root object like this:

rootObject = static_cast<QQuickWindow *> (engine.rootObjects().first());

My issue is that I need access to that rootObject from within the MyCustomType class in the mycustomtype.cpp file. Is that possible?

The only way I could think of was to pass the rootObject to the constructor. But since the MyCustomType is instatiated in the QML document, and not in C++ code, this solution won't work.

Any ideas?

Body:
I found a solution based on GrecKo's comment.

Instead of making MyCustomType extend QObject, I made it extend QQuickItem. Then it's possible to call window() from anywhere in that class and get the root object. This is simple and it works.

mycustomtype.h:

class MyCustomType : public QQuickItem
{
    Q_OBJECT

public:
    explicit MyCustomType(QQuickItem *parent = 0);

}

mycustomtype.cpp

MyCustomType::MyCustomType(QQuickItem *parent) : QQuickItem(parent)
{
    QQuickWindow *rootObject = window();
}


问:
Is there way to apply htmlspecialchars() or html_escape() whole PHP / Codeigniter base website?
I have build a Codeigniter based system.

When edit screens I take values from database and display on input fields.

Example :

```<code>   <input type="text" class="form-control" required="" name="tes_title" value="<?php echo htmlspecialchars($tes_info['tes_title']); ?>">
</code>```

So I had to use htmlspecialchars because some values contains double quotes and single quotes. But adding them manually to all input takes lot of time.

Is there any way to apply htmlspecialchars() or html_escape() whole site wise?

I mean even I use <input type="text" class="form-control" required="" name="tes_title" value="<?php echo $tes_info['tes_title']; ?>"> it should be worked as <input type="text" class="form-control" required="" name="tes_title" value="<?php echo htmlspecialchars($tes_info['tes_title']); ?>">

答:
Write a convenience function.

```<code><?php

function e($str) {
    //return escaped string.
}
</code>```

And use for output where needed:

```<code><?= e($foo) ?>
</code>```

But I'd confine it to your input outputs.  Escape where needed and escape appropriately.

Codeigniter looks to have an html_escape helper function baked in, which is a wrapper around htmlspecialchars.  It will also take an array as input.

You could preprocess the data before you pass to the view (in the controller).  But it could become confusing and unwieldy - you might not want to escape everything that you pass through to the view.

```<code>$data = array(
        'title' => 'My Title',
        'heading' => 'My Heading',
        'message' => 'My Message'
);

$escaped = html_escape($data);

$this->load->view('blogview', $escaped);
</code>```

Body:
I have build a Codeigniter based system.

When edit screens I take values from database and display on input fields.

Example :

   <input type="text" class="form-control" required="" name="tes_title" value="<?php echo htmlspecialchars($tes_info['tes_title']); ?>">

So I had to use htmlspecialchars because some values contains double quotes and single quotes. But adding them manually to all input takes lot of time.

Is there any way to apply htmlspecialchars() or html_escape() whole site wise?

I mean even I use <input type="text" class="form-control" required="" name="tes_title" value="<?php echo $tes_info['tes_title']; ?>"> it should be worked as <input type="text" class="form-control" required="" name="tes_title" value="<?php echo htmlspecialchars($tes_info['tes_title']); ?>">

Body:
Write a convenience function.

<?php

function e($str) {
    //return escaped string.
}

And use for output where needed:

<?= e($foo) ?>

But I'd confine it to your input outputs.  Escape where needed and escape appropriately.

Codeigniter looks to have an html_escape helper function baked in, which is a wrapper around htmlspecialchars.  It will also take an array as input.

You could preprocess the data before you pass to the view (in the controller).  But it could become confusing and unwieldy - you might not want to escape everything that you pass through to the view.

$data = array(
        'title' => 'My Title',
        'heading' => 'My Heading',
        'message' => 'My Message'
);

$escaped = html_escape($data);

$this->load->view('blogview', $escaped);


问:
How can I select a div if another div exists in DOM
I have this sample:

https://codepen.io/anon/pen/NwmPJa

CODE HTML:

```<code><div class="product-info-main">
  <div class="product-add-form">
    <div class="qty">

    </div>
  </div>
</div>

<div class="product-social-links">
  <ul>
    <li>1</li>
    <li>2</li>
    <li>3</li>
  </ul>
</div>
</code>```

CODE CSS:

```<code>.qty + .product-social-links{
      background: red;
}
</code>```

why does not this CSS code go?
I really want to apply the style only if the .qty div exists.

How can I do this without javascript, just from CSS?

Thanks in advance!

答:
The code you mentioned which is  .qty + .product-social-links will not work because .qty does not have the same parent as .product-social-links. They should have the same parent for this to work. A better solution would be to set the parent which is the same level as .product-social-links.

See solution below:

```<code>.product-info-main + .product-social-links {
background: red;
}
</code>```

Body:
I have this sample:

https://codepen.io/anon/pen/NwmPJa

CODE HTML:

1

2

3

CODE CSS:

.qty + .product-social-links{
      background: red;
}

why does not this CSS code go?
I really want to apply the style only if the .qty div exists.

How can I do this without javascript, just from CSS?

Thanks in advance!

Body:
The code you mentioned which is  .qty + .product-social-links will not work because .qty does not have the same parent as .product-social-links. They should have the same parent for this to work. A better solution would be to set the parent which is the same level as .product-social-links.

See solution below:

.product-info-main + .product-social-links {
background: red;
}


问:
Downside of "display: block" for images?
Is there any downside to converting img from inline-block elements into block objects with the display: block CSS property?

Most of the time, I want them to be block elements. Any useful inline aspects that I am losing? (Perhaps I am not seeing some as useful?)

Should all images be converted into block elements by default? Why are they inline-block elements according to spec?

P.S. I am asking this with considerations for layout via positioning & floats, and surrounding elements.

答:
One hack found for block display:"block".

I had this image and the wavesurfer audio wave which I wanted as inline.
But, the display:"block"; in the js of wavesurfer was not allowing it.

What I did was, saved this cdn file locally and changed the display to inline and position to absolute which solved my issue. The change is supposed to be done where the wave element is created.

Hope this helps someone. Thanku wavesurfer creators for such an amazing js.


问:
RxJava custom ArrayList changes reference list also
Structure

```<code>Class Dogs extends RealmObject{
    private RealmList<Cats> cats;
}
</code>```

dogList contains non empty list of cats.
I am trying to remove cats/set as empty list but result also affects on parent list.

```<code> protected void removeCatsFromDogs(ArrayList<Dogs> dogList) {
   ArrayList<Dogs> newList = new  ArrayList<>(dogList);

    Observable.fromIterable(newList)
            .map(dogs ->
                    {
                        dogs.setCats(null);
                        // dogs.setCats(new RealmList<>()); also not working
                        return dogs;
                    }
            ).toList()
            .doOnSuccess(dogs -> baseRealm.executeTransaction(realm -> baseRealm.copyToRealmOrUpdate(dogs)))
            .subscribe();

}
</code>```

doOnSuccess returns dogs with null list but it also reflects in original list.

I have also tried to copy objects one by one using for loop but still same issue.

答:
As stated above, you need to manually create a copy of your objects with the properties you want copied. Something like this should work:</p>

```<code>public class Dogs extends RealmObject {
    public String name;
    public RealmList<Cats> cats;

    public static Dogs shallowCopy(Dogs dogs) {
        Dogs copy = new Dogs();
        copy.name = dogs.name;
        return copy;
    }
}

protected void removeCatsFromDogs(ArrayList<Dogs> dogList) {
    ArrayList<Dogs> newList = new  ArrayList<>(dogList);
    Observable.fromIterable(newList)
        .map(dogs -> { return Dogs.shallowCopy(dogs); })
        .toList()
        .doOnSuccess(dogs -> baseRealm.executeTransaction(realm -> baseRealm.copyToRealmOrUpdate(dogs)))
        .subscribe();
}
</code>```

Body:
Structure

Class Dogs extends RealmObject{
    private RealmList<Cats> cats;
}

dogList contains non empty list of cats.
I am trying to remove cats/set as empty list but result also affects on parent list.

 protected void removeCatsFromDogs(ArrayList<Dogs> dogList) {
   ArrayList<Dogs> newList = new  ArrayList<>(dogList);

    Observable.fromIterable(newList)
            .map(dogs ->
                    {
                        dogs.setCats(null);
                        // dogs.setCats(new RealmList<>()); also not working
                        return dogs;
                    }
            ).toList()
            .doOnSuccess(dogs -> baseRealm.executeTransaction(realm -> baseRealm.copyToRealmOrUpdate(dogs)))
            .subscribe();

}

doOnSuccess returns dogs with null list but it also reflects in original list.

I have also tried to copy objects one by one using for loop but still same issue.

Body:
As stated above, you need to manually create a copy of your objects with the properties you want copied. Something like this should work:

public class Dogs extends RealmObject {
    public String name;
    public RealmList<Cats> cats;

    public static Dogs shallowCopy(Dogs dogs) {
        Dogs copy = new Dogs();
        copy.name = dogs.name;
        return copy;
    }
}

protected void removeCatsFromDogs(ArrayList<Dogs> dogList) {
    ArrayList<Dogs> newList = new  ArrayList<>(dogList);
    Observable.fromIterable(newList)
        .map(dogs -> { return Dogs.shallowCopy(dogs); })
        .toList()
        .doOnSuccess(dogs -> baseRealm.executeTransaction(realm -> baseRealm.copyToRealmOrUpdate(dogs)))
        .subscribe();
}


问:
BASH getopt inside bash function
I would like to put my getopt call into a function so I can make my script a bit more tidy. I've read a few guides Using getopts inside a Bash function but they seem to be for getopts not getopt and cannot get my head round it.

I have the following getopt call at the start of my script

```<code>#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------
getopt_results=$( getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: -- "$@" )

if test $? != 0
then
    echo "Failed to parse command line unrecognized option" >&2
    Usage
    exit 1
fi

eval set -- "$getopt_results"

while true
do
  case "$1" in
      -e | --ENVIRONMENT)
          ENVIRONMENT="$2"
          if [ ! -f "../properties/static/build_static.${ENVIRONMENT}.properties" -o ! -f "../properties/dynamic/build_dynamic.${ENVIRONMENT}.properties" ]; then
            echo "ERROR: Unable to open properties file for ${ENVIRONMENT}"
            echo "Please check they exist or supply a Correct Environment name"
            Usage
            exit 1
          else
            declare -A props
            readpropsfile "../properties/dynamic/dynamic.${ENVIRONMENT}.properties"
            readpropsfile "../properties/static/static.${ENVIRONMENT}.properties"
          fi
          shift 2
          ;;
      -h | --HELP)
          Usage
          exit 1
     ;;
      --)
         shift
         break
         ;;
      *)
         echo "$0: unparseable option $1"
         Usage
         exit 1
         ;;
  esac
done
</code>```

when I put the whole lot in function , say called parse_command_line ()
and call it with parse_command_line "$@"
my script dies because it cannot work out the parameters it was called with. I have tried making OPTIND local as per some of the guides. Any advice? Thanks.

答:
getopt shouldn't be used, but the bash-aware GNU version works fine inside a function, as demonstrated below:

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

main() {
    local getopt_results
    getopt_results=$(getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: "$@")

    eval "set -- $getopt_results" # this is less misleading than the original form

    echo "Positional arguments remaining:"
    if (( $# )); then
      printf ' - %q\n' "$@"
    else
      echo "   (none)"
    fi
}

main "$@"
</code>```

...when saved as getopt-test and run as:

```<code>./getopt-test -e foo=bar "first argument" "second argument"
</code>```

...properly emits:

Positional arguments remaining:
 - -e
 - foo=bar
 - --
 - hello
 - cruel
 - world
```

Title: BASH getopt inside bash function

Body:
I would like to put my getopt call into a function so I can make my script a bit more tidy. I've read a few guides Using getopts inside a Bash function but they seem to be for getopts not getopt and cannot get my head round it.

I have the following getopt call at the start of my script

#-------------------------------------------------------------------------------
# Main
#-------------------------------------------------------------------------------
getopt_results=$( getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: -- "$@" )

if test $? != 0
then
    echo "Failed to parse command line unrecognized option" >&2
    Usage
    exit 1
fi

eval set -- "$getopt_results"

while true
do
  case "$1" in
      -e | --ENVIRONMENT)
          ENVIRONMENT="$2"
          if [ ! -f "../properties/static/build_static.${ENVIRONMENT}.properties" -o ! -f "../properties/dynamic/build_dynamic.${ENVIRONMENT}.properties" ]; then
            echo "ERROR: Unable to open properties file for ${ENVIRONMENT}"
            echo "Please check they exist or supply a Correct Environment name"
            Usage
            exit 1
          else
            declare -A props
            readpropsfile "../properties/dynamic/dynamic.${ENVIRONMENT}.properties"
            readpropsfile "../properties/static/static.${ENVIRONMENT}.properties"
          fi
          shift 2
          ;;
      -h | --HELP)
          Usage
          exit 1
     ;;
      --)
         shift
         break
         ;;
      *)
         echo "$0: unparseable option $1"
         Usage
         exit 1
         ;;
  esac
done

when I put the whole lot in function , say called parse_command_line ()
and call it with parse_command_line "$@"
my script dies because it cannot work out the parameters it was called with. I have tried making OPTIND local as per some of the guides. Any advice? Thanks.

Body:
getopt shouldn't be used, but the bash-aware GNU version works fine inside a function, as demonstrated below:

#!/usr/bin/env bash

main() {
    local getopt_results
    getopt_results=$(getopt -s bash -o e:h --long ENVIRONMENT:,HELP:: "$@")

    eval "set -- $getopt_results" # this is less misleading than the original form

    echo "Positional arguments remaining:"
    if (( $# )); then
      printf ' - %q\n' "$@"
    else
      echo "   (none)"
    fi
}

main "$@"

...when saved as getopt-test and run as:

./getopt-test -e foo=bar "first argument" "second argument"

...properly emits:

Positional arguments remaining:
 - -e
 - foo=bar
 - --
 - hello
 - cruel
 - world

ContentLicense: CC BY-SA 4.0


问:
Line chart in openpyxl
I'm having problems creating a line chart in openpyxl.
I'm using the following code:

```<code>from datetime import date
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference, Series

list_of_num = ['Batch 1', 'Batch 2', 'Batch 3']

ms_lastc = 3

rows = [
    ['Date', 'Batch 1', 'Batch 2', 'Batch 3'],
    [date(2015, 9, 1), 40, 30, 25],
    [date(2015, 9, 2), 40, 25, 30],
    [date(2015, 9, 3), 50, 30, 45],
    [date(2015, 9, 4), 30, 25, 40],
    [date(2015, 9, 5), 25, 35, 30],
    [date(2015, 9, 6), 20, 40, 35]]

if __name__ == '__main__':
    wb = Workbook()
    ms = wb.active
    for row in rows:
        ms.append(row)
    lc = LineChart()
    x = Reference(ms,
                  min_col=1,
                  min_row=2,
                  max_col=1,
                  max_row=7)
    for i, name in enumerate(list_of_num):
        values = Reference(ms,
                           min_col=i+1,
                           min_row=2,
                           max_col=i+1,
                           max_row=7)
        serie = Series(values, xvalues=x, title=name)
        lc.append(serie)
    ms.add_chart(lc, 'A9')
    wb.save('bla.xlsx')
</code>```

The following code shows this result:

And when I open the Serie in the chart the Series values are empty.

Can someone please help me?

答:
Use a scatter chart instead:

```<code>from openpyxl.chart import ScatterChart

ls = ScatterChart()
</code>```

The default is for scatter chart points to be connected by lines, which is probably what you want.

Title: Line chart in openpyxl

Body:
I'm having problems creating a line chart in openpyxl.
I'm using the following code:

from datetime import date
from openpyxl import Workbook
from openpyxl.chart import LineChart, Reference, Series

list_of_num = ['Batch 1', 'Batch 2', 'Batch 3']

ms_lastc = 3

rows = [
    ['Date', 'Batch 1', 'Batch 2', 'Batch 3'],
    [date(2015, 9, 1), 40, 30, 25],
    [date(2015, 9, 2), 40, 25, 30],
    [date(2015, 9, 3), 50, 30, 45],
    [date(2015, 9, 4), 30, 25, 40],
    [date(2015, 9, 5), 25, 35, 30],
    [date(2015, 9, 6), 20, 40, 35]]

if __name__ == '__main__':
    wb = Workbook()
    ms = wb.active
    for row in rows:
        ms.append(row)
    lc = LineChart()
    x = Reference(ms,
                  min_col=1,
                  min_row=2,
                  max_col=1,
                  max_row=7)
    for i, name in enumerate(list_of_num):
        values = Reference(ms,
                           min_col=i+1,
                           min_row=2,
                           max_col=i+1,
                           max_row=7)
        serie = Series(values, xvalues=x, title=name)
        lc.append(serie)
    ms.add_chart(lc, 'A9')
    wb.save('bla.xlsx')

The following code shows this result:

And when I open the Serie in the chart the Series values are empty.

Can someone please help me?

Body:
Use a scatter chart instead:

from openpyxl.chart import ScatterChart

ls = ScatterChart()

The default is for scatter chart points to be connected by lines, which is probably what you want.


问:
The comma operator in a declaration
I am writing a C++ parser (actually a small subset of it) and can't find an explanation to why comma operator is not allowed in a variable initialization.

```<code>int a = 1, 2; // throws a "Expected ';' at the end of declaration" compiler error
a = 1, 2; // assigns the result of the comma binary operator to the a (2)
int a = (1, 2); // does the same as above, because paren expression is allowed as an initializer
</code>```

The C++ spec says that you can use an expression as an initializer in a variable declaration. Why is comma binary expression not allowed but all the other expressions (with higher precedence) are allowed? cppreference.com (http://en.cppreference.com/w/cpp/language/initialization) says that any expression can be used as an initializer.

Section 8.5 of the C++ spec says that initializer can contain assignment-expression only. Is this the place that regulates that assignment is the lowest-precedence expression allowed in the initialization?

答:
The language grammar interprets commas in initializers as comma-delimited declarator clauses, i.e. of the form:

```<code>int i = 2, j = 3;
</code>```

To avoid that ambiguity, you need to wrap comma-expressions in parentheses.

From [dcl.decl]:

```<code>[...]
init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator
[...]
</code>```

Title: The comma operator in a declaration

Body:
I am writing a C++ parser (actually a small subset of it) and can't find an explanation to why comma operator is not allowed in a variable initialization.

int a = 1, 2; // throws a "Expected ';' at the end of declaration" compiler error
a = 1, 2; // assigns the result of the comma binary operator to the a (2)
int a = (1, 2); // does the same as above, because paren expression is allowed as an initializer

The C++ spec says that you can use an expression as an initializer in a variable declaration. Why is comma binary expression not allowed but all the other expressions (with higher precedence) are allowed? cppreference.com (http://en.cppreference.com/w/cpp/language/initialization) says that any expression can be used as an initializer.

Section 8.5 of the C++ spec says that initializer can contain assignment-expression only. Is this the place that regulates that assignment is the lowest-precedence expression allowed in the initialization?

Body:
The language grammar interprets commas in initializers as comma-delimited declarator clauses, i.e. of the form:

int i = 2, j = 3;

To avoid that ambiguity, you need to wrap comma-expressions in parentheses.

From [dcl.decl]:

[...]
init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator
[...]


问:
How to turn on/off IDENTITY_INSERT in Redshift
I have to turn off the identity on a table in redshift and insert the historical values into that.

If I try to insert values into an identity column I am getting below error

ERROR: 0A000: cannot set an identity column to a value

答:
you can do it by following simple 2 step approach.

unload the historical table data and put it into file @s3

run copy command against this file to load target table by
specifying  explicit_ids as parameter in your copy command.


问:
Application.screenupdating set to false doensn't work
So, I'm new to VBA and I have this code that adds a new row to two tables, one to a table on sheet3 which is visible and the other to a table on sheet5 which is hidden. My problem now is, with ScreenUpdating set to false at the beginning ad true at the end, when the code is run, the screen still flickers showing hidden sheets. How do I get this flickering to stop?

```<code>            Sub Add_Observation()
            '
            Application.ScreenUpdating = False
            Sheet3.Activate
            ActiveSheet.Unprotect
            Sheet5.Visible = True
                    Dim Ar As Integer, Br As Integer, A As Integer
                    '
                    Ar = Columns("B").Find(What:="S/N", After:=Range("B26")).Row 'Searching row of "S/N" header
                    Br = Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                    A = (Br + 4)
                    B = (Br + 5)

                    Sheet5.Select
                    Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                    '
                    Qr = Columns("B").Find(What:="S/N", After:=Range("B16")).Row
                    Dr = Range("B" & Qr).End(xlDown).Row
                    D = (Dr + 4)
                    D1 = (Dr + 2)

               Sheet3.Select
                Cells(Dr, "C").Select

            If Range(Cells(Ar, 1), Cells(A, 1)).EntireRow.Hidden = False Then

                                                                            Sheet3.Activate
                                                                                Rows(A).Insert Shift:=xlDown  'Inserting new row
                                                                                Cells(Br + 1, "B") = Cells(Br, "B") + 1 'Adding a sequential Number
                                                                                Rows(Br).Copy 'Copying format of last row
                                                                                Rows(Br + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Sheet5.Select
            If Range(Cells(Qr, 1), Cells(D, 1)).EntireRow.Hidden = False Then
                                                                            Sheet5.Activate
                                                                                Selection.Rows(D).Insert Shift:=xlDown  'Inserting new row
                                                                                Rows(D1).Insert Shift:=xlDown
                                                                                Cells(Dr + 1, "B") = Cells(Dr, "B") + 1 'Adding a sequential Number
                                                                                Rows(Dr).Copy 'Copying format of last row
                                                                                Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Application.ScreenUpdating = True
            Else: GoTo G
                End If
            End If
</code>```

G:

```<code>            Sheet3.Activate
                Range(Cells(Ar, 1), Cells(A, 1)).Select
                  Selection.EntireRow.Hidden = False

            Sheet5.Activate
                Range(Cells(Qr, 1), Cells(D, 1)).Select
                Selection.EntireRow.Hidden = False

            Sheet3.Select

            Sheet5.Visible = False
            Cells(Br, "C").Select
            Sheet3.Activate
            ActiveSheet.Protect
            Application.ScreenUpdating = True
            End Sub
</code>```

答:
I'll just do the first bit to give you an idea:</p>

```<code>  Sub Add_Observation()
        '
        Application.ScreenUpdating = False
        with Sheet3
            .Unprotect
        End With
        With Sheet5
                Dim Ar As Integer, Br As Integer, A As Integer
                '
                Ar =. Columns("B").Find(What:="S/N", After:=.Range("B26")).Row 'Searching row of "S/N" header
                Br = .Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                A = (Br + 4)
                B = (Br + 5)

                Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                '
                Qr = .Columns("B").Find(What:="S/N", After:=.Range("B16")).Row
                Dr = .Range("B" & Qr).End(xlDown).Row
                D = (Dr + 4)
                D1 = (Dr + 2)

     end With
      With  Sheet3
            'Cells(Dr, "C").Select

        If .Range(.Cells(Ar, 1), .Cells(A, 1)).EntireRow.Hidden = False Then

 with sheet5
     .Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row

      Application.CutCopyMode = False 'Deactivating copy mode

 .Rows(D).Insert Shift:=xlDown  'Inserting new row

   .Rows(D1).Insert Shift:=xlDown

  .Cells(Dr + 1, "B") = 'Cells(Dr, "B") + 1 'Adding a sequential Number

  .Rows(Dr).Copy 'Copying format of last row
</code>```

Body:
So, I'm new to VBA and I have this code that adds a new row to two tables, one to a table on sheet3 which is visible and the other to a table on sheet5 which is hidden. My problem now is, with ScreenUpdating set to false at the beginning ad true at the end, when the code is run, the screen still flickers showing hidden sheets. How do I get this flickering to stop?

            Sub Add_Observation()
            '
            Application.ScreenUpdating = False
            Sheet3.Activate
            ActiveSheet.Unprotect
            Sheet5.Visible = True
                    Dim Ar As Integer, Br As Integer, A As Integer
                    '
                    Ar = Columns("B").Find(What:="S/N", After:=Range("B26")).Row 'Searching row of "S/N" header
                    Br = Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                    A = (Br + 4)
                    B = (Br + 5)

                    Sheet5.Select
                    Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                    '
                    Qr = Columns("B").Find(What:="S/N", After:=Range("B16")).Row
                    Dr = Range("B" & Qr).End(xlDown).Row
                    D = (Dr + 4)
                    D1 = (Dr + 2)

               Sheet3.Select
                Cells(Dr, "C").Select

            If Range(Cells(Ar, 1), Cells(A, 1)).EntireRow.Hidden = False Then

                                                                            Sheet3.Activate
                                                                                Rows(A).Insert Shift:=xlDown  'Inserting new row
                                                                                Cells(Br + 1, "B") = Cells(Br, "B") + 1 'Adding a sequential Number
                                                                                Rows(Br).Copy 'Copying format of last row
                                                                                Rows(Br + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Sheet5.Select
            If Range(Cells(Qr, 1), Cells(D, 1)).EntireRow.Hidden = False Then
                                                                            Sheet5.Activate
                                                                                Selection.Rows(D).Insert Shift:=xlDown  'Inserting new row
                                                                                Rows(D1).Insert Shift:=xlDown
                                                                                Cells(Dr + 1, "B") = Cells(Dr, "B") + 1 'Adding a sequential Number
                                                                                Rows(Dr).Copy 'Copying format of last row
                                                                                Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row
                                                                                Application.CutCopyMode = False 'Deactivating copy mode

            Application.ScreenUpdating = True
            Else: GoTo G
                End If
            End If

G:

            Sheet3.Activate
                Range(Cells(Ar, 1), Cells(A, 1)).Select
                  Selection.EntireRow.Hidden = False

            Sheet5.Activate
                Range(Cells(Qr, 1), Cells(D, 1)).Select
                Selection.EntireRow.Hidden = False

            Sheet3.Select

            Sheet5.Visible = False
            Cells(Br, "C").Select
            Sheet3.Activate
            ActiveSheet.Protect
            Application.ScreenUpdating = True
            End Sub

Body:
I'll just do the first bit to give you an idea:

  Sub Add_Observation()
        '
        Application.ScreenUpdating = False
        with Sheet3
            .Unprotect
        End With
        With Sheet5
                Dim Ar As Integer, Br As Integer, A As Integer
                '
                Ar =. Columns("B").Find(What:="S/N", After:=.Range("B26")).Row 'Searching row of "S/N" header
                Br = .Range("B" & Ar).End(xlDown).Row 'Searching last row in EQUIPMENT table
                A = (Br + 4)
                B = (Br + 5)

                Dim Qr As Integer, Dr As Integer, D As Integer, D1 As Integer
                '
                Qr = .Columns("B").Find(What:="S/N", After:=.Range("B16")).Row
                Dr = .Range("B" & Qr).End(xlDown).Row
                D = (Dr + 4)
                D1 = (Dr + 2)

     end With
      With  Sheet3
            'Cells(Dr, "C").Select

        If .Range(.Cells(Ar, 1), .Cells(A, 1)).EntireRow.Hidden = False Then

 with sheet5
     .Rows(Dr + 1).PasteSpecial Paste:=xlPasteFormats 'Pasting format to new row

      Application.CutCopyMode = False 'Deactivating copy mode

 .Rows(D).Insert Shift:=xlDown  'Inserting new row

   .Rows(D1).Insert Shift:=xlDown

  .Cells(Dr + 1, "B") = 'Cells(Dr, "B") + 1 'Adding a sequential Number

  .Rows(Dr).Copy 'Copying format of last row


问:
How to find xpath in mobile app using appium
I tried using Find element by id but it is not inserting required data.
Then I used Find element by xpath //android.widget.ScrollView[0]/android.widget.RelativeLayout[0]/android.widget.TextView[0]/ndroid.widget.TextView[1]/android.widget.EditText[2]")).sendKeys("Check@localmail.com");

but still it is not working.

答:
By using the available properties - index and class name, you can try with the below xpath</p>

```<code>//android.widget.EditText[@index='2']
</code>```

Body:
By using the available properties - index and class name, you can try with the below xpath

//android.widget.EditText[@index='2']


问:
Encode text files with Dos\Windows and encoded in UTF-8 from PHP
Im having an issue creating a text file on linux formatted as Dos\Windows and encoded in UTF-8.

What Im doing is this:

```<code>while($row = mysql_fetch_array($result))
 {
  $product =  $row['products_id']
  . ' ' . $row['products_name']
  . ' ' . $row['manufacturers_name']
  . ' ' . $row['products_model']
  //. ' ' . $row['products_sku']
  . ' ' . zen_href_link('product_info', 'cPath=' . $cPath .  '&products_id=' . $row['products_id'])
  . ' ' . number_format($row['products_price'],2)
  . ' ' . strip_tags(zen_get_products_description($row['products_id']))
  . ' ' . HTTP_SERVER . '/' .DIR_WS_IMAGES . $row['products_image']
  . ' ' . 'electronics'
  . "\r\n";
 $product = utf8_encode($product);
 fwrite($fh, gzencode($product,9));
</code>```

I was under the impression "\r\n" and the encoding as its done is all thats needed. Am I missing something here?

答:
I doubt you want to be gz-encoding it record by record like that.

If you need it to be gzipped, consider collating it then writing once at the end, or gzipping the file post creation.

```<code>$productList = '';

while($row = mysql_fetch_array($result)) {
  $product =  $row['products_id']
  . ' ' . $row['products_name']
  . ' ' . $row['manufacturers_name']
  . ' ' . $row['products_model']
  //. ' ' . $row['products_sku']
  . ' ' . zen_href_link('product_info', 'cPath=' . $cPath .  '&products_id=' . $row['products_id'])
  . ' ' . number_format($row['products_price'],2)
  . ' ' . strip_tags(zen_get_products_description($row['products_id']))
  . ' ' . HTTP_SERVER . '/' .DIR_WS_IMAGES . $row['products_image']
  . ' ' . 'electronics'
  . "\r\n";

  $productList .= $product;
}

fwrite($fh, gzencode(utf8_encode($product),9));
fclose($fh);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Im having an issue creating a text file on linux formatted as Dos\Windows and encoded in UTF-8.

What Im doing is this:

while($row = mysql_fetch_array($result))
 {
  $product =  $row['products_id']
  . ' ' . $row['products_name']
  . ' ' . $row['manufacturers_name']
  . ' ' . $row['products_model']
  //. ' ' . $row['products_sku']
  . ' ' . zen_href_link('product_info', 'cPath=' . $cPath .  '&products_id=' . $row['products_id'])
  . ' ' . number_format($row['products_price'],2)
  . ' ' . strip_tags(zen_get_products_description($row['products_id']))
  . ' ' . HTTP_SERVER . '/' .DIR_WS_IMAGES . $row['products_image']
  . ' ' . 'electronics'
  . "\r\n";
 $product = utf8_encode($product);
 fwrite($fh, gzencode($product,9));

I was under the impression "\r\n" and the encoding as its done is all thats needed. Am I missing something here?

Body:
I doubt you want to be gz-encoding it record by record like that.

If you need it to be gzipped, consider collating it then writing once at the end, or gzipping the file post creation.

$productList = '';

while($row = mysql_fetch_array($result)) {
  $product =  $row['products_id']
  . ' ' . $row['products_name']
  . ' ' . $row['manufacturers_name']
  . ' ' . $row['products_model']
  //. ' ' . $row['products_sku']
  . ' ' . zen_href_link('product_info', 'cPath=' . $cPath .  '&products_id=' . $row['products_id'])
  . ' ' . number_format($row['products_price'],2)
  . ' ' . strip_tags(zen_get_products_description($row['products_id']))
  . ' ' . HTTP_SERVER . '/' .DIR_WS_IMAGES . $row['products_image']
  . ' ' . 'electronics'
  . "\r\n";

  $productList .= $product;
}

fwrite($fh, gzencode(utf8_encode($product),9));
fclose($fh);


问:
File line counter in C
I want to count the lines of a c file ignoring the lines that have comments or empty lines , i came up with the following code but my string ( char pointer) only returns three chars instead of the whole line:

```<code>FILE* pf = NULL;
char *chaine;
int count=0;
int com=0;
pf=fopen("test.c","r+");
while(!feof(pf))
{
    if(com%2==0)
    count++;
    fgets(&chaine, sizeof(chaine),pf);
    if(&chaine=='\n' || &chaine==' ' || strstr(&chaine, "//") != NULL)
    {
        count--;
    }
    if(strstr(&chaine, "//*") != NULL || strstr(&chaine, "*//") != NULL)
    {
        com++;
    }
  printf("The line %d have the following string : %s\n",count,&chaine);
}
//printf("The number of lines est : %d", count);
</code>```

Solved

Thanks for the answers especially for @Michael Walz i found that i have problems with my pointers. After i re-adjusted my if conditions now the line counter works just fine and this is the working code:

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

int main(void)
{
  FILE* pf = NULL;
  char chaine[1000];
  int count = 0;
  int com = 0;
  pf = fopen("test.c", "r");

  while (1)
  {
    if (com % 2 == 0 | strstr(chaine, ";//") != NULL)
      count++;

    if (fgets(chaine, sizeof(chaine), pf) == NULL)
      break;

    if (chaine[0] == '\n' || chaine[0] == "" || strstr(chaine, "//") != NULL)
    {
      count--;
    }

    if (strstr(chaine, "/*") != NULL)
    {
      com++;
    }
    if (strstr(chaine, "*/") != NULL)
    {
      com++;
    }

  }
  fclose(pf);
  printf("The file have %d line code", count);
}
</code>```

答:
You probably want this:

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

int main(void)
{
  FILE* pf = NULL;
  char chaine[1000];
  int count = 0;
  int com = 0;
  pf = fopen("test.c", "r");

  if (pf == NULL)   // we abort if the file cannot be opened
  {
    printf("File cannot be opened\n");
    return 1;
  }

  while (1)  // see link below
  {
    if (com % 2 == 0)
      count++;

    if (fgets(chaine, sizeof(chaine), pf) == NULL)
      break;  // if fgets returns NULL we are presumably at the end of the file

    if (chaine[0] == '\n' || chaine[0] == ' ' || strstr(chaine, "//") != NULL)
    {
      count--;
    }

    if (strstr(chaine, "//*") != NULL || strstr(chaine, "*//") != NULL)
    {
      com++;
    }

    printf("The line %d have the following string : %s\n", count, chaine);
  }
}
</code>```

This is untested code, there may be errors.

Also read this: Why is “while ( !feof (file) )” always wrong?.

I also strongly recommand you to read the chapter dealing with strings and the chapter dealing with pointers in your C text book.

Title: File line counter in C

Body:
I want to count the lines of a c file ignoring the lines that have comments or empty lines , i came up with the following code but my string ( char pointer) only returns three chars instead of the whole line:

FILE* pf = NULL;
char *chaine;
int count=0;
int com=0;
pf=fopen("test.c","r+");
while(!feof(pf))
{
    if(com%2==0)
    count++;
    fgets(&chaine, sizeof(chaine),pf);
    if(&chaine=='\n' || &chaine==' ' || strstr(&chaine, "//") != NULL)
    {
        count--;
    }
    if(strstr(&chaine, "//*") != NULL || strstr(&chaine, "*//") != NULL)
    {
        com++;
    }
  printf("The line %d have the following string : %s\n",count,&chaine);
}
//printf("The number of lines est : %d", count);

Solved

Thanks for the answers especially for @Michael Walz i found that i have problems with my pointers. After i re-adjusted my if conditions now the line counter works just fine and this is the working code:

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

int main(void)
{
  FILE* pf = NULL;
  char chaine[1000];
  int count = 0;
  int com = 0;
  pf = fopen("test.c", "r");

  while (1)
  {
    if (com % 2 == 0 | strstr(chaine, ";//") != NULL)
      count++;

    if (fgets(chaine, sizeof(chaine), pf) == NULL)
      break;

    if (chaine[0] == '\n' || chaine[0] == "" || strstr(chaine, "//") != NULL)
    {
      count--;
    }

    if (strstr(chaine, "/*") != NULL)
    {
      com++;
    }
    if (strstr(chaine, "*/") != NULL)
    {
      com++;
    }

  }
  fclose(pf);
  printf("The file have %d line code", count);
}

Body:
You probably want this:

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

int main(void)
{
  FILE* pf = NULL;
  char chaine[1000];
  int count = 0;
  int com = 0;
  pf = fopen("test.c", "r");

  if (pf == NULL)   // we abort if the file cannot be opened
  {
    printf("File cannot be opened\n");
    return 1;
  }

  while (1)  // see link below
  {
    if (com % 2 == 0)
      count++;

    if (fgets(chaine, sizeof(chaine), pf) == NULL)
      break;  // if fgets returns NULL we are presumably at the end of the file

    if (chaine[0] == '\n' || chaine[0] == ' ' || strstr(chaine, "//") != NULL)
    {
      count--;
    }

    if (strstr(chaine, "//*") != NULL || strstr(chaine, "*//") != NULL)
    {
      com++;
    }

    printf("The line %d have the following string : %s\n", count, chaine);
  }
}

This is untested code, there may be errors.

Also read this: Why is “while ( !feof (file) )” always wrong?.

I also strongly recommand you to read the chapter dealing with strings and the chapter dealing with pointers in your C text book.


问:
Error Creating Custom table in Magento 1.9 for Custom Module
I've created a custom Magento plugin, and everything is working fine, except the database creation. Here is my SQL code.

```<code><?php
$installer = $this;
$installer->startSetup();
$installer->run("
-- DROP TABLE IF EXISTS {$this->getTable('store_city')};
CREATE TABLE '{$installer->getTable('store_city')}'(
  `city_id` int(11) unsigned NOT NULL auto_increment,
  `city_name` text NOT NULL default '',
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- DROP TABLE IF EXISTS {$this->getTable('store_area')};
CREATE TABLE '{$installer->getTable('store_area')}'(
  `area_id` int(11) unsigned NOT NULL auto_increment,
  `area_name` text NOT NULL default '',
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `area_city_id` int(11) unsigned,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`area_id`),
  FOREIGN KEY (`area_city_id`) REFERENCES {$this->getTable('store_city')} (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- DROP TABLE IF EXISTS {$this->getTable('store_store')};
CREATE TABLE '{$installer->getTable('store_store')}'(
  `store_id` int(11) unsigned NOT NULL auto_increment,
  `store_name` text NOT NULL default '',
  `store_address` text NOT NULL default '',
  `long` text,
  `lat` text,
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `store_area_id` int(11) unsigned,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`store_id`),
  FOREIGN KEY (`store_area_id`) REFERENCES {$this->getTable('store_area')} (`area_id`)
  ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");

$installer->endSetup();
</code>```

but it gives me this error after I copy the plugin and test it, How can i fix this, and why is this happening?

```<code>a:5:{i:0;s:435:"Error in file: "Sites/magento/app/code/community/Test/Storelocator/sql/storelocator_setup/mysql4-install-0.1.0.php" - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''store_city'(
  `city_id` int(11)  NOT NULL auto_increment,
  `c' at line 2";i:1;s:1124:"#0 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(644): Mage::exception('Mage_Core', 'Error in file: ...')
#1 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(421): Mage_Core_Model_Resource_Setup->_modifyResourceDb('install', '', '0.1.0')
#2 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(327): Mage_Core_Model_Resource_Setup->_installResourceDb('0.1.0')
#3 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(235): Mage_Core_Model_Resource_Setup->applyUpdates()
#4 Sites/magento/app/code/core/Mage/Core/Model/App.php(428): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#5 Sites/magento/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Model_App->_initModules()
#6 Sites/magento/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#7 Sites/magento/index.php(83): Mage::run('', 'store')
#8 {main}";s:3:"url";s:24:"/magento/index.php/admin";s:11:"script_name";s:18:"/magento/index.php";s:4:"skin";s:7:"default";}
</code>```

答:
There was some mistakes in the code, after finishing and now everything works, here is the code.</p>

```<code><?php
$installer= $this;
$storeCity = $installer->getTable('store_city');
$storeArea = $installer->getTable('store_area');
$storeStore = $installer->getTable('store_store');

$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS $storeCity;
CREATE TABLE $storeCity(
`city_id` int(11) unsigned NOT NULL auto_increment,
`city_name` text NOT NULL,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS $storeArea;
CREATE TABLE $storeArea(
`area_id` int(11) unsigned NOT NULL auto_increment,
`area_name` text NOT NULL ,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`area_city_id` int(11) unsigned,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`area_id`),
FOREIGN KEY (`area_city_id`) REFERENCES store_city (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS  $storeStore;
CREATE TABLE  $storeStore(
`store_id` int(11) unsigned NOT NULL auto_increment,
`store_name` text NOT NULL ,
`store_address` text NOT NULL ,
`long` text,
`lat` text,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`store_area_id` int(11) unsigned,
`created_time` datetime NULL,
`update_time` datetime NULL,
 PRIMARY KEY (`store_id`),
 FOREIGN KEY (`store_area_id`) REFERENCES store_area (`area_id`)
 ON DELETE CASCADE ON UPDATE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 ");

 $installer->endSetup();
</code>```

Body:
I've created a custom Magento plugin, and everything is working fine, except the database creation. Here is my SQL code.

<?php
$installer = $this;
$installer->startSetup();
$installer->run("
-- DROP TABLE IF EXISTS {$this->getTable('store_city')};
CREATE TABLE '{$installer->getTable('store_city')}'(
  `city_id` int(11) unsigned NOT NULL auto_increment,
  `city_name` text NOT NULL default '',
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- DROP TABLE IF EXISTS {$this->getTable('store_area')};
CREATE TABLE '{$installer->getTable('store_area')}'(
  `area_id` int(11) unsigned NOT NULL auto_increment,
  `area_name` text NOT NULL default '',
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `area_city_id` int(11) unsigned,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`area_id`),
  FOREIGN KEY (`area_city_id`) REFERENCES {$this->getTable('store_city')} (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

-- DROP TABLE IF EXISTS {$this->getTable('store_store')};
CREATE TABLE '{$installer->getTable('store_store')}'(
  `store_id` int(11) unsigned NOT NULL auto_increment,
  `store_name` text NOT NULL default '',
  `store_address` text NOT NULL default '',
  `long` text,
  `lat` text,
  `is_active` smallint(6) NOT NULL default '1',
  `sort_order` int(11) unsigned NOT NULL,
  `store_area_id` int(11) unsigned,
  `created_time` datetime NULL,
  `update_time` datetime NULL,
  PRIMARY KEY (`store_id`),
  FOREIGN KEY (`store_area_id`) REFERENCES {$this->getTable('store_area')} (`area_id`)
  ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
");

$installer->endSetup();

but it gives me this error after I copy the plugin and test it, How can i fix this, and why is this happening?

a:5:{i:0;s:435:"Error in file: "Sites/magento/app/code/community/Test/Storelocator/sql/storelocator_setup/mysql4-install-0.1.0.php" - SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''store_city'(
  `city_id` int(11)  NOT NULL auto_increment,
  `c' at line 2";i:1;s:1124:"#0 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(644): Mage::exception('Mage_Core', 'Error in file: ...')
#1 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(421): Mage_Core_Model_Resource_Setup->_modifyResourceDb('install', '', '0.1.0')
#2 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(327): Mage_Core_Model_Resource_Setup->_installResourceDb('0.1.0')
#3 Sites/magento/app/code/core/Mage/Core/Model/Resource/Setup.php(235): Mage_Core_Model_Resource_Setup->applyUpdates()
#4 Sites/magento/app/code/core/Mage/Core/Model/App.php(428): Mage_Core_Model_Resource_Setup::applyAllUpdates()
#5 Sites/magento/app/code/core/Mage/Core/Model/App.php(354): Mage_Core_Model_App->_initModules()
#6 Sites/magento/app/Mage.php(684): Mage_Core_Model_App->run(Array)
#7 Sites/magento/index.php(83): Mage::run('', 'store')
#8 {main}";s:3:"url";s:24:"/magento/index.php/admin";s:11:"script_name";s:18:"/magento/index.php";s:4:"skin";s:7:"default";}

Body:
There was some mistakes in the code, after finishing and now everything works, here is the code.

<?php
$installer= $this;
$storeCity = $installer->getTable('store_city');
$storeArea = $installer->getTable('store_area');
$storeStore = $installer->getTable('store_store');

$installer->startSetup();
$installer->run("
DROP TABLE IF EXISTS $storeCity;
CREATE TABLE $storeCity(
`city_id` int(11) unsigned NOT NULL auto_increment,
`city_name` text NOT NULL,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS $storeArea;
CREATE TABLE $storeArea(
`area_id` int(11) unsigned NOT NULL auto_increment,
`area_name` text NOT NULL ,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`area_city_id` int(11) unsigned,
`created_time` datetime NULL,
`update_time` datetime NULL,
PRIMARY KEY (`area_id`),
FOREIGN KEY (`area_city_id`) REFERENCES store_city (`city_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS  $storeStore;
CREATE TABLE  $storeStore(
`store_id` int(11) unsigned NOT NULL auto_increment,
`store_name` text NOT NULL ,
`store_address` text NOT NULL ,
`long` text,
`lat` text,
`is_active` smallint(6) NOT NULL default '1',
`sort_order` int(11) unsigned NOT NULL,
`store_area_id` int(11) unsigned,
`created_time` datetime NULL,
`update_time` datetime NULL,
 PRIMARY KEY (`store_id`),
 FOREIGN KEY (`store_area_id`) REFERENCES store_area (`area_id`)
 ON DELETE CASCADE ON UPDATE CASCADE
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 ");

 $installer->endSetup();


问:
Function with variable parameter size: How to conditionally set some arguments?
To create a boost::process with output redirection, you should do:

```<code>bp::ipstream out;
bp::child c("c++filt", std_out > out);
</code>```

Now, what would be the syntax to conditionally control the redirection:

```<code>bool redirect = true; // or false
bp::ipstream out;
bp::child c("c++filt", (redirect) ? std_out > out : "what should I put here??" );
</code>```

答:
The fancy boost::process API revolves around supplying handler objects implementing on_setup, on_error, on_success (and potentially some more, depending on current OS) methods that will be executed at process construction call in context of some internal process launcher and will be able to alter process launcher behavior. std_out > out is an overloaded operator that will return such handler. More information can be found at boost process Extensions documentation.

So the generic way to conditionally control the redirection and other parameters would be to write generic handler proxy accepting optional real handler and calling appropriate methods of real handler:

```<code>#include <boost/process.hpp>
#include <boost/process/extend.hpp>
#include <boost/optional.hpp>

#include <memory>
#include <utility>

template<typename TRealHandler> class
t_OptionalHandler
:    public ::boost::process::extend::handler
{
    private: using t_OptionalRealHandler = ::boost::optional<TRealHandler>;

    private: t_OptionalRealHandler m_real_handler;

    public:
    t_OptionalHandler(void)
    :   m_real_handler{}
    {}

    public: explicit
    t_OptionalHandler(TRealHandler && real_handler)
    :   m_real_handler{::std::move(real_handler)}
    {}

    template<typename TExecutor>
    void on_setup(TExecutor & e) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_setup(e);
        }
    }

    template<typename TExecutor>
    void on_error(TExecutor & e, const std::error_code & code) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_error(e, code);
        }
    }

    template<typename TExecutor>
    void on_success(TExecutor & e) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_success(e);
        }
    }
};

int main()
{
    bool const need_to_redirect{false};
    ::std::unique_ptr<::boost::process::ipstream> const p_stream
    {
        need_to_redirect?
        new ::boost::process::ipstream{}
        :
        nullptr
    };
    using t_OptionalStdOutRedirectionHandler = t_OptionalHandler
    <
        decltype(::boost::process::std_out > *p_stream)
     >;
    ::boost::process::child ch
    (
        "cmd"
    ,   need_to_redirect?
        t_OptionalStdOutRedirectionHandler{::boost::process::std_out > *p_stream}
        :
        t_OptionalStdOutRedirectionHandler{}
    );
    ch.wait();
    return(0);
}
</code>```

Body:
To create a boost::process with output redirection, you should do:

bp::ipstream out;
bp::child c("c++filt", std_out > out);

Now, what would be the syntax to conditionally control the redirection:

bool redirect = true; // or false
bp::ipstream out;
bp::child c("c++filt", (redirect) ? std_out > out : "what should I put here??" );

Body:
The fancy boost::process API revolves around supplying handler objects implementing on_setup, on_error, on_success (and potentially some more, depending on current OS) methods that will be executed at process construction call in context of some internal process launcher and will be able to alter process launcher behavior. std_out > out is an overloaded operator that will return such handler. More information can be found at boost process Extensions documentation.

So the generic way to conditionally control the redirection and other parameters would be to write generic handler proxy accepting optional real handler and calling appropriate methods of real handler:

#include <boost/process.hpp>
#include <boost/process/extend.hpp>
#include <boost/optional.hpp>

#include <memory>
#include <utility>

template<typename TRealHandler> class
t_OptionalHandler
:    public ::boost::process::extend::handler
{
    private: using t_OptionalRealHandler = ::boost::optional<TRealHandler>;

    private: t_OptionalRealHandler m_real_handler;

    public:
    t_OptionalHandler(void)
    :   m_real_handler{}
    {}

    public: explicit
    t_OptionalHandler(TRealHandler && real_handler)
    :   m_real_handler{::std::move(real_handler)}
    {}

    template<typename TExecutor>
    void on_setup(TExecutor & e) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_setup(e);
        }
    }

    template<typename TExecutor>
    void on_error(TExecutor & e, const std::error_code & code) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_error(e, code);
        }
    }

    template<typename TExecutor>
    void on_success(TExecutor & e) const
    {
        if(m_real_handler)
        {
            m_real_handler.get().on_success(e);
        }
    }
};

int main()
{
    bool const need_to_redirect{false};
    ::std::unique_ptr<::boost::process::ipstream> const p_stream
    {
        need_to_redirect?
        new ::boost::process::ipstream{}
        :
        nullptr
    };
    using t_OptionalStdOutRedirectionHandler = t_OptionalHandler
    <
        decltype(::boost::process::std_out > *p_stream)
     >;
    ::boost::process::child ch
    (
        "cmd"
    ,   need_to_redirect?
        t_OptionalStdOutRedirectionHandler{::boost::process::std_out > *p_stream}
        :
        t_OptionalStdOutRedirectionHandler{}
    );
    ch.wait();
    return(0);
}


问:
Xcode 9.2 Upload to App Store fails with description length and invalid toolchain errors
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

```<code>find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323
</code>```

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."

答:
Right-Click on the archive file (.xcarchive) > Show Package Contents > Products > Applications > Right-Click on the app file > Show Package Contents > Double-Click on Info.plist to edit it

Change value of DTXcodeBuild from 9C40b to 9C40

Re-submit and it will work

Edit/Disclaimer: this is just a trick to bypass the upload process, iTunesConnect still doesn't allow submission with 11.2 so this is not the right solution.

Body:
I've read through a bunch of forums including here:

https://forums.developer.apple.com/thread/87862

and some Stack Overflow posts.

I have tried modifying my plist using the proposed solution of

find Products/ -name Info.plist -print0 | xargs -0n1 plutil -replace BuildMachineOSBuild -string 16A323

in the archive directory that I'm trying to load, and I'm still receiving the error below. I believe I have valid Xcode and Mac OS versions. I'm running Xcode 9.2 which was released today and High Sierra 10.13.1. Why does my upload fail with these errors and how can I fix it?

The errors in text (to make this post more searchable):

The following issues occurred while distributing your application.

⚠ iTunes Store Operation Failed

   description length:2651858

⚠ iTunes Store Operation Failed

   ERROR ITMS-90534: "Invalid Toolchain. New apps and app updates must be built with the public (GM) versions of Xcode 6 or later, macOS, and iOS SDK or later. Don't submit apps built with beta software including beta macOS builds."


问:
about volatile and const embellishments
I find a intersting question about c++
code：

```<code>volatile const int a = 10;
int *p = const_cast<int*>(&a);
*p = 2;
cout << "value a="<< a << endl;
cout << "value *p=" <<*p << endl;
cout << "address a=" <<&a << endl;  //output 1！！
cout << "address p=" <<p << endl;
</code>```

who can tell me why address of a is 1?

答:
The behaviour of your code is undefined.

a is originally declared as const.

You attempt to change its value via a pointer that has had the const-ness cast away. The language does not allow that.

The volatile is a red-herring in this case.

Title: about volatile and const embellishments

Body:
I find a intersting question about c++
code：

volatile const int a = 10;
int *p = const_cast<int*>(&a);
*p = 2;
cout << "value a="<< a << endl;
cout << "value *p=" <<*p << endl;
cout << "address a=" <<&a << endl;  //output 1！！
cout << "address p=" <<p << endl;

who can tell me why address of a is 1?


答: The "\r\n" is correct. The utf8_encode() is redundant, if the database table already contains UTF-8. But the real problem I see is that you should wrap only the concatenation of the $product variable in the while {...} loop. You cannot restart the gzencode for each line and write chunks into the file. This will lead to an error when you try to open it. Instead of calling gzencode multiple times, simply open your output file with gzopen() instead of fopen().

Title: Encode text files with Dos\Windows and encoded in UTF-8 from PHP


问:
Executing a function on page load, ANGULAR 2
I have a simple function, checking the width of the window and according to that value it stretches the content. But when I resize the page and reload the site, nothing happens until I resize the window. How do I call a function on page load in angular2?

My whole app.component.ts file:

```<code>import { Component } from '@angular/core';

@Component({
  templateUrl: './app.component.html'
})
export class appComponent {

  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
}
</code>```

答:
First of all import OnInit from '@angular/core'module and then call a method inside ngOnInit which you want to call on load its like ng-init from angularjs.</p>

```<code>import  { Component, OnInit } from '@angular/core';

 ngOnInit() {
    this.checkScreenWidth();
  }
</code>```

Body:
I have a simple function, checking the width of the window and according to that value it stretches the content. But when I resize the page and reload the site, nothing happens until I resize the window. How do I call a function on page load in angular2?

My whole app.component.ts file:

import { Component } from '@angular/core';

@Component({
  templateUrl: './app.component.html'
})
export class appComponent {

  private checkScreenWidth() {
    if (window.innerWidth < 1000 && window.innerWidth > 499) {
      ...
    } else if (window.innerWidth < 500) {
      ...
    } else {
      ...
    }
  }
}

Body:
First of all import OnInit from '@angular/core'module and then call a method inside ngOnInit which you want to call on load its like ng-init from angularjs.

import  { Component, OnInit } from '@angular/core';

 ngOnInit() {
    this.checkScreenWidth();
  }


问:
When you uploaded an APK that is not signed with the upload certificate; do you have to use the same certificate?
I am using Android Studio and am trying to build a signed apk.
I am building a signed apk using the following steps:
Module -->app
KeyStorePath--> /Users/mshikher/Documents/SchoolCounter/app/Untitled
(SchoolCounter is name of the project).
After entering the keyStorePassword and keyPassword clicked NEXT.
Clicking on both the V1 and V2 versions clicked on Finish.
There was earlier an apk uploaded in the play.console by some other person, and now if I try to upload my apk into the production release I get this error.

```<code>You uploaded an APK that is not signed with the upload certificate. You must use the same certificate. The upload certificate has fingerprint:
[ SHA1: AA:6F:D6:9E:72:B7:9B:C6:45:63:70:69:66:B4:DA:9B:72:6D:3D:23 ]
and the certificate used to sign the APK you uploaded have fingerprint:
[ SHA1: 88:5D:A7:91:A9:5B:2C:66:DD:ED:13:96:37:49:D6:B7:4D:1E:B0:09 ]
You need to use a different version code for your APK because you already have one with version code 1.
</code>```

I have changed the version number also in the build.gradle file:

```<code>versionName "2.0"
</code>```

What should I do to upload my apk in the play.google.com ?

答:
You are changing version name versionName "2.0" please change "versionCode" and "version name" both  to other so that you can upload it and second thing please select same .jks file

You need to use a different version code for your APK because you already have one with version code 1.

you need to change version code.

Body:
I am using Android Studio and am trying to build a signed apk.
I am building a signed apk using the following steps:
Module -->app
KeyStorePath--> /Users/mshikher/Documents/SchoolCounter/app/Untitled
(SchoolCounter is name of the project).
After entering the keyStorePassword and keyPassword clicked NEXT.
Clicking on both the V1 and V2 versions clicked on Finish.
There was earlier an apk uploaded in the play.console by some other person, and now if I try to upload my apk into the production release I get this error.

You uploaded an APK that is not signed with the upload certificate. You must use the same certificate. The upload certificate has fingerprint:
[ SHA1: AA:6F:D6:9E:72:B7:9B:C6:45:63:70:69:66:B4:DA:9B:72:6D:3D:23 ]
and the certificate used to sign the APK you uploaded have fingerprint:
[ SHA1: 88:5D:A7:91:A9:5B:2C:66:DD:ED:13:96:37:49:D6:B7:4D:1E:B0:09 ]
You need to use a different version code for your APK because you already have one with version code 1.

I have changed the version number also in the build.gradle file:

versionName "2.0"

What should I do to upload my apk in the play.google.com ?