问:
Put an event on a table row in vuejs
Hi i have been looking for a simple answer to this question but cant seem to find one i have the spatie table plugin for my vue app which looks like this.

```<code>                <table-component id="table1" :data="[
                                         { firstName: 'John', birthday: '04/10/1940', songs: 72 },
                                         { firstName: 'Paul', birthday: '18/06/1942', songs: 70 },
                                         { firstName: 'George', birthday: '25/02/1943', songs: 22 },
                                         { firstName: 'Ringo', birthday: '07/07/1940', songs: 2 },
                                         ]" sort-by="songs" sort-order="asc">
                    <table-column show="firstName" label="First name"></table-column>
                    <table-column show="songs" label="Songs" data-type="numeric"></table-column>
                    <table-column show="birthday" label="Birthday" :filterable="false" data-type="date:DD/MM/YYYY"></table-column>
                </table-component>
</code>```

I want to create a method that when you click a table row it pushes my router to a different page and passes the table row information to the next router page

```<code>this.$router.push('/analytic-one');
</code>```

Any help or advice would be appreciated thank you.

答:
There are a couple of ways you could solve this.

But for the clicks themselves, in the Documentation for spatie table component, which was updated after this question was asked.

The table-component currently emits one custom event:

@rowClick: is fired when a row is clicked. Receives the row data as it's event payload.

Which tells us that the row data is returned in the payload, so we can do

```<code><table-component @rowClick="myHandlerMethod" ....
</code>```

And in our methods object

```<code>methods: {
    myHandlerMethod: function (clickedItem) {
        console.log(clickedItem)
    }
}
</code>```

And for sending the data to a new page, you could solve it in many ways.

You could use vuex to temporarily store the table information after clicking the table row, then push the router to the new page and fetch the data from the vuex state again.

Or you could use something like $router.push('route?artistId=' + clickedItem.id) and then do an ajax call to fetch data for that column again when the user lands on the new page, which is the clean way to do this. (this is pseudo code, look into vue router for the proper way of binding variables to the route.) This assumes you have an id in your data-set.

Or you could opt for using a modal instead, then you could do something like
this.selectedItem = clickedItem in the click handler.

Hope that gives you a general direction.

Title: Put an event on a table row in vuejs

Body:
Hi i have been looking for a simple answer to this question but cant seem to find one i have the spatie table plugin for my vue app which looks like this.

                <table-component id="table1" :data="[
                                         { firstName: 'John', birthday: '04/10/1940', songs: 72 },
                                         { firstName: 'Paul', birthday: '18/06/1942', songs: 70 },
                                         { firstName: 'George', birthday: '25/02/1943', songs: 22 },
                                         { firstName: 'Ringo', birthday: '07/07/1940', songs: 2 },
                                         ]" sort-by="songs" sort-order="asc">

I want to create a method that when you click a table row it pushes my router to a different page and passes the table row information to the next router page

this.$router.push('/analytic-one');

Any help or advice would be appreciated thank you.

Body:
There are a couple of ways you could solve this.

But for the clicks themselves, in the Documentation for spatie table component, which was updated after this question was asked.

The table-component currently emits one custom event:

@rowClick: is fired when a row is clicked. Receives the row data as it's event payload.

Which tells us that the row data is returned in the payload, so we can do

<table-component @rowClick="myHandlerMethod" ....

And in our methods object

methods: {
    myHandlerMethod: function (clickedItem) {
        console.log(clickedItem)
    }
}

And for sending the data to a new page, you could solve it in many ways.

You could use vuex to temporarily store the table information after clicking the table row, then push the router to the new page and fetch the data from the vuex state again.

Or you could use something like $router.push('route?artistId=' + clickedItem.id) and then do an ajax call to fetch data for that column again when the user lands on the new page, which is the clean way to do this. (this is pseudo code, look into vue router for the proper way of binding variables to the route.) This assumes you have an id in your data-set.

Or you could opt for using a modal instead, then you could do something like
this.selectedItem = clickedItem in the click handler.

Hope that gives you a general direction.


来源: stackexchange

问:
What nhibernate mapping is used for string[] in an entity?
I have a strange situation I need to persist:

```<code>public class Person
{
  public string[] Nicknames { get; set; }
}
</code>```

What mapping and table structure would be best to persist this string array?

答:
You can use some logic of yours to achieve the same thing right.. probably adding your own delimiter between the nicknames and then split it by this delimiter once you read it into memory.</p>

```<code>public class Person
{
  public string Nicknames { private get; set; }

  public string[] ArrayOfNicknames
  {
    get
    {
        return Nicknames.Split(<your_delimiter>);
    }
  }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a strange situation I need to persist:

public class Person
{
  public string[] Nicknames { get; set; }
}

What mapping and table structure would be best to persist this string array?

Body:
You can use some logic of yours to achieve the same thing right.. probably adding your own delimiter between the nicknames and then split it by this delimiter once you read it into memory.

public class Person
{
  public string Nicknames { private get; set; }

  public string[] ArrayOfNicknames
  {
    get
    {
        return Nicknames.Split(<your_delimiter>);
    }
  }
}


问:
Install Celery & Redis with Heroku
I use Django 1.9, Python 2.7 and Heroku.

Celery 3 & Redis were working well, until I switched to Celery 4.0.2 and changed the configuration.

heroku logs shows the following message:

```<code>2017-03-05T16:34:22.076383+00:00 app[worker.1]: Unknown command: 'celery'
</code>```

Here are my configurations:

__init.py__

```<code>from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']
</code>```

settings.py

```<code>INSTALLED_APPS = (
    ...
    'django_celery_beat',
)

if ENVIRONMENT == 'PROD':
    from settings_remote import *
else:
    from settings_local import *
</code>```

settings_remote.py

```<code>from __future__ import unicode_literals, absolute_import
import os
CELERY_BROKER_URL = os.environ['REDIS_URL']
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'
</code>```

celery.py

```<code>from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'terradiem.settings')
from django.conf import settings
app = Celery('terradiem')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))
</code>```

Procfile

```<code>web: gunicorn terradiem.wsgi --log-file -
worker: python manage.py celery worker --beat
</code>```

.env

```<code>REDIS_URL=redis://
</code>```

Any clue?

答:
In your Procfile, change:

```<code>worker: python manage.py celery worker --beat
</code>```

for:

```<code>worker: celery -A [nameOfYourApp] worker --beat
</code>```

and put the name of your django project in [nameOfYourApp].

It responds Unknown command: 'celery' because manage.py does not have a command name like that.

ContentLicense: CC BY-SA 3.0

Title: Install Celery & Redis with Heroku

Body:
I use Django 1.9, Python 2.7 and Heroku.

Celery 3 & Redis were working well, until I switched to Celery 4.0.2 and changed the configuration.

heroku logs shows the following message:

2017-03-05T16:34:22.076383+00:00 app[worker.1]: Unknown command: 'celery'

Here are my configurations:

__init.py__

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']

settings.py

INSTALLED_APPS = (
    ...
    'django_celery_beat',
)

if ENVIRONMENT == 'PROD':
    from settings_remote import *
else:
    from settings_local import *

settings_remote.py

from __future__ import unicode_literals, absolute_import
import os
CELERY_BROKER_URL = os.environ['REDIS_URL']
CELERY_ACCEPT_CONTENT = ['json']
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

celery.py

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'terradiem.settings')
from django.conf import settings
app = Celery('terradiem')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

Procfile

web: gunicorn terradiem.wsgi --log-file -
worker: python manage.py celery worker --beat

.env

REDIS_URL=redis://

Any clue?

Body:
In your Procfile, change:

worker: python manage.py celery worker --beat

for:

worker: celery -A [nameOfYourApp] worker --beat

and put the name of your django project in [nameOfYourApp].

It responds Unknown command: 'celery' because manage.py does not have a command name like that.


问:
How do I parse two arguments into two variables of type double?
I would like to know how to take two numbers that are separated by a comma (for example 8, 3) that are in the run arguments line and parse them into their own variables of type double.

For example, double var1 = 8 and double var2 = 3. I have tried to use parseDouble() to do it but since the string whose values I'm trying to parse into variable are in the run arguments line, Will I have to deal with the String args[] as the string I'm trying to parse?

答:
Try parseFloat:</p>

```<code>var1 = parseFloat("3.00") + "<br>";
var2 = parseFloat("8.00") + "<br>";
</code>```

Body:
Try parseFloat:

var1 = parseFloat("3.00") + "<br>";
var2 = parseFloat("8.00") + "<br>";


问:
Inject environment and system variables from gradle to Intellij run and debug mode
I have some environment variables defined in my build.gradle that I'd like IntelliJ to automatically load when I run/debug unit tests or other kinds of tests (including with coverage and individual test runs)

Example:

build.gradle

```<code>plugins {
    id 'org.unbroken-dome.test-sets' version '1.4.2'
}

apply plugin: 'java'
apply plugin: 'idea'

testSets {
    integrationTest {
        dirName = 'integration-test'
    }
}

test {
    environment 'MY_ENV_VAR_1', 'my_env_value_1'
}

integrationTest {
    environment 'MY_ENV_VAR_1', 'my_env_value_1000'
}
</code>```

test method (in both test and integration-test dirs)

```<code>@Test
public void test() {
    System.out.println(System.getenv("MY_ENV_VAR_1"));
}
</code>```

runs

gradle test prints out my_env_value_1

gradle integrationTest prints out my_env_value_1000

from IntelliJ: right click on the test and run -> prints nothing. Same for integration test.

I clicked the "Refresh all gradle projects" button in IntelliJ's gradle projects pane. No change.
The question isn't just scoped to environment variable. Ability to load system properties or others from gradle to any run/debug modes in IntelliJ would also be nice.

答:
IntelliJ doesn't support this directly. The best you can do is to generate the Intellij project files using the Idea plugin and update the gradle build file to tweak the output.

Environment variables in IntelliJ can be defined as part of the run configuration so you can tweak the gradle build to update the default run configuration for unit tests.

As  prototype, add the following to your build.gradle:

```<code>idea.workspace.iws.withXml { provider ->
def runManagerNode = provider.asNode().component.find {it.@name == 'RunManager'} as Node
def defaultConfigNode = runManagerNode.configuration.find {it.@default=='true' && it.@type=='JUnit'} as Node

def envsNode = defaultConfigNode.envs[0] as Node
envsNode.appendNode('env', [name: 'MY_ENV_VAR_1', value: test.environment.MY_ENV_VAR_1])
}
</code>```

Now run 'gradlew cleanIdea idea' and open up the resulting project.

Go to run->edit configurations->defaults->junit and you will see that the value of the environment variable has now been passed into IntelliJ.

This works as far as it goes but has a few problems that would need some thought/work:

As the workspace file isn't cleared down, you need to check if the 'env' node already existing before adding it.

I've hard coded the 'MY_ENV_VAR_1' name just to show that it works.

If you change the values, you will need to re-generate the Idea project files and delete any existing run configurations for JUnit so that they will pick up the new defaults.

I haven't thought of a way to distinguish between the test and integrationTest environment variables.

Body:
I have some environment variables defined in my build.gradle that I'd like IntelliJ to automatically load when I run/debug unit tests or other kinds of tests (including with coverage and individual test runs)

Example:

build.gradle

plugins {
    id 'org.unbroken-dome.test-sets' version '1.4.2'
}

apply plugin: 'java'
apply plugin: 'idea'

testSets {
    integrationTest {
        dirName = 'integration-test'
    }
}

test {
    environment 'MY_ENV_VAR_1', 'my_env_value_1'
}

integrationTest {
    environment 'MY_ENV_VAR_1', 'my_env_value_1000'
}

test method (in both test and integration-test dirs)

@Test
public void test() {
    System.out.println(System.getenv("MY_ENV_VAR_1"));
}

runs

gradle test prints out my_env_value_1

gradle integrationTest prints out my_env_value_1000

from IntelliJ: right click on the test and run -> prints nothing. Same for integration test.

I clicked the "Refresh all gradle projects" button in IntelliJ's gradle projects pane. No change.
The question isn't just scoped to environment variable. Ability to load system properties or others from gradle to any run/debug modes in IntelliJ would also be nice.

Body:
IntelliJ doesn't support this directly. The best you can do is to generate the Intellij project files using the Idea plugin and update the gradle build file to tweak the output.

Environment variables in IntelliJ can be defined as part of the run configuration so you can tweak the gradle build to update the default run configuration for unit tests.

As  prototype, add the following to your build.gradle:

idea.workspace.iws.withXml { provider ->
def runManagerNode = provider.asNode().component.find {it.@name == 'RunManager'} as Node
def defaultConfigNode = runManagerNode.configuration.find {it.@default=='true' && it.@type=='JUnit'} as Node

def envsNode = defaultConfigNode.envs[0] as Node
envsNode.appendNode('env', [name: 'MY_ENV_VAR_1', value: test.environment.MY_ENV_VAR_1])
}

Now run 'gradlew cleanIdea idea' and open up the resulting project.

Go to run->edit configurations->defaults->junit and you will see that the value of the environment variable has now been passed into IntelliJ.

This works as far as it goes but has a few problems that would need some thought/work:

As the workspace file isn't cleared down, you need to check if the 'env' node already existing before adding it.

I've hard coded the 'MY_ENV_VAR_1' name just to show that it works.

If you change the values, you will need to re-generate the Idea project files and delete any existing run configurations for JUnit so that they will pick up the new defaults.

I haven't thought of a way to distinguish between the test and integrationTest environment variables.


问:
Query to select and alternate records from 2 different tables
I'm trying to optimize some queries in a duplicate finder application in PHP CodeIgniter. And in order to keep the MVC pattern and stay away from DB calls directly in the views or controllers, I'm looking for a query that will alternate results from 2 different tables:

Table duplicate_leads

```<code>╔════╦══════════════╦═══════════╦════════════════════╦═══════════╗
║ id ║ original_id  ║    name   ║       email        ║   phone   ║
╠════╬══════════════╬═══════════╬════════════════════╬═══════════╣
║  1 ║      345     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║  2 ║      495     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚════╩══════════════╩═══════════╩════════════════════╩═══════════╝
</code>```

Table leads

```<code>╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝
</code>```

The duplicate_leads.original_id is the value that relates the lead to the original lead's leads.id.

Attempt #1

SELECT
    a.id,
    a.name,
    a.email,
    a.phone
FROM
    leads a
        JOIN duplicate_leads b
            ON a.id = b.original_id
```

<p>Which produces:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p>Seems to be retrieving records from one of the two tables. I don't have advanced experience in SQL so I don't know how exactly use the joins or unions for this particular case because I think that either way, what the query will return is a kind-of concatenation of result like this:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p><strong>What I'm actually expecting:</strong>
The rows shown first (because they could be multiple) should be records from the <code>leads</code> table. These records should be the ones that match the <code>original_id</code> of the <code>duplicate_leads</code> which should be the next row after the ones matched, like so:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

<p>Multiple matches example:</p>

```╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║ 677 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝
```

How can I achieve that result?

Update

SQL Fiddle: http://sqlfiddle.com/#!9/6d87a9/1

答:
Something like this:

```<code>SELECT id, name, email, phone
FROM (
    SELECT l.id, l.name, l.email, l.phone, dl.original_id
    FROM leads AS l
    JOIN duplicate_leads AS dl
        ON dl.original_id = l.id
    UNION ALL
    SELECT NULL AS id, dl.name, dl.email, dl.phone, dl.original_id
    FROM leads AS l
    JOIN duplicate_leads AS dl
        ON dl.original_id = l.id
) AS leads_combined
ORDER BY original_id ASC, id > 0 DESC, id ASC;
</code>```

should be closer to what you asked for. I've merged my previous query with the JOIN from Daniel Long's answer, to only find leads that have duplicates, and ordering the leads before the duplicates in the results.

Body:
I'm trying to optimize some queries in a duplicate finder application in PHP CodeIgniter. And in order to keep the MVC pattern and stay away from DB calls directly in the views or controllers, I'm looking for a query that will alternate results from 2 different tables:

Table duplicate_leads

╔════╦══════════════╦═══════════╦════════════════════╦═══════════╗
║ id ║ original_id  ║    name   ║       email        ║   phone   ║
╠════╬══════════════╬═══════════╬════════════════════╬═══════════╣
║  1 ║      345     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║  2 ║      495     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚════╩══════════════╩═══════════╩════════════════════╩═══════════╝

Table leads

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝

The duplicate_leads.original_id is the value that relates the lead to the original lead's leads.id.

Attempt #1

SELECT
    a.id,
    a.name,
    a.email,
    a.phone
FROM
    leads a
        JOIN duplicate_leads b
            ON a.id = b.original_id

Which produces:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

Seems to be retrieving records from one of the two tables. I don't have advanced experience in SQL so I don't know how exactly use the joins or unions for this particular case because I think that either way, what the query will return is a kind-of concatenation of result like this:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║
╚═════╩═══════════╩════════════════════╩═══════════╝

What I'm actually expecting:
The rows shown first (because they could be multiple) should be records from the leads table. These records should be the ones that match the original_id of the duplicate_leads which should be the next row after the ones matched, like so:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

Multiple matches example:

╔═════╦═══════════╦════════════════════╦═══════════╗
║ id  ║    name   ║       email        ║   phone   ║
╠═════╬═══════════╬════════════════════╬═══════════╣
║ 345 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║ 677 ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from leads
║     ║   Stack   ║ stack@overflow.com ║ 0000-0000 ║ from duplicate_leads
║ 495 ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from leads
║     ║ Exchange  ║ stack@exchange.com ║ 0000-0000 ║ from duplicate_leads
║ ... ║    ...    ║         ...        ║    ...    ║
╚═════╩═══════════╩════════════════════╩═══════════╝

How can I achieve that result?

Update

SQL Fiddle: http://sqlfiddle.com/#!9/6d87a9/1

Body:
Something like this:

SELECT id, name, email, phone
FROM (
    SELECT l.id, l.name, l.email, l.phone, dl.original_id
    FROM leads AS l
    JOIN duplicate_leads AS dl
        ON dl.original_id = l.id
    UNION ALL
    SELECT NULL AS id, dl.name, dl.email, dl.phone, dl.original_id
    FROM leads AS l
    JOIN duplicate_leads AS dl
        ON dl.original_id = l.id
) AS leads_combined
ORDER BY original_id ASC, id > 0 DESC, id ASC;

should be closer to what you asked for. I've merged my previous query with the JOIN from Daniel Long's answer, to only find leads that have duplicates, and ordering the leads before the duplicates in the results.


问:
XPath help needed for row text search column return on MorningStar
Need to extract some data from Html that looks like:

```<code><div class="r_tbar0 positionrelative">
    <h3>Financials</h3>
</div>
<table class="r_table1 text2" cellspacing="0" cellpadding="0">
    <thead>
        <tr>
            <th scope="row" align="left"></th>
            <th scope="col" id="Y0" align="right">2007-12</th>
            <th scope="col" id="Y1" align="right">2008-12</th>
            <!--More columns here-->
            <th scope="col" id="Y9" align="right">2016-12</th>
            <th scope="col" id="Y10" align="right">TTM</th>
        </tr>
    </thead>
    <tbody>
        <tr class="hr">
            <td colspan="12"></td>
        </tr>
        <tr>
            <th class="row_lbl" scope="row" id="i0">Revenue <span>USD Mil</span></th>
            <td headers="Y0 i0" align="right">5,858</td>
            <td headers="Y1 i0" align="right">5,808</td>
            <!--More cells here-->
            <td headers="Y9 i0" align="right">4,272</td>
            <td headers="Y10 i0" align="right">4,955</td>
        </tr>
        <tr class="hr">
            <td colspan="12"></td>
        </tr>
        <tr>
            <th class="row_lbl" scope="row" id="i1">Gross Margin %</th>
            <td headers="Y0 i1" align="right">37.4</td>
            <td headers="Y1 i1" align="right">39.9</td>
            <!--More cells here-->
            <td headers="Y9 i1" align="right">23.4</td>
            <td headers="Y10 i1" align="right">33.5</td>
        </tr>
        <!--More rows here-->
        <tr class="hr">
            <td colspan="12"></td>
        </tr>
    </tbody>
</table>
</code>```

I am looking to pull say the 2007 revenue data XPATH from the key ratios page by searching for the "Revenue" row then looking at the 2007 column.

XPATH Location of the 2007 revenue:

```<code>//*[@id="financials"]/table/tbody/tr[2]/td[1]
</code>```

The tr[2] represents the row that Revenue is aligned to. However, if I have a program that looks at multiple stocks I want to make sure that tr[2] still looks at revenue.

I have tried multiple versions of the following XPATH which returns a NULL value. (I am using XPATH helper a google chrome extension)

```<code>//*[@id="financials"]/table/tbody/tr[contains(text(),'Revenue')]/td[1]
</code>```

Outer html code for the Revenue row:

```<code><th class="row_lbl" scope="row" id="i0">Revenue <span>USD Mil</span></th>
</code>```

Outer html code for 2007 Revenue:

```<code><td align="right" headers="Y0 i0" class="">5,858</td>
</code>```

Update

Based on below answer I've written:

```<code>//*[@id='financials']//td[contains(@headers,'i0')][1]
</code>```

Pulls the 2017 Revenue data 5,858

答:
In "Financials" table, "Revenue" is a th, not a tr. You can get all cells in a column or row of that table by referencing the header attribute of td tags. Columns are Y0..Yn and rows are i0..in, for example:

First column has header Y0:

//*[@id='financials']//td[contains(@headers,'Y0')]

First row has header i0:

//*[@id='financials']//td[contains(@headers,'i0')]

And so on

Body:
Need to extract some data from Html that looks like:

Financials

            2007-12
            2008-12

            2016-12
            TTM

            Revenue USD Mil
            5,858
            5,808

            4,272
            4,955

            Gross Margin %
            37.4
            39.9

            23.4
            33.5

I am looking to pull say the 2007 revenue data XPATH from the key ratios page by searching for the "Revenue" row then looking at the 2007 column.

XPATH Location of the 2007 revenue:

//*[@id="financials"]/table/tbody/tr[2]/td[1]

The tr[2] represents the row that Revenue is aligned to. However, if I have a program that looks at multiple stocks I want to make sure that tr[2] still looks at revenue.

I have tried multiple versions of the following XPATH which returns a NULL value. (I am using XPATH helper a google chrome extension)

//*[@id="financials"]/table/tbody/tr[contains(text(),'Revenue')]/td[1]

Outer html code for the Revenue row:

Revenue USD Mil

Outer html code for 2007 Revenue:

5,858

Update

Based on below answer I've written:

//*[@id='financials']//td[contains(@headers,'i0')][1]

Pulls the 2017 Revenue data 5,858


问:
Why my youtube video doesn't report events?
Take a look at this code.  It actually loads the video perfectly, but it doesn't fire onPlayerStateChange when pausing, loading, or playing the video.

I've already implemented a function to print any new video status, but it doesn't even report events.

Why isn't the onPlayerStateChange firing?

Code from JSBin:

```<code><body>
    <script src="http://www.google.com/jsapi" type="text/javascript"></script>
    <script type="text/javascript">
        google.load("swfobject", "2.1");
    </script>

    <script>

        function onYouTubePlayerReady(playerId) {
            var myplayer = document.getElementById("myplayer");
            myplayer.cueVideoById("pGBMFxN_eys",0, "default");
            myplayer.addEventListener("onStateChange", onPlayerStateChange);
        }

        function onPlayerStateChange(newState){
            log(newstate);
        }

        function log(text){
        document.getElementById('logarea').innerHTML+=text+"<br/>";
        console.log(text);
        }

        function setup(){
        var params = { allowScriptAccess: "always",wmode:"transparent" };
        var atts = { id: "myplayer" };
        swfobject.embedSWF("http://www.youtube.com/apiplayer?" +
                      "&enablejsapi=1&playerapiid=mojplayer",
       "greatvideo", "400", "300", "8", null, null, params, atts);
        }

        google.setOnLoadCallback(setup);
    </script>

<div id="logarea">
</div>

<div id="greatvideo">
</div>

</body>
</code>```

答:
There are two bugs in your code that are preventing this from working.  Once you make these changes, you'll see the following output above your YouTube video:

```<code> 5
 3
 1
 0
</code>```

The bugs are as follows:

Use quotes around callback, or use an anonymous function:

```<code> // put callback in quotes or anonymous function
 myplayer.addEventListener("onStateChange", "onPlayerStateChange");
</code>```

Make sure parameter matches local variable passed to log function:

```<code> function onPlayerStateChange(newState){
        log(newState);  // variables are case sensitive
 }
</code>```

NOTE: addEventListener may not work in IE browsers.  I'm running Ubuntu and don't have IE available, but you may need to use browser detection to use attachEvent in IE browsers.  This was tested on Chrome 8.0.

I also signed up for a jsapi key.  The documentation was unclear as one google page said the API Key was required to use Google Loader, while the API page itself said it was not required.  You may not need to obtain a key, but if you still have trouble after making the above changes, I would suggest you obtain a key to rule out this variable in the equation.

http://code.google.com/apis/loader/signup.html

Resources:

YouTube Adding Event Listeners

YouTube EventListener Player Demo

UPDATE: This works in Chrome 8.0, Firefox 3.6, and IE8.  It does not work in IE7.  But instead of wasting energy on a dead browser, do the community a favor and redirect those small subset of users to an upgrade link so they can join the year 2011. :)  The IE7 build I used is part of IECollections and is not the real IE7.

If you have a subset of users who, for whatever reason, are tied to older versions of IE7, and you wish to support these users, please see javascript addEventListener onStateChange not working in IE

ContentLicense: CC BY-SA 4.0

Body:
There are two bugs in your code that are preventing this from working.  Once you make these changes, you'll see the following output above your YouTube video:

 5
 3
 1
 0

The bugs are as follows:

Use quotes around callback, or use an anonymous function:

 // put callback in quotes or anonymous function
 myplayer.addEventListener("onStateChange", "onPlayerStateChange");

Make sure parameter matches local variable passed to log function:

 function onPlayerStateChange(newState){
        log(newState);  // variables are case sensitive
 }

NOTE: addEventListener may not work in IE browsers.  I'm running Ubuntu and don't have IE available, but you may need to use browser detection to use attachEvent in IE browsers.  This was tested on Chrome 8.0.

I also signed up for a jsapi key.  The documentation was unclear as one google page said the API Key was required to use Google Loader, while the API page itself said it was not required.  You may not need to obtain a key, but if you still have trouble after making the above changes, I would suggest you obtain a key to rule out this variable in the equation.

http://code.google.com/apis/loader/signup.html

Resources:

YouTube Adding Event Listeners

YouTube EventListener Player Demo

UPDATE: This works in Chrome 8.0, Firefox 3.6, and IE8.  It does not work in IE7.  But instead of wasting energy on a dead browser, do the community a favor and redirect those small subset of users to an upgrade link so they can join the year 2011. :)  The IE7 build I used is part of IECollections and is not the real IE7.

If you have a subset of users who, for whatever reason, are tied to older versions of IE7, and you wish to support these users, please see javascript addEventListener onStateChange not working in IE


问:
Register an internal package on Pypi
I read somewhere that if you make an internal Python package for proprietary work, you should still register the name on PyPi to avoid potential future dependency issues.

How do I do this without posting my code publicly? This package contains code to be used internally at my work. Should I make an empty python package using the name I want to reserve and upload that to PyPi? And then install my package at work using git instead of PyPi?

Uploading an empty package seems like a silly thing to do that would just annoy other people. But I can't find a way to just register the name.

答:
Does not make to much sense to register in the community index a package that is not public for the community.

To reduce chances of future conflicts, I would prefix the package name with something related to your company (I.e: the name or alias). For instance: mycompany-eventualconflictingname.

Eventually, if you want to make the package public, you will need to update your internal clients requirements. But that seems less worrying than having a name conflict.

Title: Register an internal package on Pypi


问:
Automatically update id variable in two controllers using $broadcast in AngularJS
```<code>$ctrl.clicker = function(id)
{
   $rootScope.$broadcast('idBull', id);
}
</code>```

When I mouseenter an image the above function gets called. I want to share the id in another controller and broadcast whatever changes where made to this id.

```<code>$scope.$on('idBull', function (event, data) {
  console.log(data); // 'Data to send'
});
</code>```

In the other controller I used the code to do a console loge of my id but got no results.

答:
Not sure why you are not getting your code to work, maybe the controller with $scope.$on is not created/loaded when the $rootScope.$broadcast is executed?

Another solution is to use a service that you inject into both controllers and use that for communication instead. Example of broadcast solution:

```<code>var app = angular.module("app", [])
.controller("ControllerA", function($scope, $rootScope)
{
    $scope.clicker = function(id)
    {
        $rootScope.$broadcast("id changed", id);
    }
})
.controller("ControllerB", function($scope)
{
    $scope.$on("id changed", function(event, id)
    {
        // Do whatever you need to do with id
    });
});
</code>```

Example of solution with custom service:

```<code>var app = angular.module("app", [])
.factory("customService", function()
{
    var callbacks = [];

    return {
        onIdChange: function(callback)
        {
            callbacks.push(callback);
        },
        idChanged: function(id)
        {
            callbacks.forEach(function(callback)
            {
                callback(id);
            });
        }
    };
})
.controller("ControllerA", function($scope, customService)
{
    $scope.clicker = function(id)
    {
        customService.idChanged(id);
    }
})
.controller("ControllerB", function(customService)
{
    customService.onIdChange(function(id)
    {
        // Do whatever you need to do with id
    });
});
</code>```

Body:
$ctrl.clicker = function(id)
{
   $rootScope.$broadcast('idBull', id);
}

When I mouseenter an image the above function gets called. I want to share the id in another controller and broadcast whatever changes where made to this id.

$scope.$on('idBull', function (event, data) {
  console.log(data); // 'Data to send'
});

In the other controller I used the code to do a console loge of my id but got no results.

Body:
Not sure why you are not getting your code to work, maybe the controller with $scope.$on is not created/loaded when the $rootScope.$broadcast is executed?

Another solution is to use a service that you inject into both controllers and use that for communication instead. Example of broadcast solution:

var app = angular.module("app", [])
.controller("ControllerA", function($scope, $rootScope)
{
    $scope.clicker = function(id)
    {
        $rootScope.$broadcast("id changed", id);
    }
})
.controller("ControllerB", function($scope)
{
    $scope.$on("id changed", function(event, id)
    {
        // Do whatever you need to do with id
    });
});

Example of solution with custom service:

var app = angular.module("app", [])
.factory("customService", function()
{
    var callbacks = [];

    return {
        onIdChange: function(callback)
        {
            callbacks.push(callback);
        },
        idChanged: function(id)
        {
            callbacks.forEach(function(callback)
            {
                callback(id);
            });
        }
    };
})
.controller("ControllerA", function($scope, customService)
{
    $scope.clicker = function(id)
    {
        customService.idChanged(id);
    }
})
.controller("ControllerB", function(customService)
{
    customService.onIdChange(function(id)
    {
        // Do whatever you need to do with id
    });
});


问:
Bash ranges of non digit or letters
I played around with bash {..} constructs today. I knew

```<code>{a..z}
</code>```

would generate all letters,

```<code>{0..9}
</code>```

digits etc. (numbers in general obviously), but By mistake I got

```<code>{Z..a}
</code>```

yielding:

```<code>Z [  ] ^ _ ` a
</code>```

The characters in between "Z" (90) and "a" (97) are the ASCII 91-96. The astute reader will notice there is a character missing - "\", 92. I'm guessing because of it's special nature. Is this expected behavior as output? Specifically, I'm guessing the \ is being used to escape the space in front of it after substitution, but @John1024 notes that:

```<code>echo {Z..a}a
</code>```

will complain on missing backticks, while the previous version (no a) does not. How exactly is substitution working? Is there a bug?

Second, I guessed the range operator is cooler than I thought and can do any range of ASCII characters I choose, but {[.._} for example fails. Am I missing something to make this work or is this just a curiosity? Are there any more ranges besides letters/digits I can use? and if not, why not do nothing (fail, echo as is) for 'jumping' from caps to lower?

答:
The \ is being generated; however, it subsequently appears to be treated as escaping the following space. Compare:

```<code>$ printf '%s\n' 'Z' '[' ']' '^' '_' '`' 'a'
Z
[
]
^
_
`
a
$ printf '%s\n' {Z..a}
Z
[

]
^
_
`
a
</code>```

The extra blank line following the [ is the space escaped by the backslash generated by {Z..a}.

Title: Bash ranges of non digit or letters

Body:
I played around with bash {..} constructs today. I knew

{a..z}

would generate all letters,

{0..9}

digits etc. (numbers in general obviously), but By mistake I got

{Z..a}

yielding:

Z [  ] ^ _ ` a

The characters in between "Z" (90) and "a" (97) are the ASCII 91-96. The astute reader will notice there is a character missing - "\", 92. I'm guessing because of it's special nature. Is this expected behavior as output? Specifically, I'm guessing the \ is being used to escape the space in front of it after substitution, but @John1024 notes that:

echo {Z..a}a

will complain on missing backticks, while the previous version (no a) does not. How exactly is substitution working? Is there a bug?

Second, I guessed the range operator is cooler than I thought and can do any range of ASCII characters I choose, but {[.._} for example fails. Am I missing something to make this work or is this just a curiosity? Are there any more ranges besides letters/digits I can use? and if not, why not do nothing (fail, echo as is) for 'jumping' from caps to lower?

Body:
The \ is being generated; however, it subsequently appears to be treated as escaping the following space. Compare:

$ printf '%s\n' 'Z' '[' ']' '^' '_' '`' 'a'
Z
[
]
^
_
`
a
$ printf '%s\n' {Z..a}
Z
[

]
^
_
`
a

The extra blank line following the [ is the space escaped by the backslash generated by {Z..a}.


问:
How to simplify imports in Kivy
My starting code often looked like this:

```<code>import libs.apa_database
import inspect
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, StringProperty, Property
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.clock import Clock
</code>```

So, I wondered if there were a way to reduce the clutter like this:

```<code>from system_assets import APADatabase, App, Clock
from layout_assets import App, BoxLayout, GridLayout, ScrollView
from screen_assets import ScreenManager, Screen, FadeTransition
from interface_assets import DropDow, Button,
</code>```

答:
The answer is "yes":

Create new Python files as a "folder" to hold your imports

Add the import statements to that Python file

Import the assets from that file

(Will update this Q with more detail when I have time.)

Title: How to simplify imports in Kivy

Body:
My starting code often looked like this:

import libs.apa_database
import inspect
from kivy.app import App
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.gridlayout import GridLayout
from kivy.uix.scrollview import ScrollView
from kivy.properties import ObjectProperty, StringProperty, Property
from kivy.uix.screenmanager import ScreenManager, Screen, FadeTransition
from kivy.uix.dropdown import DropDown
from kivy.uix.button import Button
from kivy.clock import Clock

So, I wondered if there were a way to reduce the clutter like this:

from system_assets import APADatabase, App, Clock
from layout_assets import App, BoxLayout, GridLayout, ScrollView
from screen_assets import ScreenManager, Screen, FadeTransition
from interface_assets import DropDow, Button,


问:
Webpack 3 and importing fonts in CSS

I'm building a webpack app using Backbone and attempting to import my CSS with a line like

```<code>import './css/style.css';
</code>```

However my CSS file uses a True Type font.

```<code>@font-face {
  font-family: "Scramble";
  src: url(./scramble/Scramble.ttf) format("truetype");
}
</code>```

How can I tell webpack where to find the font?  Do I need another loader?

Currently I get:

```<code>Module not found: Error: Can't resolve './scramble/Scramble.ttf'
</code>```

答:
Webpack needs to know how to load that kind of asset. npm install url-loader and add the below rule to your webpack configuration which resolves common font file extensions.

```<code>rules : [
  {
    test: /\.(woff|woff2|ttf|eot)$/,
    use: [
      {
        loader: 'url-loader',
        options: {
          limit: 10000,
          mimetype: 'application/octet-stream'
        }
      }
    ]
  }
 // more rules
]
</code>```

Title: Webpack 3 and importing fonts in CSS

Body:
I'm building a webpack app using Backbone and attempting to import my CSS with a line like

import './css/style.css';

However my CSS file uses a True Type font.

@font-face {
  font-family: "Scramble";
  src: url(./scramble/Scramble.ttf) format("truetype");
}

How can I tell webpack where to find the font?  Do I need another loader?

Currently I get:

Module not found: Error: Can't resolve './scramble/Scramble.ttf'

Body:
Webpack needs to know how to load that kind of asset. npm install url-loader and add the below rule to your webpack configuration which resolves common font file extensions.

rules : [
  {
    test: /\.(woff|woff2|ttf|eot)$/,
    use: [
      {
        loader: 'url-loader',
        options: {
          limit: 10000,
          mimetype: 'application/octet-stream'
        }
      }
    ]
  }
 // more rules
]


问:
STL and release/debug library mess
I'm using some 3rd party. I'm using it's shared library version, since the library is big (~60MB) and is used by several applications.

Is there a way at application startup to find out that release/debug version of library is used respectively for release/debug version of my application?

Longer description

The library which exposes C++ interface. One of API methods return std::vector<std::string>.

The problem when I compile my application in debug mode, debug version of the library should be used. Same for release. If incorrect version of the library is used application is crashed.

According to gcc (see http://gcc.gnu.org/onlinedocs/libstdc++/manual/bk01pt03ch17s04.html)

but with a mixed mode standard library
  that could be using either debug-mode
  or release-mode basic_string objects,
  things get more complicated

P.S. 1

It looks like proposal of Timbo is a possible solution - use different soname for debug and release libraries. So, what should be passed to ./configure script to change library soname?

P.S. 2

My problem is not at link time, but rather at run time.

P.S. 3

Here is question demonstrating problem I is facing with.

答:
The debug mode referenced here has nothing to do with debug or release build of your application. The STL debug mode is activated with -D_GLIBCXX_DEBUG and is a special checking mode.

It is very unlikely that the 3rd party library was in fact compiled with STL checking mode, but if it was, it would likely very promptly mention that your code should also be compiled with -D_GLIBCXX_DEBUG.

If the 3rd party library was not built with checking STL, then it is compatible with your code regardless of whether you are doing optimized or debug build.

Since you state that debug build of your code linked with optimized build of 3rd party library causes a crash, that crash is most likely caused by a bug in your code (or possibly by a bug in 3rd party library).

Valgrind and GDB are your friends.

Title: STL and release/debug library mess


问:
Exclude Lambda function from deploy to a particular stage
I am trying to exclude a Lambda function from being deployed via serverless to my prod stage within AWS.

A snippet from my serverless yaml looks something like -

```<code>functions:
  some-prod-function:
    handler: prodFunction.handler
    events:
      - http:
          path: /prod-function
          method: post
  some-dev-function:
    handler: devFunction.handler
    events:
      - http:
          path: /dev-function
          method: post
</code>```

Is there a way to exclude some-dev-function from being deployed to prod?

答:
You can put those definitions on a different property and use variables in order to choose which definitions to use.

```<code>environment-functions:
  prod:
    some-prod-function:
      handler: prodFunction.handler
      events:
        - http:
            path: /prod-function
            method: post
  dev:
    some-dev-function:
      handler: devFunction.handler
      events:
        - http:
            path: /dev-function
            method: post

functions: ${self:environment-functions.${opt:stage}}
</code>```

You may need to change this depending on how you specify your stage on deployment (${opt:stage} or ${env:stage}).

Body:
I am trying to exclude a Lambda function from being deployed via serverless to my prod stage within AWS.

A snippet from my serverless yaml looks something like -

functions:
  some-prod-function:
    handler: prodFunction.handler
    events:
      - http:
          path: /prod-function
          method: post
  some-dev-function:
    handler: devFunction.handler
    events:
      - http:
          path: /dev-function
          method: post

Is there a way to exclude some-dev-function from being deployed to prod?

Body:
You can put those definitions on a different property and use variables in order to choose which definitions to use.

environment-functions:
  prod:
    some-prod-function:
      handler: prodFunction.handler
      events:
        - http:
            path: /prod-function
            method: post
  dev:
    some-dev-function:
      handler: devFunction.handler
      events:
        - http:
            path: /dev-function
            method: post

functions: ${self:environment-functions.${opt:stage}}

You may need to change this depending on how you specify your stage on deployment (${opt:stage} or ${env:stage}).


问:
How can I change a method's return type based on an argument value?
How can I change this method's return type based on the value of returnType?
I want to return ints, floats, and decimals, without creating separate methods for each one. Specifically, how can I change the decimal in the first line based on the value of returnType??

```<code>public static decimal RequestNumber(string returnType)
    {
        Console.WriteLine(inputRequest);

        decimal result;

        switch(returnType)
        case decimal:
            bool parsed = decimal.TryParse(Console.ReadLine(), out result);
        case int:
            bool parsed = int.TryParse(Console.ReadLine(), out result);
        case single:
            bool parsed = single.TryParse(Console.ReadLine(), out result);
        return result;
    }
</code>```

Any help would be much appreciated!

答:
You could use object type and then cast the return result when calling;

```<code>private static object duo(string req)
{

    if (req == "Y")
    {
        string s = "Type String";
        return s;
    }
    else
    {
        List < string > l  = new List<string> { "Type", "List" };

        return l;
    }
}
</code>```

Then to use it:

```<code>List<string> res = (List<string>)duo("H");
</code>```

Body:
How can I change this method's return type based on the value of returnType?
I want to return ints, floats, and decimals, without creating separate methods for each one. Specifically, how can I change the decimal in the first line based on the value of returnType??

public static decimal RequestNumber(string returnType)
    {
        Console.WriteLine(inputRequest);

        decimal result;

        switch(returnType)
        case decimal:
            bool parsed = decimal.TryParse(Console.ReadLine(), out result);
        case int:
            bool parsed = int.TryParse(Console.ReadLine(), out result);
        case single:
            bool parsed = single.TryParse(Console.ReadLine(), out result);
        return result;
    }

Any help would be much appreciated!

Body:
You could use object type and then cast the return result when calling;

private static object duo(string req)
{

    if (req == "Y")
    {
        string s = "Type String";
        return s;
    }
    else
    {
        List < string > l  = new List<string> { "Type", "List" };

        return l;
    }
}

Then to use it:

List<string> res = (List<string>)duo("H");


问:
How to import SQL database from PC to Android app
I'm working on Android app which will use SQL database. I created the database with data on my PC. I have SQL dump file for this database. I would like to use this dump file to create and use SQLite database as a part of the app. How could I achieve this? I will appreciate the hints.

Thanks!

答:
You can Converts your MySQL dump to SQLite3 compatible dump using this link as . You must have git and GitHub installed on your computer . please use this link Sql to SQLite
Worked fine for me , Good Luck</p>


问:
Which one to use: Java Swing or GTK+ for GNOME desktop application?
I am considering developing a GNOME desktop application with a graphical user interface. I know GTK+ is the first choice, especially when developing for the GNOME environment. End users also consider GTK+ as the first choice for applications they use. I am, however, considering future improvements: what if my application will need a port to another environments or OS like KDE or Mac or Windows? Which is the best way to go: Java Swing (because it's platform independent) or GTK+?</p>

答:
```<code>UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI( this );
</code>```

On *nix variants, that should produce the GTK PLAF in Swing.  On Apple(1) it will probably produce a theme with 'Aqua' in the name, and on Windows(1) it will be something like 'Windows'.

1) I doubt that Windows or Apple users want to see a 'GTK look' app. on their desk-top. ;)

Body:
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
SwingUtilities.updateComponentTreeUI( this );

On *nix variants, that should produce the GTK PLAF in Swing.  On Apple(1) it will probably produce a theme with 'Aqua' in the name, and on Windows(1) it will be something like 'Windows'.

1) I doubt that Windows or Apple users want to see a 'GTK look' app. on their desk-top. ;)


问:
css is hover not working on class
I'm trying to get a bar to transition in when the li is hovered over however the hover seems to be ignored and nothing happens. If I instead put 'nav ul:hover', it works but the bar pops in under all the li's.

```<code><nav>
  <ul>
    <li class="nav-li">All Departments</li>
    <li class="nav-li">Shop by Room</li>
    <li class="nav-li">DIY Projects & Ideas</li>
    <li class="nav-li">Home Services</li>
    <li class="nav-li">Speacials & Offers</li>
    <li class="nav-li">Local Ad</li>
  </ul>
</nav>
</code>```

CSS

```<code>.nav-li {
margin-right: 40px;
display: inline-block;
padding-bottom: 2em;
transition: all .5s ease;
cursor: pointer;
position: relative;
}

.nav-li::after {
content: "";
display: block;
position: absolute;
left: 0;
bottom: 0;
height: 3px;
width: 0;
transition: width .5s ease;
}

.nav-li:hover .nav-li::after {
background-color: #f96302;
width: 100%;
}
</code>```

答:
The .nav-li:hover .nav-li::after should be .nav-li:hover::after

.nav-li {
  margin-right: 40px;
  display: inline-block;
  padding-bottom: 2em;
  transition: all .5s ease;
  cursor: pointer;
  position: relative;
}

.nav-li::after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 0;
  transition: width .5s ease;
}

.nav-li:hover::after {
  background-color: #f96302;
  width: 100%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav>
  <ul>
    <li class="nav-li">All Departments</li>
    <li class="nav-li">Shop by Room</li>
    <li class="nav-li">DIY Projects & Ideas</li>
    <li class="nav-li">Home Services</li>
    <li class="nav-li">Speacials & Offers</li>
    <li class="nav-li">Local Ad</li>
  </ul>
</nav></code>```

Title: css is hover not working on class

Body:
I'm trying to get a bar to transition in when the li is hovered over however the hover seems to be ignored and nothing happens. If I instead put 'nav ul:hover', it works but the bar pops in under all the li's.

All Departments

Shop by Room

DIY Projects & Ideas

Home Services

Speacials & Offers

Local Ad

CSS

.nav-li {
margin-right: 40px;
display: inline-block;
padding-bottom: 2em;
transition: all .5s ease;
cursor: pointer;
position: relative;
}

.nav-li::after {
content: "";
display: block;
position: absolute;
left: 0;
bottom: 0;
height: 3px;
width: 0;
transition: width .5s ease;
}

.nav-li:hover .nav-li::after {
background-color: #f96302;
width: 100%;
}

Body:
The .nav-li:hover .nav-li::after should be .nav-li:hover::after

.nav-li {
  margin-right: 40px;
  display: inline-block;
  padding-bottom: 2em;
  transition: all .5s ease;
  cursor: pointer;
  position: relative;
}

.nav-li::after {
  content: "";
  display: block;
  position: absolute;
  left: 0;
  bottom: 0;
  height: 3px;
  width: 0;
  transition: width .5s ease;
}

.nav-li:hover::after {
  background-color: #f96302;
  width: 100%;
}

<nav>
  <ul>
    <li class="nav-li">All Departments</li>
    <li class="nav-li">Shop by Room</li>
    <li class="nav-li">DIY Projects & Ideas</li>
    <li class="nav-li">Home Services</li>
    <li class="nav-li">Speacials & Offers</li>
    <li class="nav-li">Local Ad</li>
  </ul>
</nav>


问:
UITableView in UIPopover hides content while displaying keyboard
I have a UITableView embedded in a UIPopoverController, as shown below.

When I select a cell, the textField in the cell becomes firstResponder. But instead of keeping the tableview scrolled to the top, all content goes away (even though there are no more than 4 cells). It is impossible to scroll to the top will this happens. After dismissing the keyboard everything is normal again.

The following code does not resolve the problem:

```<code>- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CRShoppingListItemCell *cell = (CRShoppingListItemCell *) [tableView   cellForRowAtIndexPath:indexPath];
    cell.itemTextField.enabled = YES;
    cell.itemTextField.delegate = self;
    [cell.itemTextField becomeFirstResponder];
    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
</code>```

答: My guess is you aren't using the UITableViewController. Inside that controller's viewWillAppear it checks for isInViewControllerThatHandlesKeyboardAvoidance (private) and one of those controllers is the popover controller. So if it is that then the keyboard avoiding behaviour you would usually want when the table is full screen is turned off.</p>

Body:
I have a UITableView embedded in a UIPopoverController, as shown below.

When I select a cell, the textField in the cell becomes firstResponder. But instead of keeping the tableview scrolled to the top, all content goes away (even though there are no more than 4 cells). It is impossible to scroll to the top will this happens. After dismissing the keyboard everything is normal again.

The following code does not resolve the problem:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    CRShoppingListItemCell *cell = (CRShoppingListItemCell *) [tableView   cellForRowAtIndexPath:indexPath];
    cell.itemTextField.enabled = YES;
    cell.itemTextField.delegate = self;
    [cell.itemTextField becomeFirstResponder];
    [tableView scrollToNearestSelectedRowAtScrollPosition:UITableViewScrollPositionNone animated:YES];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


问:
Batch looping an if statement on the same line
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

```<code>if exist "*%num%*" (set /a num+=jump)
</code>```

update

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%
</code>```

答:
What is sounds like you are attempting to do is:

```<code>WHILE IF NOT EXIST "*%num%*" SET /A num+=jump
</code>```

There is no such thing. You have a very limited amount of usable commands to program with in a batch file. Here is all the commands you can use.

What you can do to get it onto 2 lines is this

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

:loop
if exist "*%num%*" (set /a num+=jump & GOTO loop)

MD %num%_%usrname%
</code>```

And if you really want to shorten it up you can use conditional execution. When the directory already exists, increment the number and goto the loop.

```<code>@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

:loop
MD "%num%_%usrname%" 2>nul || (set /a num+=jump & GOTO loop)
</code>```

Body:
I want to loop the if exist line once so that the line will run continuously until a unused sequential number is found (it has to loop on the same line so it becomes part of the if statement). Is there a better way to achieve this ?

if exist "*%num%*" (set /a num+=jump)

update

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

if exist "*%num%*" (set /a num+=jump)

MD %num%_%usrname%

Body:
What is sounds like you are attempting to do is:

WHILE IF NOT EXIST "*%num%*" SET /A num+=jump

There is no such thing. You have a very limited amount of usable commands to program with in a batch file. Here is all the commands you can use.

What you can do to get it onto 2 lines is this

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

:loop
if exist "*%num%*" (set /a num+=jump & GOTO loop)

MD %num%_%usrname%

And if you really want to shorten it up you can use conditional execution. When the directory already exists, increment the number and goto the loop.

@echo off
set /p usrname=enter folder name
set /a num=100
set /a jump=10

:loop
MD "%num%_%usrname%" 2>nul || (set /a num+=jump & GOTO loop)


问:
Change binary search tree to balance
I have just learnt how to create a binary search data structure, which is going to be used to store thousands of words from a dictionary. The problem that I am getting is that it is taking a long time to count add and remove data. Usually 199263ms or 200 seconds for 100000 words to count. I was told that having a tree that can self balance will improve the efficiency and make the operations faster.

My question is how can I make my tree auto balance so to make it efficient. I have made slight improvements by eliminating duplicate words to make the height of the tree to be shorter.

If someone can give me advice on how i can make the tree efficient and how I can implement balancing tree in java will be helpful.

答:
To balance a binary tree, it may be easier to just construct a new one, adding elements in a better order

```<code>BinaryTree balance(BinaryTree tree)
{
    BinaryTree out = new BinaryTree();
    String[] values = tree.toArray(); //a sorted array
    for(int i = Integer.highestOneBit(values.length); i > 0; i >>= 1)
        for(int j = i; j <= values.length; j += i)
            out.add(values[j - 1]);
    return out;
}
</code>```

By extension of this, if the words read in do not need to be put into a tree and sorted right away, Arrays.sort(Object[]) is likely to be faster

```<code>List<String> wordList = new LinkedList<String>();
BufferedReader reader = [...];
for(String line = reader.readLine(); line != null; line = reader.readLine())
    wordList.add(line);
String[] words = wordList.toArray(new String[0]);
Arrays.sort(words);
BinaryTree tree = new BinaryTree();
for(int i = Integer.highestOneBit(words.length); i > 0; i >>= 1)
    for(int j = i; j <= words.length; j += i)
        out.add(words[j - 1]);
</code>```

Depending on what you're actually using this data for (just a lookup table?) it may be faster to use a HashSet instead

```<code>Set<String> dict = new HashSet<String>();
BufferedReader reader = [...];
for(String line = reader.readLine(); line != null; line = reader.readLine())
    dict.add(line);
</code>```

Title: Change binary search tree to balance

Body:
To balance a binary tree, it may be easier to just construct a new one, adding elements in a better order

BinaryTree balance(BinaryTree tree)
{
    BinaryTree out = new BinaryTree();
    String[] values = tree.toArray(); //a sorted array
    for(int i = Integer.highestOneBit(values.length); i > 0; i >>= 1)
        for(int j = i; j <= values.length; j += i)
            out.add(values[j - 1]);
    return out;
}

By extension of this, if the words read in do not need to be put into a tree and sorted right away, Arrays.sort(Object[]) is likely to be faster

List<String> wordList = new LinkedList<String>();
BufferedReader reader = [...];
for(String line = reader.readLine(); line != null; line = reader.readLine())
    wordList.add(line);
String[] words = wordList.toArray(new String[0]);
Arrays.sort(words);
BinaryTree tree = new BinaryTree();
for(int i = Integer.highestOneBit(words.length); i > 0; i >>= 1)
    for(int j = i; j <= words.length; j += i)
        out.add(words[j - 1]);

Depending on what you're actually using this data for (just a lookup table?) it may be faster to use a HashSet instead

Set<String> dict = new HashSet<String>();
BufferedReader reader = [...];
for(String line = reader.readLine(); line != null; line = reader.readLine())
    dict.add(line);


问:
AWS S3 Bucket Policy - Allow GetObject only within a prefix
I'm trying to put a policy on my bucket to allow public 'GetObject' access on my objects, but only those within a certain prefix.  Like this:

```<code>    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::mybucket/publicstuff/*"
    }
</code>```

The problem is, AWS warns me that this makes the entire bucket public.  And sure enough, it does; if I try to GET an object from /mybucket/anywhereelse/, S3 serves it up freely.  So everything after 'mybucket' is ignored.

Is there any way to build a bucket policy applicable to a specific prefix within the bucket?  I tried a policy condition, but found the s3:prefix cannot be used when using the s3:GetObject action.

答: Thanks @michael and @mok, I've found the answer: I'm a moron.  The other objects that I used to verify the standard behavior happen to have individual permissions on them to allow getObject, and I didn't remember putting them there or notice them being there.  When I removed these permissions, It appeared I could still access these objects, but I was actually picking up cached copies.  When removing these spurious permissions, and using a completely different browser, I verified that my originally posted policy was correct.  Sorry for the trouble. </p>

Body:
I'm trying to put a policy on my bucket to allow public 'GetObject' access on my objects, but only those within a certain prefix.  Like this:

    {
        "Effect": "Allow",
        "Principal": "*",
        "Action": "s3:GetObject",
        "Resource": "arn:aws:s3:::mybucket/publicstuff/*"
    }

The problem is, AWS warns me that this makes the entire bucket public.  And sure enough, it does; if I try to GET an object from /mybucket/anywhereelse/, S3 serves it up freely.  So everything after 'mybucket' is ignored.

Is there any way to build a bucket policy applicable to a specific prefix within the bucket?  I tried a policy condition, but found the s3:prefix cannot be used when using the s3:GetObject action.


问:
asp.net mvc vs javascript build whole site
i am building a site. There are two choices for me.

asp.net mvc 3.0 + ajax.

build whole site with ajax(javascript). Firstly, use ajax to get data with json format, and   then fill the whole page with the data. In this way, the page will be produced only via javascript.

Could anyone tell me the advantages and disadvantages of these two ways?

Thanks in advance.

答: If you choose the second option, it won't work in browsers with no JavaScript support. This may not seem all that important to you, but consider: most search engines don't support JavaScript. If search engines can't get the content on your site, it won't get ranked well.</p>


问:
Read remote file beginning with "smb://" using R
To read a file in R, I'd normally do something like the following:

```<code>read.csv('/Users/myusername/myfilename.csv')
</code>```

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

```<code>read.csv('smb://server.msu.edu/.../myfilename.csv')
</code>```

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

答:
TL;DR

Here's a portable approach that uses cURL and doesn't require mounting remote filesystems:

```<code>> install.packages("curl")
> require("curl")
> handle <- new_handle()
> handle_setopt(handle, username = "domain\\username")
> handle_setopt(handle, password = "secret") # If needed
> request <- curl_fetch_memory("smb://host.example.com/share/file.txt", handle = handle)
> contents <- rawToChar(request$content)
</code>```

If we need to read the contents as CSV, like in the question, we can stream the file through another function:

```<code>> stream <- curl("smb://host.example.com/share/file.txt", handle = handle)
> contents <- read.csv(stream)
</code>```

Let's take a look at a more robust way to access remote files through smb:// URLs besides the approach described in other answers that mounts the remote filesystem. Unfortunately, I'm a bit late to this one, but I hope this helps future readers.

In some cases, we may not have the privileges needed to mount a filesystem (this requires admin or root access on many systems), or we simply may not want to mount an entire filesystem just to read a single file. We'll use the cURL library to read the file instead. This approach improves the flexibility and portability of our programs because we don't need to depend on the existence of an externally mounted filesystem. We'll examine two different ways: through a system() call, and by using a package that provides a cURL API.

Some background: for those not familiar with it, cURL provides tools used to transfer data over various protocols. Since version 7.40, cURL supports the SMB/CIFS protocol typically used for Windows file-sharing services. cURL includes a command-line tool that we can use to fetch the contents of a file:

```<code>$ curl -u 'domain\username' 'smb://host.example.com/share/file.txt'
</code>```

The command above reads and outputs (to STDOUT) the contents of file.txt from the remote server host.example.com authenticating as the specified user on the domain. The command will prompt us for a password if needed. We can remove the domain portion from the username if our network doesn't use a domain.

System Call

We can achieve the same functionality in R by using the system() function:

```<code>system("curl -u 'domain\\username' 'smb://host.example.com/share/file.txt'")
</code>```

Note the double backslash in domain\\username. This escapes the backslash character so that R doesn't interpret it as an escape character in the string. We can capture file contents from the command output into a variable by setting the intern parameter of the system() function to TRUE:

```<code>contents <- system("curl -u 'domain\\username' 'smb://host.example.com/share/file.txt'", intern = TRUE)
</code>```

...or by calling system2() instead, which quotes the command arguments for safety and better handles process redirection between platforms:

```<code>contents <- system2('curl', c("-u", "domain\\\\username", "smb://host.example.com/share/file.txt"), stdout = TRUE)
</code>```

The curl command will still prompt us for a password if required by the remote server. While we can specify a password using -u 'domain\\username:password' to avoid the prompt, doing so exposes the plain-text password in the command string. For a more secure approach, read the section below that describes the usage of a package.

We can also add the -s or --silent flag to the curl command to suppress the progress status output. Note that doing so will also hide error messages, so we may also want to add -S (--show-error) as well. The contents variable will contain a vector of the lines of the file—similar to the value returned by readLines("file.txt")—that we can squash back together using paste(contents, collapse = "\n").

cURL API

While this all works fine, we can improve upon this approach by using a dedicated cURL library. This curl package provides R bindings to libcurl so that we can use the cURL API in our program directly. First we need to install the package:

```<code>install.packages("curl")
require("curl")
</code>```

(Linux users will need to install libcurl development files.)

Then, we can read the remote file into a variable using the curl_fetch_memory() function:

```<code>handle <- new_handle()
handle_setopt(handle, username = "domain\\username")
handle_setopt(handle, password = "secret") # If needed
request <- curl_fetch_memory("smb://host.example.com/share/file.txt", handle = handle)
content <- rawToChar(request$content)
</code>```

First we create a handle to configure the request by setting any authentication options needed. Then, we execute the request and assign the contents of the file to a variable. As shown, set the password CURLOPT if needed.

To process a remote file like we would with read.csv(), we need to create a streaming connection. The curl() function creates a connection object that we can use to stream the file contents through any function that supports an argument returned by the standard url() function. For example, here's a way to read the remote file as CSV, like in the question:

```<code>handle = new_handle()
...
stream <- curl("smb://host.example.com/share/file.txt", handle = handle)
contents <- read.csv(stream)
</code>```

Of course, the concepts described above apply to fetching the contents or response body over any protocol supported by cURL, not just SMB/CIFS. If needed, we can also use these tools to download files to the filesystem instead of just reading the contents into memory.

Body:
To read a file in R, I'd normally do something like the following:

read.csv('/Users/myusername/myfilename.csv')

But, I'm trying to read a file located on a remote server (Windows SMB/CIFS share) which I access on my Mac via the Finder → Go → Connect to Server menu item.

When I view that file's properties, the file path is different than what I'm used to. Instead of beginning with: /Users/myusername/..., it is smb://server.msu.edu/.../myfilename.csv.

Trying to read the file, I tried the following:

read.csv('smb://server.msu.edu/.../myfilename.csv')

But, this didn't work.

Instead of the usual "No such file or directory" error, this returned:

smb://server.msu.edu/.../myfilename.csv does not exist in current working directory

I imagine the file path needs a different format, but I can't figure what.

How can you read this type of file in R?

Body:
TL;DR

Here's a portable approach that uses cURL and doesn't require mounting remote filesystems:

> install.packages("curl")
> require("curl")
> handle <- new_handle()
> handle_setopt(handle, username = "domain\\username")
> handle_setopt(handle, password = "secret") # If needed
> request <- curl_fetch_memory("smb://host.example.com/share/file.txt", handle = handle)
> contents <- rawToChar(request$content)

If we need to read the contents as CSV, like in the question, we can stream the file through another function:

> stream <- curl("smb://host.example.com/share/file.txt", handle = handle)
> contents <- read.csv(stream)

Let's take a look at a more robust way to access remote files through smb:// URLs besides the approach described in other answers that mounts the remote filesystem. Unfortunately, I'm a bit late to this one, but I hope this helps future readers.

In some cases, we may not have the privileges needed to mount a filesystem (this requires admin or root access on many systems), or we simply may not want to mount an entire filesystem just to read a single file. We'll use the cURL library to read the file instead. This approach improves the flexibility and portability of our programs because we don't need to depend on the existence of an externally mounted filesystem. We'll examine two different ways: through a system() call, and by using a package that provides a cURL API.

Some background: for those not familiar with it, cURL provides tools used to transfer data over various protocols. Since version 7.40, cURL supports the SMB/CIFS protocol typically used for Windows file-sharing services. cURL includes a command-line tool that we can use to fetch the contents of a file:

$ curl -u 'domain\username' 'smb://host.example.com/share/file.txt'

The command above reads and outputs (to STDOUT) the contents of file.txt from the remote server host.example.com authenticating as the specified user on the domain. The command will prompt us for a password if needed. We can remove the domain portion from the username if our network doesn't use a domain.

System Call

We can achieve the same functionality in R by using the system() function:

system("curl -u 'domain\\username' 'smb://host.example.com/share/file.txt'")

Note the double backslash in domain\\username. This escapes the backslash character so that R doesn't interpret it as an escape character in the string. We can capture file contents from the command output into a variable by setting the intern parameter of the system() function to TRUE:

contents <- system("curl -u 'domain\\username' 'smb://host.example.com/share/file.txt'", intern = TRUE)

...or by calling system2() instead, which quotes the command arguments for safety and better handles process redirection between platforms:

contents <- system2('curl', c("-u", "domain\\\\username", "smb://host.example.com/share/file.txt"), stdout = TRUE)

The curl command will still prompt us for a password if required by the remote server. While we can specify a password using -u 'domain\\username:password' to avoid the prompt, doing so exposes the plain-text password in the command string. For a more secure approach, read the section below that describes the usage of a package.

We can also add the -s or --silent flag to the curl command to suppress the progress status output. Note that doing so will also hide error messages, so we may also want to add -S (--show-error) as well. The contents variable will contain a vector of the lines of the file—similar to the value returned by readLines("file.txt")—that we can squash back together using paste(contents, collapse = "\n").

cURL API

While this all works fine, we can improve upon this approach by using a dedicated cURL library. This curl package provides R bindings to libcurl so that we can use the cURL API in our program directly. First we need to install the package:

install.packages("curl")
require("curl")

(Linux users will need to install libcurl development files.)

Then, we can read the remote file into a variable using the curl_fetch_memory() function:

handle <- new_handle()
handle_setopt(handle, username = "domain\\username")
handle_setopt(handle, password = "secret") # If needed
request <- curl_fetch_memory("smb://host.example.com/share/file.txt", handle = handle)
content <- rawToChar(request$content)

First we create a handle to configure the request by setting any authentication options needed. Then, we execute the request and assign the contents of the file to a variable. As shown, set the password CURLOPT if needed.

To process a remote file like we would with read.csv(), we need to create a streaming connection. The curl() function creates a connection object that we can use to stream the file contents through any function that supports an argument returned by the standard url() function. For example, here's a way to read the remote file as CSV, like in the question:

handle = new_handle()
...
stream <- curl("smb://host.example.com/share/file.txt", handle = handle)
contents <- read.csv(stream)

Of course, the concepts described above apply to fetching the contents or response body over any protocol supported by cURL, not just SMB/CIFS. If needed, we can also use these tools to download files to the filesystem instead of just reading the contents into memory.


问:
How to check the multiple permission at single request in Android M?
I want to use the

android.permission.CAMERA

android.permission.WRITE_EXTERNAL_STORAGE

in single request using

```<code>ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode);
</code>```

But my problem is at time I request only one permission,
I read about group-permission,But it's work for only Same group which one decided by Developer, Like CONTACT_GROUP : read_contact,write_contact etc.

I want create the custom group permission which ask me only one request & provide me only one response.

Thanks

答: Based on what i've searched, i think this is the best answers that i've found out Android 6.0 multiple permissions</p>

Body:
I want to use the

android.permission.CAMERA

android.permission.WRITE_EXTERNAL_STORAGE

in single request using

ActivityCompat.requestPermissions(Activity activity,new String permisionList[],int permissionRequestcode);

But my problem is at time I request only one permission,
I read about group-permission,But it's work for only Same group which one decided by Developer, Like CONTACT_GROUP : read_contact,write_contact etc.

I want create the custom group permission which ask me only one request & provide me only one response.

Thanks


问:
Recursive Function?
fnord Function

Can someone please explain what exactly this code does. it is a task for me but I can not understand it well.

I tried it. When I entered a value between 0 and 9 it return the same value?

```<code>double fnord(double v){
    int c = getchar();
    if(c>='0' && c<='9')
        return fnord(v*10+(c-'0'));
    ungetc(c,stdin);
    return v;
}
</code>```

In the main function I have done so :

```<code>int main(){
    double v;
    scanf("%lf",&v);
    printf("%lf",fnord(v));
}
</code>```

答:
```<code>#include <stdio.h>

// convert typed characters to the double number
// stop calculations if non digit character is encounter
// Example: input = 123X<enter>
// the first argument for fnord for  will have a value
// 0*10 + 1  (since '1' = 0x31 and '0' = 0x30)
// then recursive function is called with argument 1
// v= 1
// and digit '2' is entered
// v = 1*10 + 2 ((since '2' = 0x32 and '0' = 0x30)
// v= 12 and fnord will process third character '3' = 0x33
// v = 12*10 +3
// when 'X' is encountered in the input the processing will stop, (X is returned back to the input string)
// and when ENTER is ecountered the last calculated v is returned
// v = 123 as the double number.

double fnord(double v){
    int c = getchar();
    if(c>='0' && c<='9')
        return fnord(v*10+(c-'0'));
    ungetc(c,stdin);
    return v;
}

int main()
{
    double v=0;
    printf("%f",fnord(v));
    return 0;
}
</code>```

INPUT:

```<code>    123X
</code>```

OUTPUT:

```<code>    123.000000
</code>```

Title: Recursive Function?

Body:
fnord Function

Can someone please explain what exactly this code does. it is a task for me but I can not understand it well.

I tried it. When I entered a value between 0 and 9 it return the same value?

double fnord(double v){
    int c = getchar();
    if(c>='0' && c<='9')
        return fnord(v*10+(c-'0'));
    ungetc(c,stdin);
    return v;
}

In the main function I have done so :

int main(){
    double v;
    scanf("%lf",&v);
    printf("%lf",fnord(v));
}

Body:
#include <stdio.h>

// convert typed characters to the double number
// stop calculations if non digit character is encounter
// Example: input = 123X<enter>
// the first argument for fnord for  will have a value
// 0*10 + 1  (since '1' = 0x31 and '0' = 0x30)
// then recursive function is called with argument 1
// v= 1
// and digit '2' is entered
// v = 1*10 + 2 ((since '2' = 0x32 and '0' = 0x30)
// v= 12 and fnord will process third character '3' = 0x33
// v = 12*10 +3
// when 'X' is encountered in the input the processing will stop, (X is returned back to the input string)
// and when ENTER is ecountered the last calculated v is returned
// v = 123 as the double number.

double fnord(double v){
    int c = getchar();
    if(c>='0' && c<='9')
        return fnord(v*10+(c-'0'));
    ungetc(c,stdin);
    return v;
}

int main()
{
    double v=0;
    printf("%f",fnord(v));
    return 0;
}

INPUT:

    123X

OUTPUT:

    123.000000


问:
How instantiate case class from Map[String, String]
Lets say I have

```<code>case class Sample(i:Int, b:Boolean)
</code>```

and

```<code>Map[String, String]("i" => "1", "b" => "false")
</code>```

What is most concise way to instantiate any case class(if all fields are in map), signature like this:

```<code> get[T](map:[String, String]) : T
</code>```

Probably shapeless can help acomplish this task, but I am almost unfamiliar with it. Thanks!

答:
Firstly you can transform Map[String, String] into Map[Symbol, Any] and then use type classes shapeless.ops.maps.FromMap (or extention method .toRecord) and LabelledGeneric:

```<code>import shapeless.LabelledGeneric
import shapeless.record.Record
import shapeless.syntax.std.maps._

case class Sample(i: Int, b: Boolean)
val rec = Map('i -> 1, 'b -> false).toRecord[Record.`'i -> Int, 'b -> Boolean`.T].get
LabelledGeneric[Sample].from(rec) //Sample(1,false)
</code>```

Body:
Lets say I have

case class Sample(i:Int, b:Boolean)

and

Map[String, String]("i" => "1", "b" => "false")

What is most concise way to instantiate any case class(if all fields are in map), signature like this:

 get[T](map:[String, String]) : T

Probably shapeless can help acomplish this task, but I am almost unfamiliar with it. Thanks!

Body:
Firstly you can transform Map[String, String] into Map[Symbol, Any] and then use type classes shapeless.ops.maps.FromMap (or extention method .toRecord) and LabelledGeneric:

import shapeless.LabelledGeneric
import shapeless.record.Record
import shapeless.syntax.std.maps._

case class Sample(i: Int, b: Boolean)
val rec = Map('i -> 1, 'b -> false).toRecord[Record.`'i -> Int, 'b -> Boolean`.T].get
LabelledGeneric[Sample].from(rec) //Sample(1,false)


问:
Python get an error code from exception
In python, I have code that handles exceptions and prints error codes and messages.

```<code>try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e))
</code>```

However, e.code is not the proper way to get the error name (NameError), and I cannot find the answer to this. How am I supossed to get the error code?

答:
Try this:

```<code>try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e)))
</code>```

Read this for a more detailed explanation.

Title: Python get an error code from exception

Body:
In python, I have code that handles exceptions and prints error codes and messages.

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = e.code, m = str(e))

However, e.code is not the proper way to get the error name (NameError), and I cannot find the answer to this. How am I supossed to get the error code?

Body:
Try this:

try:
    somecode() #raises NameError
except Exception as e:
    print('Error! Code: {c}, Message, {m}'.format(c = type(e).__name__, m = str(e)))

Read this for a more detailed explanation.


问:
How do I apply an edited actionscript class to an MXML component in Flex 4?
I was wondering how I apply an edited actionscript class to a component??

I've made a few changes to the TileLayout class (spark.layout.supportClasses.LayoutBase), but am unable to apply this new layout format to my group in my application... is it treated like a different tag within the layout tag?

eg

<s:layout> <s:TileLayout horizontalAlign="justify" /> </s:layout>

to

<s:layout> <s:MyNewLayoutClass horizontalAlign="justify" /> </s:layout>

Thanks a lot in advance, I really appreciate the answers this community provides!

Josh

答:
Is it treated like a different tag
  within the layout tag?

Yes, but instead of <s:MyNewLayoutClass .../>, where the s references the spark namespace, you would use your own custom namespace, relative to where ever you placed this class in your project directory.  So, say your new class is in a folder labeled "layouts" in your "src" directory, then in your Application tag in your main MXML file you would add a namespace for that folder:

```<code>xmlns:layouts="layouts.*"
</code>```

and then your markup would look something like:

```<code><layouts:MyNewLayoutClass .../>
</code>```

Note: The name you use for the namespace does not necessarily have to match to the name of the folder.

Body:
Is it treated like a different tag
  within the layout tag?

Yes, but instead of <s:MyNewLayoutClass .../>, where the s references the spark namespace, you would use your own custom namespace, relative to where ever you placed this class in your project directory.  So, say your new class is in a folder labeled "layouts" in your "src" directory, then in your Application tag in your main MXML file you would add a namespace for that folder:

xmlns:layouts="layouts.*"

and then your markup would look something like:

<layouts:MyNewLayoutClass .../>

Note: The name you use for the namespace does not necessarily have to match to the name of the folder.