问:
Cannot get stripe charge work with app engine Golang
So here is my problem, i have been following the github readme for app engine users in order to implement stripe into my app but the thing is that i can’t make it work as it seems that the http.DefaultTransport and http.DefaultClient are not available in App Engine.

I have seen that in the readme you show us how to initialize the Stripe client with app engine but i cannot find any charge card example so this is why i have come to this implementation.

I am used to this problem, since i have been working with app engine for a long time but for some reason i still get this akward error :

cannot use stripe.BackendConfiguration literal (type stripe.BackendConfiguration) as type stripe.Backend in assignment: stripe.BackendConfiguration does not implement stripe.Backend (Call method has pointer receiver)

Here is the code :

```<code>func setStripeChargeClient(context context.Context, key string) *charge.Client {
    c := &charge.Client{}

    var b stripe.Backend
    b = stripe.BackendConfiguration{
        stripe.APIBackend,
        "https://api.stripe.com/v1",
        urlfetch.Client(context),
    }

    c.Key = key
    c.B = b

    return c
}
</code>```

Getting the error on that b assignation …

What i can’t figure it out is why this example seems to work all around the web and does not work in my app, if you could please enlighten me on this one, i would be in your debt hahaha

and then calling it this way

stripeClient := setStripeChargeClient(context, "sk_live_key »)

答:
The error message tells you the problem. The stripe.BackendConfiguration type does not implement stripe.Backend interface.  The error message also gives the helpful hint that the missing Call method is on the pointer receiver.

The fix is to use a pointer value:

```<code>b = &stripe.BackendConfiguration{  // note the &
    stripe.APIBackend,
    "https://api.stripe.com/v1",
    urlfetch.Client(context),
}
</code>```

See the specification regarding method sets.  The method set of a value receiver does not include the pointer receiver methods.

Body:
So here is my problem, i have been following the github readme for app engine users in order to implement stripe into my app but the thing is that i can’t make it work as it seems that the http.DefaultTransport and http.DefaultClient are not available in App Engine.

I have seen that in the readme you show us how to initialize the Stripe client with app engine but i cannot find any charge card example so this is why i have come to this implementation.

I am used to this problem, since i have been working with app engine for a long time but for some reason i still get this akward error :

cannot use stripe.BackendConfiguration literal (type stripe.BackendConfiguration) as type stripe.Backend in assignment: stripe.BackendConfiguration does not implement stripe.Backend (Call method has pointer receiver)

Here is the code :

func setStripeChargeClient(context context.Context, key string) *charge.Client {
    c := &charge.Client{}

    var b stripe.Backend
    b = stripe.BackendConfiguration{
        stripe.APIBackend,
        "https://api.stripe.com/v1",
        urlfetch.Client(context),
    }

    c.Key = key
    c.B = b

    return c
}

Getting the error on that b assignation …

What i can’t figure it out is why this example seems to work all around the web and does not work in my app, if you could please enlighten me on this one, i would be in your debt hahaha

and then calling it this way

stripeClient := setStripeChargeClient(context, "sk_live_key »)

Body:
The error message tells you the problem. The stripe.BackendConfiguration type does not implement stripe.Backend interface.  The error message also gives the helpful hint that the missing Call method is on the pointer receiver.

The fix is to use a pointer value:

b = &stripe.BackendConfiguration{  // note the &
    stripe.APIBackend,
    "https://api.stripe.com/v1",
    urlfetch.Client(context),
}

See the specification regarding method sets.  The method set of a value receiver does not include the pointer receiver methods.


来源: stackexchange

问:
Can I yield to a child process and return the response in Node.js?
In short, I've run into an issue where multiple parallel GET requests to my Node.js server cause the server to get "clogged up" and hang, thus resulting in timeouts for the clients (503, service unavailable).

After a lot of performance analysis, I've realized it's a CPU issue. The specific request (we'll call it GET /foo) queries data from multiple services over HTTP, and then does a lot of computation, and returns the results to the client, like this:

Client request GET /foo

/foo controller queries data over HTTP from multiple other services`

/foo controller then does a bunch of iterations over the data to compile some output for the client

Step 3 takes around 2 seconds to complete. However, if I send 2 requests in parallel to /foo, each client will receive their response in about 4 seconds. When I run the app in a cluster using more cores, the requests run much faster, but not quite what I want.

Seems like I have several options here:

pre-compute the response (ideally would like to avoid this for now, since it will require a whole "cache invalidation" scheme), or

/foo sends the CPU-blocking computation asynchronously to another process (using Heroku, so that would be another dyno), and then I can use a websocket or something to push the results to the client (again, very complex for my situation), or

somehow yield to a child process in the request and return the results to the client

Would love to do something like option 3. Something like this:

```<code>get('/foo', function*(request) {
  // I/O, so not blocking the event loop (I think)
  let data = yield getData(request)

  // make this happen in a different process
  let response = yield doSomeHeavyProcessing(data)

  return response
})
</code>```

I've omitted a lot of implementation details above, but if it's necessary to know, I'm using Koa and Node.js 6.

Ideally, doSomeHeavyProcessing would do the CPU-intensive computation in some separate process, and when it's done, still send the results back in a "synchronous" fashion to the request client.

Been trying to wrap my head around child processes, web workers, fibers, etc., and have been doing some basic "hello worlds" with these to get them to do basically the above, but to no avail. Can post more details if necessary.

答:
You could utilize Child process with additional wrapper for convenience.

worker.js - this module will run in a separate process and will do the heavy work

```<code>const crypto = require('crypto');

function doHeavyWork(data) {
  return crypto.pbkdf2Sync(data, 'salt', 100000, 64, 'sha512');
}

process.on('message', (message) => {
  const result = doHeavyWork(message.data);
  process.send({ id: message.id, result });
});
</code>```

client.js - a convenience (but primitive) wrapper for Child process

```<code>const cp = require('child_process');

let worker;
const resolves = new Map();

module.exports = {
  init(moduleName, errorCallback) {
    worker = cp.fork(moduleName);
    worker.on('error', errorCallback);

    worker.on('message', (message) => {
      const resolve = resolves.get(message.id);
      resolves.delete(message.id);
      if (!resolve) {
        errorCallback(new Error(`Got response from worker with unknown id: ${message.id}`));
        return;
      }

      resolve(message.result);
    });

    console.log(`Service PID: ${process.pid}, Worker PID: ${worker.pid}`);
  },

  doHeavyWorkRemotly(data) {
    const id = `${Date.now()}${Math.random()}`;

    return new Promise((resolve) => {
      worker.send({ id, data });
      resolves.set(id, resolve);
    });
  }
}
</code>```

I use fork() to utilize an additional communication channel as it is stated in the docs.

Also I keep a record of all submitted to worker process requests (const resolves = new Map();) and resolve Promises (resolve(message.result);) only when the worker process returns response for the specific request (const resolve = resolves.get(message.id);).

run.js - a startup module, it utilizes co to 'execute' generators.

```<code>const co = require('co');

const client = require('./client');

function errorCallback(error) {
  console.log('Got an unexpected error!');
  console.log(error);
}

client.init('./worker.js', errorCallback);

function* run() {
  while(true) {
    yield client.doHeavyWorkRemotly('mydata');
  }
}

co(run);
</code>```

To test it simply run node run.js, it will print

Service PID: XXXX, Worker PID: XXXX

then take a look at CPU utilization, worker process will probably take around 100% of CPU while Service will be quite idle.

ContentLicense: CC BY-SA 3.0

Body:
In short, I've run into an issue where multiple parallel GET requests to my Node.js server cause the server to get "clogged up" and hang, thus resulting in timeouts for the clients (503, service unavailable).

After a lot of performance analysis, I've realized it's a CPU issue. The specific request (we'll call it GET /foo) queries data from multiple services over HTTP, and then does a lot of computation, and returns the results to the client, like this:

Client request GET /foo

/foo controller queries data over HTTP from multiple other services`

/foo controller then does a bunch of iterations over the data to compile some output for the client

Step 3 takes around 2 seconds to complete. However, if I send 2 requests in parallel to /foo, each client will receive their response in about 4 seconds. When I run the app in a cluster using more cores, the requests run much faster, but not quite what I want.

Seems like I have several options here:

pre-compute the response (ideally would like to avoid this for now, since it will require a whole "cache invalidation" scheme), or

/foo sends the CPU-blocking computation asynchronously to another process (using Heroku, so that would be another dyno), and then I can use a websocket or something to push the results to the client (again, very complex for my situation), or

somehow yield to a child process in the request and return the results to the client

Would love to do something like option 3. Something like this:

get('/foo', function*(request) {
  // I/O, so not blocking the event loop (I think)
  let data = yield getData(request)

  // make this happen in a different process
  let response = yield doSomeHeavyProcessing(data)

  return response
})

I've omitted a lot of implementation details above, but if it's necessary to know, I'm using Koa and Node.js 6.

Ideally, doSomeHeavyProcessing would do the CPU-intensive computation in some separate process, and when it's done, still send the results back in a "synchronous" fashion to the request client.

Been trying to wrap my head around child processes, web workers, fibers, etc., and have been doing some basic "hello worlds" with these to get them to do basically the above, but to no avail. Can post more details if necessary.

Body:
You could utilize Child process with additional wrapper for convenience.

worker.js - this module will run in a separate process and will do the heavy work

const crypto = require('crypto');

function doHeavyWork(data) {
  return crypto.pbkdf2Sync(data, 'salt', 100000, 64, 'sha512');
}

process.on('message', (message) => {
  const result = doHeavyWork(message.data);
  process.send({ id: message.id, result });
});

client.js - a convenience (but primitive) wrapper for Child process

const cp = require('child_process');

let worker;
const resolves = new Map();

module.exports = {
  init(moduleName, errorCallback) {
    worker = cp.fork(moduleName);
    worker.on('error', errorCallback);

    worker.on('message', (message) => {
      const resolve = resolves.get(message.id);
      resolves.delete(message.id);
      if (!resolve) {
        errorCallback(new Error(`Got response from worker with unknown id: ${message.id}`));
        return;
      }

      resolve(message.result);
    });

    console.log(`Service PID: ${process.pid}, Worker PID: ${worker.pid}`);
  },

  doHeavyWorkRemotly(data) {
    const id = `${Date.now()}${Math.random()}`;

    return new Promise((resolve) => {
      worker.send({ id, data });
      resolves.set(id, resolve);
    });
  }
}

I use fork() to utilize an additional communication channel as it is stated in the docs.

Also I keep a record of all submitted to worker process requests (const resolves = new Map();) and resolve Promises (resolve(message.result);) only when the worker process returns response for the specific request (const resolve = resolves.get(message.id);).

run.js - a startup module, it utilizes co to 'execute' generators.

const co = require('co');

const client = require('./client');

function errorCallback(error) {
  console.log('Got an unexpected error!');
  console.log(error);
}

client.init('./worker.js', errorCallback);

function* run() {
  while(true) {
    yield client.doHeavyWorkRemotly('mydata');
  }
}

co(run);

To test it simply run node run.js, it will print

Service PID: XXXX, Worker PID: XXXX

then take a look at CPU utilization, worker process will probably take around 100% of CPU while Service will be quite idle.


问:
Sass error : Invalid CSS after "typography-config" angular 4.x
I want to integrate my custom fonts for my angular 4.x project which are in assets folder. and I am using angular material. so for material I am setting custom typography in my styles.sass

Here's the code:

```<code>@import '~@angular/material/theming'

$used-fonts : 'Avenir', arial

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
)

@include mat-core($general-typography)
</code>```

The error which I got:

```<code>Invalid CSS after "...ography-config(": expected expression (e.g. 1px, bold), was "{"
</code>```

giving me an error at :

any idea?

答:
I suggest to try adding semicolons after each declaration. CSS requires a semicolon after each declaration except the last declaration in a rule (which is optional), and I think SASS follows suit.</p>

```<code>@import '~@angular/material/theming';

$used-fonts : 'Avenir', arial;

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
);

@include mat-core($general-typography);
</code>```

Body:
I want to integrate my custom fonts for my angular 4.x project which are in assets folder. and I am using angular material. so for material I am setting custom typography in my styles.sass

Here's the code:

@import '~@angular/material/theming'

$used-fonts : 'Avenir', arial

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
)

@include mat-core($general-typography)

The error which I got:

Invalid CSS after "...ography-config(": expected expression (e.g. 1px, bold), was "{"

giving me an error at :

any idea?

Body:
I suggest to try adding semicolons after each declaration. CSS requires a semicolon after each declaration except the last declaration in a rule (which is optional), and I think SASS follows suit.

@import '~@angular/material/theming';

$used-fonts : 'Avenir', arial;

$general-typography : mat-typography-config(
  $font-family: quote($used-fonts)
);

@include mat-core($general-typography);


问:
WebExtensions: Intercept special protocol links
I'd like to write a simple WebExtension that handles certain types of links. I don't want a system wide protocol handler, it should simply work for websites open in my browser.

So for instance when anything causes a magnet:// link to be opened, I'd like to intercept that so that the WebExtension handles it.

And if possible I'd like to prevent system applications from handling it while the WebExtension is enabled.

At first I thought that I could use registerProtocolHandler:

```<code>navigator.registerProtocolHandler("magnet", "*%s", "Magnet handler");
</code>```

But I don't think that this would do what I want it to...

My next idea was to use a click event on all a-elements:

```<code>document.getElementsByTagName('a').addEventListener('click', event => {
    let link = event.target.href
    if (link.startsWith('magnet://')) {
        // handle magnet link
        return false
    }
}
</code>```

But that would only work for links that were clicked on. A link that is opened using JavaScript would not be affected, so that wouldn't work either..

答:
I used a trick in an extension to do just that:
Register your protocol handler in the manifest:

```<code>  "protocol_handlers": [
    {
      "protocol": "magnet",
      "name": "Torrent Control Reloaded Magnet Handler",
      "uriTemplate": "https://torrent-control-reloaded.invalid/%s"
    }
  ]
</code>```

then handle the request as you wish:

```<code>   browser.webRequest.onBeforeRequest.addListener(
        (details) => {
            var parser = document.createElement('a');
            parser.href = details.url;
            var magnetUri = decodeURIComponent(parser.pathname).substr(1);
            // do what you want with magnetUri
            return {cancel: true}
        },
        {urls: ['https://torrent-control-reloaded.invalid/*']},
        ['blocking']
    );
</code>```

It's not nice, but it works.
You can find the extension here: https://github.com/Mika-/torrent-control/

Body:
I'd like to write a simple WebExtension that handles certain types of links. I don't want a system wide protocol handler, it should simply work for websites open in my browser.

So for instance when anything causes a magnet:// link to be opened, I'd like to intercept that so that the WebExtension handles it.

And if possible I'd like to prevent system applications from handling it while the WebExtension is enabled.

At first I thought that I could use registerProtocolHandler:

navigator.registerProtocolHandler("magnet", "*%s", "Magnet handler");

But I don't think that this would do what I want it to...

My next idea was to use a click event on all a-elements:

document.getElementsByTagName('a').addEventListener('click', event => {
    let link = event.target.href
    if (link.startsWith('magnet://')) {
        // handle magnet link
        return false
    }
}

But that would only work for links that were clicked on. A link that is opened using JavaScript would not be affected, so that wouldn't work either..

Body:
I used a trick in an extension to do just that:
Register your protocol handler in the manifest:

  "protocol_handlers": [
    {
      "protocol": "magnet",
      "name": "Torrent Control Reloaded Magnet Handler",
      "uriTemplate": "https://torrent-control-reloaded.invalid/%s"
    }
  ]

then handle the request as you wish:

   browser.webRequest.onBeforeRequest.addListener(
        (details) => {
            var parser = document.createElement('a');
            parser.href = details.url;
            var magnetUri = decodeURIComponent(parser.pathname).substr(1);
            // do what you want with magnetUri
            return {cancel: true}
        },
        {urls: ['https://torrent-control-reloaded.invalid/*']},
        ['blocking']
    );

It's not nice, but it works.
You can find the extension here: https://github.com/Mika-/torrent-control/


问:
Stuck with my query
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

```<code>select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;
</code>```

Where am I making the mistake?

Thanks in advance!

答:
use the below query</p>

```<code>select ename,sal,((select max(sal) from emp)-sal) as saldiff from emp
</code>```

Title: Stuck with my query

Body:
Would really appreciate if someone could help me with my query.

I need it to show the difference between max salary and salary of others.

select e.ename, f.sal, e.sal
from emp e , (select max(sal) as "sal" from emp) f
where 1=1 ;

Where am I making the mistake?

Thanks in advance!

Body:
use the below query

select ename,sal,((select max(sal) from emp)-sal) as saldiff from emp


问:
How to avoid time conflict or overlap for CalDAV?
I am studying CalDAV protocol.

I have some question for time conflict or overlap for CalDAV.

Let me explain by instance for some scenario.
I made an event PM1 ~ PM6 in calendar. And then I try to made another event PM2~7 in same calendar. It is time conflict or overlap.

How does CalDav server resolve this conflict? Does server make error when second event make?

I did search out RFC 6638. But I could not find solution.
Please help my question.

Thanks for reading.

答:
The functionality Kim is asking for a very common one for business calendaring systems (not have the same person booked twice etc).

I think in the CalDAV world there are two parts to this:

a) First the client is supposed to perform a freebusy query to check
  whether a user is available. And then show a conflict warning or
  whatever seems appropriate.

This is how many systems, including btw Exchange work. Siri also does this kind of conflict detection (“hey, you already have an event at the time, shall I still create the conflicting one, master?”)

b) But in a reasonable system you actually need to guarantee that
 the information isn’t outdated at PUT time. I.e. that no second
 client has scheduled the same attendee/resource.

I think in CalDAV you can accomplish that by testing the sync-token or the CTag using an If header on the PUT. I.e. let the PUT only succeed if the whole underlying collection didn’t change. And if it did (the PUT will fail with a conflict), redo the freebusy, then try again.

I don’t think that there is a reliable way to do this in CalDAV cross collections (calendars), that is, if the availability of a resource changed because it got booked in a different calendar, the targeted sync collection won’t usually change its sync tag and the PUT would run through.
The bad thing about CalDAV (w/ scheduling) is that PUTs are not idempotent anymore. Otherwise you could do the PUT, recheck whether it still has no conflicts, and if so drop it after the fact.


问:
Invalid Syntax with Print Statement
I have a line of code that is saying that there is invalid syntax in my print statement. Does anyone know about how to fix this? I've tried deleting the parentheses and have tried changing the +'s to ,'s.</p>

```<code>print(stockName[random] + ' - $' + Names[0, amod] + ' : You have ' + x + ' of this stock')
</code>```

答: If you use ' x ' with + operator it should be a string else you should use coma.</p>

Title: Invalid Syntax with Print Statement

Body:
I have a line of code that is saying that there is invalid syntax in my print statement. Does anyone know about how to fix this? I've tried deleting the parentheses and have tried changing the +'s to ,'s.

print(stockName[random] + ' - $' + Names[0, amod] + ' : You have ' + x + ' of this stock')


问:
How to make 0 in all column in a specific table where value is null using MSSQL
Let the table name is "MyTable"

My current data looks like:

Following, I need after a query on above table:

Actually I need to update all column where value is "NULL", in a single query.

答:
Update table
    Set column1 = coalesce (column1,0), ....


问:
Prevent stretching of an image while keeping dimensions
Is there a way to prevent the stretching of an image, to crop it somehow but keep the dimensions..?

img {
  width: 90px;
  height: 120px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt=""></code>```

答:
To keep the exact same dimensions of this image you should only set one of the two dimensions. The other one will automatically be calculated:

img {
  width: 90px;
  /*height: 120px;*/
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt=""></code>```

Hope I helped out.

Body:
To keep the exact same dimensions of this image you should only set one of the two dimensions. The other one will automatically be calculated:

img {
  width: 90px;
  /*height: 120px;*/
}

<img src="https://i.pinimg.com/736x/d4/c3/dc/d4c3dc946ae1e087d24def574215e266--image-search-google-search.jpg" alt="">

Hope I helped out.


问:
Global Hotkey for Firefox
Is there a way to add hotkeys (such as the media buttons) for the webbrowser?

This would need to cause a javascript event.

I except a firefox extension is required and i am ok if the solution requires greasemonkey as well (i seen growl use them both for javascript interaction. But thats javascript->pc not the other way around)

-edit- is this not possible ATM?

答:
Firefox supports something called an AppCommand event. On Windows and Linux, only 7 commands are supported: Back, Forward, Reload, Stop, Search, Bookmarks and Home.

To implement extra commands, supported would have to be added to widget/src/windows/nsWindow.cpp and widget/src/gtk2/nsWindow.cpp to generate those additional types of AppCommand event. These events could then be intercepted by an extension to perform custom actions.

On Android, a different set of events are supported: Clear, VolumeUp, VolumeDown, Menu, Search. I don't know whether these events are used by Fennec.

For completeness, OS/2 builds of Firefox support Back, Forward, Reload and Stop.

ContentLicense: CC BY-SA 2.5

Title: Global Hotkey for Firefox


问:
How can I extract the data between a tag
I am learning web scraping. I wrote the following code:

```<code>import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url= 'DON'T WANT TO SHARE'
uClient= uReq(my_url)
page_html= uClient.read()
uClient.close()

page_soup= soup(page_html, "html.parser")
contents=page_soup.findAll("data")
print (contents)
</code>```

Upon printing the contents I am getting something like this:

```<code><data>
------------------------------------
SIM: B01N2W56MD
(P)UBLISHER NAME: Monster
------------------------------------
(I)[ 0] Publisher: Monster
(I)[ 1] Title: Monster
(I)[12] Subject Keyword: nos
------------------------------------
(S)[ 0] Marketplace ID:  1
(S)[ 1] Replenishment Category:  Non Replenishable
(S)[ 5] Title type:  Main title 1
(S)[ 9] Product Group:  No operation Product Handling Group
(S)[19] Product Subcategory:  A
(S)[32] Are batteries required?:  N
------------------------------------
(K)[ 0] IDC: 030347493342
(K)[ 1] ORC: 6800532606463
------------------------------------
</data>
</code>```

How can I extract these values and print or store them, i.e., the value of SIM or Title or IDC and ORC.

答:
You can get extract these values using regular expressions

```<code>import  re

data = """
<data>
------------------------------------
SIM: B01N2W56MD
(P)UBLISHER NAME: Monster
------------------------------------
(I)[ 0] Publisher: Monster
(I)[ 1] Title: Monster
(I)[12] Subject Keyword: nos
------------------------------------
(S)[ 0] Marketplace ID:  1
(S)[ 1] Replenishment Category:  Non Replenishable
(S)[ 5] Title type:  Main title 1
(S)[ 9] Product Group:  No operation Product Handling Group
(S)[19] Product Subcategory:  A
(S)[32] Are batteries required?:  N
------------------------------------
(K)[ 0] IDC: 030347493342
(K)[ 1] ORC: 6800532606463
------------------------------------
</data>"""

sim= re.search(r'SIM:\s(.*?)\n', data).group(1)
dic= re.search(r'IDC:\s(.*?)\n', data).group(1)
title = re.search(r'Title:\s(.*?)\n', data).group(1)

print(sim)
print(dic)
print(title)
</code>```

The code above simply looks for data within "SIM" and a "\n" (newline) and saves that data in a variable. Exactl same logic applies to finding value of "DIC" and "Title".

Body:
I am learning web scraping. I wrote the following code:

import bs4
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url= 'DON'T WANT TO SHARE'
uClient= uReq(my_url)
page_html= uClient.read()
uClient.close()

page_soup= soup(page_html, "html.parser")
contents=page_soup.findAll("data")
print (contents)

Upon printing the contents I am getting something like this:

<data>
------------------------------------
SIM: B01N2W56MD
(P)UBLISHER NAME: Monster
------------------------------------
(I)[ 0] Publisher: Monster
(I)[ 1] Title: Monster
(I)[12] Subject Keyword: nos
------------------------------------
(S)[ 0] Marketplace ID:  1
(S)[ 1] Replenishment Category:  Non Replenishable
(S)[ 5] Title type:  Main title 1
(S)[ 9] Product Group:  No operation Product Handling Group
(S)[19] Product Subcategory:  A
(S)[32] Are batteries required?:  N
------------------------------------
(K)[ 0] IDC: 030347493342
(K)[ 1] ORC: 6800532606463
------------------------------------
</data>

How can I extract these values and print or store them, i.e., the value of SIM or Title or IDC and ORC.

Body:
You can get extract these values using regular expressions

import  re

data = """
<data>
------------------------------------
SIM: B01N2W56MD
(P)UBLISHER NAME: Monster
------------------------------------
(I)[ 0] Publisher: Monster
(I)[ 1] Title: Monster
(I)[12] Subject Keyword: nos
------------------------------------
(S)[ 0] Marketplace ID:  1
(S)[ 1] Replenishment Category:  Non Replenishable
(S)[ 5] Title type:  Main title 1
(S)[ 9] Product Group:  No operation Product Handling Group
(S)[19] Product Subcategory:  A
(S)[32] Are batteries required?:  N
------------------------------------
(K)[ 0] IDC: 030347493342
(K)[ 1] ORC: 6800532606463
------------------------------------
</data>"""

sim= re.search(r'SIM:\s(.*?)\n', data).group(1)
dic= re.search(r'IDC:\s(.*?)\n', data).group(1)
title = re.search(r'Title:\s(.*?)\n', data).group(1)

print(sim)
print(dic)
print(title)

The code above simply looks for data within "SIM" and a "\n" (newline) and saves that data in a variable. Exactl same logic applies to finding value of "DIC" and "Title".


问:
Why overloaded methods defined in OOPS?
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

```<code>//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}
</code>```

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

答:
Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

First of all, overloading is not related to OOP. From Programming -- Principles and Practice Using C++ by Bjarne Stroustrup:

The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.

Note that overloading is not one of the key principles of OOP.

Now if we come to overloading, then the logic to support it is to make the code readable (though it can be considered as opinion based). For example, C has following functions:

```<code>int abs(int j);
long int labs(long int j);
double fabs(double x);
float fabsf(float x);
</code>```

But C++ has overloaded version of abs with different types (C++ still support C functions for backward compatibility though). Instead of inventing new names for same functionality with different types, it is easier and more readable if compiler itself can differentiate among functions with same name but different types, i.e. overloaded functions. This is also known as static polymorphism as the comment from @Basilevs pointed.

We can get the intention of Bjarne Stroustrup, the creator of C++, from his book The Design and Evolution of C++. According to him, several people wanted operator overloading but he was initially reluctant as:

It was hard to implement.

It was hard to teach and hard to define precisely.

Code using operator overloading was reputed to be inefficient.

It was reputed to make the code incomprehensible.

However if those problems could be solved then it could solve some real problem and many people wanted that support. He eventually overcame these problems and overloading became a part of C++. From the book:

However, if all of these conjectures were false, overloading would solve some real problems for C++ users. There were people who would like to have complex numbers, matrices, and APL-like vectors in C++. There were people who would like range-checked arrays, multidimensional arrays, and strings. There were at least two separate applications for which people wanted to overload logical operators such as I (or), & (and), and A (exclusive or). The way I saw it, the list was long and would grow with the size and the diversity of the c++ user population. My answer to [4], "overloading makes code obscure," was that several of my friends, whose opinion I valued and whose experience was measured in decades, claimed that their code would become cleaner if they had overloading. So what if one can write obscure code with overloading? It is possible to write obscure code in any language. It matters more how a feature can be used well than how it can be misused.

The related portion(page 78) is available in Google Books for free preview. Please have a look into it for more detailed discussion.

Though this was the design decision made by the inventor of C++, I think similar rationally applies to other languages too.

Title: Why overloaded methods defined in OOPS?

Body:
Interviewer had asked me what is method overloading and I had given answer saying, method overloading is within same class where two or more methods have same name but different signature, with following example -

//method with two parameters
public int add(int a, int b){
  return a + b;
}

//method with three parameters
public int add(int a, int b, int c){
  return a + b + c;
}

To this example, he said why do we need two methods with same name i.e. add. Instead we can have two methods with different names i.e. addTwoNumbers and addThreeNumbers which indicates, method names are more verbose and if we follow this approach, we don't need method overloading. (And same is true for other Java apis where method overloading is used.)

Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

Body:
Considering his above thought, he asked why OOPS principle still have method overloading and why is being used so intensively? What is intention of inventors to introduce concept of method overloading?

First of all, overloading is not related to OOP. From Programming -- Principles and Practice Using C++ by Bjarne Stroustrup:

The use of inheritance, run-time polymorphism, and encapsulation is the most common definition of object-oriented programming.

Note that overloading is not one of the key principles of OOP.

Now if we come to overloading, then the logic to support it is to make the code readable (though it can be considered as opinion based). For example, C has following functions:

int abs(int j);
long int labs(long int j);
double fabs(double x);
float fabsf(float x);

But C++ has overloaded version of abs with different types (C++ still support C functions for backward compatibility though). Instead of inventing new names for same functionality with different types, it is easier and more readable if compiler itself can differentiate among functions with same name but different types, i.e. overloaded functions. This is also known as static polymorphism as the comment from @Basilevs pointed.

We can get the intention of Bjarne Stroustrup, the creator of C++, from his book The Design and Evolution of C++. According to him, several people wanted operator overloading but he was initially reluctant as:

It was hard to implement.

It was hard to teach and hard to define precisely.

Code using operator overloading was reputed to be inefficient.

It was reputed to make the code incomprehensible.

However if those problems could be solved then it could solve some real problem and many people wanted that support. He eventually overcame these problems and overloading became a part of C++. From the book:

However, if all of these conjectures were false, overloading would solve some real problems for C++ users. There were people who would like to have complex numbers, matrices, and APL-like vectors in C++. There were people who would like range-checked arrays, multidimensional arrays, and strings. There were at least two separate applications for which people wanted to overload logical operators such as I (or), & (and), and A (exclusive or). The way I saw it, the list was long and would grow with the size and the diversity of the c++ user population. My answer to [4], "overloading makes code obscure," was that several of my friends, whose opinion I valued and whose experience was measured in decades, claimed that their code would become cleaner if they had overloading. So what if one can write obscure code with overloading? It is possible to write obscure code in any language. It matters more how a feature can be used well than how it can be misused.

The related portion(page 78) is available in Google Books for free preview. Please have a look into it for more detailed discussion.

Though this was the design decision made by the inventor of C++, I think similar rationally applies to other languages too.


问:
Superfish menu vertically and opening to the left?
I'm trying to use Superfish vertically but aligned to the right of page and thus opening any submenus to the left. I've been tweaking some CSS properties to achieve this but it doesn't work perfectly - the arrows are always positioned to the right of any parent menu text when in this case they should be at left of text and the positioning of the submenus to the left doesn't work exactly the same way in level 2 and level 3!

This is driving me crazy! Anyone has achieved this working perfectly? Any tips or examples?

Thanks in advance,
LM

[EDIT]

I managed to put the arrows at left (commented in CSS [uppercase MY EDIT:...) and also managed to open the submenus at left (using the latest version of SuperFish with class .sf-vertical) but I'm still having problems with 3rd level submenus - the shadow is misplaced!

here is the html page and the CSS code I've altered (arrows in 'superfish.css' and position in 'superfish-vertical.css':

```<code><!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <title></title>
  <link media="screen" rel="stylesheet" href="_assets/superfish.css" />
  <link media="screen" rel="stylesheet" href="_assets/superfish-vertical.css" />
  <script type="text/javascript" src="_assets/jquery-1.10.2.min.js" charset="utf-8"></script>
  <script type="text/javascript" src="_assets/superfish.js"></script>
  <script type="text/javascript" src="_assets/hoverIntent.js"></script>
  <script type="text/javascript" src="_assets/supersubs.js"></script>
</head>
<body style="margin: 0;">

 <div style="width: 150px; position: absolute; top: 0px; right: 200px; background: #CCC;">
   <ul class="sf-menu sf-vertical" id="myMenu">
     <!--MENU-01-->
     <li><a href="#"><b>MENU-1</b></a></li>
     <!--MENU-02-->
     <li><a href="#"><b>MENU-2</b></a></li>
     <!--MENU-03-->
     <li>
       <a href="javascript:void(0);"><b>MENU-3</b></a>
       <ul>
         <li><a href="#">MENU-3.1</a></li>
         <li>
           <a href="javascript:void(0);">MENU-3.2</a>
           <ul>
             <li><a href="#">MENU-3.2.1</a></li>
             <li><a href="#">MENU-3.2.2</a></li>
             <li><a href="#">MENU-3.2.3</a></li>
             <li><a href="#">MENU-3.2.4</a></li>
           </ul>
         </li>
       </ul>
     </li>
     <!--MENU-04-->
     <li><a href="#"><b>MENU-4</b></a></li>
   </ul>
 </div>

 <script type="text/javascript">
 $(document).ready(function () {
   $('ul.sf-menu').supersubs({
     minWidth:'150px', maxWidth: '150px', extraWidth: 0
   }).superfish();
 });
 </script>

</body>
</html>
</code>```

superfish.css

```<code>/*** ESSENTIAL STYLES ***/
.sf-menu, .sf-menu * {
    margin: 0;
    padding: 0;
    list-style: none;
    font-family: Arial, Helvetica, Sans-Serif; font-size: 12px; color: #FFFFFF;
}
.sf-menu li {
    position: relative;
}
.sf-menu ul {
    position: absolute;
    display: none;
    top: 100%;
    left: 0;
    z-index: 99;
}
.sf-menu > li {
    float: left;
}
.sf-menu li:hover > ul, .sf-menu li.sfHover > ul {
    display: block;
}

.sf-menu a {
    display: block;
    position: relative;
}
.sf-menu ul ul {
    top: 0;
    left: 100%;
}

/*** DEMO SKIN ***/
.sf-menu {
    float: left;
    margin-bottom: 1em;
}
.sf-menu ul {
    box-shadow: 2px 2px 6px rgba(0,0,0,0.2);
    min-width: 12em; /* allow long menu items to determine submenu width */
    *width: 12em; /* no auto sub width for IE7, see white-space comment below */
}
.sf-menu a {
    /*border-left: 1px solid #fff;*/
    border-top: 1px solid #dFeEFF; /* fallback colour must use full shorthand */
    border-top: 1px solid rgba(255,255,255,0.5);
    padding: .75em 1em;
    text-decoration: none;
    zoom: 1; /* IE7 */
}
.sf-menu a {
    color: #13a;
}
.sf-menu li {
    background: #BDD2FF;
    white-space: nowrap; /* no need for Supersubs plugin */
    *white-space: normal; /* ...unless you support IE7 (let it wrap) */
    -webkit-transition: background .2s;
    transition: background .2s;
}
.sf-menu ul li {
    background: #AABDE6;
}
.sf-menu ul ul li {
    background: #9AAEDB;
}
.sf-menu li:hover, .sf-menu li.sfHover {
    background: #CFDEFF;
    /* only transition out, not in */
    -webkit-transition: none;
    transition: none;
}

/*** arrows (for all except IE7) **/
.sf-arrows .sf-with-ul {
    padding-right: 2.5em;
    *padding-right: 1em; /* no CSS arrows for IE7 (lack pseudo-elements) */
}
/* styling for both css and generated arrows */
.sf-arrows .sf-with-ul:after {
    content: '';
    position: absolute;
    top: 50%;
    left: 2px; /* MY EDIT: PLACES ARROWS AT MOST LEFT, IT WORKS OK */
    margin-top: -3px;
    height: 0;
    width: 0;
    /* order of following 3 rules important for fallbacks to work */
    border: 5px solid transparent;
    border-top-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-top-color: rgba(255,255,255,0.5);
}
.sf-arrows > li > .sf-with-ul:focus:after,
.sf-arrows > li:hover > .sf-with-ul:after,
.sf-arrows > .sfHover > .sf-with-ul:after {
    border-top-color: white; /* IE8 fallback colour */
}
/* styling for right-facing arrows */
.sf-arrows ul .sf-with-ul:after {
    margin-top: -5px;
    margin-right: -3px;
    border-color: transparent;
    border-left-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-left-color: rgba(255,255,255,0.5);
}
.sf-arrows ul li > .sf-with-ul:focus:after,
.sf-arrows ul li:hover > .sf-with-ul:after,
.sf-arrows ul .sfHover > .sf-with-ul:after {
    border-left-color: white;
}
</code>```

and finally superfish-vertical.css

```<code>/* adding sf-vertical class in addition to sf-menu creates a vertical menu */
/* eg. <ul class="sf-menu sf-vertical"> ... */
.sf-vertical {
    width: 150px;
/* If you want the width of the closed menu to expand to its
widest top-level menu item (like its "Supersubs" submenus do),
replace the width rule above with the following two rules. */

/*
min-width: 12em;
*width: 12em;
*/
}

.sf-vertical ul {
    left: -100%; /* MY EDIT: THIS WORKS OK AT 2nd LEVEL */
    top: 0;
}
.sf-vertical > li {
    float: none;
}
.sf-vertical li {
    width: 100%;
}

.sf-vertical ul ul li {
    left: -200%; /* MY EDIT: THIS WORKS OK AT 3rd LEVEL BUT SHADOW IS MISPLACED */
    top: 0;
}

/*** alter arrow directions ***/
.sf-vertical.sf-arrows > li > .sf-with-ul:after {
    margin-top: -5px;
    margin-right: -3px;
    border-color: transparent;
    border-left-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-left-color: rgba(255,255,255,0.5);
}
.sf-vertical.sf-arrows li > .sf-with-ul:focus:after,
.sf-vertical.sf-arrows li:hover > .sf-with-ul:after,
.sf-vertical.sf-arrows .sfHover > .sf-with-ul:after {
    border-left-color: white;
}
</code>```

答:
This question may be old, but it may help some one, please try this jsfiddle.</p>

```<code>(function($) { //create closure so we can safely use $ as alias for jQuery
    $(document).ready(function() {
        // initialise plugin
        var example = $('.sf-menu').superfish({
            //add options here if required
        }).supposition();
    });
})(jQuery);
</code>```

Body:
I'm trying to use Superfish vertically but aligned to the right of page and thus opening any submenus to the left. I've been tweaking some CSS properties to achieve this but it doesn't work perfectly - the arrows are always positioned to the right of any parent menu text when in this case they should be at left of text and the positioning of the submenus to the left doesn't work exactly the same way in level 2 and level 3!

This is driving me crazy! Anyone has achieved this working perfectly? Any tips or examples?

Thanks in advance,
LM

[EDIT]

I managed to put the arrows at left (commented in CSS [uppercase MY EDIT:...) and also managed to open the submenus at left (using the latest version of SuperFish with class .sf-vertical) but I'm still having problems with 3rd level submenus - the shadow is misplaced!

here is the html page and the CSS code I've altered (arrows in 'superfish.css' and position in 'superfish-vertical.css':

<!DOCTYPE html>

  <title></title>
  <link media="screen" rel="stylesheet" href="_assets/superfish.css" />
  <link media="screen" rel="stylesheet" href="_assets/superfish-vertical.css" />

MENU-1

MENU-2

       MENU-3

MENU-3.1

           MENU-3.2

MENU-3.2.1

MENU-3.2.2

MENU-3.2.3

MENU-3.2.4

MENU-4

superfish.css

/*** ESSENTIAL STYLES ***/
.sf-menu, .sf-menu * {
    margin: 0;
    padding: 0;
    list-style: none;
    font-family: Arial, Helvetica, Sans-Serif; font-size: 12px; color: #FFFFFF;
}
.sf-menu li {
    position: relative;
}
.sf-menu ul {
    position: absolute;
    display: none;
    top: 100%;
    left: 0;
    z-index: 99;
}
.sf-menu > li {
    float: left;
}
.sf-menu li:hover > ul, .sf-menu li.sfHover > ul {
    display: block;
}

.sf-menu a {
    display: block;
    position: relative;
}
.sf-menu ul ul {
    top: 0;
    left: 100%;
}

/*** DEMO SKIN ***/
.sf-menu {
    float: left;
    margin-bottom: 1em;
}
.sf-menu ul {
    box-shadow: 2px 2px 6px rgba(0,0,0,0.2);
    min-width: 12em; /* allow long menu items to determine submenu width */
    *width: 12em; /* no auto sub width for IE7, see white-space comment below */
}
.sf-menu a {
    /*border-left: 1px solid #fff;*/
    border-top: 1px solid #dFeEFF; /* fallback colour must use full shorthand */
    border-top: 1px solid rgba(255,255,255,0.5);
    padding: .75em 1em;
    text-decoration: none;
    zoom: 1; /* IE7 */
}
.sf-menu a {
    color: #13a;
}
.sf-menu li {
    background: #BDD2FF;
    white-space: nowrap; /* no need for Supersubs plugin */
    *white-space: normal; /* ...unless you support IE7 (let it wrap) */
    -webkit-transition: background .2s;
    transition: background .2s;
}
.sf-menu ul li {
    background: #AABDE6;
}
.sf-menu ul ul li {
    background: #9AAEDB;
}
.sf-menu li:hover, .sf-menu li.sfHover {
    background: #CFDEFF;
    /* only transition out, not in */
    -webkit-transition: none;
    transition: none;
}

/*** arrows (for all except IE7) **/
.sf-arrows .sf-with-ul {
    padding-right: 2.5em;
    *padding-right: 1em; /* no CSS arrows for IE7 (lack pseudo-elements) */
}
/* styling for both css and generated arrows */
.sf-arrows .sf-with-ul:after {
    content: '';
    position: absolute;
    top: 50%;
    left: 2px; /* MY EDIT: PLACES ARROWS AT MOST LEFT, IT WORKS OK */
    margin-top: -3px;
    height: 0;
    width: 0;
    /* order of following 3 rules important for fallbacks to work */
    border: 5px solid transparent;
    border-top-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-top-color: rgba(255,255,255,0.5);
}
.sf-arrows > li > .sf-with-ul:focus:after,
.sf-arrows > li:hover > .sf-with-ul:after,
.sf-arrows > .sfHover > .sf-with-ul:after {
    border-top-color: white; /* IE8 fallback colour */
}
/* styling for right-facing arrows */
.sf-arrows ul .sf-with-ul:after {
    margin-top: -5px;
    margin-right: -3px;
    border-color: transparent;
    border-left-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-left-color: rgba(255,255,255,0.5);
}
.sf-arrows ul li > .sf-with-ul:focus:after,
.sf-arrows ul li:hover > .sf-with-ul:after,
.sf-arrows ul .sfHover > .sf-with-ul:after {
    border-left-color: white;
}

and finally superfish-vertical.css

/* adding sf-vertical class in addition to sf-menu creates a vertical menu */
/* eg.
 ... */
.sf-vertical {
    width: 150px;
/* If you want the width of the closed menu to expand to its
widest top-level menu item (like its "Supersubs" submenus do),
replace the width rule above with the following two rules. */

/*
min-width: 12em;
*width: 12em;
*/
}

.sf-vertical ul {
    left: -100%; /* MY EDIT: THIS WORKS OK AT 2nd LEVEL */
    top: 0;
}
.sf-vertical > li {
    float: none;
}
.sf-vertical li {
    width: 100%;
}

.sf-vertical ul ul li {
    left: -200%; /* MY EDIT: THIS WORKS OK AT 3rd LEVEL BUT SHADOW IS MISPLACED */
    top: 0;
}

/*** alter arrow directions ***/
.sf-vertical.sf-arrows > li > .sf-with-ul:after {
    margin-top: -5px;
    margin-right: -3px;
    border-color: transparent;
    border-left-color: #dFeEFF; /* edit this to suit design (no rgba in IE8) */
    border-left-color: rgba(255,255,255,0.5);
}
.sf-vertical.sf-arrows li > .sf-with-ul:focus:after,
.sf-vertical.sf-arrows li:hover > .sf-with-ul:after,
.sf-vertical.sf-arrows .sfHover > .sf-with-ul:after {
    border-left-color: white;
}

Body:
This question may be old, but it may help some one, please try this jsfiddle.

(function($) { //create closure so we can safely use $ as alias for jQuery
    $(document).ready(function() {
        // initialise plugin
        var example = $('.sf-menu').superfish({
            //add options here if required
        }).supposition();
    });
})(jQuery);


问:
How can i use TextInput & Dropdown by using Nativebase on react-native
am new react-native & nativebase. I try to use nativebase to build Textinput and Dropdown(Picker) in the same page but I cannot. I want to use both of them in the same page. Can u tell me how to. Thank you so much

//I want this to be Textinput
<CardItem style={{bottom: 60}}>
  <Text style={{fontSize: 20, fontWeight: 'bold' }}>Text Input</Text>
</CardItem>
<CardItem style={{bottom: 75}}>
  <Item rounded style={{borderColor: '#708090' }}>
    <Input placeholder="" />
  </Item>
</CardItem>

//I want this to be Dropdown
<CardItem style={{bottom: 75}}>
  <Text style={{fontSize: 20, fontWeight: 'bold' }}>Dropdown</Text>
</CardItem>
<CardItem style={{bottom: 90}}>
  <Item rounded style={{borderColor: '#708090' }}>
    <Input placeholder="" />
  </Item>
</CardItem>
```

答:
try this

import React from "react";
import {
  Container,
  Header,
  Content,
  Card,
  CardItem,
  Body,
  Text,
  Form,
  Item,
  Input,
  Picker,
} from "native-base";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected1: "key1",
    };
  }
  onValueChange(value) {
    this.setState({
      selected1: value,
    });
  }

  render() {
    return (
      <Container>

        <Content>
          <Card>
            <CardItem>

                <Text>Text Input</Text>

            </CardItem>
            <CardItem>

                <Item rounded style={{ borderColor: "#708090" }}>
                  <Input placeholder="" />
                </Item>

            </CardItem>
            <CardItem>

            </CardItem>
          </Card>

          <Card>
            <Text style={{ margin: 15 }}>Drop Down</Text>
            <Form style={{ marginLeft: 10, marginRight: 15 }}>
              <Picker
                iosHeader="Select one"
                mode="dropdown"
                selectedValue={this.state.selected1}
                onValueChange={this.onValueChange.bind(this)}
              >
                <Item label="Wallet" value="key0" />
                <Item label="ATM Card" value="key1" />
                <Item label="Debit Card" value="key2" />
                <Item label="Credit Card" value="key3" />
                <Item label="Net Banking" value="key4" />
              </Picker>
            </Form>
          </Card>
        </Content>
      </Container>
    );
  }
}
```

see this link

ContentLicense: CC BY-SA 4.0

Body:
try this

import React from "react";
import {
  Container,
  Header,
  Content,
  Card,
  CardItem,
  Body,
  Text,
  Form,
  Item,
  Input,
  Picker,
} from "native-base";

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      selected1: "key1",
    };
  }
  onValueChange(value) {
    this.setState({
      selected1: value,
    });
  }

  render() {
    return (
      <Container>
        <Header />
        <Content>
          <Card>
            <CardItem>
              <Body>
                <Text>Text Input</Text>
              </Body>
            </CardItem>
            <CardItem>
              <Body>
                <Item rounded style={{ borderColor: "#708090" }}>
                  <Input placeholder="" />
                </Item>
              </Body>
            </CardItem>
            <CardItem>
              <Body />
            </CardItem>
          </Card>

          <Card>
            <Text style={{ margin: 15 }}>Drop Down</Text>
            <Form style={{ marginLeft: 10, marginRight: 15 }}>
              <Picker
                iosHeader="Select one"
                mode="dropdown"
                selectedValue={this.state.selected1}
                onValueChange={this.onValueChange.bind(this)}
              >
                <Item label="Wallet" value="key0" />
                <Item label="ATM Card" value="key1" />
                <Item label="Debit Card" value="key2" />
                <Item label="Credit Card" value="key3" />
                <Item label="Net Banking" value="key4" />
              </Picker>
            </Form>
          </Card>
        </Content>
      </Container>
    );
  }
}

see this link


问:
What languages support covariance on inherited methods' return types?
I originally asked this question, but in finding an answer, discovered that my original problem was a lack of support in C# for covariance on inherited methods' return types. After discovering that, I became curious as to what languages do support this feature.

I will accept the answer of whoever can name the most.

EDIT: John Millikin correctly pointed out that lots of dynamic languages support this. To clarify:

I am only looking for static/strongly typed languages.

答:
C++

Java

REALbasic

Eiffel

Sather

Modula-3

OwnerDisplayName: Luke

LastEditorDisplayName: Constantin

OwnerDisplayName: Ivan Hamilton


问:
Convert PDF to doc or docx format using npm/node module or via code?
I haven't been successful in finding a node module or some code that can convert a PDF to doc/docx format using Node JS. Is there any way to do it? </p>

答:
node-unoconv

A node.js wrapper for converting documents with unoconv.

https://github.com/gfloyd/node-unoconv


问:
Promise-based functions for dialogflow's action map
Setting up a Google Assistant App via the NodeJS Google Actions SDK is done this way:

It seems that these are synchronous functions (per the documentation given on https://developers.google.com/actions/reference/nodejs/ActionsSdkApp#ActionsSdkApp

```<code>const app = new App({request: req, response: res});
function pickOption (app) {
   /*A bunch of steps here*/
}
function optionPicked (app) {
   /*Another bunch of steps here*/
}

const actionMap = new Map();
actionMap.set(app.StandardIntents.TEXT, pickOption);
actionMap.set(app.StandardIntents.OPTION, optionPicked);

app.handleRequest(actionMap);
</code>```

Is it possible for pickOption and optionPicked to be asynchronous functions? i.e., would it be correct to have pickOption be implemented as

```<code>function pickOption(){
   var pickOptionPromise = Q.defer();
   pickOptionPromise.resolve({
     /*Some results here*/
   });
   return pickOptionPromise.promise;
}
</code>```

答:
For starters, there is no requirement that you use app.handleRequest() at all. (You don't even need to use app, but that's not your question.) It is there as a convenience method to map intents to functions, but you're free to do that task via other means. I tend to do things like

```<code>function handler1( app ){
  // Does the logic asynchronously, but no voice response for some situation.
  // Returns a Promise that resolves to an Object about what we did
}

function handler2( app ){
  // Does the logic asynchronously, but no voice response for some situation.
  // Returns a Promise that resolves to an Object about what we did
}

function chooseHandler( app ){
  // Some logic which may be async, but which returns
  // a Promise that will resolve to either handler1 or 2
}

function sendResponse( app, handlerResult ){
  // Uses the handlerResult object to determine what to
  // send back to the user. This may involve async database calls.
  // Calls either app.ask(), or app.tell(), or a related call.
  // Returns a Promise indicating success
}

chooseHandler( app )
  .then( handler => handler( app ) )
  .then( result  => sendResponse( app, result ) )
  .catch( err => {
    // Log the error or something
  } );
</code>```

(This is meant to be illustrative. It isn't actually tested, nor guaranteed to be the highest quality or best design for a particular purpose.)

In this, the chooseHandler() is usually synchronous, but could be async if we need to do things like check if the user has been with us before and choose a different handler based on that. The handlers are almost always async, and the important bit is that they don't actually pick the phrases that are sent back to the user - that is done in sendResponse() and also may involve a database call which is async.

Body:
Setting up a Google Assistant App via the NodeJS Google Actions SDK is done this way:

It seems that these are synchronous functions (per the documentation given on https://developers.google.com/actions/reference/nodejs/ActionsSdkApp#ActionsSdkApp

const app = new App({request: req, response: res});
function pickOption (app) {
   /*A bunch of steps here*/
}
function optionPicked (app) {
   /*Another bunch of steps here*/
}

const actionMap = new Map();
actionMap.set(app.StandardIntents.TEXT, pickOption);
actionMap.set(app.StandardIntents.OPTION, optionPicked);

app.handleRequest(actionMap);

Is it possible for pickOption and optionPicked to be asynchronous functions? i.e., would it be correct to have pickOption be implemented as

function pickOption(){
   var pickOptionPromise = Q.defer();
   pickOptionPromise.resolve({
     /*Some results here*/
   });
   return pickOptionPromise.promise;
}

Body:
For starters, there is no requirement that you use app.handleRequest() at all. (You don't even need to use app, but that's not your question.) It is there as a convenience method to map intents to functions, but you're free to do that task via other means. I tend to do things like

function handler1( app ){
  // Does the logic asynchronously, but no voice response for some situation.
  // Returns a Promise that resolves to an Object about what we did
}

function handler2( app ){
  // Does the logic asynchronously, but no voice response for some situation.
  // Returns a Promise that resolves to an Object about what we did
}

function chooseHandler( app ){
  // Some logic which may be async, but which returns
  // a Promise that will resolve to either handler1 or 2
}

function sendResponse( app, handlerResult ){
  // Uses the handlerResult object to determine what to
  // send back to the user. This may involve async database calls.
  // Calls either app.ask(), or app.tell(), or a related call.
  // Returns a Promise indicating success
}

chooseHandler( app )
  .then( handler => handler( app ) )
  .then( result  => sendResponse( app, result ) )
  .catch( err => {
    // Log the error or something
  } );

(This is meant to be illustrative. It isn't actually tested, nor guaranteed to be the highest quality or best design for a particular purpose.)

In this, the chooseHandler() is usually synchronous, but could be async if we need to do things like check if the user has been with us before and choose a different handler based on that. The handlers are almost always async, and the important bit is that they don't actually pick the phrases that are sent back to the user - that is done in sendResponse() and also may involve a database call which is async.


问:
Avoid sub framework embedding iOS
I'm developing a Swift framework, MainFW, which uses 2 Objective-C frameworks.

I imported the legacy framework using a module map file in order to use it from Swift. Here is my code:

```<code>module SwiftFrameworkA {
  header "../Frameworks/A.framework/Headers/A.h"
  export *
}

module SwiftFrameworkB {
  header "../Frameworks/B.framework/Headers/B.h"
  export *
}
</code>```

When building MainFW this frameworks are "embedded", producing just a MainFW.framework.

What I need is that just one of them results embedded, the other must be also used in an ExternalApp which needs to use MainFW.framework and FrameworkB.framework

How can I instruct the build to not embed FrameworkB but using external app given FrameworkB.framework ?

Now ExternalApp says that classes are duplicated and doesn't know which one is used.

FrameworkB in addition is a non-modular framework.

Thank you.

答:
When you build the MainFW, you have to let it and FrameworkB be a sub project in an app project, then the app will compile FrameworkB separately, you just need to include the headers of FrameworkB to MainFW, then you can build your MainFW without FrameworkB inside it.

After that you can use both of them in an app project without duplicate classes

Title: Avoid sub framework embedding iOS

Body:
I'm developing a Swift framework, MainFW, which uses 2 Objective-C frameworks.

I imported the legacy framework using a module map file in order to use it from Swift. Here is my code:

module SwiftFrameworkA {
  header "../Frameworks/A.framework/Headers/A.h"
  export *
}

module SwiftFrameworkB {
  header "../Frameworks/B.framework/Headers/B.h"
  export *
}

When building MainFW this frameworks are "embedded", producing just a MainFW.framework.

What I need is that just one of them results embedded, the other must be also used in an ExternalApp which needs to use MainFW.framework and FrameworkB.framework

How can I instruct the build to not embed FrameworkB but using external app given FrameworkB.framework ?

Now ExternalApp says that classes are duplicated and doesn't know which one is used.

FrameworkB in addition is a non-modular framework.

Thank you.


问:
What are the alternatives for high order component in react?
Coming with php background not sure how to implement a design with reusable code,

the problem:
we are creating a react/redux app with a lot of similar components that share a lot of functionality... I've read about HOC but was wondering if there are another solutions that would help in this situation!?

答:
Component inheritance.
You can extend one component from some ComponentBase to share some functionality between them. But actually its different way from creating HOC. Hoc just allows you to pass some props to child, inheritance give you an ability to share methods and state.


问:
JSONPath Syntax when dot in key
Please forgive me if I use the incorrect terminology, I am quite the novice.

I have some simple JSON:

```<code>{
"properties": {
    "footer.navigationLinks": {
        "group": "layout"
    ,   "default": [
            {
                "text": "Link a"
            ,   "href": "#"
            }
        ]
    }
}
}
</code>```

I am trying to pinpoint "footer.navigationLinks" but I am having trouble with the dot in the key name. I am using http://jsonpath.com/ and when I enter

```<code>$.properties['footer.navigationLinks']
</code>```

I get 'No match'. If I change the key to "footernavigationLinks" it works but I cannot control the key names in the JSON file.

Please can someone help me target that key name?

答:
Having a json response:

```<code>{
  "0": {
    "SKU": "somevalue",
    "Merchant.Id": 234
    }
}
</code>```

I can target a key with a . (dot) in the name.

```<code>jsonPath.getJsonObject("0.\"Merchant.Id\"")
</code>```

Note: the quotes and the fact that they are escaped.

Note not sure of other versions, but I'm using

'com.jayway.restassured', name: 'json-path', version: '2.9.0'

A few samples/solutions I've seen, was using singe quotes with brackets, but did not work for me.

Title: JSONPath Syntax when dot in key

Body:
Please forgive me if I use the incorrect terminology, I am quite the novice.

I have some simple JSON:

{
"properties": {
    "footer.navigationLinks": {
        "group": "layout"
    ,   "default": [
            {
                "text": "Link a"
            ,   "href": "#"
            }
        ]
    }
}
}

I am trying to pinpoint "footer.navigationLinks" but I am having trouble with the dot in the key name. I am using http://jsonpath.com/ and when I enter

$.properties['footer.navigationLinks']

I get 'No match'. If I change the key to "footernavigationLinks" it works but I cannot control the key names in the JSON file.

Please can someone help me target that key name?

Body:
Having a json response:

{
  "0": {
    "SKU": "somevalue",
    "Merchant.Id": 234
    }
}

I can target a key with a . (dot) in the name.

jsonPath.getJsonObject("0.\"Merchant.Id\"")

Note: the quotes and the fact that they are escaped.

Note not sure of other versions, but I'm using

'com.jayway.restassured', name: 'json-path', version: '2.9.0'

A few samples/solutions I've seen, was using singe quotes with brackets, but did not work for me.


问:
Unity3d - Audio rough sound when transition between play and pause
I have a Unity script that will play audio (foot step) while the player is moving. The script is working, but there is one more problem, the audio seems too rough (and maybe can harm my speaker hehe) when transition between play and pause.

This is my script

```<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour {
    Rigidbody playerRigid;
    private Vector3 pindah;
    public AudioSource audioSource;
    public AudioClip audioClip;
    public float lowPitchRange = .95f;
    public float hiPitchRange = 1.05f;

    void Awake () {
        audioSource = GetComponent<AudioSource> ();
        audioSource.clip = audioClip;
        float randomPitch = Random.Range (lowPitchRange, hiPitchRange);
        audioSource.pitch = randomPitch;
    }

    // Use this for initialization
    void Start () {
        //mengambil komponen rigidbody player
        playerRigid = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        //untuk mendapatkan input dari virtual joystick button
        float h = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
        float v = CrossPlatformInputManager.GetAxisRaw ("Vertical");

        if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
            audioSource.Play ();
        } else {
            audioSource.Pause ();
        }
        //memindah posisi player sesuai input yang didapat
        pindah = new Vector3 (h, 0.0f, v);
        playerRigid.velocity = pindah;
    }
}
</code>```

答:
If the problem is the audio source pops when you pause it, maybe you should consider to fade the volume instead with something similar to this (I haven't tested myself, I will try it later):</p>

```<code>// fade/increase time in seconds
public float rateTime = 1;

public FadeSound() {
    //audioSource.Play ();
    StartCoroutine(_FadeSound);
    }

public IncreaseSound() {
    StartCoroutine(_IncreaseSound);
}

IEnumerator _FadeSound() {
    float t = rateTime;

    while (t > 0) {
        yield return null;
        t-= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
    //yield audioSource.Pause ();
}

IEnumerator _IncreaseSound() {
    float t = 0;

    while (t < 1) {
        yield return null;
        t+= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
}

if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
    IncreaseSound();
} else {
    FadeSound();
}
</code>```

Body:
I have a Unity script that will play audio (foot step) while the player is moving. The script is working, but there is one more problem, the audio seems too rough (and maybe can harm my speaker hehe) when transition between play and pause.

This is my script

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityStandardAssets.CrossPlatformInput;

public class PlayerController : MonoBehaviour {
    Rigidbody playerRigid;
    private Vector3 pindah;
    public AudioSource audioSource;
    public AudioClip audioClip;
    public float lowPitchRange = .95f;
    public float hiPitchRange = 1.05f;

    void Awake () {
        audioSource = GetComponent<AudioSource> ();
        audioSource.clip = audioClip;
        float randomPitch = Random.Range (lowPitchRange, hiPitchRange);
        audioSource.pitch = randomPitch;
    }

    // Use this for initialization
    void Start () {
        //mengambil komponen rigidbody player
        playerRigid = GetComponent<Rigidbody> ();
    }

    // Update is called once per frame
    void Update () {
        //untuk mendapatkan input dari virtual joystick button
        float h = CrossPlatformInputManager.GetAxisRaw ("Horizontal");
        float v = CrossPlatformInputManager.GetAxisRaw ("Vertical");

        if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
            audioSource.Play ();
        } else {
            audioSource.Pause ();
        }
        //memindah posisi player sesuai input yang didapat
        pindah = new Vector3 (h, 0.0f, v);
        playerRigid.velocity = pindah;
    }
}

Body:
If the problem is the audio source pops when you pause it, maybe you should consider to fade the volume instead with something similar to this (I haven't tested myself, I will try it later):

// fade/increase time in seconds
public float rateTime = 1;

public FadeSound() {
    //audioSource.Play ();
    StartCoroutine(_FadeSound);
    }

public IncreaseSound() {
    StartCoroutine(_IncreaseSound);
}

IEnumerator _FadeSound() {
    float t = rateTime;

    while (t > 0) {
        yield return null;
        t-= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
    //yield audioSource.Pause ();
}

IEnumerator _IncreaseSound() {
    float t = 0;

    while (t < 1) {
        yield return null;
        t+= Time.deltaTime;
        source.volume = t/rateTime;
    }
    yield break;
}

if ((h != 0f || v != 0f) && !audioSource.isPlaying) {
    IncreaseSound();
} else {
    FadeSound();
}


问:
Similar to jQuery .closest() but traversing descendants?
Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is .find() function, but it returns all possible matches, not closest.

Edit:

Here is definition of closest (at least for me):

In first place all childrens are traversed, then each individuals childrens are traversed.

In example given below id='2' is closest .closest descendants of id="find-my-closest-descendant"

```<code><div id="find-my-closest-descendant">
    <div>
        <div class="closest" Id='1'></div>
    </div>
    <div class="closest" Id='2'></div>
</div>
</code>```

Please see JSfiddle link.

答:
What about this approach?

```<code>$('find-my-closest-descendant').find('> div');
</code>```

This "direct child" selector works for me.

Body:
Is there a function similar to jQuery .closest() but for traversing descendants and returning only closest ones?

I know that there is .find() function, but it returns all possible matches, not closest.

Edit:

Here is definition of closest (at least for me):

In first place all childrens are traversed, then each individuals childrens are traversed.

In example given below id='2' is closest .closest descendants of id="find-my-closest-descendant"

Please see JSfiddle link.

Body:
What about this approach?

$('find-my-closest-descendant').find('> div');

This "direct child" selector works for me.


问:
Angular 4 lifecycle hook for template rendering
I'm developing an Angular 4 application using the Foundation 6 framework for styling and UI. Among others, I'm using its 'Tabs' element to display several pages of information on the same div. To make it work, the application must run $(document).foundation() to initialize all the stuff needed. The problem is that, on start, the component where I use the 'Tabs' element is hidden using a *ngIf directive, and it's only shown when the user selects an object identifier from a list.
To try to fix it, when the user selects an object ID and the component is loaded, I run the following code when I get the results from the DB:

```<code>$(function() {
  $('#tabbed_element').foundation();
  $('#tabbed_element').foundation('selectTab', 'objectTab');
});
</code>```

This solution has the following drawbacks:

As the code is ran everytime I click on an object, I call multiple times to the foundation function, getting this warning from the second time:

Tried to initialize tabs on an element that already has a Foundation plugin.

In theory, running the 'selectTab' function should select the wanted tab ('objectTab' in this case) and it does BUT the first time that the 'Tabs' element is shown I can see the tabs on the left (it's a vertical tab) but nothing on the right, where the data should be. Selecting another tab makes it work perfectly.

Everything runs fine until I hide the object panel. When I do this and double click on an object id again, I have the same trouble (no data shown).

I've tried to run the code in all the Angular lifecycle hooks (such as ngAfterViewInit, ngAfterContentInit etc) but I couldn't get it working.

I'm quite sure that the problem comes from the fact that I call the foundation function when the DOM isn't fully loaded (perhaps because the 'Tabs' element is inside a div with a '*ngIf' directive, only shown when the user selects an object). So, my question is, is there any hook being called when the component template is ready to show? This way, I would initialize foundation from it instead of when I get the data from the DB.

Many thanks,

答:
I found a solution using the 'ngAfterViewChecked' hook like this:

```<code>ngAfterViewChecked() {
  // Check if the DOM has an element with template name 'item_panel_tabs' (obtained through ViewChild on the component's beginning)
  if (this.itemTabsElement) {
    // If the element exists, check if we have initialized it (this is done by running the foundation() function on the element)
    if(!this.tabsInit) {
      // If not, 1) call Foundation function
      $(this.itemTabsElement.nativeElement).foundation();

      // 2) Change to the 'objectPanel' tab
      $(this.itemTabsElement.nativeElement).foundation('selectTab', 'objectPanel');

      // And 3) Mark the component as initialized
      this.tabsInit = true;
    }
  }
  else {
    // If the element doesn't exist in the DOM, mark it as uninitialized
    this.tabsInit = false;
  }
}
</code>```

In the component code:

```<code>@ViewChild('item_panel_tabs') itemTabsElement : ElementRef;
private tabsInit : boolean = false;
</code>```

In the HTML template:

```<code><ul class="vertical tabs" data-tabs id="item-panel-tabs" #item_panel_tabs>
  <li class="tabs-title"><a href="#objectPanel"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Object</a></li>
  <li class="tabs-title"><a href="#infoPanel"><i class="fa fa-info-circle" aria-hidden="true"></i> Info</a></li>
</ul>
</code>```

Cheers,

Body:
I'm developing an Angular 4 application using the Foundation 6 framework for styling and UI. Among others, I'm using its 'Tabs' element to display several pages of information on the same div. To make it work, the application must run $(document).foundation() to initialize all the stuff needed. The problem is that, on start, the component where I use the 'Tabs' element is hidden using a *ngIf directive, and it's only shown when the user selects an object identifier from a list.
To try to fix it, when the user selects an object ID and the component is loaded, I run the following code when I get the results from the DB:

$(function() {
  $('#tabbed_element').foundation();
  $('#tabbed_element').foundation('selectTab', 'objectTab');
});

This solution has the following drawbacks:

As the code is ran everytime I click on an object, I call multiple times to the foundation function, getting this warning from the second time:

Tried to initialize tabs on an element that already has a Foundation plugin.

In theory, running the 'selectTab' function should select the wanted tab ('objectTab' in this case) and it does BUT the first time that the 'Tabs' element is shown I can see the tabs on the left (it's a vertical tab) but nothing on the right, where the data should be. Selecting another tab makes it work perfectly.

Everything runs fine until I hide the object panel. When I do this and double click on an object id again, I have the same trouble (no data shown).

I've tried to run the code in all the Angular lifecycle hooks (such as ngAfterViewInit, ngAfterContentInit etc) but I couldn't get it working.

I'm quite sure that the problem comes from the fact that I call the foundation function when the DOM isn't fully loaded (perhaps because the 'Tabs' element is inside a div with a '*ngIf' directive, only shown when the user selects an object). So, my question is, is there any hook being called when the component template is ready to show? This way, I would initialize foundation from it instead of when I get the data from the DB.

Many thanks,

Body:
I found a solution using the 'ngAfterViewChecked' hook like this:

ngAfterViewChecked() {
  // Check if the DOM has an element with template name 'item_panel_tabs' (obtained through ViewChild on the component's beginning)
  if (this.itemTabsElement) {
    // If the element exists, check if we have initialized it (this is done by running the foundation() function on the element)
    if(!this.tabsInit) {
      // If not, 1) call Foundation function
      $(this.itemTabsElement.nativeElement).foundation();

      // 2) Change to the 'objectPanel' tab
      $(this.itemTabsElement.nativeElement).foundation('selectTab', 'objectPanel');

      // And 3) Mark the component as initialized
      this.tabsInit = true;
    }
  }
  else {
    // If the element doesn't exist in the DOM, mark it as uninitialized
    this.tabsInit = false;
  }
}

In the component code:

@ViewChild('item_panel_tabs') itemTabsElement : ElementRef;
private tabsInit : boolean = false;

In the HTML template:

<ul class="vertical tabs" data-tabs id="item-panel-tabs" #item_panel_tabs>
  <li class="tabs-title"><a href="#objectPanel"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Object</a></li>
  <li class="tabs-title"><a href="#infoPanel"><i class="fa fa-info-circle" aria-hidden="true"></i> Info</a></li>
</ul>

Cheers,


问:
Access service from an injected module in Angular 1
I have an angular 1 app with two modules, main and secondary. secondary is injected in main, and main have a service:

```<code>angular.module('main', ['secondary'])
.run(function(){
  console.log('main module run');
})
.service('mainService', function(){
  this.servMeth = function(){
    console.log('main service');
  };
});

angular.module('secondary', [])
.run(function(){
  console.log('secondary module run');
});
</code>```

Is there a way to access mainService from main in secondary module?

答:
You just need to inject it in a component or other service like this:</p>

```<code>angular.module('secondary', [])
.run(function(){
  console.log('secondary module run');
})
.component('secondary-component', {
  controller: ['mainService', function(mainService) {
    this.$onInit = function() {
      mainService.servMeth();
    }
  }]
});
</code>```

Body:
I have an angular 1 app with two modules, main and secondary. secondary is injected in main, and main have a service:

angular.module('main', ['secondary'])
.run(function(){
  console.log('main module run');
})
.service('mainService', function(){
  this.servMeth = function(){
    console.log('main service');
  };
});

angular.module('secondary', [])
.run(function(){
  console.log('secondary module run');
});

Is there a way to access mainService from main in secondary module?

Body:
You just need to inject it in a component or other service like this:

angular.module('secondary', [])
.run(function(){
  console.log('secondary module run');
})
.component('secondary-component', {
  controller: ['mainService', function(mainService) {
    this.$onInit = function() {
      mainService.servMeth();
    }
  }]
});


问:
Chart.js line chart is cut off at the top?
For some reasone all graphs are cut off at the highest value.
How can i fix this? I can't use a fixed y-axis

答:
I ran into this Chart.js bug, too.

A very recent fix is shown here.
You'd have to manually edit your Chart.js file src/controllers/controller.line.js
(For Angular 2, this file path will be located inside directory node_modules/chart.js/.)

Or just wait for the next Chart.js release which will most likely contain the fix.

An alternative workaround is described in comment 1 of this bug ticket:
https://github.com/chartjs/Chart.js/issues/4202


问:
Writing c++ dll with Qt GUI, displaying fails in custom widget
I am writing a dll for an application that I cannot modify. This application is sending requests to my dll and I can run this application in single request mode or automatic where it works in some kind of loop sending requests and processing responses. I am not aware of how exactly this automatic mode works and I don't have access to source code to see the difference.

In my dll I have a custom MainWindow class inheriting QMainWindow that contains two objects: LogWindow inheriting QPlainTextEdit, and custom Widget inheriting QWidget. I would like to display some text and change some properties in my widget on request from main application. It all works well with single request. However, in automatic mode only the text is updated. I need some help to also make updates in widget. Now some implementation details:

In my dll code I have global variables for application and main window:

```<code>QApplication * app = nullptr;
MainWindow * win = nullptr;
</code>```

I create them on loading of the dll:

```<code>app = new QApplication(*argc, argv);
win = new MainWindow;
win->show();
app->processEvents();
</code>```

My MainWindow looks like this:

```<code>MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(this, &MainWindow::message_received, ui->log_window, &LogWindow::appendMessage);
    connect(this, &MainWindow::colors_received, ui->custom_widget, &CustomWidget::set_colors);
}

void MainWindow::append_log(std::string const & str) {
    emit message_received(QString::fromStdString(str));
}
void MainWindow::display_colors(Colors const & colors) {
    emit colors_received(colors);
}
</code>```

I call 'append_log()' and 'display_colors()' on request from application. And these are the slots being called:

```<code>void LogWindow::appendMessage(const QString & message) {
    this->appendPlainText(message);
}
</code>```

And in Custom Widget:

```<code>void CustomWidget::set_colors(Colors const & colors) {
    setStyleSheet("background-color: red");
}
</code>```

On request from dll I am calling both  'win->append_log()' and 'win->display_colors()'. As I said in automatic mode only text gets displayed, but no update to colors. I am guessing PlainTextEdit::appendPlainText() method must be calling some update, but I cannot figure out how to duplicate the behaviour onto my class. I tried 'update()' and 'repaint()' but nothing seems to work.

I guess noone had similar problem before, but I would appreciate some suggestions on what to try or where to look for.

Update

Turns out that CustomWidget::set_colors() method is not called when running in "automatic" mode. I assumed it is called, because I am using exactly the same method to call it as with LogWindow::appendMessage().

Now the question is why it is not called. Some code details:

```<code>class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void append_log(std::string const &);
    void display_colors(Colors const &);
signals:
    void message_received(QString const &);
    void colors_received(Colors const &);

private:
    Ui::MainWindow *ui;
};

class LogWindow : public QPlainTextEdit
{
public:
    LogWindow();
    LogWindow(QWidget * parent);
public slots:
    void appendMessage(QString const &);
};

class CustomWidget : public QWidget
{
    Q_OBJECT

public:
    CustomWidget(QWidget *);
    CustomWidget(QWidget *, Colors);

public slots:
    void set_colors(Colors const &);

};
</code>```

From generated setupUi() function:

```<code>centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
log_window = new LogWindow(centralWidget);
log_window->setObjectName(QStringLiteral("log_window"));
log_window->setGeometry(QRect(10, 10, 421, 561));
custom_widget = new CustomWidget(centralWidget);
custom_widget->setObjectName(QStringLiteral("custom_widget"));
custom_widget->setGeometry(QRect(439, 9, 381, 331));
MainWindow->setCentralWidget(centralWidget);
</code>```

Probably I am missing something, but to me it looks like both methods are called exactly the same way. Unfortunately only one of them is working. Looking for suggestions what could be the issue.

答:
The slot/signal mechanism was not working with custom class Colors, because it was not registered in Qt Meta Object system. Adding this line before signal connection solved the problem:

```<code>qRegisterMetaType<Colors>("Colors");
</code>```

Body:
I am writing a dll for an application that I cannot modify. This application is sending requests to my dll and I can run this application in single request mode or automatic where it works in some kind of loop sending requests and processing responses. I am not aware of how exactly this automatic mode works and I don't have access to source code to see the difference.

In my dll I have a custom MainWindow class inheriting QMainWindow that contains two objects: LogWindow inheriting QPlainTextEdit, and custom Widget inheriting QWidget. I would like to display some text and change some properties in my widget on request from main application. It all works well with single request. However, in automatic mode only the text is updated. I need some help to also make updates in widget. Now some implementation details:

In my dll code I have global variables for application and main window:

QApplication * app = nullptr;
MainWindow * win = nullptr;

I create them on loading of the dll:

app = new QApplication(*argc, argv);
win = new MainWindow;
win->show();
app->processEvents();

My MainWindow looks like this:

MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    connect(this, &MainWindow::message_received, ui->log_window, &LogWindow::appendMessage);
    connect(this, &MainWindow::colors_received, ui->custom_widget, &CustomWidget::set_colors);
}

void MainWindow::append_log(std::string const & str) {
    emit message_received(QString::fromStdString(str));
}
void MainWindow::display_colors(Colors const & colors) {
    emit colors_received(colors);
}

I call 'append_log()' and 'display_colors()' on request from application. And these are the slots being called:

void LogWindow::appendMessage(const QString & message) {
    this->appendPlainText(message);
}

And in Custom Widget:

void CustomWidget::set_colors(Colors const & colors) {
    setStyleSheet("background-color: red");
}

On request from dll I am calling both  'win->append_log()' and 'win->display_colors()'. As I said in automatic mode only text gets displayed, but no update to colors. I am guessing PlainTextEdit::appendPlainText() method must be calling some update, but I cannot figure out how to duplicate the behaviour onto my class. I tried 'update()' and 'repaint()' but nothing seems to work.

I guess noone had similar problem before, but I would appreciate some suggestions on what to try or where to look for.

Update

Turns out that CustomWidget::set_colors() method is not called when running in "automatic" mode. I assumed it is called, because I am using exactly the same method to call it as with LogWindow::appendMessage().

Now the question is why it is not called. Some code details:

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void append_log(std::string const &);
    void display_colors(Colors const &);
signals:
    void message_received(QString const &);
    void colors_received(Colors const &);

private:
    Ui::MainWindow *ui;
};

class LogWindow : public QPlainTextEdit
{
public:
    LogWindow();
    LogWindow(QWidget * parent);
public slots:
    void appendMessage(QString const &);
};

class CustomWidget : public QWidget
{
    Q_OBJECT

public:
    CustomWidget(QWidget *);
    CustomWidget(QWidget *, Colors);

public slots:
    void set_colors(Colors const &);

};

From generated setupUi() function:

centralWidget = new QWidget(MainWindow);
centralWidget->setObjectName(QStringLiteral("centralWidget"));
log_window = new LogWindow(centralWidget);
log_window->setObjectName(QStringLiteral("log_window"));
log_window->setGeometry(QRect(10, 10, 421, 561));
custom_widget = new CustomWidget(centralWidget);
custom_widget->setObjectName(QStringLiteral("custom_widget"));
custom_widget->setGeometry(QRect(439, 9, 381, 331));
MainWindow->setCentralWidget(centralWidget);

Probably I am missing something, but to me it looks like both methods are called exactly the same way. Unfortunately only one of them is working. Looking for suggestions what could be the issue.

Body:
The slot/signal mechanism was not working with custom class Colors, because it was not registered in Qt Meta Object system. Adding this line before signal connection solved the problem:

qRegisterMetaType<Colors>("Colors");