问:
How can I use the Keras OCR example?
I found examples/image_ocr.py which seems to for OCR. Hence it should be possible to give the model an image and receive text. However, I have no idea how to do so. How do I feed the model with a new image? Which kind of preprocessing is necessary?

What I did

Installing the depencencies:

Install cairocffi: sudo apt-get install python-cairocffi

Install editdistance: sudo -H pip install editdistance

Change train to return the model and save the trained model.

Run the script to train the model.

Now I have a model.h5. What's next?

See https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras for my current code. I know how to load the model (see below) and this seems to work. The problem is that I don't know how to feed new scans of images with text to the model.

Related side questions

What is CTC? Connectionist Temporal Classification?

Are there algorithms which reliably detect the rotation of a document?

Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

What I tried

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

from keras import backend as K
import keras
from keras.models import load_model
import os

from image_ocr import ctc_lambda_func, create_model, TextImageGenerator
from keras.layers import Lambda
from keras.utils.data_utils import get_file
import scipy.ndimage
import numpy

img_h = 64
img_w = 512
pool_size = 2
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))
if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=32,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
print("Input shape: {}".format(input_shape))
model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)

model.load_weights("my_model.h5")

x = scipy.ndimage.imread('example.png', mode='L').transpose()
x = x.reshape(x.shape + (1,))

# Does not work
print(model.predict(x))
</code>```

this gives

```<code>2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
  File "eval_example.py", line 45, in <module>
    print(model.predict(x))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict
    check_batch_axis=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1)
</code>```

答:
Here, you created a model that needs 4 inputs:

```<code>model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)
</code>```

Your predict attempt, on the other hand, is loading just an image.

Hence the message: The model expects 4 arrays, but only received one array

From your code, the necessary inputs are:

```<code>input_data = Input(name='the_input', shape=input_shape, dtype='float32')
labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len],dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')
</code>```

The original code and your training work because they're using the TextImageGenerator. This generator cares to give you the four necessary inputs for the model.

So, what you have to do is to predict using the generator. As you have the fit_generator() method for training with the generator, you also have the predict_generator() method for predicting with the generator.

Now, for a complete answer and solution, I'd have to study your generator and see how it works (which would take me some time). But now you know what is to be done, you can probably figure it out.

You can either use the generator as it is, and predict probably a huge lot of data, or you can try to replicate a generator that will yield just one or a few images with the necessary labels, length and label length.

Or maybe, if possible, just create the 3 remaining arrays manually, but making sure they have the same shapes (except for the first, which is the batch size) as the generator outputs.

The one thing you must assert, though, is: have 4 arrays with the same shapes as the generator outputs, except for the first dimension.

Title: How can I use the Keras OCR example?

Body:
I found examples/image_ocr.py which seems to for OCR. Hence it should be possible to give the model an image and receive text. However, I have no idea how to do so. How do I feed the model with a new image? Which kind of preprocessing is necessary?

What I did

Installing the depencencies:

Install cairocffi: sudo apt-get install python-cairocffi

Install editdistance: sudo -H pip install editdistance

Change train to return the model and save the trained model.

Run the script to train the model.

Now I have a model.h5. What's next?

See https://github.com/MartinThoma/algorithms/tree/master/ML/ocr/keras for my current code. I know how to load the model (see below) and this seems to work. The problem is that I don't know how to feed new scans of images with text to the model.

Related side questions

What is CTC? Connectionist Temporal Classification?

Are there algorithms which reliably detect the rotation of a document?

Are there algorithms which reliably detect lines / text blocks / tables / images (hence make a reasonable segmentation)? I guess edge detection with smoothing and line-wise histograms already works reasonably well for that?

What I tried

#!/usr/bin/env python

from keras import backend as K
import keras
from keras.models import load_model
import os

from image_ocr import ctc_lambda_func, create_model, TextImageGenerator
from keras.layers import Lambda
from keras.utils.data_utils import get_file
import scipy.ndimage
import numpy

img_h = 64
img_w = 512
pool_size = 2
words_per_epoch = 16000
val_split = 0.2
val_words = int(words_per_epoch * (val_split))
if K.image_data_format() == 'channels_first':
    input_shape = (1, img_w, img_h)
else:
    input_shape = (img_w, img_h, 1)

fdir = os.path.dirname(get_file('wordlists.tgz',
                                origin='http://www.mythic-ai.com/datasets/wordlists.tgz', untar=True))

img_gen = TextImageGenerator(monogram_file=os.path.join(fdir, 'wordlist_mono_clean.txt'),
                             bigram_file=os.path.join(fdir, 'wordlist_bi_clean.txt'),
                             minibatch_size=32,
                             img_w=img_w,
                             img_h=img_h,
                             downsample_factor=(pool_size ** 2),
                             val_split=words_per_epoch - val_words
                             )
print("Input shape: {}".format(input_shape))
model, _, _ = create_model(input_shape, img_gen, pool_size, img_w, img_h)

model.load_weights("my_model.h5")

x = scipy.ndimage.imread('example.png', mode='L').transpose()
x = x.reshape(x.shape + (1,))

# Does not work
print(model.predict(x))

this gives

2017-07-05 22:07:58.695665: I tensorflow/core/common_runtime/gpu/gpu_device.cc:996] Creating TensorFlow device (/gpu:0) -> (device: 0, name: GeForce GTX TITAN Black, pci bus id: 0000:01:00.0)
Traceback (most recent call last):
  File "eval_example.py", line 45, in <module>
    print(model.predict(x))
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 1567, in predict
    check_batch_axis=False)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/training.py", line 106, in _standardize_input_data
    'Found: array with shape ' + str(data.shape))
ValueError: The model expects 4 arrays, but only received one array. Found: array with shape (512, 64, 1)

Body:
Here, you created a model that needs 4 inputs:

model = Model(inputs=[input_data, labels, input_length, label_length], outputs=loss_out)

Your predict attempt, on the other hand, is loading just an image.

Hence the message: The model expects 4 arrays, but only received one array

From your code, the necessary inputs are:

input_data = Input(name='the_input', shape=input_shape, dtype='float32')
labels = Input(name='the_labels', shape=[img_gen.absolute_max_string_len],dtype='float32')
input_length = Input(name='input_length', shape=[1], dtype='int64')
label_length = Input(name='label_length', shape=[1], dtype='int64')

The original code and your training work because they're using the TextImageGenerator. This generator cares to give you the four necessary inputs for the model.

So, what you have to do is to predict using the generator. As you have the fit_generator() method for training with the generator, you also have the predict_generator() method for predicting with the generator.

Now, for a complete answer and solution, I'd have to study your generator and see how it works (which would take me some time). But now you know what is to be done, you can probably figure it out.

You can either use the generator as it is, and predict probably a huge lot of data, or you can try to replicate a generator that will yield just one or a few images with the necessary labels, length and label length.

Or maybe, if possible, just create the 3 remaining arrays manually, but making sure they have the same shapes (except for the first, which is the batch size) as the generator outputs.

The one thing you must assert, though, is: have 4 arrays with the same shapes as the generator outputs, except for the first dimension.


来源: stackexchange

问:
Whois list of Top Level Domain against their corresponding registrar
I'm trying to find a list of TLD's to their corresponding whois server, for example

.com americanWhoisServer
.net someOtherWhoisServer
.au australianWhoisServer

In the end i'm aiming for something like a Dictionary where the key is the TLD and the value is the whois server address (eg whois.apnic.net).

Ah snap, i just realised that i am given the IP addresses and not domain names but a list could still come in handy.

How can i determine which whois server to use given a IP address? Guess and check?

答: You can get the official (?) tld list from http://data.iana.org/TLD/tlds-alpha-by-domain.txt and then query the IANA whois server (whois.iana.org at port 43) for each tld to get information about it. Slightly more export-friendly and official than the HTML tld list at http://www.iana.org/domains/root/db/.</p>

ContentLicense: CC BY-SA 2.5


问:
"SyntaxError: Unexpected token < in JSON at position 0"
In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.

Feed.js:

```<code>import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '',
            text: '',
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author,
                                text: text,
                                included: included,
                                victim: victim
                              })
    this.setState({author: '',
                  text: '',
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (
    <div className="threadsBox">
      <h1>Feed</h1>
      <div>
        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />
      </div>
    </div>
    )
  }
})

module.exports = ThreadsBox
</code>```

In Chrome developer tools, the error seems to be coming from this function:

```<code> loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },
</code>```

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

答:
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:

```<code>{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}
</code>```

If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.

When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8 header which contains invalid JSON in the response body you'll see this error.

If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:

```<code><b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
    "success": false,
    "data": [{ ... }]
}
</code>```

95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.

Here's the module:

```<code>/**
 * Track Incomplete XHR Requests
 *
 * Extend httpInterceptor to track XHR completions and keep a queue
 * of our HTTP requests in order to find if any are incomplete or
 * never finish, usually this is the source  of the issue if it's
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );
</code>```

More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.

ContentLicense: CC BY-SA 4.0

Body:
In a React app component which handles Facebook-like content feeds, I am running into an error:

Feed.js:94 undefined "parsererror" "SyntaxError: Unexpected token < in JSON at position 0

I ran into a similar error which turned out to be a typo in the HTML within the render function, but that doesn't seem to be the case here.

More confusingly, I rolled the code back to an earlier, known-working version and I'm still getting the error.

Feed.js:

import React from 'react';

var ThreadForm = React.createClass({
  getInitialState: function () {
    return {author: '',
            text: '',
            included: '',
            victim: ''
            }
  },
  handleAuthorChange: function (e) {
    this.setState({author: e.target.value})
  },
  handleTextChange: function (e) {
    this.setState({text: e.target.value})
  },
  handleIncludedChange: function (e) {
    this.setState({included: e.target.value})
  },
  handleVictimChange: function (e) {
    this.setState({victim: e.target.value})
  },
  handleSubmit: function (e) {
    e.preventDefault()
    var author = this.state.author.trim()
    var text = this.state.text.trim()
    var included = this.state.included.trim()
    var victim = this.state.victim.trim()
    if (!text || !author || !included || !victim) {
      return
    }
    this.props.onThreadSubmit({author: author,
                                text: text,
                                included: included,
                                victim: victim
                              })
    this.setState({author: '',
                  text: '',
                  included: '',
                  victim: ''
                  })
  },
  render: function () {
    return (
    <form className="threadForm" onSubmit={this.handleSubmit}>
      <input
        type="text"
        placeholder="Your name"
        value={this.state.author}
        onChange={this.handleAuthorChange} />
      <input
        type="text"
        placeholder="Say something..."
        value={this.state.text}
        onChange={this.handleTextChange} />
      <input
        type="text"
        placeholder="Name your victim"
        value={this.state.victim}
        onChange={this.handleVictimChange} />
      <input
        type="text"
        placeholder="Who can see?"
        value={this.state.included}
        onChange={this.handleIncludedChange} />
      <input type="submit" value="Post" />
    </form>
    )
  }
})

var ThreadsBox = React.createClass({
  loadThreadsFromServer: function () {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  handleThreadSubmit: function (thread) {
    var threads = this.state.data
    var newThreads = threads.concat([thread])
    this.setState({data: newThreads})
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      type: 'POST',
      data: thread,
      success: function (data) {
        this.setState({data: data})
      }.bind(this),
      error: function (xhr, status, err) {
        this.setState({data: threads})
        console.error(this.props.url, status, err.toString())
      }.bind(this)
    })
  },
  getInitialState: function () {
    return {data: []}
  },
  componentDidMount: function () {
    this.loadThreadsFromServer()
    setInterval(this.loadThreadsFromServer, this.props.pollInterval)
  },
  render: function () {
    return (

Feed

        <ThreadForm onThreadSubmit={this.handleThreadSubmit} />

    )
  }
})

module.exports = ThreadsBox

In Chrome developer tools, the error seems to be coming from this function:

 loadThreadsFromServer: function loadThreadsFromServer() {
    $.ajax({
      url: this.props.url,
      dataType: 'json',
      cache: false,
      success: function (data) {
        this.setState({ data: data });
      }.bind(this),
      error: function (xhr, status, err) {
        console.error(this.props.url, status, err.toString());
      }.bind(this)
    });
  },

with the line console.error(this.props.url, status, err.toString() underlined.

Since it looks like the error seems to have something to do with pulling JSON data from the server, I tried starting from a blank db, but the error persists. The error seems to be called in an infinite loop presumably as React continuously tries to connect to the server and eventually crashes the browser.

EDIT:

I've checked the server response with Chrome dev tools and Chrome REST client, and the data appears to be proper JSON.

EDIT 2:

It appears that though the intended API endpoint is indeed returning the correct JSON data and format, React is polling http://localhost:3000/?_=1463499798727 instead of the expected http://localhost:3001/api/threads.

I am running a webpack hot-reload server on port 3000 with the express app running on port 3001 to return the backend data. What's frustrating here is that this was working correctly the last time I worked on it and can't find what I could have possibly changed to break it.

Body:
On a general level this error occurs when a JSON object is parsed that has syntax errors in it. Think of something like this, where the message property contains unescaped double quotes:

{
    "data": [{
        "code": "1",
        "message": "This message has "unescaped" quotes, which is a JSON syntax error."
    }]
}

If you have JSON in your app somewhere then it's good to run it through JSONLint to verify that it doesn't have a syntax error. Usually this isn't the case though in my experience, it's usually JSON returned from an API that's the culprit.

When an XHR request is made to an HTTP API that returns a response with a Content-Type:application/json; charset=UTF-8 header which contains invalid JSON in the response body you'll see this error.

If a server-side API controller is improperly handling a syntax error, and it's being printed out as part of the response, that will break the structure of JSON returned. A good example of this would be an API response containing a PHP Warning or Notice in the response body:

<b>Notice</b>:  Undefined variable: something in <b>/path/to/some-api-controller.php</b> on line <b>99</b><br />
{
    "success": false,
    "data": [{ ... }]
}

95% of the time this is the source of the issue for me, and though it's somewhat addressed here in the other responses I didn't feel it was clearly described. Hopefully this helps, if you're looking for a handy way to track down which API response contains a JSON syntax error I've written an Angular module for that.

Here's the module:

/**
 * Track Incomplete XHR Requests
 *
 * Extend httpInterceptor to track XHR completions and keep a queue
 * of our HTTP requests in order to find if any are incomplete or
 * never finish, usually this is the source  of the issue if it's
 * XHR related
 */
angular.module( "xhrErrorTracking", [
        'ng',
        'ngResource'
    ] )
    .factory( 'xhrErrorTracking', [ '$q', function( $q ) {
        var currentResponse = false;

        return {
            response: function( response ) {
                currentResponse = response;
                return response || $q.when( response );
            },
            responseError: function( rejection ) {
                var requestDesc = currentResponse.config.method + ' ' + currentResponse.config.url;
                if ( currentResponse.config.params ) requestDesc += ' ' + JSON.stringify( currentResponse.config.params );

                console.warn( 'JSON Errors Found in XHR Response: ' + requestDesc, currentResponse );

                return $q.reject( rejection );
            }
        };
    } ] )
    .config( [ '$httpProvider', function( $httpProvider ) {
        $httpProvider.interceptors.push( 'xhrErrorTracking' );
    } ] );

More details can be found in the blog article referenced above, I haven't posted everything found there here as it's probably not all relevant.

ContentLicense: CC BY-SA 3.0


问:
How to get twitter data of tweets within a certain time frame?
what do I put in my code to make it where I can force the program to stop printing data when the tweets data back to a certain point. For example, how can I get all tweets about Verratti from within a month of running this?</p>

```<code>from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json

access_token = the code
access_token_secret = the code
consumer_key = the code
consumer_secret = the code

#print
class StdOutListener(StreamListener):

    def on_data(self, data):
        print (json.loads(data)['text'])
        return True

    def on_error(self, status):
        print (status)

#find
if __name__ == '__main__':

    #This handles Twitter authetification and the connection to Twitter         Streaming API
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)

    #This line filter Twitter Streams to capture data by the keywords:     'python', 'javascript', 'ruby'
    stream.filter(track=['Verratti'])
</code>```

答:
Nice question. It turns out that the Twitter API only lets you look back one week from the current date. There is a way around it though, someone made a github library that can search for any timeframe using twitter's advanced search function and you don't even have to bother with the whole authentication process.

Check it out: https://github.com/Jefferson-Henrique/GetOldTweets-python

Body:
what do I put in my code to make it where I can force the program to stop printing data when the tweets data back to a certain point. For example, how can I get all tweets about Verratti from within a month of running this?

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
import json

access_token = the code
access_token_secret = the code
consumer_key = the code
consumer_secret = the code

#print
class StdOutListener(StreamListener):

    def on_data(self, data):
        print (json.loads(data)['text'])
        return True

    def on_error(self, status):
        print (status)

#find
if __name__ == '__main__':

    #This handles Twitter authetification and the connection to Twitter         Streaming API
    l = StdOutListener()
    auth = OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    stream = Stream(auth, l)

    #This line filter Twitter Streams to capture data by the keywords:     'python', 'javascript', 'ruby'
    stream.filter(track=['Verratti'])


问:
JavaScript function redirects to index page after execution MVC 5
I'm calling the function via

```<code>@Html.ActionLink("Edit", "", null, new { onclick = "editshow('"+ item.vend_id + "','" + item.vend_name + "','" + item.vend_addr + "','" + item.vend_pno + "');" })
</code>```

and the script is

```<code><script type="text/javascript">
function editshow(i, n, a, p) {
    document.getElementById("vid").value = i;
    document.getElementById("vnam").value = n;
    document.getElementById("vad").value = a;
    document.getElementById("vpno").value = p;

}
</code>```

after its execution, it always redirects to the index page. How to stop it?

答:
I am going to assume that you intentionally left your Action name blank.

Since you do not want to hit the server when clicked, you should return a false from your javascript function.

```<code>    function editshow(i, n, a, p) {
      document.getElementById("vid").value = i;
      document.getElementById("vnam").value = n;
      document.getElementById("vad").value = a;
      document.getElementById("vpno").value = p;

      return false;
   }
</code>```

If you do not return a false from a button click handler, most likely it will result in a postback behavior. In that case, it will go find the default page and in your case it probably is index.cshtml

Body:
I'm calling the function via

@Html.ActionLink("Edit", "", null, new { onclick = "editshow('"+ item.vend_id + "','" + item.vend_name + "','" + item.vend_addr + "','" + item.vend_pno + "');" })

and the script is

Body:
I am going to assume that you intentionally left your Action name blank.

Since you do not want to hit the server when clicked, you should return a false from your javascript function.

    function editshow(i, n, a, p) {
      document.getElementById("vid").value = i;
      document.getElementById("vnam").value = n;
      document.getElementById("vad").value = a;
      document.getElementById("vpno").value = p;

      return false;
   }

If you do not return a false from a button click handler, most likely it will result in a postback behavior. In that case, it will go find the default page and in your case it probably is index.cshtml


问:
Extending a Attribute Directive
I would like to extend the built-in routerLink directive to create my own directive called customRouterLink.

I have simply created a class that extends RouterLinkWithHref:

```<code>@Directive({
     selector: 'a[customRouterLink]'
})
export class CustomLinkDirective extends RouterLinkWithHref {

  constructor(router: Router, route: ActivatedRoute, locationStrategy:  LocationStrategy) {
    super(router, route, locationStrategy);
  }

  @Input()
  set customRouterLink(data: any[]|string) {
      console.log("custom directive input", data);
  }

}
</code>```

I am attempting to create an instance of this directive:

```<code><a [customRouterLink]="'http://www.google.com'">custom link</a>
</code>```

Which is causing the following error:

```<code>Can't bind to 'customRouterLink' since it isn't a known property of 'a'.
</code>```

However, if I remove extends RouterLinkWithHref from the directive definition it works.

Example plunkers:

CustomLinkDirective extends RouterLinkWithHref - Shows error above

CustomLinkDirective not extending RouterLinkWithHref - Directive created without error

答: I ran into the same error when attempting to extend the RouterLinkWithHref class. The error is coming from the fact that you do not include an @Input decorator for your directive. You are attempting to pass in your url string custom link, but Angular cannot find a property to bind this value to within your class and throws an error. To resolve this simply add @input('customRouterLink') link: string.

Title: Extending a Attribute Directive

Body:
I would like to extend the built-in routerLink directive to create my own directive called customRouterLink.

I have simply created a class that extends RouterLinkWithHref:

@Directive({
     selector: 'a[customRouterLink]'
})
export class CustomLinkDirective extends RouterLinkWithHref {

  constructor(router: Router, route: ActivatedRoute, locationStrategy:  LocationStrategy) {
    super(router, route, locationStrategy);
  }

  @Input()
  set customRouterLink(data: any[]|string) {
      console.log("custom directive input", data);
  }

}

I am attempting to create an instance of this directive:

custom link

Which is causing the following error:

Can't bind to 'customRouterLink' since it isn't a known property of 'a'.

However, if I remove extends RouterLinkWithHref from the directive definition it works.

Example plunkers:

CustomLinkDirective extends RouterLinkWithHref - Shows error above

CustomLinkDirective not extending RouterLinkWithHref - Directive created without error

Body: I ran into the same error when attempting to extend the RouterLinkWithHref class. The error is coming from the fact that you do not include an @Input decorator for your directive. You are attempting to pass in your url string <a [customRouterLink]="'http://www.google.com'">custom link</a>, but Angular cannot find a property to bind this value to within your class and throws an error. To resolve this simply add @input('customRouterLink') link: string.


问:
Set command parameter of a subreport equal to a main report parameter
In my main report, I insert a number for column ID into the selection criteria. It grabs all relevant information where the ID matches.

Now I have a subreport that uses a COMMAND with a SQL Query. Inside, there is a WHERE clause where ID = {?PM-ID}.

How can I configure my SQL Query to pull in the specific ID value I entered into the selection Criteria of the main Report?

答:
Try this, right click on Subreport > Change Sub reports Links

In that window you have to match the ID with the respective column in your sql query.


问:
Find location of a cell's value without knowing table or column name in a sql server database
I need to find a certain table of data but I do not know the name of the table or the columns in it. I have the data in the table at hand. The database is huge do not have the patience it manually go through and look. Is there a query that can be used to search through each of the thousands of tables searching for an exact value that I have.</p>

答:
Having been working as a system admin on systems I did not develop this is an issue I face frequently.  Here is how I approach it:

1) Is there a test system and a UI you can insert the values from?  If so, do a profile trace or extended events to see where the data is going.

2) Is there a data dictionary for the product you can look through and hopefully find the table location?

3) The hardest way is to use information_Schema.columns and information_schema.tables and make educated guesses as to what the table might be named and review the data in it and see if you have it right or not.


问:
Openmdao - AttributeError: 'float' object has no attribute 'size' in Paraboloid Tutorial
I am learning OpenMDAO with the first Paraboloid Tutorial. However, where I run the code with the constrained case (add_constraint(...)) I get the error: AttributeError: 'float' object has no attribute 'size'.
I just copied-pasted the code from the tutorial but I can not fine the error. Here is the code:

```<code>from __future__ import print_function
from openmdao.api import IndepVarComp, Component, Problem, Group
from openmdao.api import ScipyOptimizer
from openmdao.api import ExecComp

class Paraboloid(Component):
    def __init__(self):
        super(Paraboloid, self).__init__()

        self.add_param('x', val=0.0)
        self.add_param('y', val=0.0)

        self.add_output('f_xy', shape=1)

    def solve_nonlinear(self, params, unknowns, resids):
        """f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3
        """

        x = params['x']
        y = params['y']

        unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0

    def linearize(self, params, unknowns, resids):
        """ Jacobian for our paraboloid."""

        x = params['x']
        y = params['y']
        J = {}

        J['f_xy', 'x'] = 2.0*x - 6.0 + y
        J['f_xy', 'y'] = 2.0*y + 8.0 + x
        return J

if __name__ == "__main__":

    top = Problem()

    root = top.root = Group()

    root.add('p1', IndepVarComp('x', 3.0))
    root.add('p2', IndepVarComp('y', -4.0))
    root.add('p', Paraboloid())

    # Constraint Equation
    root.add('con', ExecComp('c = x-y'))

    root.connect('p1.x', 'p.x')
    root.connect('p2.y', 'p.y')
    root.connect('p.x', 'con.x')
    root.connect('p.y', 'con.y')

    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'

    top.driver.add_desvar('p1.x', lower=-50, upper=50)
    top.driver.add_desvar('p2.y', lower=-50, upper=50)
    top.driver.add_objective('p.f_xy')
    top.driver.add_constraint('con.c', lower=15.0)

    top.setup()
    top.run()

    print('\n')
    print('Minimum of %f found at (%f, %f)' % (top['p.f_xy'], top['p.x'], top['p.y']))
</code>```

I run the script and I get the following:

```<code>##############################################
Setup: Checking root problem for potential issues...

No recorders have been specified, so no data will be saved.

Setup: Check of root problem complete.
##############################################

Traceback (most recent call last):
  File "paraboloid.py", line 65, in <module>
    top.run()
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1151, in run
    self.driver.run(self)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 211, in run
    options=self.opt_settings)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/_minimize.py", line 458, in minimize
    constraints, callback=callback, **options)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/slsqp.py", line 390, in _minimize_slsqp
    g = append(fprime(x),0.0)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
    return function(*(wrapper_args + args))
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 334, in _gradfunc
    return_format='array')
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/driver.py", line 834, in calc_gradient
    sparsity=sparsity, inactives=inactives)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1310, in calc_gradient
    inactives=inactives)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1561, in _calc_gradient_ln_solver
    root._sys_linearize(root.params, unknowns, root.resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
    self._jacobian_cache = linearize(params, unknowns, resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/group.py", line 836, in linearize
    sub._sys_linearize(sub.params, sub.unknowns, sub.resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
    self._jacobian_cache = linearize(params, unknowns, resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/components/exec_comp.py", line 273, in linearize
    J[(u, param)] = numpy.zeros((jval.size, psize))
AttributeError: 'float' object has no attribute 'size'
</code>```

The error message appear only when I put the constraint equation.
I believe it is a silly error but, can anyone point me the right direction?
Thank you in advance of your help !

答: I think you may be using an older version of numpy, under which the imag method doesn't return an array. Can you try upgrading to a later version of numpy? I am using 1.12.0 and the code works for me.

Body:
I am learning OpenMDAO with the first Paraboloid Tutorial. However, where I run the code with the constrained case (add_constraint(...)) I get the error: AttributeError: 'float' object has no attribute 'size'.
I just copied-pasted the code from the tutorial but I can not fine the error. Here is the code:

from __future__ import print_function
from openmdao.api import IndepVarComp, Component, Problem, Group
from openmdao.api import ScipyOptimizer
from openmdao.api import ExecComp

class Paraboloid(Component):
    def __init__(self):
        super(Paraboloid, self).__init__()

        self.add_param('x', val=0.0)
        self.add_param('y', val=0.0)

        self.add_output('f_xy', shape=1)

    def solve_nonlinear(self, params, unknowns, resids):
        """f(x,y) = (x-3)^2 + xy + (y+4)^2 - 3
        """

        x = params['x']
        y = params['y']

        unknowns['f_xy'] = (x-3.0)**2 + x*y + (y+4.0)**2 - 3.0

    def linearize(self, params, unknowns, resids):
        """ Jacobian for our paraboloid."""

        x = params['x']
        y = params['y']
        J = {}

        J['f_xy', 'x'] = 2.0*x - 6.0 + y
        J['f_xy', 'y'] = 2.0*y + 8.0 + x
        return J

if __name__ == "__main__":

    top = Problem()

    root = top.root = Group()

    root.add('p1', IndepVarComp('x', 3.0))
    root.add('p2', IndepVarComp('y', -4.0))
    root.add('p', Paraboloid())

    # Constraint Equation
    root.add('con', ExecComp('c = x-y'))

    root.connect('p1.x', 'p.x')
    root.connect('p2.y', 'p.y')
    root.connect('p.x', 'con.x')
    root.connect('p.y', 'con.y')

    top.driver = ScipyOptimizer()
    top.driver.options['optimizer'] = 'SLSQP'

    top.driver.add_desvar('p1.x', lower=-50, upper=50)
    top.driver.add_desvar('p2.y', lower=-50, upper=50)
    top.driver.add_objective('p.f_xy')
    top.driver.add_constraint('con.c', lower=15.0)

    top.setup()
    top.run()

    print('\n')
    print('Minimum of %f found at (%f, %f)' % (top['p.f_xy'], top['p.x'], top['p.y']))

I run the script and I get the following:

##############################################
Setup: Checking root problem for potential issues...

No recorders have been specified, so no data will be saved.

Setup: Check of root problem complete.
##############################################

Traceback (most recent call last):
  File "paraboloid.py", line 65, in <module>
    top.run()
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1151, in run
    self.driver.run(self)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 211, in run
    options=self.opt_settings)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/_minimize.py", line 458, in minimize
    constraints, callback=callback, **options)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/slsqp.py", line 390, in _minimize_slsqp
    g = append(fprime(x),0.0)
  File "/home/sim/.local/lib/python2.7/site-packages/scipy/optimize/optimize.py", line 292, in function_wrapper
    return function(*(wrapper_args + args))
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/drivers/scipy_optimizer.py", line 334, in _gradfunc
    return_format='array')
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/driver.py", line 834, in calc_gradient
    sparsity=sparsity, inactives=inactives)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1310, in calc_gradient
    inactives=inactives)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/problem.py", line 1561, in _calc_gradient_ln_solver
    root._sys_linearize(root.params, unknowns, root.resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
    self._jacobian_cache = linearize(params, unknowns, resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/group.py", line 836, in linearize
    sub._sys_linearize(sub.params, sub.unknowns, sub.resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/core/system.py", line 947, in _sys_linearize
    self._jacobian_cache = linearize(params, unknowns, resids)
  File "/home/sim/.local/lib/python2.7/site-packages/openmdao/components/exec_comp.py", line 273, in linearize
    J[(u, param)] = numpy.zeros((jval.size, psize))
AttributeError: 'float' object has no attribute 'size'

The error message appear only when I put the constraint equation.
I believe it is a silly error but, can anyone point me the right direction?
Thank you in advance of your help !


问:
How do I use third party JS modules in my Angular project?
I'm currently working on an Angular (Angular 4.2.5) project and have been able to add a few third party modules. However, in most cases, if the third party module required me to include a script (like a .js file), I had to add it to my index.html file.

For example, this is what is in my index.html for Bootstrap:

```<code><script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
</code>```

This was also the case for my CSS files but recently found that I could import them into my style.css. Here's an example of what exists in that file for bootstrap as well:

```<code>@import '~bootstrap/dist/css/bootstrap.min.css';
</code>```

Now when I look online, I see that I should be able to add the path to the script in question to my angular-cli.json file but every time I have done that, the third party component fails. Only when I add the [script] tag for that component into index.html does it work.

I've tried several online guides but none seem to work. I'm certain I'm missing some minor setting somewhere to ensure that I'm using the angular-cli.json path listed but I can't seem to find it.

Some details in the event you need it:

@angular/cli: 1.2.0

node: 6.10.0

os: win32 x64

@angular/animations: 4.2.5

@angular/common: 4.2.5

@angular/compiler: 4.2.5

@angular/core: 4.2.5

@angular/forms: 4.2.5

@angular/http: 4.2.5

@angular/material: 2.0.0-beta.7

@angular/platform-browser: 4.2.5

@angular/platform-browser-dynamic: 4.2.5

@angular/router: 4.2.5

@angular/compiler-cli: 4.2.5

[Edit 07/08/2017]
To be clear, I do have the following in my angular-cli.json but it still doesn't work unless I have it included in my index.html.

```<code>"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "ang2-crm",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/bootstrap/dist/bootstrap.min.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],
</code>```

答:
You can either import them via styles.css or index.html using a link.
Additionally, you can import scripts in your angular-cli.json under scripts: []

Body:
I'm currently working on an Angular (Angular 4.2.5) project and have been able to add a few third party modules. However, in most cases, if the third party module required me to include a script (like a .js file), I had to add it to my index.html file.

For example, this is what is in my index.html for Bootstrap:

This was also the case for my CSS files but recently found that I could import them into my style.css. Here's an example of what exists in that file for bootstrap as well:

@import '~bootstrap/dist/css/bootstrap.min.css';

Now when I look online, I see that I should be able to add the path to the script in question to my angular-cli.json file but every time I have done that, the third party component fails. Only when I add the [script] tag for that component into index.html does it work.

I've tried several online guides but none seem to work. I'm certain I'm missing some minor setting somewhere to ensure that I'm using the angular-cli.json path listed but I can't seem to find it.

Some details in the event you need it:

@angular/cli: 1.2.0

node: 6.10.0

os: win32 x64

@angular/animations: 4.2.5

@angular/common: 4.2.5

@angular/compiler: 4.2.5

@angular/core: 4.2.5

@angular/forms: 4.2.5

@angular/http: 4.2.5

@angular/material: 2.0.0-beta.7

@angular/platform-browser: 4.2.5

@angular/platform-browser-dynamic: 4.2.5

@angular/router: 4.2.5

@angular/compiler-cli: 4.2.5

[Edit 07/08/2017]
To be clear, I do have the following in my angular-cli.json but it still doesn't work unless I have it included in my index.html.

"apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
      "index": "index.html",
      "main": "main.ts",
      "polyfills": "polyfills.ts",
      "test": "test.ts",
      "tsconfig": "tsconfig.json",
      "prefix": "ang2-crm",
      "styles": [
        "../node_modules/bootstrap/dist/css/bootstrap.css",
        "../node_modules/font-awesome/css/font-awesome.css",
        "styles.css"
      ],
      "scripts": [
        "../node_modules/bootstrap/dist/bootstrap.min.js"
      ],
      "environments": {
        "source": "environments/environment.ts",
        "dev": "environments/environment.ts",
        "prod": "environments/environment.prod.ts"
      }
    }
  ],


问:
jQuery: Get value of url in load() function
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

```<code><a onclick="$('#myDiv').load('/?__=634285190817664832&sort=Id&sortdir=ASC&page=1 #myDiv');" href="#">1</a>
</code>```

How can I get the value of the 'url' parameter?

答:
Try this:

```<code><a href="http://google.de" onclick="alert(this.href);">Link</a>
</code>```

Or did you mean this?

```<code>$(function() {
    var a = $('#link').attr('onclick');
    var l = (a+"").split("'");
    alert(l[3]);
});
</code>```

You can also replace the "$" object (Beware! This is solution is working in chome, but I did not do too much testing...)

```<code>$(function() {
    var a = $('#link').attr('onclick');
    var temp = $;

    // Override jQuery
    $ = function (t) {
        var s = new Object;
        s.load = function(url) { alert(url); };
        return s
    }
    a();

    // ...and back again
    $ = temp;

    // Is jQuery still working?
    alert($('#link').text());
});
</code>```

Body:
I'm using a library which has already defined an onclick event handler on a hyperlink eg:

1

How can I get the value of the 'url' parameter?

Body:
Try this:

<a href="http://google.de" onclick="alert(this.href);">Link</a>

Or did you mean this?

$(function() {
    var a = $('#link').attr('onclick');
    var l = (a+"").split("'");
    alert(l[3]);
});

You can also replace the "$" object (Beware! This is solution is working in chome, but I did not do too much testing...)

$(function() {
    var a = $('#link').attr('onclick');
    var temp = $;

    // Override jQuery
    $ = function (t) {
        var s = new Object;
        s.load = function(url) { alert(url); };
        return s
    }
    a();

    // ...and back again
    $ = temp;

    // Is jQuery still working?
    alert($('#link').text());
});


问:
Target double quotes using regular expressions in Swift
I have been trying to extract a piece of text inside an string using regular expressions in Swift. The text I want to extract is inside double quotes so I'm trying to target those double quotes and get the piece of text inside.

This is the RegExp that I'm using: (?<=")(?:\\.|[^"\\])*(?=")

It work pretty well with any kind of text and it could be even simpler since I'm looking for anything that could be inside those double quotes.

When I try to use this RegExp with Swift I have to scape the double quotes in it, but for some reason the RegExp doesn't work with escaped double quotes e.g. (?<=\")(?:\\.|[^\"\\])*(?=\").

Even if I try some as simple as this \" the RegExp doesn't match any double quote in the string.

Code Example

```<code>func extractText(sentence: String?) -> String {
    let pattern = "(?<=\")(?:\\.|[^\"\\])*(?=\")"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "Text: \(source[range])"
    }

    return ""
}

extractText("Hello \"this is\" a test") -> "this is"
</code>```

To have in mind:

All these RegExps must be inside double quotes to create the string literal that is going to be used as a pattern.

I'm using the String's range method with the .regularExpression option to match the content.

I'm using Swift 4 with an Xcode 9 Playground

How can I scape double quotes in Swift to successfully match these in a string?

Solution

Thanks to @Atlas_Gondal and @vadian I noticed the problem "in part" is not the RegExp but the string I'm getting which is using a different type of double quotes “ ... ” so I have to change my pattern to something like this "(?<=“).*(?=”)" in order to use it.

The resulted code looks like this:

```<code>func extractText(sentence: String?) -> String {
    let pattern = "(?<=“).*(?=”)"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "\(source[range])"
    }

    return ""
}
</code>```

答:
try this code:

```<code>extension String {
func capturedGroups(withRegex pattern: String) -> [String] {
    var results = [String]()

    var regex: NSRegularExpression
    do {
        regex = try NSRegularExpression(pattern: pattern, options: [])
    } catch {
        return results
    }

    let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.characters.count))

    guard let match = matches.first else { return results }

    let lastRangeIndex = match.numberOfRanges - 1
    guard lastRangeIndex >= 1 else { return results }

    for i in 1...lastRangeIndex {
        let capturedGroupIndex = match.rangeAt(i)
        let matchedString = (self as NSString).substring(with: capturedGroupIndex)
        results.append(matchedString)
    }

    return results
}
}
</code>```

Use extension like this:

```<code>print("This is \"My String \"".capturedGroups(withRegex: "\"(.*)\""))
</code>```

Sample Screenshot

Body:
I have been trying to extract a piece of text inside an string using regular expressions in Swift. The text I want to extract is inside double quotes so I'm trying to target those double quotes and get the piece of text inside.

This is the RegExp that I'm using: (?<=")(?:\\.|[^"\\])*(?=")

It work pretty well with any kind of text and it could be even simpler since I'm looking for anything that could be inside those double quotes.

When I try to use this RegExp with Swift I have to scape the double quotes in it, but for some reason the RegExp doesn't work with escaped double quotes e.g. (?<=\")(?:\\.|[^\"\\])*(?=\").

Even if I try some as simple as this \" the RegExp doesn't match any double quote in the string.

Code Example

func extractText(sentence: String?) -> String {
    let pattern = "(?<=\")(?:\\.|[^\"\\])*(?=\")"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "Text: \(source[range])"
    }

    return ""
}

extractText("Hello \"this is\" a test") -> "this is"

To have in mind:

All these RegExps must be inside double quotes to create the string literal that is going to be used as a pattern.

I'm using the String's range method with the .regularExpression option to match the content.

I'm using Swift 4 with an Xcode 9 Playground

How can I scape double quotes in Swift to successfully match these in a string?

Solution

Thanks to @Atlas_Gondal and @vadian I noticed the problem "in part" is not the RegExp but the string I'm getting which is using a different type of double quotes “ ... ” so I have to change my pattern to something like this "(?<=“).*(?=”)" in order to use it.

The resulted code looks like this:

func extractText(sentence: String?) -> String {
    let pattern = "(?<=“).*(?=”)"
    let source = sentence!

    if let range = source.range(of: pattern, options: .regularExpression) {
        return "\(source[range])"
    }

    return ""
}

Body:
try this code:

extension String {
func capturedGroups(withRegex pattern: String) -> [String] {
    var results = [String]()

    var regex: NSRegularExpression
    do {
        regex = try NSRegularExpression(pattern: pattern, options: [])
    } catch {
        return results
    }

    let matches = regex.matches(in: self, options: [], range: NSRange(location:0, length: self.characters.count))

    guard let match = matches.first else { return results }

    let lastRangeIndex = match.numberOfRanges - 1
    guard lastRangeIndex >= 1 else { return results }

    for i in 1...lastRangeIndex {
        let capturedGroupIndex = match.rangeAt(i)
        let matchedString = (self as NSString).substring(with: capturedGroupIndex)
        results.append(matchedString)
    }

    return results
}
}

Use extension like this:

print("This is \"My String \"".capturedGroups(withRegex: "\"(.*)\""))

Sample Screenshot


问:
WooCommerce 'woocommerce_payment_complete' not running on PayPal Sandbox payments
I am creating a custom system for a client. He already had Wordpress with WooCommerce setup for selling his products. I know that it actually works though. His sales, shipping, tracking, all of it works fine.

What I am trying to do, is capture every valid, successful sale and pass the data to a 3rd party API (mine created on Yii2 framework). My system needs to be "told" of every completed sale. I don't care about pending, only completed.

After finding other SO threads regarding this, I used the woocommerce_payment_complete action hook. Looks legit :)

However, when I use it, it only works on free checkouts (when paypal is bypassed due to 100% off coupon). It sends the data to my 3rd party API just fine. I then tested with a PayPal Sandbox transaction. Both with a full charge, and a 99% off coupon (to not blow through sandbox funds during testing). When PayPal is being used, it all looks good from the user end (return to merchant, successful receipt page), but no data is passed to my 3rd party API. Weird, because on free purchases (100% off coupon bypassing paypal) it works perfect.

Maybe this action hook doesn't work right. Maybe WooCommerce has a new one now, and I am using an old one? Which action hook should I use?

Maybe this action hook doesn't work right when WooCommerce is using PayPal sandbox? I haven't tested a real transaction with real money yet, that is the point of sandbox, to test with lol! For all I know, it could work during a live test.

Maybe this action hook doesn't work with PayPal?

Hopefully someone with more Wordpress and WooCommerce experience can help me narrow this down.

Here are the guts of my custom plugin to capture the action hook. My custom plugin just has a simple 1 option page to enter the API url so it can be easily changed from the WP admin dashboard (truncated for SO).

```<code><?php

if ( ! defined( 'ABSPATH' ) ) {
    die('Access Denied!');
}

define('WCO_ROOT_DIR', __DIR__);

function init()
{
    add_action( 'woocommerce_payment_complete', 'wco_payment_complete' );
}

function wco_payment_complete( $order_id )
{
    $order = wc_get_order( $order_id );
    $billingEmail = $order->billing_email;
    $products = $order->get_items();

    $items = [];
    foreach($products as $prod){
        $items[$prod['product_id']] = $prod['name'];
    }

    // gets the API url from database
    $url = get_option('wco_api_url');

    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array( 'billingemail' => $billingEmail, 'items' => $items ),
        'cookies' => array()
        )
    );

    if ( is_wp_error( $response ) )
    {
        $error_message = $response->get_error_message();
        file_put_contents(ABSPATH . '/wco-orders.log', '[WooCompletedOrders] Error: ' . $error_message, FILE_APPEND | LOCK_EX);
    } else {
        $logData = '--------------------' . PHP_EOL;
        $logData .= '[WooCompletedOrders] Success: Posted data to API: ' . PHP_EOL;
        $logData .= print_r($order, true);
        $logData .= '--------------------' . PHP_EOL;

        file_put_contents(ABSPATH . '/wco-orders.log', $logData, FILE_APPEND | LOCK_EX);
    }

}

init();
</code>```

答:
I got it!

The issue was that I didn't update the Advanced options: Receiver email address under WooCommerce -> Settings -> Checkout (tab) -> PayPal (sub-link). This should also match right above it, for your PayPal email address. Remember, this is sandbox, so it should have -facilitator at the end of your email, before the @. I actually created -seller and -buyer to make things easier to remember. Also, ensure you have the sandbox options checked. Before making a purchase, ensure the paypal url is sandbox.paypal.com, else you will spend real money lol.

If you click the order number (under the orders list) and look at the notes on the right hand side, it was saying the email address didn't match the one for the IPN. So once I did the above, and both emails matched (my PP sandbox seller emails), boom, they worked :) It actually came in under yellow "processing", then refreshed the page, and it was green "completed". So it takes a few seconds for PP to send the IPN. Give it 30 seconds, refresh your orders list, and it should show completed.

After that was ironed out, the woocommerce_payment_complete hook was triggered, and my 3rd party API logged the data!

How to getting WooCommerce PayPal Sandbox to work.

I had issues using Google Chrome with the Developers and Sandbox sections of PayPal. I remember dealing with them a long time ago, and had the same problems! So the dev and sandbox sections of PayPal, flat out suck. I switched to FireFox though, and things worked a LOT better!

So use FireFox, it will save you some frustrating issues. I was trying to create sandbox accounts, and they were all failing to create. Switched to FF and they worked instantly.

Create new sandbox accounts (from within your developer.paypal.com account). It will use your real email, only append -something to it. So I created myemail-seller@gmail.com and myemail-buyer@gmail.com. Then delete, or just don't use, the pre-created ones, like facilitator. The -seller and -buyer just make more sense and are easier to remember and type...

When creating a buyer account, give yourself a lot of money, like 99999. You can't edit the funds later! So it will save you from having to create a new buyer test account.

Ensure WooCommerce is in Sandbox mode.

Ensure paypal emails are using the sandbox email (you-seller@somewhere.com), whichever your using as your seller sandbox account, it must be the same on the PayPal settings page. It will ensure the IPN matches the seller accounts email, and fail if not. When woo thinks it's a fake/fraud attempt, it marks it "on hold".

So if your orders are "On Hold", then double check your Woo PayPal settings, specifically the email addresses your using.

IPN URL: Login at sandbox.paypal.com to your sellers sandbox account (you-seller@somewhere.com). Go to Profile > My Selling Tools, Then click the link for Instant payment notifications.

Enter this URL, but replace the placeholder with your own domain and path:

http://[YOURSITE.COM]?wc-api=WC_Gateway_Paypal

So if your wordpress is joesblog.com it would be http://joesblog.com?wc-api=WC_Gateway_Paypal

In this instance, I have wordpress on a dev sub-domain AND within a blog folder. So if that is you, then here is an example for that IPN URL:

http://dev.mysite.com/blog/?wc-api=WC_Gateway_Paypal

I hope this helps someone :) Good Luck!

Body:
I am creating a custom system for a client. He already had Wordpress with WooCommerce setup for selling his products. I know that it actually works though. His sales, shipping, tracking, all of it works fine.

What I am trying to do, is capture every valid, successful sale and pass the data to a 3rd party API (mine created on Yii2 framework). My system needs to be "told" of every completed sale. I don't care about pending, only completed.

After finding other SO threads regarding this, I used the woocommerce_payment_complete action hook. Looks legit :)

However, when I use it, it only works on free checkouts (when paypal is bypassed due to 100% off coupon). It sends the data to my 3rd party API just fine. I then tested with a PayPal Sandbox transaction. Both with a full charge, and a 99% off coupon (to not blow through sandbox funds during testing). When PayPal is being used, it all looks good from the user end (return to merchant, successful receipt page), but no data is passed to my 3rd party API. Weird, because on free purchases (100% off coupon bypassing paypal) it works perfect.

Maybe this action hook doesn't work right. Maybe WooCommerce has a new one now, and I am using an old one? Which action hook should I use?

Maybe this action hook doesn't work right when WooCommerce is using PayPal sandbox? I haven't tested a real transaction with real money yet, that is the point of sandbox, to test with lol! For all I know, it could work during a live test.

Maybe this action hook doesn't work with PayPal?

Hopefully someone with more Wordpress and WooCommerce experience can help me narrow this down.

Here are the guts of my custom plugin to capture the action hook. My custom plugin just has a simple 1 option page to enter the API url so it can be easily changed from the WP admin dashboard (truncated for SO).

<?php

if ( ! defined( 'ABSPATH' ) ) {
    die('Access Denied!');
}

define('WCO_ROOT_DIR', __DIR__);

function init()
{
    add_action( 'woocommerce_payment_complete', 'wco_payment_complete' );
}

function wco_payment_complete( $order_id )
{
    $order = wc_get_order( $order_id );
    $billingEmail = $order->billing_email;
    $products = $order->get_items();

    $items = [];
    foreach($products as $prod){
        $items[$prod['product_id']] = $prod['name'];
    }

    // gets the API url from database
    $url = get_option('wco_api_url');

    $response = wp_remote_post( $url, array(
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 5,
        'httpversion' => '1.0',
        'blocking' => true,
        'headers' => array(),
        'body' => array( 'billingemail' => $billingEmail, 'items' => $items ),
        'cookies' => array()
        )
    );

    if ( is_wp_error( $response ) )
    {
        $error_message = $response->get_error_message();
        file_put_contents(ABSPATH . '/wco-orders.log', '[WooCompletedOrders] Error: ' . $error_message, FILE_APPEND | LOCK_EX);
    } else {
        $logData = '--------------------' . PHP_EOL;
        $logData .= '[WooCompletedOrders] Success: Posted data to API: ' . PHP_EOL;
        $logData .= print_r($order, true);
        $logData .= '--------------------' . PHP_EOL;

        file_put_contents(ABSPATH . '/wco-orders.log', $logData, FILE_APPEND | LOCK_EX);
    }

}

init();


问:
c3.js - How can I set the y lines value to the first value from url (json data)
How can I set the y lines value to the first value from URL? (JSON data)

```<code>var chartDisplay = c3.generate({
    bindto: '.chart',
    data: {
        url: '/stats',
        mimeType: 'json',
    },
    grid: {
        y: {
            lines: [ {
                value: data1  <---- this is what I cant figure out
                }
            ]
        }
    }
});
</code>```

The json data looks like this:

```<code>{
  "data1": 3000,
  "data2": [
    3000,
    3300.0,
    3410.0,
    4520.0,
  ]
}
</code>```

答:
try adding this to your chart declaration,

```<code>    onrendered: function () {
        this.api.ygrids([
          {value: this.data.targets[0].values[0].value, text:'data 1 value'},
        ]);
    },
</code>```

this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry

http://jsfiddle.net/y7axwubf/1/

Body:
How can I set the y lines value to the first value from URL? (JSON data)

var chartDisplay = c3.generate({
    bindto: '.chart',
    data: {
        url: '/stats',
        mimeType: 'json',
    },
    grid: {
        y: {
            lines: [ {
                value: data1  <---- this is what I cant figure out
                }
            ]
        }
    }
});

The json data looks like this:

{
  "data1": 3000,
  "data2": [
    3000,
    3300.0,
    3410.0,
    4520.0,
  ]
}

Body:
try adding this to your chart declaration,

    onrendered: function () {
        this.api.ygrids([
          {value: this.data.targets[0].values[0].value, text:'data 1 value'},
        ]);
    },

this.api is basically the same as the 'chart' variable, and this.data is a pointer to the loaded dataset. targets[0] will be the first series loaded (data1) and values[0].value will be the value of the first entry

http://jsfiddle.net/y7axwubf/1/


问:
How to retrieve PHAsset from UIImagePickerController
I'm trying to retrieve a PHAsset however PHAsset.fetchAssets(withALAssetURLs:options:) is deprecated from iOS 8 so how can I properly retrieve a PHAsset?</p>

答:
I am not sure what you want.

Are you trying to target iOS 8?

This is how I fetch photos and it works in iOS (8.0 and later), macOS (10.11 and later), tvOS (10.0 and later).
Code is commented where it may be confusing

The first functions sets the options to fetch the photos

The second function will actually fetch them

```<code> //import the Photos framework
 import Photos
 //in these arrays I store my images and assets
 var images = [UIImage]()
 var assets = [PHAsset]()

 fileprivate func setPhotoOptions() -> PHFetchOptions{
        let fetchOptions = PHFetchOptions()
        fetchOptions.fetchLimit = 15
        let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
        fetchOptions.sortDescriptors = [sortDescriptor]
        return fetchOptions
    }

fileprivate func fetchPhotos() {
let allPhotos = PHAsset.fetchAssets(with: .image, options: setPhotoOptions())

DispatchQueue.global(qos: .background).async {

    allPhotos.enumerateObjects({ (asset, count, stop) in
        let imageManager = PHImageManager.default()
        let targetSize = CGSize(width: 200, height: 200)
        let options = PHImageRequestOptions()
        options.isSynchronous = true
        imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) in

            if let image = image {
                self.images.append(image)
                self.assets.append(asset)

            }

            if count == allPhotos.count - 1 {
                DispatchQueue.main.async {
                    //basically, here you can do what you want
                    //(after you finish retrieving your assets)
                    //I am reloading my collection view
                    self.collectionView?.reloadData()
                }
            }

        })

    })

}
</code>```

}

Edit based on OP's clarification

You need to set the delegate UIImagePickerControllerDelegate

then implement the following function

```<code>func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
</code>```

within said method, get the image like this:

```<code>var image : UIImage = info[UIImagePickerControllerEditedImage] as! UIImage
</code>```

Body:
I am not sure what you want.

Are you trying to target iOS 8?

This is how I fetch photos and it works in iOS (8.0 and later), macOS (10.11 and later), tvOS (10.0 and later).
Code is commented where it may be confusing

The first functions sets the options to fetch the photos

The second function will actually fetch them

 //import the Photos framework
 import Photos
 //in these arrays I store my images and assets
 var images = [UIImage]()
 var assets = [PHAsset]()

 fileprivate func setPhotoOptions() -> PHFetchOptions{
        let fetchOptions = PHFetchOptions()
        fetchOptions.fetchLimit = 15
        let sortDescriptor = NSSortDescriptor(key: "creationDate", ascending: false)
        fetchOptions.sortDescriptors = [sortDescriptor]
        return fetchOptions
    }

fileprivate func fetchPhotos() {
let allPhotos = PHAsset.fetchAssets(with: .image, options: setPhotoOptions())

DispatchQueue.global(qos: .background).async {

    allPhotos.enumerateObjects({ (asset, count, stop) in
        let imageManager = PHImageManager.default()
        let targetSize = CGSize(width: 200, height: 200)
        let options = PHImageRequestOptions()
        options.isSynchronous = true
        imageManager.requestImage(for: asset, targetSize: targetSize, contentMode: .aspectFit, options: options, resultHandler: { (image, info) in

            if let image = image {
                self.images.append(image)
                self.assets.append(asset)

            }

            if count == allPhotos.count - 1 {
                DispatchQueue.main.async {
                    //basically, here you can do what you want
                    //(after you finish retrieving your assets)
                    //I am reloading my collection view
                    self.collectionView?.reloadData()
                }
            }

        })

    })

}

}

Edit based on OP's clarification

You need to set the delegate UIImagePickerControllerDelegate

then implement the following function

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {

within said method, get the image like this:

var image : UIImage = info[UIImagePickerControllerEditedImage] as! UIImage


问:
Module build failed: SyntaxError: Unexpected token regarding quotation marks
Why is it giving this error when i surround the key with quotation marks?:</p>

```<code>data[0].push({ "col" + (i+1): results.data[i].id});
</code>```

答:
Try using brackets (computed property name from ES6):

```<code>data[0].push({ ["col" + (i+1)]: results.data[i].id});
</code>```

EDIT: If you are able to use ES6, you can also use template literal, as suggested by Ismael:

```<code>data[0].push({ [`col${i+1}`]: results.data[i].id});
</code>```

Body:
Why is it giving this error when i surround the key with quotation marks?:

data[0].push({ "col" + (i+1): results.data[i].id});

Body:
Try using brackets (computed property name from ES6):

data[0].push({ ["col" + (i+1)]: results.data[i].id});

EDIT: If you are able to use ES6, you can also use template literal, as suggested by Ismael:

data[0].push({ [`col${i+1}`]: results.data[i].id});


问:
Is there a way to put columns of a table in divs using DataTable?
So what I'm trying to do is make it so that the user can choose which columns of a table to display after it has already been generated. I already have functionality that does this, after the user changes their options it destroys the current table and then reinitializes it with different visibility settings for certain columns. While this works, it's sorta slow and doesn't look as pretty as say, the columns just disappearing. I think if I put the columns in uniquely id'd divs and then edited their css to say display: none; using jquery when the user deselects them it would work quicker and more attractively, but I haven't been able to find a way to put the columns in divs.

答:
Answering my own question because I managed to find a function called column().visible that can target columns by index and change their visibility. It works perfectly, and I wasn't able to implement the solutions that others posted. </p>

<p>Also for anyone that comes in later to figure out if you can put the columns in divs, as far as I can tell you cannot, but you might not need to for whatever it is you're doing. </p>

Body:
Answering my own question because I managed to find a function called column().visible that can target columns by index and change their visibility. It works perfectly, and I wasn't able to implement the solutions that others posted.

Also for anyone that comes in later to figure out if you can put the columns in divs, as far as I can tell you cannot, but you might not need to for whatever it is you're doing.


问:
Android Studio: Boolean function crashes my app
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

```<code>    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }
</code>```

activity_main.xml

```<code>    <?xml version="1.0" encoding="utf-8"?>
  <android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.leuchtstein.flashlight.MainActivity">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />
</code>```

Well, thanks in advance.

答:
Don't call

```<code>TextView text = (TextView) findViewById(R.id.textView)   ;
</code>```

in initialisation, rather call it in onCreate() method.

This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.

Put

```<code>text = (TextView) findViewById(R.id.textView);
</code>```

in onCreate() and put

```<code>TextView text;
</code>```

in initialisation instead.

Body:
Im trying to learn how to use android studio, im not unfamiliar with java though.
I tried making a boolean and if it is true, a text changes to "ON", otherwise it will change to "OFF"
My app just crashes when im using USB-Debugging though.

Code:
MainActivity.java

    package com.leuchtstein.flashlight;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
public boolean stat = false;
TextView text = (TextView) findViewById(R.id.textView)   ;

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

 public void triggerlight(View view) {

 if (stat == false) {

    text.setText("ON");
    stat = true;

} else {

    text.setText("OFF");
    stat = false;

  }

  }

 }

activity_main.xml

    <?xml version="1.0" encoding="utf-8"?>
  <android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context="com.leuchtstein.flashlight.MainActivity">

<TextView
    android:id="@+id/textView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="16dp"
    android:text="@string/desc_textview"
          android:textAppearance="@android:style/TextAppearance.DeviceDefault.Large"
    app:layout_constraintHorizontal_bias="0.95"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<Button
    android:id="@+id/button"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="triggerlight"
    android:text="Turn on/off"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/textView"
    app:layout_constraintVertical_bias="0.387" />

Well, thanks in advance.

Body:
Don't call

TextView text = (TextView) findViewById(R.id.textView)   ;

in initialisation, rather call it in onCreate() method.

This is because Android first initializes the script, and calls onCreate only when setContentView() has been called and it has set up the button, &c. Thus findViewById(int id) can't find anything yet.

Put

text = (TextView) findViewById(R.id.textView);

in onCreate() and put

TextView text;

in initialisation instead.


问:
Update table column using sum()
I am trying to do two thing with my SQL code. I want it to copy data from another column (hours) , that’s located in another table (works- table), and place it into a new column (numHours) in a different table (Employee- table). However, I want it to use the sum of the hours worked for each employee id (eid) and then place that sum into the new column.

This is what I wrote, but two things are wrong. When I execute just the select statement every employee id has the same number of hours worked. When I run the whole statement I get this error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

```<code>UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);
</code>```

These are my tables

```<code>CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,

CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);

CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,

CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);

CREATE TABLE Works(
eid INT,
did INT,
hours INT,

CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did  FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);
</code>```

How would I properly code this?

答:
Use JOIN and UPDATE:

```<code>UPDATE E
SET E.numHours=H.totalHours
FROM Employee E JOIN
    (Select sum(hours) AS totalHours,eid
     From works
     Group by eid)H on H.eid=E.eid
WHERE E.numHours IS NULL
</code>```

Explanation:

Inner query will select Total hours for each employee. Then use it to update Employee table.

Title: Update table column using sum()

Body:
I am trying to do two thing with my SQL code. I want it to copy data from another column (hours) , that’s located in another table (works- table), and place it into a new column (numHours) in a different table (Employee- table). However, I want it to use the sum of the hours worked for each employee id (eid) and then place that sum into the new column.

This is what I wrote, but two things are wrong. When I execute just the select statement every employee id has the same number of hours worked. When I run the whole statement I get this error

Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression.
The statement has been terminated.

UPDATE Employee
SET numHours= (SELECT sum(w.hours) AS totalHours From works w, Employee e WHERE
numHours IS NULL AND e.eid = w.eid Group by w.eid);

These are my tables

CREATE TABLE Employee(
eid INT,
ename VARCHAR(30),
age INT,
salary INT,

CONSTRAINT Pk_key_eid PRIMARY KEY (eid)
);

CREATE TABLE Department(
did INT,
dname VARCHAR(30),
budget int,
managerid INT,

CONSTRAINT Validate_managerid CHECK(managerid < 1000),
CONSTRAINT Pk_key_did PRIMARY KEY (did)
);

CREATE TABLE Works(
eid INT,
did INT,
hours INT,

CONSTRAINT fk_key_eid FOREIGN KEY (eid) REFERENCES Employee (eid) ON DELETE CASCADE,
CONSTRAINT fk_key_Did  FOREIGN KEY (did) REFERENCES Department (did) ON DELETE CASCADE
);

How would I properly code this?

Body:
Use JOIN and UPDATE:

UPDATE E
SET E.numHours=H.totalHours
FROM Employee E JOIN
    (Select sum(hours) AS totalHours,eid
     From works
     Group by eid)H on H.eid=E.eid
WHERE E.numHours IS NULL

Explanation:

Inner query will select Total hours for each employee. Then use it to update Employee table.


问:
Build chromedriver for linux
I'm trying to build chromedriver from source for use in selenium for Linux.
i use this manual https://chromium.googlesource.com/chromium/src/+/master/docs/linux_build_instructions.md
but when i build without any error my chromedriver less for 2mb that if i download form google code site. and this chromedriver not work with selenium. just blank error.
Have someone any idea what wrong? Thank You</p>

答:
We'd need more information... Here is a dockerfile (largely taken from here) that worked for me. Most of the commands come from the chromium build docs.</p>

```<code>FROM ubuntu:14.04

# Install Chromium build dependencies.
RUN echo "deb http://archive.ubuntu.com/ubuntu trusty multiverse" >> /etc/apt/sources.list # && dpkg --add-architecture i386
RUN sudo apt-get update && apt-get install -qy git build-essential clang curl

# Install Chromium's depot_tools.
ENV DEPOT_TOOLS /usr/bin/depot_tools
RUN git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git $DEPOT_TOOLS
ENV PATH $PATH:$DEPOT_TOOLS
RUN echo -e "\n# Add Chromium's depot_tools to the PATH." >> .bashrc
RUN echo "export PATH=\"\$PATH:$DEPOT_TOOLS\"" >> .bashrc

RUN git config --global https.postBuffer 1048576000

# Download Chromium sources.
RUN fetch --nohooks --no-history chromium

WORKDIR /

RUN gclient runhooks

WORKDIR src

RUN build/install-build-deps.sh --no-prompt

RUN gn gen out/Release --args="is_debug=false"
RUN ninja -C out/Release chromedriver

RUN cp out/Release/chromedriver /usr/bin/chromedriver

WORKDIR /
</code>```

Title: Build chromedriver for linux

Body:
We'd need more information... Here is a dockerfile (largely taken from here) that worked for me. Most of the commands come from the chromium build docs.

FROM ubuntu:14.04

# Install Chromium build dependencies.
RUN echo "deb http://archive.ubuntu.com/ubuntu trusty multiverse" >> /etc/apt/sources.list # && dpkg --add-architecture i386
RUN sudo apt-get update && apt-get install -qy git build-essential clang curl

# Install Chromium's depot_tools.
ENV DEPOT_TOOLS /usr/bin/depot_tools
RUN git clone https://chromium.googlesource.com/chromium/tools/depot_tools.git $DEPOT_TOOLS
ENV PATH $PATH:$DEPOT_TOOLS
RUN echo -e "\n# Add Chromium's depot_tools to the PATH." >> .bashrc
RUN echo "export PATH=\"\$PATH:$DEPOT_TOOLS\"" >> .bashrc

RUN git config --global https.postBuffer 1048576000

# Download Chromium sources.
RUN fetch --nohooks --no-history chromium

WORKDIR /

RUN gclient runhooks

WORKDIR src

RUN build/install-build-deps.sh --no-prompt

RUN gn gen out/Release --args="is_debug=false"
RUN ninja -C out/Release chromedriver

RUN cp out/Release/chromedriver /usr/bin/chromedriver

WORKDIR /


问:
Structure for an array of bits in C
It has come to my attention that there is no builtin structure for a single bit in C. There is (unsigned) char and int, which are 8 bits (one byte), and long which is 64+ bits, and so on (uint64_t, bool...)

I came across this while coding up a huffman tree, and the encodings for certain characters were not necessarily exactly 8 bits long (like 00101), so there was no efficient way to store the encodings. I had to find makeshift solutions such as strings or boolean arrays, but this takes far more memory.

But anyways, my question is more general: is there a good way to store an array of bits, or some sort of user-defined struct? I scoured the web for one but the smallest structure seems to be 8 bits (one byte). I tried things such as int a : 1 but it didn't work. I read about bit fields but they do not simply achieve exactly what I want to do. I know questions have already been asked about this in C++ and if there is a struct for a single bit, but mostly I want to know specifically what would be the most memory-efficient way to store an encoding such as 00101 in C.

答:
If you really want the most memory efficiency, you can encode the Huffman tree itself as a stream of bits. See, for example:

https://www.siggraph.org/education/materials/HyperGraph/video/mpeg/mpegfaq/huffman_tutorial.html

Then just encode those bits as an array of bytes, with a possible waste of 7 bits.

But that would be a horrible idea. For the structure in memory to be useful, it must be easy to access. You can still do that very efficiently. Let's say you want to encode up to 12-bit codes. Use a 16-bit integer and bitfields:

```<code>struct huffcode {
    uint16_t length: 4,
             value: 12;
}
</code>```

C will store this as a single 16-bit value, and allow you to access the length and value fields separately. The complete Huffman node would also contain the input code value, and tree pointers (which, if you want further compactness, can be integer indices into an array).

Title: Structure for an array of bits in C

Body:
If you really want the most memory efficiency, you can encode the Huffman tree itself as a stream of bits. See, for example:

https://www.siggraph.org/education/materials/HyperGraph/video/mpeg/mpegfaq/huffman_tutorial.html

Then just encode those bits as an array of bytes, with a possible waste of 7 bits.

But that would be a horrible idea. For the structure in memory to be useful, it must be easy to access. You can still do that very efficiently. Let's say you want to encode up to 12-bit codes. Use a 16-bit integer and bitfields:

struct huffcode {
    uint16_t length: 4,
             value: 12;
}

C will store this as a single 16-bit value, and allow you to access the length and value fields separately. The complete Huffman node would also contain the input code value, and tree pointers (which, if you want further compactness, can be integer indices into an array).


问:
How can I pass a dynamic filter to the List component with Admin On Rest?
I am using Show to show a student page. On the student page, I want to show a list of many courses and the list must be paginated.

```<code>    export const StudentShow = (props) => (
        <Show title='Student' {...props}>
            <SimpleShowLayout>
                // correctly displays the student ID
                <TextField label='id' source='id' />
                <ReferenceManyField
                    label='Courses'
                    target='course'
                    id='student.id'
                    reference='courses'>
                    // how can I properly pass the student ID to List?
                    <List {...props} filter={{ student: student.id }}>
                        <Datagrid>
                            <TextField source='code' />
                        </Datagrid>
                    </List>
                </ReferenceManyField>
            </SimpleShowLayout>
        </Show>
    );
</code>```

The ReferenceManyField correctly makes an API call to /courses/?student=<studentId>, however List just makes a call to /courses/. I am not able to pass down the student ID to the List component.

How do I pass student ID to the List component?

答:
I was able to access the parent record by creating another component.</p>

```<code>const Courses = props => (
    let studentRecord = props.record;

    <div className='field'>
        <ReferenceManyField
            target='course'
            reference='courses'>
            <List {...props} filter={{ student: studentRecord.id }}>
                <Datagrid>
                    <TextField label='id' source='id' />
                </Datagrid>
            </List>
        </ReferenceManyField>
    </div>
);

export const StudentShow = (props) => (
    <Show title='Student' {...props}>
        <SimpleShowLayout>
            // correctly displays the student ID
            <TextField label='id' source='id' />
            <Courses {...props} />
        </SimpleShowLayout>
    </Show>
);
</code>```

Body:
I am using Show to show a student page. On the student page, I want to show a list of many courses and the list must be paginated.

    export const StudentShow = (props) => (
        <Show title='Student' {...props}>
            <SimpleShowLayout>
                // correctly displays the student ID
                <TextField label='id' source='id' />
                <ReferenceManyField
                    label='Courses'
                    target='course'
                    id='student.id'
                    reference='courses'>
                    // how can I properly pass the student ID to List?
                    <List {...props} filter={{ student: student.id }}>
                        <Datagrid>
                            <TextField source='code' />
                        </Datagrid>
                    </List>
                </ReferenceManyField>
            </SimpleShowLayout>
        </Show>
    );

The ReferenceManyField correctly makes an API call to /courses/?student=<studentId>, however List just makes a call to /courses/. I am not able to pass down the student ID to the List component.

How do I pass student ID to the List component?

Body:
I was able to access the parent record by creating another component.

const Courses = props => (
    let studentRecord = props.record;

    <div className='field'>
        <ReferenceManyField
            target='course'
            reference='courses'>
            <List {...props} filter={{ student: studentRecord.id }}>
                <Datagrid>
                    <TextField label='id' source='id' />
                </Datagrid>
            </List>
        </ReferenceManyField>
    </div>
);

export const StudentShow = (props) => (
    <Show title='Student' {...props}>
        <SimpleShowLayout>
            // correctly displays the student ID
            <TextField label='id' source='id' />
            <Courses {...props} />
        </SimpleShowLayout>
    </Show>
);