问:
Python spark: IndexError: tuple index out of range
I'm working on spark and python.

When I call any action on csv file, it gives me IndexError: tuple index out of range

here is code snippet.

```<code>test_rdd = sc.textFile("/mapr/data/airflow-test.csv").map(lambda line: line.split())
print(test_rdd.first())
print(test_rdd.count())
</code>```

Here is full Traceback.

```<code>File "pysparktask.py", line 15, in <module>
    print(test_rdd.first())
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 1328, in first
    rs = self.take(1)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 1310, in take
    res = self.context.runJob(self, takeUpToNumLeft, p)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/context.py", line 933, in runJob
    port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2403, in _jrdd
    self._jrdd_deserializer, profiler)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2336, in _wrap_function
    pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2315, in _prepare_for_python_RDD
    pickled_command = ser.dumps(command)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/serializers.py", line 428, in dumps
  return cloudpickle.dumps(obj, 2)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 657, in dumps
    cp.dump(obj)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 107, in dump
    return Pickler.dump(self, obj)
File "/anaconda3/lib/python3.6/pickle.py", line 409, in dump
    self.save(obj)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/anaconda3/lib/python3.6/pickle.py", line 751, in save_tuple
    save(element)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 241, in save_function_tuple
    save((code, closure, base_globals))
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/anaconda3/lib/python3.6/pickle.py", line 736, in save_tuple
    save(element)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 781, in save_list
    self._batch_appends(obj)
  File "/anaconda3/lib/python3.6/pickle.py", line 805, in _batch_appends
    save(x)
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 241, in save_function_tuple
    save((code, closure, base_globals))
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 736, in save_tuple
    save(element)
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 781, in save_list
    self._batch_appends(obj)
  File "/anaconda3/lib/python3.6/pickle.py", line 808, in _batch_appends
    save(tmp[0])
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 234, in save_function_tuple
    code, f_globals, defaults, closure, dct, base_globals = self.extract_func_data(func)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 296, in extract_func_data
    func_global_refs = self.extract_code_globals(code)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 278, in extract_code_globals
    out_names.add(names[oparg])
IndexError: tuple index out of range
</code>```

any suggestions?

答:
You're using unsupported Python version. As of today no released version, including Spark 2.0.1, supports Python 3.6.

You should downgrade Python 3.5 or patch with https://github.com/apache/spark/pull/17374

Detailed description of the problem can be found in SPARK-19019

Body:
I'm working on spark and python.

When I call any action on csv file, it gives me IndexError: tuple index out of range

here is code snippet.

test_rdd = sc.textFile("/mapr/data/airflow-test.csv").map(lambda line: line.split())
print(test_rdd.first())
print(test_rdd.count())

Here is full Traceback.

File "pysparktask.py", line 15, in <module>
    print(test_rdd.first())
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 1328, in first
    rs = self.take(1)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 1310, in take
    res = self.context.runJob(self, takeUpToNumLeft, p)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/context.py", line 933, in runJob
    port = self._jvm.PythonRDD.runJob(self._jsc.sc(), mappedRDD._jrdd, partitions)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2403, in _jrdd
    self._jrdd_deserializer, profiler)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2336, in _wrap_function
    pickled_command, broadcast_vars, env, includes = _prepare_for_python_RDD(sc, command)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/rdd.py", line 2315, in _prepare_for_python_RDD
    pickled_command = ser.dumps(command)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/serializers.py", line 428, in dumps
  return cloudpickle.dumps(obj, 2)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 657, in dumps
    cp.dump(obj)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 107, in dump
    return Pickler.dump(self, obj)
File "/anaconda3/lib/python3.6/pickle.py", line 409, in dump
    self.save(obj)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/anaconda3/lib/python3.6/pickle.py", line 751, in save_tuple
    save(element)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 241, in save_function_tuple
    save((code, closure, base_globals))
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
File "/anaconda3/lib/python3.6/pickle.py", line 736, in save_tuple
    save(element)
File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 781, in save_list
    self._batch_appends(obj)
  File "/anaconda3/lib/python3.6/pickle.py", line 805, in _batch_appends
    save(x)
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 241, in save_function_tuple
    save((code, closure, base_globals))
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 736, in save_tuple
    save(element)
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/anaconda3/lib/python3.6/pickle.py", line 781, in save_list
    self._batch_appends(obj)
  File "/anaconda3/lib/python3.6/pickle.py", line 808, in _batch_appends
    save(tmp[0])
  File "/anaconda3/lib/python3.6/pickle.py", line 476, in save
    f(self, obj) # Call unbound method with explicit self
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 204, in save_function
    self.save_function_tuple(obj)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 234, in save_function_tuple
    code, f_globals, defaults, closure, dct, base_globals = self.extract_func_data(func)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 296, in extract_func_data
    func_global_refs = self.extract_code_globals(code)
  File "/opt/mapr/spark/spark-2.0.1/python/pyspark/cloudpickle.py", line 278, in extract_code_globals
    out_names.add(names[oparg])
IndexError: tuple index out of range

any suggestions?


来源: stackexchange

问:
How to configure DateFormatter to capture microseconds
iOS Date() returns date with at least microsecond precision.

I checked this statement by calling Date().timeIntervalSince1970 which results in 1490891661.074981

Then I need to convert date into string with microsecond precision.

I am using DateFormatter in following way:

```<code>let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"
print(formatter.string(from: date))
</code>```

which results in

"2017-03-30T16:34:21.075000Z"

Now if we compare two results:

1490891661.074981 and "2017-03-30T16:34:21.075000Z"

we can notice that DateFormatter rounds date to millisecond precision while still presenting zeros for microseconds.

Does anybody know how to configure DateFormatter so I can keep microseconds and get correct result: "2017-03-30T16:34:21.074981Z"?

答:
Thanks to @MartinR for solving first half of my problem and to @ForestKunecke for giving me tips how to solve second half of the problem.

Based on their help I created ready to use solution which converts date from string and vice versa with microsecond precision:

```<code>public final class MicrosecondPrecisionDateFormatter: DateFormatter {

    private let microsecondsPrefix = "."

    override public init() {
        super.init()
        locale = Locale(identifier: "en_US_POSIX")
        timeZone = TimeZone(secondsFromGMT: 0)
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func string(from date: Date) -> String {
        dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        let components = calendar.dateComponents(Set([Calendar.Component.nanosecond]), from: date)

        let nanosecondsInMicrosecond = Double(1000)
        let microseconds = lrint(Double(components.nanosecond!) / nanosecondsInMicrosecond)

        // Subtract nanoseconds from date to ensure string(from: Date) doesn't attempt faulty rounding.
        let updatedDate = calendar.date(byAdding: .nanosecond, value: -(components.nanosecond!), to: date)!
        let dateTimeString = super.string(from: updatedDate)

        let string = String(format: "%@.%06ldZ",
                            dateTimeString,
                            microseconds)

        return string
    }

    override public func date(from string: String) -> Date? {
        dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

        guard let microsecondsPrefixRange = string.range(of: microsecondsPrefix) else { return nil }
        let microsecondsWithTimeZoneString = String(string.suffix(from: microsecondsPrefixRange.upperBound))

        let nonDigitsCharacterSet = CharacterSet.decimalDigits.inverted
        guard let timeZoneRangePrefixRange = microsecondsWithTimeZoneString.rangeOfCharacter(from: nonDigitsCharacterSet) else { return nil }

        let microsecondsString = String(microsecondsWithTimeZoneString.prefix(upTo: timeZoneRangePrefixRange.lowerBound))
        guard let microsecondsCount = Double(microsecondsString) else { return nil }

        let dateStringExludingMicroseconds = string
            .replacingOccurrences(of: microsecondsString, with: "")
            .replacingOccurrences(of: microsecondsPrefix, with: "")

        guard let date = super.date(from: dateStringExludingMicroseconds) else { return nil }
        let microsecondsInSecond = Double(1000000)
        let dateWithMicroseconds = date + microsecondsCount / microsecondsInSecond

        return dateWithMicroseconds
    }
}
</code>```

Usage:

```<code>let formatter = MicrosecondPrecisionDateFormatter()
let date = Date(timeIntervalSince1970: 1490891661.074981)
let formattedString = formatter.string(from: date) // 2017-03-30T16:34:21.074981Z
</code>```

ContentLicense: CC BY-SA 3.0

Body:
iOS Date() returns date with at least microsecond precision.

I checked this statement by calling Date().timeIntervalSince1970 which results in 1490891661.074981

Then I need to convert date into string with microsecond precision.

I am using DateFormatter in following way:

let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"
print(formatter.string(from: date))

which results in

"2017-03-30T16:34:21.075000Z"

Now if we compare two results:

1490891661.074981 and "2017-03-30T16:34:21.075000Z"

we can notice that DateFormatter rounds date to millisecond precision while still presenting zeros for microseconds.

Does anybody know how to configure DateFormatter so I can keep microseconds and get correct result: "2017-03-30T16:34:21.074981Z"?

Body:
Thanks to @MartinR for solving first half of my problem and to @ForestKunecke for giving me tips how to solve second half of the problem.

Based on their help I created ready to use solution which converts date from string and vice versa with microsecond precision:

public final class MicrosecondPrecisionDateFormatter: DateFormatter {

    private let microsecondsPrefix = "."

    override public init() {
        super.init()
        locale = Locale(identifier: "en_US_POSIX")
        timeZone = TimeZone(secondsFromGMT: 0)
    }

    required public init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    override public func string(from date: Date) -> String {
        dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
        let components = calendar.dateComponents(Set([Calendar.Component.nanosecond]), from: date)

        let nanosecondsInMicrosecond = Double(1000)
        let microseconds = lrint(Double(components.nanosecond!) / nanosecondsInMicrosecond)

        // Subtract nanoseconds from date to ensure string(from: Date) doesn't attempt faulty rounding.
        let updatedDate = calendar.date(byAdding: .nanosecond, value: -(components.nanosecond!), to: date)!
        let dateTimeString = super.string(from: updatedDate)

        let string = String(format: "%@.%06ldZ",
                            dateTimeString,
                            microseconds)

        return string
    }

    override public func date(from string: String) -> Date? {
        dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

        guard let microsecondsPrefixRange = string.range(of: microsecondsPrefix) else { return nil }
        let microsecondsWithTimeZoneString = String(string.suffix(from: microsecondsPrefixRange.upperBound))

        let nonDigitsCharacterSet = CharacterSet.decimalDigits.inverted
        guard let timeZoneRangePrefixRange = microsecondsWithTimeZoneString.rangeOfCharacter(from: nonDigitsCharacterSet) else { return nil }

        let microsecondsString = String(microsecondsWithTimeZoneString.prefix(upTo: timeZoneRangePrefixRange.lowerBound))
        guard let microsecondsCount = Double(microsecondsString) else { return nil }

        let dateStringExludingMicroseconds = string
            .replacingOccurrences(of: microsecondsString, with: "")
            .replacingOccurrences(of: microsecondsPrefix, with: "")

        guard let date = super.date(from: dateStringExludingMicroseconds) else { return nil }
        let microsecondsInSecond = Double(1000000)
        let dateWithMicroseconds = date + microsecondsCount / microsecondsInSecond

        return dateWithMicroseconds
    }
}

Usage:

let formatter = MicrosecondPrecisionDateFormatter()
let date = Date(timeIntervalSince1970: 1490891661.074981)
let formattedString = formatter.string(from: date) // 2017-03-30T16:34:21.074981Z

ContentLicense: CC BY-SA 4.0


问:
Is it possible to use full text search on encrypted column in SQL Server 2008
I have a column, that is encrypted using symmetric key in a database. An encrypted content is just a text. I would like to query this text using full text search. Is it possible?
I was thinking about using full text search filters  to index a column, but didn't find any ready-to-use filter.
So is it possible to develop such a filter, in particular, is it possible to access encryption key, that is stored in a database, from filter code and decrypt the text from the column?
Could you recommend any tutorial, how to start with such a development?</p>

答:
From what I understand, there is no support for encrypted indexes. You basically have two options:

You can index partial data in clear (without encryption) and match the partial data to the fully encrypted data.

Decrypt the data before searching

Although this post was for SQL Server 2005, it remains true for SQL Server 2008.

ContentLicense: CC BY-SA 2.5


问:
POSIXct objects showing as numeric
```<code>k <- file.Folder$LPRS.time[1] + lag*60
> k
[1] "2017-03-31 00:15:00 IST"
> file.Folder$start.time[1] <- file.Folder$LPRS.time[1] + lag*60
> file.Folder$start.time[1]
[1] 1490899500
</code>```

file.Folder$start.time is a new column created just at the last step.
Why is it showing properly as date in scenario 1 and as number in scenario 2??

答:
To answer the question "why?" we would need to see the results of str(file.Folder), in particular the class of file.Folder$start.time: This short test session shows that assigning to a non-time, numeric column will coerce the result to the underlying seconds since the start of the epoch. This effect is not the result if assigning to an individual values using "[":

```<code>> test <- data.frame(tm=Sys.time() , num=1)
> test$num[1] <- test$tm +60
> test
                   tm        num
1 2017-03-30 16:49:03 1490917803
> test <- cbind(test, other.tm=Sys.time())
> test$othernum <- test$tm +60
> test
                   tm        num            other.tm            othernum
1 2017-03-30 16:49:03 1490917803 2017-03-30 16:50:25 2017-03-30 16:50:03
> test$othernum[1] <- test$tm +60
> test
                   tm        num            other.tm            othernum
1 2017-03-30 16:49:03 1490917803 2017-03-30 16:50:25 2017-03-30 16:50:03
</code>```

Title: POSIXct objects showing as numeric

Body:
k <- file.Folder$LPRS.time[1] + lag*60
> k
[1] "2017-03-31 00:15:00 IST"
> file.Folder$start.time[1] <- file.Folder$LPRS.time[1] + lag*60
> file.Folder$start.time[1]
[1] 1490899500

file.Folder$start.time is a new column created just at the last step.
Why is it showing properly as date in scenario 1 and as number in scenario 2??

Body:
To answer the question "why?" we would need to see the results of str(file.Folder), in particular the class of file.Folder$start.time: This short test session shows that assigning to a non-time, numeric column will coerce the result to the underlying seconds since the start of the epoch. This effect is not the result if assigning to an individual values using "[":

> test <- data.frame(tm=Sys.time() , num=1)
> test$num[1] <- test$tm +60
> test
                   tm        num
1 2017-03-30 16:49:03 1490917803
> test <- cbind(test, other.tm=Sys.time())
> test$othernum <- test$tm +60
> test
                   tm        num            other.tm            othernum
1 2017-03-30 16:49:03 1490917803 2017-03-30 16:50:25 2017-03-30 16:50:03
> test$othernum[1] <- test$tm +60
> test
                   tm        num            other.tm            othernum
1 2017-03-30 16:49:03 1490917803 2017-03-30 16:50:25 2017-03-30 16:50:03


问:
CSS grid wrapping
Is it possible to make a CSS grid wrap without using media queries?

In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.

Here's some sample code:

.grid {
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-columns: 186px 186px 186px 186px;
}

.grid > * {
  background-color: green;
  height: 200px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid">
  <div>1</div>
  <div>2</div>
  <div>3</div>
  <div>4</div>
</div></code>```

And here's a GIF image:

As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with grid-template-columns that would be great. I'd prefer the children to specify their own width.

答:
You want either auto-fit or auto-fill inside the repeat() function:

```<code>grid-template-columns: repeat(auto-fit, 186px);
</code>```

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

```<code>grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));
</code>```

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:

Title: CSS grid wrapping

Body:
Is it possible to make a CSS grid wrap without using media queries?

In my case, I have a non-deterministic number of items that I want placed in a grid and I want that grid to wrap. Using Flexbox, I'm unable to reliably space things nicely. I'd like to avoid a bunch of media queries too.

Here's some sample code:

.grid {
  display: grid;
  grid-gap: 10px;
  grid-auto-flow: column;
  grid-template-columns: 186px 186px 186px 186px;
}

.grid > * {
  background-color: green;
  height: 200px;
}

1

2

3

4

And here's a GIF image:

As a side-note, if anyone can tell me how I could avoid specifying the width of all the items like I am with grid-template-columns that would be great. I'd prefer the children to specify their own width.

Body:
You want either auto-fit or auto-fill inside the repeat() function:

grid-template-columns: repeat(auto-fit, 186px);

The difference between the two becomes apparent if you also use a minmax() to allow for flexible column sizes:

grid-template-columns: repeat(auto-fill, minmax(186px, 1fr));

This allows your columns to flex in size, ranging from 186 pixels to equal-width columns stretching across the full width of the container. auto-fill will create as many columns as will fit in the width. If, say, five columns fit, even though you have only four grid items, there will be a fifth empty column:

Using auto-fit instead will prevent empty columns, stretching yours further if necessary:


问:
Zend Framework 1 - remote database connection via ssh tunnel
I want to connect to my customer remote database.

I'm able to establish ssh tunnel with command:

```<code>ssh -vvv -i path_to_private_key -L 3308:127.0.0.1:3307 ssh_user@ssh_host
</code>```

and connect to his database with:

```<code>mysql -u database_user -p -h 127.0.0.1 -P 3308
</code>```

But when I want to configure my zend framework project to read data from this database, nothing happen (even there is no logs in apache2 error logs)

Below my configurations from application.ini file:

```<code>resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3308

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password
resources.db.params.profiler = false
</code>```

I have no idea what could be wrong. Any ideas?

答:
Try this with a slight change to your ssh command.

```<code>ssh -N -L -i path_to_private_key 3307:mysqlhost:3306 ssh-user@ssh-host
</code>```

Where 3307 is your local port and mysqlhost is the mysql host you're connecting to, not localhost. Now, your config should look like:

```<code>resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3307

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password
</code>```

For reference from the manual:

```<code>-N      Do not execute a remote command.  This is useful for just forwarding ports (pro-
         tocol version 2 only).
</code>```

Hope that helps.

Body:
I want to connect to my customer remote database.

I'm able to establish ssh tunnel with command:

ssh -vvv -i path_to_private_key -L 3308:127.0.0.1:3307 ssh_user@ssh_host

and connect to his database with:

mysql -u database_user -p -h 127.0.0.1 -P 3308

But when I want to configure my zend framework project to read data from this database, nothing happen (even there is no logs in apache2 error logs)

Below my configurations from application.ini file:

resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3308

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password
resources.db.params.profiler = false

I have no idea what could be wrong. Any ideas?

Body:
Try this with a slight change to your ssh command.

ssh -N -L -i path_to_private_key 3307:mysqlhost:3306 ssh-user@ssh-host

Where 3307 is your local port and mysqlhost is the mysql host you're connecting to, not localhost. Now, your config should look like:

resources.db.adapter = "mysqli"
resources.db.params.host = 127.0.0.1
resources.db.params.port = 3307

resources.db.params.dbname = database_name
resources.db.params.username = database_user
resources.db.params.password = database_password

For reference from the manual:

-N      Do not execute a remote command.  This is useful for just forwarding ports (pro-
         tocol version 2 only).

Hope that helps.


问:
React Native to limit lines in TextInput
If set multiline as true, React Native will accept unlimited lines in TextInput, there has maxLength but it just limits the maximum number of characters, so how to set maximum lines on TextInput?</p>

答:
I don't think you can on iOS. As mentioned, Android has the prop numberOfLines. The closest I can think of would be to try to estimate the width of your input and limit the characters based on that dimension but it's my opinion that it may be a dark path to go down.

Should you choose to do so, someone was trying to get the number of lines here. A combination of the onLayout function to get the width of your TextInput and onChangeText to limit it might work.


问:
What is an "Abort trap" & how do I debug it?
I'm getting this message each time I compile my project:

```<code>RunIPhoneUnitTest.sh: line 92: 31389 Abort trap              "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents
</code>```

I understand is a problem in my code, but then I don't figure how solve or found it.

The strange thing, is that I get this with this call:

```<code>-- This is the interface
@interface DbObject : NSObject {
    NSInteger Id;
    NSDate* timeStamp;
}

@property (nonatomic) NSInteger Id;
@property (nonatomic, retain) NSDate *timeStamp;
----
This fail with above error
----
NSString * filter = [NSString stringWithFormat:"id = %@", ds.Id, nil];
</code>```

BUT the wird thing is that I delete that line, that method and still get it! Is making my crazy.

Currently, I'm thinking in delete code until not get a error & start adding it, but wonder if exist a more pragmatic solution...

答:
An abort trap usually means that abort was called somewhere. This is most likely happening because your unit test harness code is throwing an exception that it's not expecting and simply handling this by calling abort(3). The abort call is not very easy to debug because it provides no information regarding who called it or why, never returns and generates a SIGABRT. You could install a new handler for SIGABRT and place a breakpoint there and then at least examine the current call stack... but read the rest for information on why this is happening in the first place.

However, the problem with your code above is that NSInteger is not an object type, it's a regular primitive. To correct your error, replace the failing line with this:

```<code>NSString *filter = [NSString stringWithFormat:@"id = %lld", (long long)ds.Id];
</code>```

First, stringWithFormat takes an NSString object as a parameter, so you need to use the '@' character to specify that the string literal is an NSString. This is very important since @"blah blah" is actually translated into an object. The call you're making to stringWithFormat is expecting the NSString object information to be resident at that memory address, but instead it's getting a string of characters and is most likely exploding there. Make sure that all your string literals are @"blah blah" where an NSString type is expected and that they're not simple c-strings.

Second, the '@' character in the format string specifies an object. Since NSInteger is not an object, you can't use this format character. Instead use %lld to specify a long long integer. Finally, you don't need to add the nil at the end of the parameter list when using stringWithFormat since the format string itself specifies how many parameters to expect.

As an aside, the reason that %lld is used instead of just %d is that NSInteger changes size depending on whether you're compiling for a 32-bit or 64-bit target. By promoting the NSInteger to the long long type and using the %lld specifier you make sure that you won't have truncation issues in the future if you compile for 64-bit and your NSInteger value requires more than 32 bits to store.

OwnerDisplayName: mamcx

Body:
I'm getting this message each time I compile my project:

RunIPhoneUnitTest.sh: line 92: 31389 Abort trap              "$TARGET_BUILD_DIR/$EXECUTABLE_PATH" -RegisterForSystemEvents

I understand is a problem in my code, but then I don't figure how solve or found it.

The strange thing, is that I get this with this call:

-- This is the interface
@interface DbObject : NSObject {
    NSInteger Id;
    NSDate* timeStamp;
}

@property (nonatomic) NSInteger Id;
@property (nonatomic, retain) NSDate *timeStamp;
----
This fail with above error
----
NSString * filter = [NSString stringWithFormat:"id = %@", ds.Id, nil];

BUT the wird thing is that I delete that line, that method and still get it! Is making my crazy.

Currently, I'm thinking in delete code until not get a error & start adding it, but wonder if exist a more pragmatic solution...

LastEditorDisplayName: Hank Gay

Body:
An abort trap usually means that abort was called somewhere. This is most likely happening because your unit test harness code is throwing an exception that it's not expecting and simply handling this by calling abort(3). The abort call is not very easy to debug because it provides no information regarding who called it or why, never returns and generates a SIGABRT. You could install a new handler for SIGABRT and place a breakpoint there and then at least examine the current call stack... but read the rest for information on why this is happening in the first place.

However, the problem with your code above is that NSInteger is not an object type, it's a regular primitive. To correct your error, replace the failing line with this:

NSString *filter = [NSString stringWithFormat:@"id = %lld", (long long)ds.Id];

First, stringWithFormat takes an NSString object as a parameter, so you need to use the '@' character to specify that the string literal is an NSString. This is very important since @"blah blah" is actually translated into an object. The call you're making to stringWithFormat is expecting the NSString object information to be resident at that memory address, but instead it's getting a string of characters and is most likely exploding there. Make sure that all your string literals are @"blah blah" where an NSString type is expected and that they're not simple c-strings.

Second, the '@' character in the format string specifies an object. Since NSInteger is not an object, you can't use this format character. Instead use %lld to specify a long long integer. Finally, you don't need to add the nil at the end of the parameter list when using stringWithFormat since the format string itself specifies how many parameters to expect.

As an aside, the reason that %lld is used instead of just %d is that NSInteger changes size depending on whether you're compiling for a 32-bit or 64-bit target. By promoting the NSInteger to the long long type and using the %lld specifier you make sure that you won't have truncation issues in the future if you compile for 64-bit and your NSInteger value requires more than 32 bits to store.

OwnerDisplayName: Jason Coco

LastEditorDisplayName: Jason Coco


问:
Pointer instantly 0x0
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

```<code>TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */
</code>```

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

```<code>151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()
</code>```

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

答:
Better code would actually be to initialise the variable immediately on use by calling getColumn at the point of declaration:

TreeViewColumn *col = preview->get_column(pcFolder);

If this function can return NULL (as it appears to) you must then check before you use the pointer, thus:

```<code>if( col != NULL )
{
   col->set_resizable( true );
}
// else handle the "error" if you want
</code>```

Title: Pointer instantly 0x0

Body:
i have this code. the pointer turns 0x0 immediately before using it. short before, it had the correct address.

TreeViewColumn *col;
col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
col->set_resizable(true);            /* col = 0x0 */

i use Gtkmm 2.4, but it returns the expected value, it just turns 0x0. whats wrong?

gdb proof:

151             col = preview->get_column(pcFolder); /* col = 0x7fff5fc404a0 */
(gdb) print col
$1 = ('Gtk::TreeViewColumn' *) 0x7fff5fc404a0
(gdb) print *col
warning: can't find linker symbol for virtual table for `Gtk::TreeViewColumn' value
$2 = {
  <Gtk::Object> = {
    <Glib::Object> = {
      <Glib::ObjectBase> = <invalid address>,
      members of Glib::Object:
      _vptr$Object = 0x7fff5fc06a20,
      static object_class_ = {<No data fields>}
    },
    members of Gtk::Object:
    static object_class_ = {<No data fields>},
    referenced_ = 21,
    gobject_disposed_ = 60
  },
  members of Gtk::TreeViewColumn:
  static treeviewcolumn_class_ = {<No data fields>}
}
(gdb) next
152             col->set_resizable(true);            /* col = 0x0 */
(gdb) print col
$3 = ('Gtk::TreeViewColumn' *) 0x0
(gdb) print *col
Cannot access memory at address 0x0
(gdb) next

Program received signal EXC_BAD_ACCESS, Could not access memory.
Reason: KERN_INVALID_ADDRESS at address: 0x0000000000000000
0x00000001000edc68 in Gtk::TreeViewColumn::set_resizable ()

i have no idea what causes this phenomenon. do you have?

Solution:
reading the documentation. the function returning pcFolder counts from 1, get_column() from 0.

Body:
Better code would actually be to initialise the variable immediately on use by calling getColumn at the point of declaration:

TreeViewColumn *col = preview->get_column(pcFolder);

If this function can return NULL (as it appears to) you must then check before you use the pointer, thus:

if( col != NULL )
{
   col->set_resizable( true );
}
// else handle the "error" if you want


问:
Open an activity window in Android WebView passing a String in JavaScript?
I want to open an activity window in Android WebView passing a String in JavaScript, but I always get this undefined error:

05-18 06:32:02.586  13351-13351/com.vaydesign.tw3 I/chromium﹕
  [INFO:CONSOLE(11)] "Uncaught TypeError: Cannot read property
  'openActivity' of undefined", source: file:///android_asset/index.html
  (11)

Part of my MainActivity.java:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    myWebView.setWebViewClient(new WebViewClient());

    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl("file:///android_asset/index.html");
    // Caching
    myWebView.getSettings().setDomStorageEnabled(true);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    myWebView.getSettings().setAppCachePath(appCachePath);
    myWebView.getSettings().setAllowFileAccess(true);
    myWebView.getSettings().setAppCacheEnabled(true);
}

public class WebAppInterface {
    public Context mContext;
    WebAppInterface(Context c) {
        mContext = c;
    }
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    public void openActivity(String activity){
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(activity));
        mContext.startActivity(i);
    }
}
</code>```

HTML:

```<code><div class="entry" onclick="window.JSInterface.openActivity('About');">About</div>
</code>```

答:
I spent all day debugging a similar issue, I was getting the error:

"Uncaught TypeError: window.Android.openActivity is not a function"

I had set my annotated method to private by mistake.

Check your method signature to make sure it is public if you are  going to be calling it from Javascript.

Body:
I want to open an activity window in Android WebView passing a String in JavaScript, but I always get this undefined error:

05-18 06:32:02.586  13351-13351/com.vaydesign.tw3 I/chromium﹕
  [INFO:CONSOLE(11)] "Uncaught TypeError: Cannot read property
  'openActivity' of undefined", source: file:///android_asset/index.html
  (11)

Part of my MainActivity.java:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    WebView myWebView = (WebView) findViewById(R.id.webView1);
    myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
    myWebView.setWebViewClient(new WebViewClient());

    myWebView.getSettings().setJavaScriptEnabled(true);
    myWebView.loadUrl("file:///android_asset/index.html");
    // Caching
    myWebView.getSettings().setDomStorageEnabled(true);
    String appCachePath = getApplicationContext().getCacheDir().getAbsolutePath();
    myWebView.getSettings().setAppCachePath(appCachePath);
    myWebView.getSettings().setAllowFileAccess(true);
    myWebView.getSettings().setAppCacheEnabled(true);
}

public class WebAppInterface {
    public Context mContext;
    WebAppInterface(Context c) {
        mContext = c;
    }
    @JavascriptInterface
    public void showToast(String toast) {
        Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
    }

    public void openActivity(String activity){
        Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(activity));
        mContext.startActivity(i);
    }
}

HTML:

About


问:
Reduce FFmpeg CPU Usage with cpulimit and PHP
I run FFmpeg on my server using PHP exec().

It currently uses 100% of the cpu thread while encoding.

I followed this gude that uses a program called cpulimit to reduce it to 30%.

PHP

```<code>$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
exec(escapeshellcmd($args));
</code>```

FFmpeg/PHP works, and it will work with nice/cpulimit through the terminal, but after adding

 nice -19 cpulimit -l 30 -- to the PHP script it no longer works with exec().

Output

FFmpeg output returns blank. I'm not able to see the full output, I tried using:

```<code>$output = shell_exec($args);
echo "<p>$output</p>"
</code>```

and

```<code>file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);
</code>```

But they return 1 empty line.

Solution

My thought is that www-data runs FFmpeg and nice/cpulimit may need root?

How can I get PHP exec() to work with FFmpeg args and cpulimit?

Or is there an alternative way to limit the usage %?

答: If safemode is enabled then, the execution of programes are limited. Check this documentation here, http://php.net/manual/en/function.exec.php</p>

Body:
I run FFmpeg on my server using PHP exec().

It currently uses 100% of the cpu thread while encoding.

I followed this gude that uses a program called cpulimit to reduce it to 30%.

PHP

$args = "nice -19 cpulimit -l 30 -- ffmpeg -y -i intput.avi -vcodec libx264 -acodec aac -b:a 192k -threads 1 output.mp4"
exec(escapeshellcmd($args));

FFmpeg/PHP works, and it will work with nice/cpulimit through the terminal, but after adding

 nice -19 cpulimit -l 30 -- to the PHP script it no longer works with exec().

Output

FFmpeg output returns blank. I'm not able to see the full output, I tried using:

$output = shell_exec($args);
echo "
$output
"

and

file_put_contents("/var/www/mysite/logs/$output.log", $line . PHP_EOL, FILE_APPEND);

But they return 1 empty line.

Solution

My thought is that www-data runs FFmpeg and nice/cpulimit may need root?

How can I get PHP exec() to work with FFmpeg args and cpulimit?

Or is there an alternative way to limit the usage %?


问:
JavaScript Sort compare function fails in Internet Explorer
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]```
</div>
</div>
</p>

<p>This is my function:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot < b)) || (a > b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});</code>```

答:
The issue is that your sort algorithm is sensitive to the order in which dates are passed to it. IE uses a different sort algorithm so gets the source data in a different order to Firefox, so sometimes you get a different result and sometimes you don't, depending on the order of dates in the original array.

So not IE's fault, you should be grateful that it helpd identify an issue with your algorithm. ;-)

There some other flaws in your code. If you follow the error messages provided by moment.js, you'll see that the line:

```<code>var pivot = moment(readingStartDate).format("DD-MMM");
</code>```

Throws a warning:

Deprecation warning: value provided is not in a recognized RFC2822 or
  ISO format. moment construction falls back to js Date(), which is not
  reliable across all browsers and versions. Non RFC2822/ISO date
  formats are discouraged and will be removed in an upcoming major
  release. Please refer to
  http://momentjs.com/guides/#/warnings/js-date/ for more info.
  Arguments:  [0] _isAMomentObject: true, _isUTC: false, _useUTC: false,
  _l: undefined, _i: 31-Mar, _f: undefined, _strict: undefined, _locale: [object Object] undefined

Changing that line to:

```<code>var pivot = moment(readingStartDate,'DD-MM').format('DD-MMM');
</code>```

removes the warning. Also, in the line:

```<code>(a < pivot) && (pivot < b)
</code>```

you are comparing a moment object (pivot), to Date objects (a and b). The simplest fix is if pivot is also a date, so:

```<code>var pivot = moment(readingStartDate,'DD-MM').format('DD-MMM').toDate();
</code>```

You can run the following in IE 7, but unfortunately SO snippets don't support even IE 10 so you'll have to run it elsewhere to test IE. It runs in Firefox 38 though.

It demonstrates that passing the same values in a different order produces a different result.

var statsDataPoints1 = [{"_Name": "30-Mar"}, {"_Name": " 1-Apr"}, {"_Name": "31-Mar"}];
var statsDataPoints2 = [{"_Name": "30-Mar"}, {"_Name": "31-Mar"}, {"_Name": " 1-Apr"}];

var readingStartDate = "31-Mar";
var dummyYear = 2000;
var pivot = moment(readingStartDate, 'DD-MM').format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear).toDate();

function doStuff(statsDataPoints) {
  statsDataPoints.sort(function(aDate, bDate) {

    var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
    var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

    if (((a < pivot) && (pivot  b)) {
      return 1;
    } else if (((b < pivot) && (pivot < a)) || (a < b)) {
      return -1;
    }
    return 0;
  });
}

// This source data sequence gives different results in Firefox and IE
doStuff(statsDataPoints1);
for (var i = 0, iLen = statsDataPoints1.length; i < iLen; i++) {
  console.log(statsDataPoints1[i]._Name);
};

// Same data values as statsDataPoints1, different sequence
// Result has the same order in Firefox and IE
doStuff(statsDataPoints2);
for (var i = 0, iLen = statsDataPoints2.length; i < iLen; i++) {
  console.log(statsDataPoints2[i]._Name);
};```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script></code>```

Body:
I have a function which orders dates based on a pivot. Note that this function ignores the year of the supplied dates. For example, given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.  The problem seems to be with my sort compare function which works perfectly fine in Chrome and Firefox, however fails in IE.  The resulting statsDataPoints (Array) does not get sorted.

This is what the dates array looks like:

[{"Min":"6.0", "Mean":"10.8", "Max":"32.1", "StdDev":"7.5", "LowerPercentile":"6.7", "Median":"8.0", "UpperPercentile":"11.2", "_Name":"30-Mar"}, {"Min":"6.0", "Mean":"11.1", "Max":"31.7", "StdDev":"7.4", "LowerPercentile":"7.3", "Median":"8.7", "UpperPercentile":"11.1", "_Name":"31-Mar"}, {"Min":"6.0", "Mean":"10.9", "Max":"31.4", "StdDev":"7.3", "LowerPercentile":"7.2", "Median":"8.4", "UpperPercentile":"11.0", "_Name":" 1-Apr"}, ... ]

This is my function:

/**
 * Returns a function which orders dates based on a pivot. Note that this function ignores the year of the
 * supplied dates. It is easiest to illustrate how this function works with an example:
 * Given a pivot date of 1-July, all dates will be ordered from 1-July to 31-June.
 *
 * @param {Array}  dates    An array of objects containing a date key.
 * @param {String} pivot    The pivot date we are sorting from (should be in the same format as dateKey)
 */

var dummyYear = 2000;
var pivot = moment(readingStartDate).format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear);

statsDataPoints.sort(function(aDate, bDate) {

 var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
 var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

 if (((a < pivot) && (pivot  b)) {
  return 1;
 } else if (((b < pivot) && (pivot < a)) || (a < b)) {
  return -1;
 }
 return 0;

});

Body:
The issue is that your sort algorithm is sensitive to the order in which dates are passed to it. IE uses a different sort algorithm so gets the source data in a different order to Firefox, so sometimes you get a different result and sometimes you don't, depending on the order of dates in the original array.

So not IE's fault, you should be grateful that it helpd identify an issue with your algorithm. ;-)

There some other flaws in your code. If you follow the error messages provided by moment.js, you'll see that the line:

var pivot = moment(readingStartDate).format("DD-MMM");

Throws a warning:

Deprecation warning: value provided is not in a recognized RFC2822 or
  ISO format. moment construction falls back to js Date(), which is not
  reliable across all browsers and versions. Non RFC2822/ISO date
  formats are discouraged and will be removed in an upcoming major
  release. Please refer to
  http://momentjs.com/guides/#/warnings/js-date/ for more info.
  Arguments:  [0] _isAMomentObject: true, _isUTC: false, _useUTC: false,
  _l: undefined, _i: 31-Mar, _f: undefined, _strict: undefined, _locale: [object Object] undefined

Changing that line to:

var pivot = moment(readingStartDate,'DD-MM').format('DD-MMM');

removes the warning. Also, in the line:

(a < pivot) && (pivot < b)

you are comparing a moment object (pivot), to Date objects (a and b). The simplest fix is if pivot is also a date, so:

var pivot = moment(readingStartDate,'DD-MM').format('DD-MMM').toDate();

You can run the following in IE 7, but unfortunately SO snippets don't support even IE 10 so you'll have to run it elsewhere to test IE. It runs in Firefox 38 though.

It demonstrates that passing the same values in a different order produces a different result.

var statsDataPoints1 = [{"_Name": "30-Mar"}, {"_Name": " 1-Apr"}, {"_Name": "31-Mar"}];
var statsDataPoints2 = [{"_Name": "30-Mar"}, {"_Name": "31-Mar"}, {"_Name": " 1-Apr"}];

var readingStartDate = "31-Mar";
var dummyYear = 2000;
var pivot = moment(readingStartDate, 'DD-MM').format("DD-MMM");
pivot = moment(pivot, "DD-MMM").year(dummyYear).toDate();

function doStuff(statsDataPoints) {
  statsDataPoints.sort(function(aDate, bDate) {

    var a = moment(aDate["_Name"], "DD-MMM").year(dummyYear).toDate();
    var b = moment(bDate["_Name"], "DD-MMM").year(dummyYear).toDate();

    if (((a < pivot) && (pivot < b)) || (a > b)) {
      return 1;
    } else if (((b < pivot) && (pivot < a)) || (a < b)) {
      return -1;
    }
    return 0;
  });
}

// This source data sequence gives different results in Firefox and IE
doStuff(statsDataPoints1);
for (var i = 0, iLen = statsDataPoints1.length; i < iLen; i++) {
  console.log(statsDataPoints1[i]._Name);
};

// Same data values as statsDataPoints1, different sequence
// Result has the same order in Firefox and IE
doStuff(statsDataPoints2);
for (var i = 0, iLen = statsDataPoints2.length; i < iLen; i++) {
  console.log(statsDataPoints2[i]._Name);
};

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.js"></script>


问:
STL std::map, pass by ref to const and the necessity of const_casting
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

```<code>#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};
</code>```

Definition:

```<code>#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}
</code>```

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

答:
Why not change hasWidget to take a Widget*? The interface is dodgy at the moment, because it implies that you're looking for Widgets by value in the underlying map, when you're actually looking for them by address. The method should also be const, I reckon:

```<code>bool hasWidget(Widget *) const;
</code>```

Body:
I have a simple question regarding const_cast and best practices regarding STL containers. Consider the following where class Foo has a private STL std::map from Widget* to int:

Declaration:

#include <map>
using std::map;

class Widget;

class Foo {
public:
     Foo(int n);
     virtual ~Foo();

     bool hasWidget(const Widget&);

private:
     map<Widget*,int> widget_map;
};

Definition:

#include <map>
#include "Foo.h"
#include "Widget.h"

using std::map;

Foo::Foo(int n)
{
     for (int i = 0; i < n; i++) {
          widget_map[new Widget()] = 1;
     }
}

Foo::~Foo()
{
     map<Widget*, int>::iterator it;
     for (it = widget_map.begin(); it != widget_map.end(); it++) {
          delete it->first;
     }
}

bool Foo::hasWidget(const Widget& w)
{
     map<Widget*, int>::iterator it;
     it = this->widget_map.find(const_cast<Widget*>(&w));
     return ( ! ( it == widget_map.end() ) );
}

Given that hasWidget takes a reference to const as its parameter, the constness needs to be cast away when calling map::find (wiget_map being from Wiget* to int). As far as I can tell, this approach is both sensible and desirable -- but I'm reluctant to accept it as such without feedback from more experienced C++ programmers.

It seems to me that this is one of the few cases of using const_cast appropriately given that we're passing the result of the cast to an STL method. Am I correct?

I realise that other permutations of this question have been posed already (for example, const_cast for vector with object) but none seem to directly address the above.

Thanks in advance.

Body:
Why not change hasWidget to take a Widget*? The interface is dodgy at the moment, because it implies that you're looking for Widgets by value in the underlying map, when you're actually looking for them by address. The method should also be const, I reckon:

bool hasWidget(Widget *) const;


问:
firebase api requests on react native not working
I am using firebase for my app, whenever i click the logout button i get ('evaluating 'this.firebase.unauth'). What is wrong with my api request?

logout() {
    this.firebase.unauth();
  }
  //this is the api request

  onPress() {
  Actions.logout();
  }
  //this is the action method. ```

答:
Are you using import firebase from 'firebase'; ? In that case you dont need this, just firebase.unauth(); should do it. However, is there really a method called unauth() ? The docs refer to using:

```<code>firebase.auth().signOut().then(function() {
  // Sign-out successful.
}).catch(function(error) {
  // An error happened.
});
</code>```

Body:
Are you using import firebase from 'firebase'; ? In that case you dont need this, just firebase.unauth(); should do it. However, is there really a method called unauth() ? The docs refer to using:

firebase.auth().signOut().then(function() {
  // Sign-out successful.
}).catch(function(error) {
  // An error happened.
});


问:
Only allow fields that are in the index template
I have logstash pushing docs into an elasticsearch cluster.

And I apply a template to the indices with logstash:

```<code>elasticsearch {
  hosts => 1.1.1.1.,2.2.2.2.
  index => "logstash-myindex-%{+YYYY-MM-dd}"
  template_name => "mytemplate"
  template => "/etc/logstash/index_templates/mytemplate.json"
  template_overwrite => true
}
</code>```

Is there a way I can have only the fields defined in the template get added to the docs? Because sometimes the docs have a bunch of other fields I don't care about and I don't want to manually filter out each one. I want to be able to say if field not in index template do not add.

edit:
I did this in my index template but fields not specified in the template are still getting added to docs:

```<code>{
  "template": "logstash-myindex*",
  "order": 10,
  "mappings": {
    "_default_": {
      "dynamic": "scrict",
      "_all": {
        "enabled": false
      },
      "properties": {
        "@timestamp": {
          "type": "date",
          "include_in_all": false
        },
        "@version": {
          "type": "keyword",
          "include_in_all": false
        },
        "bytesReceived": {
          "type": "text",
          "norms": false,
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        },
         .... etc
</code>```

答:
I'm not familiar with logstash - but I'm assuming this is just like creating an index in ElasticSearch.

In ElasticSearch you can disabled the dynamic creation of fields by adding:

```<code>"dynamic": false
</code>```

to the mapping.

This would look something like this:

```<code>{
  "mappings": {
    "_default_": {
      "dynamic": false
    }
  }
}
</code>```

Body:
I have logstash pushing docs into an elasticsearch cluster.

And I apply a template to the indices with logstash:

elasticsearch {
  hosts => 1.1.1.1.,2.2.2.2.
  index => "logstash-myindex-%{+YYYY-MM-dd}"
  template_name => "mytemplate"
  template => "/etc/logstash/index_templates/mytemplate.json"
  template_overwrite => true
}

Is there a way I can have only the fields defined in the template get added to the docs? Because sometimes the docs have a bunch of other fields I don't care about and I don't want to manually filter out each one. I want to be able to say if field not in index template do not add.

edit:
I did this in my index template but fields not specified in the template are still getting added to docs:

{
  "template": "logstash-myindex*",
  "order": 10,
  "mappings": {
    "_default_": {
      "dynamic": "scrict",
      "_all": {
        "enabled": false
      },
      "properties": {
        "@timestamp": {
          "type": "date",
          "include_in_all": false
        },
        "@version": {
          "type": "keyword",
          "include_in_all": false
        },
        "bytesReceived": {
          "type": "text",
          "norms": false,
          "fields": {
            "keyword": {
              "type": "keyword"
            }
          }
        },
         .... etc

Body:
I'm not familiar with logstash - but I'm assuming this is just like creating an index in ElasticSearch.

In ElasticSearch you can disabled the dynamic creation of fields by adding:

"dynamic": false

to the mapping.

This would look something like this:

{
  "mappings": {
    "_default_": {
      "dynamic": false
    }
  }
}


问:
Using Supervisor to run ratchet websockets and queue in laravel
I have made an artisan command to run a websockets on some port like below

```<code>class webSockets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'run:socket {port?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run websockets for specified port';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(RedisInterface $redis)
    {
        $this->redis=$redis;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
       $port = $this->argument('port');
       if($port=='8182') {
            $server = IoServer::factory(
                         new SocketController($this->redis),$port
                    );
       }
       else if($port=='8181'){
            $server = IoServer::factory(
                         new Socket1Controller($this->redis),$port
                    );
       }

       $server->run();
    }
}
</code>```

I can run those sockets easily running an artisan command like below

```<code>php artisan run:socket 8181
php artisan run :socket 8182
</code>```

I need to deploy it on a production server where thousand of devices are connected on that web sockets . I tried supervisor to daemonize the process but no luck

My conf file looks like below

```<code>[program:ratchet]
command                 = php /var/www/v3 artisan run:socket 8181;php /var/www/v3 artisan run:socket 8182
process_name            = Ratchet
numprocs                = 1
autostart               = true
autorestart             = true
stdout_logfile          = ./logs/info.log
stderr_logfile          = ./logs/error.log
</code>```

I realised both port 8181 and 8182 are free and are not receiving any messages.

When I tried sudo service supervisorctl I saw all process have uptime 0:00:00 and different pids

```<code>laravel_queue                    RUNNING   pid 62246, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62245, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62305, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62304, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62419, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62418, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62553, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62552, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62689, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62688, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62819, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62818, uptime 0:00:00
supervisor> status
</code>```

Is there anything I missed?

答:
I managed to fix it by making seperate process on supervisor

Manage queue

In /etc/supervisord/conf.d/ create laravel_queue.conf:

```<code>[program:laravel_queue]
command= php artisan queue:listen redis --timeout=7200
directory=/var/www/gpsv3
stderr_logfile=/var/www/gpsv3/storage/logs/laraqueue.err.log
stdout_logfile=/var/www/gpsv3/storage/logs/laraqueue.out.log
redirect_stderr=true
</code>```

Give it execute permissions: chmod +x laravel_queue.conf

Now update Supervisor with: sudo supervisorctl reread. And start using those changes with: sudo supervisorctl update.

socket Listener

In /etc/supervisord/conf.d/ create socket.conf:

```<code>[program:socket]
command= php artisan run:socket 8182
directory=/var/www/gpsv3
stderr_logfile=/var/www/gpsv3/storage/logs/socket.err.log
stdout_logfile=/var/www/gpsv3/storage/logs/socket.out.log
redirect_stderr=true
</code>```

Give it execute permissions: chmod +x socket.conf

Now update Supervisor with: sudo supervisorctl reread. And start using those changes with: sudo supervisorctl update.

Body:
I have made an artisan command to run a websockets on some port like below

class webSockets extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'run:socket {port?}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Run websockets for specified port';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct(RedisInterface $redis)
    {
        $this->redis=$redis;
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //
       $port = $this->argument('port');
       if($port=='8182') {
            $server = IoServer::factory(
                         new SocketController($this->redis),$port
                    );
       }
       else if($port=='8181'){
            $server = IoServer::factory(
                         new Socket1Controller($this->redis),$port
                    );
       }

       $server->run();
    }
}

I can run those sockets easily running an artisan command like below

php artisan run:socket 8181
php artisan run :socket 8182

I need to deploy it on a production server where thousand of devices are connected on that web sockets . I tried supervisor to daemonize the process but no luck

My conf file looks like below

[program:ratchet]
command                 = php /var/www/v3 artisan run:socket 8181;php /var/www/v3 artisan run:socket 8182
process_name            = Ratchet
numprocs                = 1
autostart               = true
autorestart             = true
stdout_logfile          = ./logs/info.log
stderr_logfile          = ./logs/error.log

I realised both port 8181 and 8182 are free and are not receiving any messages.

When I tried sudo service supervisorctl I saw all process have uptime 0:00:00 and different pids

laravel_queue                    RUNNING   pid 62246, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62245, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62305, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62304, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62419, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62418, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62553, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62552, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62689, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62688, uptime 0:00:00
supervisor> status
laravel_queue                    RUNNING   pid 62819, uptime 0:00:00
ratchet:Ratchet                  RUNNING   pid 62818, uptime 0:00:00
supervisor> status

Is there anything I missed?

Body:
I managed to fix it by making seperate process on supervisor

Manage queue

In /etc/supervisord/conf.d/ create laravel_queue.conf:

[program:laravel_queue]
command= php artisan queue:listen redis --timeout=7200
directory=/var/www/gpsv3
stderr_logfile=/var/www/gpsv3/storage/logs/laraqueue.err.log
stdout_logfile=/var/www/gpsv3/storage/logs/laraqueue.out.log
redirect_stderr=true

Give it execute permissions: chmod +x laravel_queue.conf

Now update Supervisor with: sudo supervisorctl reread. And start using those changes with: sudo supervisorctl update.

socket Listener

In /etc/supervisord/conf.d/ create socket.conf:

[program:socket]
command= php artisan run:socket 8182
directory=/var/www/gpsv3
stderr_logfile=/var/www/gpsv3/storage/logs/socket.err.log
stdout_logfile=/var/www/gpsv3/storage/logs/socket.out.log
redirect_stderr=true

Give it execute permissions: chmod +x socket.conf

Now update Supervisor with: sudo supervisorctl reread. And start using those changes with: sudo supervisorctl update.


问:
XmlReader.Read() getting name and value
I've been at this for a few hours now and was hoping someone could point me in the right direction.
my psuedo xml file:

```<code><Parent>
    <child Seq="1">
        <Num1>1137555</Num1>
    </Child>
    <Child2>
        <Text1>random text</Text1>
    </Child2>
</Parent>
</code>```

I'm trying to get a reference to the Elements Name(in this case "Num1") and it's value("1137555"). I understand that the reader will read Num1 first, and then the content but my code seems to be skipping over a large chunk of my xml. I have about 16 different child elements nested in the parent element but i'm only getting back perhaps the last half of them.
My Code:

```<code>while (xmlReader.Read())
{
    if (xmlReader.NodeType == XmlNodeType.Element)
    {
        Console.WriteLine(xmlReader.Name);
    }
    if (xmlReader.HasValue)
    {
        Console.WriteLine(xmlReader.Value);
    }
}
</code>```

答:
Try a combination of XmlReader and Xml linq</p>

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            while (!reader.EOF)
            {
                if (reader.Name != "Parent")
                {
                    reader.ReadToFollowing("Parent");
                }
                if (!reader.EOF)
                {
                    XElement parent = (XElement)XDocument.ReadFrom(reader);
                    foreach (XElement child in parent.Elements())
                    {
                        XElement grandchild = child.Elements().FirstOrDefault();
                        Console.WriteLine("tag : '{0}', value : '{1}'", grandchild.Name.LocalName, (string)grandchild);
                    }

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

Title: XmlReader.Read() getting name and value

Body:
I've been at this for a few hours now and was hoping someone could point me in the right direction.
my psuedo xml file:

<Parent>
    <child Seq="1">
        <Num1>1137555</Num1>
    </Child>
    <Child2>
        <Text1>random text</Text1>
    </Child2>
</Parent>

I'm trying to get a reference to the Elements Name(in this case "Num1") and it's value("1137555"). I understand that the reader will read Num1 first, and then the content but my code seems to be skipping over a large chunk of my xml. I have about 16 different child elements nested in the parent element but i'm only getting back perhaps the last half of them.
My Code:

while (xmlReader.Read())
{
    if (xmlReader.NodeType == XmlNodeType.Element)
    {
        Console.WriteLine(xmlReader.Name);
    }
    if (xmlReader.HasValue)
    {
        Console.WriteLine(xmlReader.Value);
    }
}

Body:
Try a combination of XmlReader and Xml linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XmlReader reader = XmlReader.Create(FILENAME);

            while (!reader.EOF)
            {
                if (reader.Name != "Parent")
                {
                    reader.ReadToFollowing("Parent");
                }
                if (!reader.EOF)
                {
                    XElement parent = (XElement)XDocument.ReadFrom(reader);
                    foreach (XElement child in parent.Elements())
                    {
                        XElement grandchild = child.Elements().FirstOrDefault();
                        Console.WriteLine("tag : '{0}', value : '{1}'", grandchild.Name.LocalName, (string)grandchild);
                    }

                }
            }
            Console.ReadLine();
        }
    }
}


问:
Proper Asynchronous Request Handling - JS
I am making an application. The application makes two requests, the first is to the MapBox API to load a map and the second is to the Yelp Fusion API (through my node server). The through throttling testing I have found that the MapBox Call takes aproximately 1/2 the time to complete as the Yelp Call.

I am a bit confused how to manage the two requests. Do I load one and then the next? Do I load them both and then create two input functions to account for the Yelp loading first/ the MapBox loading first?

Here is how my code is structured currently:

```<code>      // -------------------------- // Yelp API Call // ------------------------- //
$.ajax({
    type: 'POST',
    data: {
      "food_type": getParameterByName('type', window.location.href),
      "geolocation": false,
      "long": -1,
      "lat": -1,
      "radius": 1000,
      "limit": 30
    },
    success: function(response) {
      YelpCallback(response);
    },
    error: function(xhr) {
      console.log("Failure");
      console.log(xhr)
    },
    url: POST_baseurl + "yelp"
  });

  // -------------------------- // MapBox API Call // ------------------------- //
  mapboxgl.accessToken = 'pk.<accesstoken>.<accesstoken>';
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/jeremysmorgan/<mapstyle url>',
    center: [lat, long],
    zoom: 13
  });
  map.on('load', function(e) {
    var map_load_time = new Date().getTime() - map_start_time;
    console.log("map_load_time: " + map_load_time);

    MapCallback(e);
  });

    function YelpCallback(data) {
  yelp_loaded = true;
  yelp_data = data;
  if (map_loaded) {
    main();
  }
}

function MapCallback(e) {
  map_loaded = true;
  if (YelpCallback) {
    main();
  }
}
</code>```

答:
Something like this should work. Read up on callbacks (proper ones), they're very helpful. http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/

```<code>function YelpAjax(callback)
{
  $.ajax({
    //yelp request,
    success: function(response){
      callback(response); //once done, call this argument with parameter: response
    }
  });
}

map.onload('load', function(e){
  //same stuff

  YelpAjax(function(response){ //this anonymous function is the argument.
    main();
  })
})
</code>```

Contain your Yelp AJAX request in a function with a callback. Put this function in map.onload. Call main() afterwards.

It's effectively like putting main() inside your Ajax success, but with less literal nesting.

```<code>$.ajax({
  //yelp request,
  success: function(response){
    main();
  }
});
</code>```

You could also try the async library which allows you to control asynchronous functions very elegantly, but you might need to brush up first before tackling something like that. http://caolan.github.io/async/

Body:
I am making an application. The application makes two requests, the first is to the MapBox API to load a map and the second is to the Yelp Fusion API (through my node server). The through throttling testing I have found that the MapBox Call takes aproximately 1/2 the time to complete as the Yelp Call.

I am a bit confused how to manage the two requests. Do I load one and then the next? Do I load them both and then create two input functions to account for the Yelp loading first/ the MapBox loading first?

Here is how my code is structured currently:

      // -------------------------- // Yelp API Call // ------------------------- //
$.ajax({
    type: 'POST',
    data: {
      "food_type": getParameterByName('type', window.location.href),
      "geolocation": false,
      "long": -1,
      "lat": -1,
      "radius": 1000,
      "limit": 30
    },
    success: function(response) {
      YelpCallback(response);
    },
    error: function(xhr) {
      console.log("Failure");
      console.log(xhr)
    },
    url: POST_baseurl + "yelp"
  });

  // -------------------------- // MapBox API Call // ------------------------- //
  mapboxgl.accessToken = 'pk.<accesstoken>.<accesstoken>';
  var map = new mapboxgl.Map({
    container: 'map',
    style: 'mapbox://styles/jeremysmorgan/<mapstyle url>',
    center: [lat, long],
    zoom: 13
  });
  map.on('load', function(e) {
    var map_load_time = new Date().getTime() - map_start_time;
    console.log("map_load_time: " + map_load_time);

    MapCallback(e);
  });

    function YelpCallback(data) {
  yelp_loaded = true;
  yelp_data = data;
  if (map_loaded) {
    main();
  }
}

function MapCallback(e) {
  map_loaded = true;
  if (YelpCallback) {
    main();
  }
}

Body:
Something like this should work. Read up on callbacks (proper ones), they're very helpful. http://cwbuecheler.com/web/tutorials/2013/javascript-callbacks/

function YelpAjax(callback)
{
  $.ajax({
    //yelp request,
    success: function(response){
      callback(response); //once done, call this argument with parameter: response
    }
  });
}

map.onload('load', function(e){
  //same stuff

  YelpAjax(function(response){ //this anonymous function is the argument.
    main();
  })
})

Contain your Yelp AJAX request in a function with a callback. Put this function in map.onload. Call main() afterwards.

It's effectively like putting main() inside your Ajax success, but with less literal nesting.

$.ajax({
  //yelp request,
  success: function(response){
    main();
  }
});

You could also try the async library which allows you to control asynchronous functions very elegantly, but you might need to brush up first before tackling something like that. http://caolan.github.io/async/


问:
link to local disk
Is it possible to put a html link on a page that opens a file in local disk?

Like c:/myFolder/myfile.xls

This page is not actually going to be on web, but this feature would be needed for demostration purposes only. When the page is on web, the file is too, and link has url value.

答: Tried it, but link does not open a thing. Sorry, I could not put this as a comment. Please edit.</p>

Title: link to local disk


问:
How to zip an iterator with an infinite range?
I want to keep track of index as I iterate through an iterator. In Haskell, I could just zip the iterator with an infinite list of integers, [1..]. However, I'm not aware of functionality like this in Python. What's the easiest way to construct an iterator that works as below?

```<code>for (case,i) in zip(data, magic_infinite_list):
    print('Case #{}: {}'.format(i,case))
</code>```

(I know I could just make a variable i and manually increment it, that's not the point -- I want to know if it's possible to do this with iterators)

答:
You should use enumerate. Note that here i is 0-based:

```<code>for (i, case) in enumerate(data):
    print('Case #{}: {}'.format(i + 1, case))
</code>```

Body:
I want to keep track of index as I iterate through an iterator. In Haskell, I could just zip the iterator with an infinite list of integers, [1..]. However, I'm not aware of functionality like this in Python. What's the easiest way to construct an iterator that works as below?

for (case,i) in zip(data, magic_infinite_list):
    print('Case #{}: {}'.format(i,case))

(I know I could just make a variable i and manually increment it, that's not the point -- I want to know if it's possible to do this with iterators)

Body:
You should use enumerate. Note that here i is 0-based:

for (i, case) in enumerate(data):
    print('Case #{}: {}'.format(i + 1, case))


问:
What name should I be using for heroku postgres DB?
In the UI, I note that there are effectively two names of the db. Which one should I be using when trying to make a connection?

This main one:

And then this one under the credentials section:

答: You should navigate to Settings in your Heroku account and use the value defined in the DATABASE_URL env var.


问:
Accent insensitive searching in RadComboBox
I'm relatively new to using ASP webforms and Telerik, but I'm looking for a way that allows me to type special characters (é, ù, à, ...) in a RadComboBox.

Lets say I have a name in my ObjectDataSource called "René Somebody". I need to be able to find him by searching for "Rene" and "René", but so far no luck.

In the application they managed to do this on a RadGrid with filters, but this same solution doesn't work for the RadComboBox as far as I know.

The solution they used in the RadGrid: http://www.telerik.com/forums/accent-insensitive-filtering-filtering-on-a-different-column#YS1QT8P1U0-cRPFNfjvDzA

答:
I have no access to the backend components but the demo you linked contains frontend code and it looks like you can hack in there. It looks like this control may be both client-server and client-side only. For client-side only hacks looks kind of complicated and invloves non-public API (_onInputChange) but for client-server case (which is probably your case) the doc on client side of RadComboBox Object mentions requestItems method so hacking it is probably reasonably future safe:

var hackRadComboBoxFilter = function (combobox, filterProcessingFunction) {
    var oldRequestItems = combobox.requestItems;

    combobox.requestItems = function() {
        var args = Array.prototype.slice.call(arguments);
        // requestItems has several arguments but the text seems to be the
        // first one, so let's modify it and call the original method
        var origFilter = args[0];
        args[0] = filterProcessingFunction(origFilter);
        oldRequestItems.apply(this, args);
    }
};
```

<p>Unfortunately I don't know a built-in way to deal with accents in JS but you can hack something simple here as well:</p>

<pre class="lang-js prettyprint-override"><code>var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var mappedAccents = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
var removeAccents = function (origStr) {
    var components = [];
    var len = origStr.length;
    var afterLastAccent = 0;
    for (var i = 0; i < len; i++) {
        var mapPos = accents.indexOf(origStr[i]);
        if (mapPos != -1) {
            components.push(origStr.substr(afterLastAccent, i - afterLastAccent) + mappedAccents[mapPos]);
            afterLastAccent = i + 1;
        }
    }
    if (afterLastAccent < len)
        components.push(origStr.substr(afterLastAccent, len - afterLastAccent));
    return components.join('');
};
</code>```

So now you can combine it in something like this:

// In real app you probably want something like this
// var targetComboBox = $find("<%= RadComboBox1.ClientID %>");
// but for test let's just hack first combobox on the page
var targetComboBox = Telerik.Web.UI.RadComboBox.ComboBoxes[0];
hackRadComboBoxFilter(targetComboBox, removeAccents);
```

<p>or if you want to modify all the comboboxes on the page, you can change prototype using the same trick:</p>

<pre class="lang-js prettyprint-override"><code>hackRadComboBoxFilter(Telerik.Web.UI.RadComboBox.prototype, removeAccents)
</code>```

Body:
I have no access to the backend components but the demo you linked contains frontend code and it looks like you can hack in there. It looks like this control may be both client-server and client-side only. For client-side only hacks looks kind of complicated and invloves non-public API (_onInputChange) but for client-server case (which is probably your case) the doc on client side of RadComboBox Object mentions requestItems method so hacking it is probably reasonably future safe:

var hackRadComboBoxFilter = function (combobox, filterProcessingFunction) {
    var oldRequestItems = combobox.requestItems;

    combobox.requestItems = function() {
        var args = Array.prototype.slice.call(arguments);
        // requestItems has several arguments but the text seems to be the
        // first one, so let's modify it and call the original method
        var origFilter = args[0];
        args[0] = filterProcessingFunction(origFilter);
        oldRequestItems.apply(this, args);
    }
};

Unfortunately I don't know a built-in way to deal with accents in JS but you can hack something simple here as well:

var accents = 'ÀÁÂÃÄÅàáâãäåÒÓÔÕÕÖØòóôõöøÈÉÊËèéêëðÇçÐÌÍÎÏìíîïÙÚÛÜùúûüÑñŠšŸÿýŽž';
var mappedAccents = "AAAAAAaaaaaaOOOOOOOooooooEEEEeeeeeCcDIIIIiiiiUUUUuuuuNnSsYyyZz";
var removeAccents = function (origStr) {
    var components = [];
    var len = origStr.length;
    var afterLastAccent = 0;
    for (var i = 0; i < len; i++) {
        var mapPos = accents.indexOf(origStr[i]);
        if (mapPos != -1) {
            components.push(origStr.substr(afterLastAccent, i - afterLastAccent) + mappedAccents[mapPos]);
            afterLastAccent = i + 1;
        }
    }
    if (afterLastAccent < len)
        components.push(origStr.substr(afterLastAccent, len - afterLastAccent));
    return components.join('');
};

So now you can combine it in something like this:

// In real app you probably want something like this
// var targetComboBox = $find("<%= RadComboBox1.ClientID %>");
// but for test let's just hack first combobox on the page
var targetComboBox = Telerik.Web.UI.RadComboBox.ComboBoxes[0];
hackRadComboBoxFilter(targetComboBox, removeAccents);

or if you want to modify all the comboboxes on the page, you can change prototype using the same trick:

hackRadComboBoxFilter(Telerik.Web.UI.RadComboBox.prototype, removeAccents)


问:
How to send submitted forms in ionic apps to email?
I have an Ionic app and contact form page (with Name, Email, and Phone).
After the user clicks the Submit button, I want this form data to be sent to my E-mail. How do I do this? </p>

答:
You'd need to setup some kind of REST api, so that when the user clicks on the submit button, the data in the contact form is sent to the REST api you've set up, which will trigger it to send an email to you with the contents of the user's message.

Since you've tagged this with Node.JS, I would suggest that you have the contact form's action be send to something like 'http://yoursite.com/sendemail/' and then your API would handle the call with something like:

```<code>router.route('/sendemail/')
.post(function(req, res) {
    var userInput = req.body;
    var message = {
     text:    userInput.message,
     from:    userInput.name + ' <' + userInput.email + '>',
     to:      'youremail@email.com',
     subject: userInput.subject,
     attachment:
     [
        {data: this.text, alternative:true},
     ]
  };
  server.send(message, function(err, message) {
    if(err) {
      res.status(400);
      console.log(err);
    } else {
      res.status(200)
    }
  });
});
</code>```

(you'll need to change some variables to fit your code)

Hope this helps!

Body:
You'd need to setup some kind of REST api, so that when the user clicks on the submit button, the data in the contact form is sent to the REST api you've set up, which will trigger it to send an email to you with the contents of the user's message.

Since you've tagged this with Node.JS, I would suggest that you have the contact form's action be send to something like 'http://yoursite.com/sendemail/' and then your API would handle the call with something like:

router.route('/sendemail/')
.post(function(req, res) {
    var userInput = req.body;
    var message = {
     text:    userInput.message,
     from:    userInput.name + ' <' + userInput.email + '>',
     to:      'youremail@email.com',
     subject: userInput.subject,
     attachment:
     [
        {data: this.text, alternative:true},
     ]
  };
  server.send(message, function(err, message) {
    if(err) {
      res.status(400);
      console.log(err);
    } else {
      res.status(200)
    }
  });
});

(you'll need to change some variables to fit your code)

Hope this helps!


答:
A map with a key where the key is pointer is unwieldy - the only way to look it up is to have the same pointer. For this to work, you have to guarantee that the the hasWidget method will get called with an object that has the same address!

Surely you should implement Widget properly such that it has the correct operators overloaded to act as a key in a std::map! In your map, you can then simply have:

```<code>std::map<Widget, int>
</code>```

And then your find doesn't need a const_cast!

Title: STL std::map, pass by ref to const and the necessity of const_casting

Body:
A map with a key where the key is pointer is unwieldy - the only way to look it up is to have the same pointer. For this to work, you have to guarantee that the the hasWidget method will get called with an object that has the same address!

Surely you should implement Widget properly such that it has the correct operators overloaded to act as a key in a std::map! In your map, you can then simply have:

std::map<Widget, int>

And then your find doesn't need a const_cast!