问:
ValueError: invalid literal for int() with base 10: ' ' [Django]
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database.
But while migrating the app I'm getting this error:

```<code>ValueError: invalid literal for int() with base 10: ''
</code>```

What should I change in code to resolve this error?
Here's the traceback:

```<code>Traceback (most recent call last):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
    field,
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql
    default_value = self.effective_default(field)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
    prepared=False)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''
</code>```

How to fix this problem?

Here's my code for models.py:

```<code>from django.db import models
from django.contrib.postgres.fields import JSONField

class Projects(models.Model):
        data = JSONField(null=False)
        project_id=models.CharField(max_length=100)
        project_name=models.CharField(max_length=100)
        status=models.CharField(max_length=10)
        country=models.CharField(max_length=100)
        locations=JSONField()
        mjtheme=models.CharField(max_length=50)
        project_docs=JSONField()
        source=models.CharField(max_length=10)
        mjtheme_namecode=models.CharField(max_length=10)
        docty=models.TextField()
        countryname=models.CharField(max_length=100)
        countrycode=models.CharField(max_length=10)
        themecode=models.IntegerField()
        theme_namecode=models.IntegerField()
        project_url=models.TextField()
        totalcommamt=models.IntegerField()
        mjthemecode=models.IntegerField()
        sector1=models.CharField(max_length=10)
        theme1=models.CharField(max_length=10)
        theme2=models.CharField(max_length=10)
        theme3=models.CharField(max_length=10)
        projectinfo=models.TextField()
        country_namecode=models.CharField(max_length=5)
        p2a_updated_date=models.IntegerField()
        p2a_flag=models.CharField(max_length=5)
        project_abstract=JSONField()
</code>```

And here's the code for fetch.py file which is stored under /management/commands/fetch.py:

```<code>import requests
from django.core.management.base import BaseCommand
from worldBank.worldBankApp.models import Projects

class Command(BaseCommand):
    def handle(self, **options):
        response = requests.get("https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=7")
        data = response.json()
        projects = data['projects']

        #print(data)

        for project in projects:
            print(projects[project])
            print("\n\n")

            data = projects[project]

            Projects.objects.create(

                project_id = data['id'],
                project_name = data['project_name'],
                status = data['status'],
                country = data['countryshortname'],
                locations = data['locations'],
                mjtheme = data['mjtheme'],
                project_docs = data['projectdocs'],
                source = data['source'],
                mjtheme_namecode = data['mjtheme_namecode'],
                docty = data['docty'],
                countryname = data['countryname'],
                countrycode = data['countrycode'],
                themecode = data['themecode'],
                theme_namecode = data['theme_namecode'],
                project_url = data['url'],
                totalcommamt = data['totalcommamt'],
                mjthemecode = data['mjthemecode'],
                sector1 = data['sector1'],
                theme1 = data['theme1'],
                theme2 = data['theme2'],
                theme3 = data['theme3'],
                projectinfo = data['projectinfo'],
                country_namecode = ['country_namecode'],
                p2a_updated_date = data['p2a_updated_date'],
                p2a_flag = data['p2a_flag'],
                project_abstract = data['project_abstract']

                )
</code>```

答:
Error is coming for any of the following IntegerField .

```<code>themecode=models.IntegerField()
theme_namecode=models.IntegerField()
totalcommamt=models.IntegerField()
mjthemecode=models.IntegerField()
p2a_updated_date=models.IntegerField()
</code>```

reason: you supposed to assign integer value(e.g. 4 or '4') instead its not. Please check the value of above fields.

===== EDIT

value coming in response for integer field(s):

```<code>themecode: "79,77,66", # invalid
mjthemecode: "10,10,5", # invalid
p2a_updated_date: "2017-09-01 00:00:00.0", # invalid
theme_namecode: [] # invalid
</code>```

==== EDIT: Place following code after data = projects[project]

```<code>for k, v in data.items():
    try:
        int(v)
    except ValueError:
        print k, v
        break
</code>```

Body:
I'm working on a Django application which fetches JSON data from an API and stores it in PostgreSQL database.
But while migrating the app I'm getting this error:

ValueError: invalid literal for int() with base 10: ''

What should I change in code to resolve this error?
Here's the traceback:

Traceback (most recent call last):

File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line
    utility.execute()
  File "/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
    output = self.handle(*args, **options)
  File "/python/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
    fake_initial=fake_initial,
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
    state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/python/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/python/lib/python3.6/site-packages/django/db/migrations/migration.py", line 129, in apply
    operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
  File "/python/lib/python3.6/site-packages/django/db/migrations/operations/fields.py", line 87, in database_forwards
    field,
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 415, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 155, in column_sql
    default_value = self.effective_default(field)
  File "/python/lib/python3.6/site-packages/django/db/backends/base/schema.py", line 229, in effective_default
    default = field.get_db_prep_save(default, self.connection)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 770, in get_db_prep_save
    prepared=False)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 762, in get_db_prep_value
    value = self.get_prep_value(value)
  File "/python/lib/python3.6/site-packages/django/db/models/fields/__init__.py", line 1853, in get_prep_value
    return int(value)
ValueError: invalid literal for int() with base 10: ''

How to fix this problem?

Here's my code for models.py:

from django.db import models
from django.contrib.postgres.fields import JSONField

class Projects(models.Model):
        data = JSONField(null=False)
        project_id=models.CharField(max_length=100)
        project_name=models.CharField(max_length=100)
        status=models.CharField(max_length=10)
        country=models.CharField(max_length=100)
        locations=JSONField()
        mjtheme=models.CharField(max_length=50)
        project_docs=JSONField()
        source=models.CharField(max_length=10)
        mjtheme_namecode=models.CharField(max_length=10)
        docty=models.TextField()
        countryname=models.CharField(max_length=100)
        countrycode=models.CharField(max_length=10)
        themecode=models.IntegerField()
        theme_namecode=models.IntegerField()
        project_url=models.TextField()
        totalcommamt=models.IntegerField()
        mjthemecode=models.IntegerField()
        sector1=models.CharField(max_length=10)
        theme1=models.CharField(max_length=10)
        theme2=models.CharField(max_length=10)
        theme3=models.CharField(max_length=10)
        projectinfo=models.TextField()
        country_namecode=models.CharField(max_length=5)
        p2a_updated_date=models.IntegerField()
        p2a_flag=models.CharField(max_length=5)
        project_abstract=JSONField()

And here's the code for fetch.py file which is stored under /management/commands/fetch.py:

import requests
from django.core.management.base import BaseCommand
from worldBank.worldBankApp.models import Projects

class Command(BaseCommand):
    def handle(self, **options):
        response = requests.get("https://search.worldbank.org/api/v2/projects?format=json&countryshortname_exact=India&source=IBRD&kw=N&rows=7")
        data = response.json()
        projects = data['projects']

        #print(data)

        for project in projects:
            print(projects[project])
            print("\n\n")

            data = projects[project]

            Projects.objects.create(

                project_id = data['id'],
                project_name = data['project_name'],
                status = data['status'],
                country = data['countryshortname'],
                locations = data['locations'],
                mjtheme = data['mjtheme'],
                project_docs = data['projectdocs'],
                source = data['source'],
                mjtheme_namecode = data['mjtheme_namecode'],
                docty = data['docty'],
                countryname = data['countryname'],
                countrycode = data['countrycode'],
                themecode = data['themecode'],
                theme_namecode = data['theme_namecode'],
                project_url = data['url'],
                totalcommamt = data['totalcommamt'],
                mjthemecode = data['mjthemecode'],
                sector1 = data['sector1'],
                theme1 = data['theme1'],
                theme2 = data['theme2'],
                theme3 = data['theme3'],
                projectinfo = data['projectinfo'],
                country_namecode = ['country_namecode'],
                p2a_updated_date = data['p2a_updated_date'],
                p2a_flag = data['p2a_flag'],
                project_abstract = data['project_abstract']

                )

Body:
Error is coming for any of the following IntegerField .

themecode=models.IntegerField()
theme_namecode=models.IntegerField()
totalcommamt=models.IntegerField()
mjthemecode=models.IntegerField()
p2a_updated_date=models.IntegerField()

reason: you supposed to assign integer value(e.g. 4 or '4') instead its not. Please check the value of above fields.

===== EDIT

value coming in response for integer field(s):

themecode: "79,77,66", # invalid
mjthemecode: "10,10,5", # invalid
p2a_updated_date: "2017-09-01 00:00:00.0", # invalid
theme_namecode: [] # invalid

==== EDIT: Place following code after data = projects[project]

for k, v in data.items():
    try:
        int(v)
    except ValueError:
        print k, v
        break


来源: stackexchange

问:
How to provide default values for an empty string in a destructured object
While performing object destructuring it is possible to provide default values if the key does not exist (i.e. undefinedKey).

If the (string) key does exist, it does not get overwritten (even if empty).

I'm wondering if it's possible to specify an override for an empty string while destructuring. In the example below, I would like emptyKey to print Override for empty key

const testObject = {
  emptyKey: '',
  filledKey: 'Some Initial Value',
};

const {
  emptyKey = 'Override for empty key',
  filledKey = 'Override for filled key',
  undefinedKey = 'Override for undefined key',
} = testObject;

console.log(emptyKey); //''
console.log(filledKey); //'Some Initial Value'
console.log(undefinedKey); //'Override for undefined key'```

答:
I'm wondering if it's possible to specify an override for an empty string while destructuring.

No, default values are only considered if the property value is undefined. There is no way to override this behavior.

As a workaround, you could build your own little default value handler, such as

function defaults(obj, test, defaults) {
  return Object.keys(defaults).reduce((acc, prop) => {
    acc[prop] = test(obj[prop]) ? defaults[prop] : obj[prop];
    return acc;
  }, {});
}

const testObject = {
  emptyKey: '',
  filledKey: 'Some Initial Value',
};

const {
  emptyKey,
  filledKey,
  undefinedKey,
} = defaults(
  testObject,
  v => v === undefined || v === '',
  {
    emptyKey: 'Override for empty key',
    filledKey: 'Override for filled key',
    undefinedKey:'Override for undefined key',
  }
);

console.log(emptyKey, filledKey, undefinedKey);```

Not quite as elegant, but flexible.

ContentLicense: CC BY-SA 3.0

Body:
I'm wondering if it's possible to specify an override for an empty string while destructuring.

No, default values are only considered if the property value is undefined. There is no way to override this behavior.

As a workaround, you could build your own little default value handler, such as

function defaults(obj, test, defaults) {
  return Object.keys(defaults).reduce((acc, prop) => {
    acc[prop] = test(obj[prop]) ? defaults[prop] : obj[prop];
    return acc;
  }, {});
}

const testObject = {
  emptyKey: '',
  filledKey: 'Some Initial Value',
};

const {
  emptyKey,
  filledKey,
  undefinedKey,
} = defaults(
  testObject,
  v => v === undefined || v === '',
  {
    emptyKey: 'Override for empty key',
    filledKey: 'Override for filled key',
    undefinedKey:'Override for undefined key',
  }
);

console.log(emptyKey, filledKey, undefinedKey);

Not quite as elegant, but flexible.


问:
Full Outer Join self with null values
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

```<code>N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6
</code>```

(where N is a general index column to enable a self-join on sequential groups) and I do:

```<code>SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name
</code>```

I want:

```<code>N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6
</code>```

but what I get is more like a cross-join:

```<code>n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6
</code>```

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

答:
So far I've been only able to see doing this as a union. and a left and right join since the criteria of what you're after changes.

```<code>SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
LEFT JOIN Data b on a.Name = b.Name
   and B.N = 2
WHERE A.N = 1
UNION
SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
RIGHT JOIN Data b on a.Name = b.Name
   and A.N = 1
WHERE B.N = 2
</code>```

Giving us:

```<code>+------+---+----+
| NAME | A |  B |
+------+---+----+
| ABC  | 8 |  9 |
| DEF  | 7 |    |
| XYZ  |   |  6 |
+------+---+----+
</code>```

However this relies on a hardcoded N value which I don't think is that useful... working on better.

Title: Full Outer Join self with null values

Body:
I want to do a full outer self-join that includes nulls.  For example, if the table Data looks like:

N   Name   Val
--------------
1   ABC    8
1   DEF    7
2   ABC    9
2   XYZ    6

(where N is a general index column to enable a self-join on sequential groups) and I do:

SELECT COALESCE(a.n, b.n) as n, COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
     FULL OUTER JOIN Data b on a.N = b.N - 1 and a.Name = b.Name

I want:

N  Name  A    B
---------------
1  ABC   8    9
1  DEF   7    NULL
1  XYZ   NULL 6

but what I get is more like a cross-join:

n  Name  A    B
--------------
1  ABC   8    9
1  DEF   7    NULL
2  ABC   9    NULL
2  XYZ   6    NULL
1  ABC   NULL    8
1  DEF   NULL    7
2  XYZ   NULL    6

How do I perform this full outer join in order to get the condensed self-join results?

(Note: In practice column N is a generalized index, so solutions that require naming the values of N aren't practical.)

Body:
So far I've been only able to see doing this as a union. and a left and right join since the criteria of what you're after changes.

SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
LEFT JOIN Data b on a.Name = b.Name
   and B.N = 2
WHERE A.N = 1
UNION
SELECT COALESCE(a.Name, b.Name) as Name, a.Val as A, b.Val as B
FROM Data a
RIGHT JOIN Data b on a.Name = b.Name
   and A.N = 1
WHERE B.N = 2

Giving us:

+------+---+----+
| NAME | A |  B |
+------+---+----+
| ABC  | 8 |  9 |
| DEF  | 7 |    |
| XYZ  |   |  6 |
+------+---+----+

However this relies on a hardcoded N value which I don't think is that useful... working on better.


问:
SSIS package name which updated table
Please help me to get SSIS package details based table name.

Eg: I have a table A which is update based on ssis package. so i would like to name of that package.

Is there any query i can get it from back end.

答: SSIS packages are basically just XML-files, so you can open it in some text editor and then use the editors Find-function to locate references to your table.</p>

Title: SSIS package name which updated table


问:
Duration of UILocalNotification custom sound when app is in background is 5 seconds
I am using deprecated UILocal notifications, and use custom tracks of .caf type, the duration of the audio is 27 seconds. When device is locked and notifications arrives so the sound plays fully, but when the app is in the background mode and device is not locked, the notification appears and sound plays but just 5 seconds.
Could you please advice is there any documented Apple suggestions, or why it is like that? </p>

答:
The problem is because of the Type of the notification is by default a 'Banner' (which makes the notification dismisses it self automatically after 5 seconds, which results the audio to stop), change the notification type of your app to 'Alert' (from the phone's settings) and your problem will be solved.
Unfortunately i couldn't find anyway to change the notification type programmatically, only the user can change it manually from the settings (maybe use an in-app popup to ask the user to do so).</p>


问:
Convert large hex string to decimal string
I need to convert a large (too large for the built-in data types) hex string to a string with it's decimal representation. For example:

```<code>std::string sHex = "07AA17C660F3DD1D2A1B48F1B746C148";
std::string sDec; // should end up with: "10187768649047767717933300899576725832"
</code>```

I'm currently using the c++ BigInt Class which offers a very easy way to achieve this (but is GPL only):

```<code>BigInt::Vin vbiTemp(sHex, 16);
sDec = vbiTemp.toStrDec();
</code>```

Is there simple way to do this conversion without a 3rd party arithmetic library? Or can you recommend a free (non-GPL) alternative with similar simplicity (efficiency is irrelevant)?

答: std::istringstream (sHex ) >> std::hex >> sDec;</p>

ContentLicense: CC BY-SA 2.5

Body:
I need to convert a large (too large for the built-in data types) hex string to a string with it's decimal representation. For example:

std::string sHex = "07AA17C660F3DD1D2A1B48F1B746C148";
std::string sDec; // should end up with: "10187768649047767717933300899576725832"

I'm currently using the c++ BigInt Class which offers a very easy way to achieve this (but is GPL only):

BigInt::Vin vbiTemp(sHex, 16);
sDec = vbiTemp.toStrDec();

Is there simple way to do this conversion without a 3rd party arithmetic library? Or can you recommend a free (non-GPL) alternative with similar simplicity (efficiency is irrelevant)?


问:
Tableau: stacked side-by-side bars with two different dimensions splitting the columns
I am trying to create a stacked side-by-side bar chart over time with 2 measures:

Total Calls (Split by type of a call)

Requests (Split by type of a request)

I have reached a point where I can get this view:

I am struggling with getting 'Calls' bar colored by the call type, and Requests by the its own type, to ultimately receive this:

(purple colors: types of calls, red-orange-blue colors: types of requests.

答:
Don't Use a Dual Axis. Instead, put [Measure Values] on the shelf and filter your measures to  Requests and Calls.  This should create the stacked side by side effect you're going for.

If you're data is structured in a tidy format such that each row level record is either a call or request, then to get the colors right, you can create a calculated field that uses the appropriate dimension for color based up on whether the record is a call or request.  E.g.

```<code>If ISNULL([Call]) THEN [Request Type] ELSE [Call Type]
</code>```

If your request and call measure are contained in the same row level record, that you will have to use use a combined dimension, with both dimensions on the color shelf.

Body:
Don't Use a Dual Axis. Instead, put [Measure Values] on the shelf and filter your measures to  Requests and Calls.  This should create the stacked side by side effect you're going for.

If you're data is structured in a tidy format such that each row level record is either a call or request, then to get the colors right, you can create a calculated field that uses the appropriate dimension for color based up on whether the record is a call or request.  E.g.

If ISNULL([Call]) THEN [Request Type] ELSE [Call Type]

If your request and call measure are contained in the same row level record, that you will have to use use a combined dimension, with both dimensions on the color shelf.


问:
Selenium/ Python How to get full text after expanding the text using Selenium?
I am trying to scrape reviews from TripAdvisor which, for long reviews, display only partial reviews that require clicking 'More' for the full review to be displayed. I tried getting the text after clicking more (and I can see that the text is expanded) but all I get is the partial review.

My code (to scrape one specific review) is as follow:

```<code>driver = webdriver.Firefox()
driver.get(url)
review = driver.find_element_by_id("review_541350982")
review.find_element_by_class_name("taLnk.ulBlueLinks").click()
driver.wait = WebDriverWait(driver, 5)
new_review = driver.find_element_by_id("review_541350982")
entry = new_review.find_element_by_class_name("partial_entry")
print entry.text
</code>```

This is the HTML before clicking on 'More':

```<code><p class="partial_entry">This place blah blah blah What an...
<span class="taLnk ulBlueLinks" onclick="widgetEvCall('handlers.clickExpand',event,this);">More</span>
</p>
</code>```

and this is the HTML after:

```<code><p class="partial_entry">This place blah blah blah What an incredible monument from both a historic and construction point of view.</p>
<span class="taLnk ulBlueLinks" onclick="widgetEvCall('handlers.clickCollapse',event,this);">Show less</span>
</code>```

I noticed that now  comes after
 after clicking 'More'. Not sure if this is useful.

Any advice is greatly appreciated!

EDIT: Noticed that introducing time.sleep(1) instead of driver.wait solved the problem. Wonder if there is a better way to do this such that the new entry is obtained automatically after it changes and not having to set an arbitrary waiting time?

答:
Locate the review and click more:

```<code>review = driver.find_element_by_id("review_541350982")
partial_text = review.find_element_by_tag_name('p')
partial_text.find_element_by_tag_name('span').click()
</code>```

Relocate the review using XPath and output the text:

```<code>new_review = driver.find_element_by_xpath('(//*[@id="review_541350982"]//p)[1]')
print(new_review.text)
</code>```

HTH

Body:
I am trying to scrape reviews from TripAdvisor which, for long reviews, display only partial reviews that require clicking 'More' for the full review to be displayed. I tried getting the text after clicking more (and I can see that the text is expanded) but all I get is the partial review.

My code (to scrape one specific review) is as follow:

driver = webdriver.Firefox()
driver.get(url)
review = driver.find_element_by_id("review_541350982")
review.find_element_by_class_name("taLnk.ulBlueLinks").click()
driver.wait = WebDriverWait(driver, 5)
new_review = driver.find_element_by_id("review_541350982")
entry = new_review.find_element_by_class_name("partial_entry")
print entry.text

This is the HTML before clicking on 'More':

This place blah blah blah What an...
More

and this is the HTML after:

This place blah blah blah What an incredible monument from both a historic and construction point of view.

Show less

I noticed that now  comes after
 after clicking 'More'. Not sure if this is useful.

Any advice is greatly appreciated!

EDIT: Noticed that introducing time.sleep(1) instead of driver.wait solved the problem. Wonder if there is a better way to do this such that the new entry is obtained automatically after it changes and not having to set an arbitrary waiting time?

Body:
Locate the review and click more:

review = driver.find_element_by_id("review_541350982")
partial_text = review.find_element_by_tag_name('p')
partial_text.find_element_by_tag_name('span').click()

Relocate the review using XPath and output the text:

new_review = driver.find_element_by_xpath('(//*[@id="review_541350982"]//p)[1]')
print(new_review.text)

HTH


问:
Correctly use ThreadPool with Generators
I am having trouble using ThreadPools with a Generator when processing a CSV file in Python 2.7. Here is some sample code that illustrates my point:

```<code>from multiprocessing.dummy import Pool as ThreadPool
import time

def getNextBatch():
    # Reads lines from a huge CSV and yields them as required.
    for i in range(5):
        yield i;

def processBatch(batch):
    # This simulates a slow network request that happens.
    time.sleep(1);
    print "Processed Batch " + str(batch);

# We use 4 threads to attempt to aleviate the bottleneck caused by network I/O.
threadPool = ThreadPool(processes = 4)

batchGenerator = getNextBatch()

for batch in batchGenerator:
    threadPool.map(processBatch, (batch,))

threadPool.close()
threadPool.join()
</code>```

When I run this, I get the expected output:

Processed Batch 0

Processed Batch 1

Processed Batch 2

Processed Batch 3

Processed Batch 4

The problem is that they appear with a 1 second delay between each print. Effectively, my script is running sequentially (and not using multiple threads as I would like it to).

The goal here is to get those printed statements to all appear after ~1 second, rather than one per second for 5 seconds.

答:
here's your problem

```<code>for batch in batchGenerator:
    threadPool.map(processBatch, (batch,))
</code>```

when I tried

threadPool.map(processBatch, batchGenerator)

it worked as expected (but not in order). The for loop is using a threadPool to process each batch one-at-a-time. so it finishes one, then moved on, then ...

Body:
I am having trouble using ThreadPools with a Generator when processing a CSV file in Python 2.7. Here is some sample code that illustrates my point:

from multiprocessing.dummy import Pool as ThreadPool
import time

def getNextBatch():
    # Reads lines from a huge CSV and yields them as required.
    for i in range(5):
        yield i;

def processBatch(batch):
    # This simulates a slow network request that happens.
    time.sleep(1);
    print "Processed Batch " + str(batch);

# We use 4 threads to attempt to aleviate the bottleneck caused by network I/O.
threadPool = ThreadPool(processes = 4)

batchGenerator = getNextBatch()

for batch in batchGenerator:
    threadPool.map(processBatch, (batch,))

threadPool.close()
threadPool.join()

When I run this, I get the expected output:

Processed Batch 0

Processed Batch 1

Processed Batch 2

Processed Batch 3

Processed Batch 4

The problem is that they appear with a 1 second delay between each print. Effectively, my script is running sequentially (and not using multiple threads as I would like it to).

The goal here is to get those printed statements to all appear after ~1 second, rather than one per second for 5 seconds.

Body:
here's your problem

for batch in batchGenerator:
    threadPool.map(processBatch, (batch,))

when I tried

threadPool.map(processBatch, batchGenerator)

it worked as expected (but not in order). The for loop is using a threadPool to process each batch one-at-a-time. so it finishes one, then moved on, then ...


问:
counting number of directories in a specific directory
How to count the number of folders in a specific directory. I am using the following command, but it always provides an extra one.

```<code>find /directory/ -maxdepth 1 -type d -print| wc -l
</code>```

For example, if I have 3 folders, this command provides 4. If it contains 5 folders, the command provides 6. Why is that?

答:
Count all files and subfolders, windows style:</p>

```<code>dir=/YOUR/PATH;f=$(find $dir -type f | wc -l); d=$(find $dir -mindepth 1 -type d | wc -l); echo "$f Files, $d Folders"
</code>```

Body:
How to count the number of folders in a specific directory. I am using the following command, but it always provides an extra one.

find /directory/ -maxdepth 1 -type d -print| wc -l

For example, if I have 3 folders, this command provides 4. If it contains 5 folders, the command provides 6. Why is that?

Body:
Count all files and subfolders, windows style:

dir=/YOUR/PATH;f=$(find $dir -type f | wc -l); d=$(find $dir -mindepth 1 -type d | wc -l); echo "$f Files, $d Folders"


问:
Html 5 datepicker in firefox
Is there any way that I can set enable a datepicker in firefox(version 21) with HTML 5. I dont want to use a jQuery based datepicker because javascript will be disabled in the browsers where the website will be used. The datepicker works fine with Chrome.

So if html 5 datepicker is not supported,how can I add a datepicker without jquery ?

答:
Firefox 57 finally has a datepicker with a clickable calender (<input type="date">).

The timepicker is just a text field that limits input to valid times. Sadly, it only supports 12 hour time format (<input type="time">).

datetime-local still isn't supported (<input type="datetime-local">).

Title: Html 5 datepicker in firefox


问:
How to add box shadow for highchart chart?
I want to have the following style on my chart border

```<code>border-radius: 4px;
box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
border: solid 1px #e1e1e1;
</code>```

There is shadow property for the chart but it doesn't seem to work, can someone point out my mistake?

Thanks

Here is the jsfiddle

Edit: I want it to look like this

答:
Why not just apply it to the container? Here is the Jsfiddle</p>

```<code>#container {
    border-radius: 4px;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
    border: solid 1px #e1e1e1;
}
</code>```

Body:
I want to have the following style on my chart border

border-radius: 4px;
box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
border: solid 1px #e1e1e1;

There is shadow property for the chart but it doesn't seem to work, can someone point out my mistake?

Thanks

Here is the jsfiddle

Edit: I want it to look like this

Body:
Why not just apply it to the container? Here is the Jsfiddle

#container {
    border-radius: 4px;
    box-shadow: 0 1px 4px 0 rgba(0, 0, 0, 0.1);
    border: solid 1px #e1e1e1;
}


问:
Spark 2.1 register UDF to functionRegistry
Hi I want to register a UDF object that is already created.  I'm using spark 2.1, and the sparkSession.udf.register() function does not accept a UDF parameter only a regular scala function.  It's easy to miss something from the large Spark API so just asking is there a function or constructor that will allow this in 2.1?</p>

答:
In this case I'd reverse the the problem and use udf registration to get UserDefinedFunction:

```<code>import org.apache.spark.sql.expressions.UserDefinedFunction

val id: UserDefinedFunction = spark.udf.register("id", (x: Int) => x)
</code>```

Which would work both in DataFrames:

```<code>val id: UserDefinedFunction = spark.udf.register("id", (x: Int) => x)
</code>```

and SQL:

```<code>spark.sql("SELECT id(id) FROM RANGE(42)")
</code>```

Body:
In this case I'd reverse the the problem and use udf registration to get UserDefinedFunction:

import org.apache.spark.sql.expressions.UserDefinedFunction

val id: UserDefinedFunction = spark.udf.register("id", (x: Int) => x)

Which would work both in DataFrames:

val id: UserDefinedFunction = spark.udf.register("id", (x: Int) => x)

and SQL:

spark.sql("SELECT id(id) FROM RANGE(42)")


问:
Adding Server Timestamp field to the Object which being added
I have a Challenge object, which has it's own properties and I'm able to add it to the database successfully like this:

```<code>DocumentReference challengeRef=usersRef.document(loggedUserEmail).collection("challenges_feed").
                document(callengeID);
challengeRef.set(currentChallenge);
</code>```

This is how it looks like in the database:

I'd like to make a new field in the database (under this challenge) which called latestUpdateTimetamp. This is how it should look like (I have added it manually):

I have tried to set it in the constructor of the object like this:

```<code>private Map<String,String> latestUpdateTimestamp;

public Challenge(String id, String senderName,  String senderEmail) {
            this.senderName=senderName;
            this.senderEmail = senderEmail;

            this.latestUpdateTimestamp= ServerValue.TIMESTAMP;
        }
</code>```

But this is what I get in the database:

I'm trying to add the latestUpdateTimestamp to the Challenge and the Challenge object itself to the database at the same call. Is it possible?

Can I somehow add this timestamp as a property to this object before adding it?

I know I'm able to make a new call and add this field, but I'm wondering if it's possible at once.

答:
Yes you can, using a Map. First of all, according to official docs it will be necessary to use an annotation that looks like this:

```<code>@ServerTimestamp Date time;
</code>```

Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.

This is how you can update the latestUpdateTimestamp field with the server timestamp and the challangeId with the desired value at the same time.

```<code>DocumentReference senderRef = challengeRef
    .document(loggedUserEmail)
    .collection("challenges_feed")
    .document(callengeID);

Map<String, Object> updates = new HashMap<>();
updates.put("latestUpdateTimestamp", FieldValue.serverTimestamp());
updates.put("challangeId", "newChallangeId");
senderRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Challenge object, which has it's own properties and I'm able to add it to the database successfully like this:

DocumentReference challengeRef=usersRef.document(loggedUserEmail).collection("challenges_feed").
                document(callengeID);
challengeRef.set(currentChallenge);

This is how it looks like in the database:

I'd like to make a new field in the database (under this challenge) which called latestUpdateTimetamp. This is how it should look like (I have added it manually):

I have tried to set it in the constructor of the object like this:

private Map<String,String> latestUpdateTimestamp;

public Challenge(String id, String senderName,  String senderEmail) {
            this.senderName=senderName;
            this.senderEmail = senderEmail;

            this.latestUpdateTimestamp= ServerValue.TIMESTAMP;
        }

But this is what I get in the database:

I'm trying to add the latestUpdateTimestamp to the Challenge and the Challenge object itself to the database at the same call. Is it possible?

Can I somehow add this timestamp as a property to this object before adding it?

I know I'm able to make a new call and add this field, but I'm wondering if it's possible at once.

Body:
Yes you can, using a Map. First of all, according to official docs it will be necessary to use an annotation that looks like this:

@ServerTimestamp Date time;

Annotation used to mark a Date field to be populated with a server timestamp. If a POJO being written contains null for a @ServerTimestamp-annotated field, it will be replaced with a server-generated timestamp.

This is how you can update the latestUpdateTimestamp field with the server timestamp and the challangeId with the desired value at the same time.

DocumentReference senderRef = challengeRef
    .document(loggedUserEmail)
    .collection("challenges_feed")
    .document(callengeID);

Map<String, Object> updates = new HashMap<>();
updates.put("latestUpdateTimestamp", FieldValue.serverTimestamp());
updates.put("challangeId", "newChallangeId");
senderRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {/* ... */}


答:
Change shadow, offsetX and offsetY to a number instead of string:

```<code>Highcharts.chart('container', {
    chart: {
        shadow: {
            color: 'rgba(0, 0, 0, 0.1)',
            offsetX: 1,
            offsetY: 1,
            opacity: '0.1',
            width: 10
        }
    }
});
</code>```

Updated Fiddle

Title: How to add box shadow for highchart chart?

Body:
Change shadow, offsetX and offsetY to a number instead of string:

Highcharts.chart('container', {
    chart: {
        shadow: {
            color: 'rgba(0, 0, 0, 0.1)',
            offsetX: 1,
            offsetY: 1,
            opacity: '0.1',
            width: 10
        }
    }
});

Updated Fiddle


问:
Azure / U-SQL - Regex substitution
I have some data containing spaces () and hyphens (-) that I'd like to convert to underscore characters (_).  In other languages (ie R) I can write something like this:

```<code>var1 <- gsub(var1, "s+|\\-", "_")
</code>```

which will look for multiple characters and convert them all to some other character.

Is there a way to do this in U-SQL?

EDIT:

I tried this and it ran without error but did not change the data:

```<code>@t2 = SELECT var1,
           var2,
           var3.Replace("s+|\\'|\\-","_") AS var3
    FROM @t1;
</code>```

答:
You are almost there but you are using the System.String.Replace instead of the one for a regular expression. So change

```<code>@t2 = SELECT var1,
       var2,
       var3.Replace("s+|\\'|\\-","_") AS var3
FROM @t1;
</code>```

to

```<code>@t2 = SELECT var1,
       var2,
       Regex.Replace(var3, "s+|\\'|\\-", "_") AS var3
FROM @t1;
</code>```

Edit: I am not an expert on regular expression so I did not validate the expression itself.

Title: Azure / U-SQL - Regex substitution

Body:
I have some data containing spaces () and hyphens (-) that I'd like to convert to underscore characters (_).  In other languages (ie R) I can write something like this:

var1 <- gsub(var1, "s+|\\-", "_")

which will look for multiple characters and convert them all to some other character.

Is there a way to do this in U-SQL?

EDIT:

I tried this and it ran without error but did not change the data:

@t2 = SELECT var1,
           var2,
           var3.Replace("s+|\\'|\\-","_") AS var3
    FROM @t1;

Body:
You are almost there but you are using the System.String.Replace instead of the one for a regular expression. So change

@t2 = SELECT var1,
       var2,
       var3.Replace("s+|\\'|\\-","_") AS var3
FROM @t1;

to

@t2 = SELECT var1,
       var2,
       Regex.Replace(var3, "s+|\\'|\\-", "_") AS var3
FROM @t1;

Edit: I am not an expert on regular expression so I did not validate the expression itself.


问:
How to get X largest values from array
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

```<code>getHighest(2): 25, 5
getHighest(3): 25, 5, 4
</code>```

答:
Sort the array and take the first X elements

Use your language's max function to find the largest element.  Extract it from the array.  Repeat X times.

Title: How to get X largest values from array

Body:
I have array:
[2 , 4 , 5, 1 , 4 , 20]

How to get X highest values from this array?

Like this:

getHighest(2): 25, 5
getHighest(3): 25, 5, 4


问:
How to extract just the URL from string with doesn't contains the "http" or "https" and remove it
I have a form with multiple text fields.

I want to get rid of all links in the user's input (whether starting with http(s) or not).

For example:

Hello guys, please check my website: http://www.example.com/page.php?id=5,
  here is my facebook page http://facebook.com/home and my twitter www.twitter.com/home

I would like to get rid of all the links, here is what I've tried so far:

```<code>$userInput = preg_replace("/\S+\.\S+/", "", $userInput);
</code>```

It works but it also removes words like P.H.P.

It also fails if the user doesn't add a whitespace after link.

How do I edit my RegEx to achieve my requirements?

答:
You could try

```<code>(?:https?://)?\w{3,}\.\S+
</code>```

See a demo on regex101.com, this may need some fiddling though.

Broken down:

```<code>(?:https?://)? # http:// or https://, both are optional
\w{3,}         # at least three word characters
\.             # a dot
\S+            # not a whitespace, 1+
</code>```

In PHP:

```<code>$new_string = preg_replace('~?:https?://)?\w{3,}\.\S+~', '', $your_string_here);
</code>```

Body:
I have a form with multiple text fields.

I want to get rid of all links in the user's input (whether starting with http(s) or not).

For example:

Hello guys, please check my website: http://www.example.com/page.php?id=5,
  here is my facebook page http://facebook.com/home and my twitter www.twitter.com/home

I would like to get rid of all the links, here is what I've tried so far:

$userInput = preg_replace("/\S+\.\S+/", "", $userInput);

It works but it also removes words like P.H.P.

It also fails if the user doesn't add a whitespace after link.

How do I edit my RegEx to achieve my requirements?

Body:
You could try

(?:https?://)?\w{3,}\.\S+

See a demo on regex101.com, this may need some fiddling though.

Broken down:

(?:https?://)? # http:// or https://, both are optional
\w{3,}         # at least three word characters
\.             # a dot
\S+            # not a whitespace, 1+

In PHP:

$new_string = preg_replace('~?:https?://)?\w{3,}\.\S+~', '', $your_string_here);


问:
How to read the data in a razor variable , assigned by a checkbox from a controller
My View has a list of rows for Edit , and each row has multiple checkbox . So I want to index each checkbox value with its corresponding row index.
For this I have in view :

```<code>List<string> FilterIds =new List<string>();
</code>```

.
.
.

```<code><td width="200px">
                        <div class="form-group">
                            <div class=" text-left">Apply Filter(s)</div>
                            <div class="col-md-10">

                                    @foreach (var item in ViewBag.Filters)
                                    {

                                    <input type="checkbox" value="@item.FilterId" name="@FilterIds"/>@item.FilterId
                                    <text> </text>
                                       //FilterId[i] = FilterIds;

                                    }
</code>```

And my controller looks like this :

```<code>public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, List<string> FilterIds)
</code>```

Any quick solutions , how I can read the checked value per row ?

答:
You have to create a view method for control every value's checkbox and you have to use CheckboxFor for bind it with model i couldn't help correctly because i don't know well too but i had a problem like this i used many textbox with data

This is my question and answer worked at me it's can be helpful: How can i take many textboxes' value on Post in MVC

And if you want to examine my solution (Page2.cshtml): https://github.com/kadirkalkan/WorkCubeFormMvc

Body:
My View has a list of rows for Edit , and each row has multiple checkbox . So I want to index each checkbox value with its corresponding row index.
For this I have in view :

List<string> FilterIds =new List<string>();

.
.
.

Apply Filter(s)

                                    @foreach (var item in ViewBag.Filters)
                                    {

                                    <input type="checkbox" value="@item.FilterId" name="@FilterIds"/>@item.FilterId
                                    <text> </text>
                                       //FilterId[i] = FilterIds;

                                    }

And my controller looks like this :

public ActionResult Edit([Bind(Include = "Conf_ActionTypeCTAMeta_V1_Id,Conf_CTAId,Conf_Clicklistid,ApprovedBy,DateApproved,EditedBy,DateEdited,Conf_TrackingActionTypeUnique_Id,ConfMarketid,MarketFilterId")] Conf_ActionTypeCTAMeta_V1[] conf_ActionTypeCTAMeta_V1, List<string> FilterIds)

Any quick solutions , how I can read the checked value per row ?


问:
Android Studio 2.3 cannot install emulator
I'm new to android and I'm confused with this error.
Android studio 2.3
Tried to install emulator but it stucked and does not download.

error view

I wanted to create a AVD and with the steps it showed this error.

This is the previous view in AVD. I clicked "install emulator" link to download it.

AVD view

Any help highly appreciated.

答:
try downloading what you need through Android Studio built-in SDK Manager.

on Windows: File > Settings

on Mac OSX: Android Studio > Preferences

then type "Android SDK" in search bar (or "SDK" or "manager")

you will see the SDK Manager

check Show Package Details on the bottom right

then choose the System Image you need, click ok and proceed with installation

next time you enter AVD Manager, your system image should be available to pick up


问:
utl_file_dir paramete is null. Unable to use utl_file
I wanted to use utl_file package for reading file and uploading them into db.

```<code>       declare
           l_fhandle utl_file.file_type;
           l_clob    CLOB;
           l_buffer  VARCHAR2(4096);
     BEGIN
     l_fhandle := utl_file.fopen('admin',
                          'FILE.TXT',
                          'R');
     dbms_lob.createtemporary(l_clob, TRUE, DBMS_LOB.CALL);
     LOOP
     BEGIN
      utl_file.get_line(L_FHANDLE, l_buffer);
      dbms_output.put_line(l_buffer);
      dbms_lob.writeappend(l_clob, length(l_buffer), l_buffer);

      EXCEPTION
      WHEN no_data_found THEN
    INSERT INTO interfacetable
      (FILENAME, content)
    VALUES
      ('FILE', l_clob);
    EXIT;

        END;
     END LOOP;
   END;
  /
</code>```

Created directory using sql

```<code>create or replace directory admin as 'D:\temp';
</code>```

But getting error when run the procedure

declare
  * ERROR at line 1: ORA-29280: invalid directory path ORA-06512: at "SYS.UTL_FILE", line 41 ORA-06512: at "SYS.UTL_FILE", line 478
  ORA-06512: at line 6

Please help

答:
You may have two cases then :

Try upper case letters for the directory name

i.e. instead of admin use ADMIN

Be sure that the OS level user has permission to write to a folder

```<code> create or replace directory ADMIN as 'D:\temp';   /
 grant read, write on directory ADMIN to {user | role | PUBLIC};   /
</code>```

Body:
I wanted to use utl_file package for reading file and uploading them into db.

       declare
           l_fhandle utl_file.file_type;
           l_clob    CLOB;
           l_buffer  VARCHAR2(4096);
     BEGIN
     l_fhandle := utl_file.fopen('admin',
                          'FILE.TXT',
                          'R');
     dbms_lob.createtemporary(l_clob, TRUE, DBMS_LOB.CALL);
     LOOP
     BEGIN
      utl_file.get_line(L_FHANDLE, l_buffer);
      dbms_output.put_line(l_buffer);
      dbms_lob.writeappend(l_clob, length(l_buffer), l_buffer);

      EXCEPTION
      WHEN no_data_found THEN
    INSERT INTO interfacetable
      (FILENAME, content)
    VALUES
      ('FILE', l_clob);
    EXIT;

        END;
     END LOOP;
   END;
  /

Created directory using sql

create or replace directory admin as 'D:\temp';

But getting error when run the procedure

declare
  * ERROR at line 1: ORA-29280: invalid directory path ORA-06512: at "SYS.UTL_FILE", line 41 ORA-06512: at "SYS.UTL_FILE", line 478
  ORA-06512: at line 6

Please help

Body:
You may have two cases then :

Try upper case letters for the directory name

i.e. instead of admin use ADMIN

Be sure that the OS level user has permission to write to a folder

 create or replace directory ADMIN as 'D:\temp';   /
 grant read, write on directory ADMIN to {user | role | PUBLIC};   /


问:
Add records to List
Here is my public class:

```<code>public class CharactersOnline
{
    public int connectionId;
    public int characterId;
    public string characterName;
}
</code>```

Here is my code:

```<code>public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();
chraractersOnline[chraractersOnline.Count + 1].connectionId = 1;
chraractersOnline[chraractersOnline.Count + 1].characterId = 2;
chraractersOnline[chraractersOnline.Count + 1].characterName = "Test";
</code>```

Where is my mistake? Why i'm not able to add these records to the list ?

答:
You could do something like this (not tested):</p>

```<code>public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();

var characterOnline = new CharactersOnline{connectionId = 1, characterId = 2, characterName = "test"}; //creates a new instance of your object

charactersOnline.Add(characterOnline); //adds the single new instance of your object to the list
</code>```

Title: Add records to List

Body:
Here is my public class:

public class CharactersOnline
{
    public int connectionId;
    public int characterId;
    public string characterName;
}

Here is my code:

public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();
chraractersOnline[chraractersOnline.Count + 1].connectionId = 1;
chraractersOnline[chraractersOnline.Count + 1].characterId = 2;
chraractersOnline[chraractersOnline.Count + 1].characterName = "Test";

Where is my mistake? Why i'm not able to add these records to the list ?

Body:
You could do something like this (not tested):

public List<CharactersOnline> charactersOnline = new List<CharactersOnline>();

var characterOnline = new CharactersOnline{connectionId = 1, characterId = 2, characterName = "test"}; //creates a new instance of your object

charactersOnline.Add(characterOnline); //adds the single new instance of your object to the list


问:
Dynamically determine header based on GET parameters
For one of our REST webservices, we have implemented a GET method having the following URI:

```<code>http://ourcompany.com/doSomething/getSomething?parameter1=ABC&parameter2=123
</code>```

Now, one of the headers required for security is the following

userName: ABC123, derived from concatenating the values of parameter1 and parameter2

My question is, how, in SoapUI (preferably via the SoapUI interface, itself), do I dynamically generate this header value from the parameter values supplied in the GET method?

答:
You can create test case level custom properties instead of string value for the parameters which you have currently, say

name as PROPERTY1, and value as ABC

name as PROPERTY2, and value as 123

In the GET request step, provide values as Property Expansion, say
${#TestCase#PROPERTY1}, ${#TestCase#PROPERTY2} respectively for the parameters.

Coming to the headers, define the required header and use Property Expansion again. i.e., header name as userName and value as ${#TestCase#PROPERTY1}${#TestCase#PROPERTY2}

Hope the above should resolve the issue.

Body:
For one of our REST webservices, we have implemented a GET method having the following URI:

http://ourcompany.com/doSomething/getSomething?parameter1=ABC&parameter2=123

Now, one of the headers required for security is the following

userName: ABC123, derived from concatenating the values of parameter1 and parameter2

My question is, how, in SoapUI (preferably via the SoapUI interface, itself), do I dynamically generate this header value from the parameter values supplied in the GET method?


问:
Is there a built in way to avoid magic strings with the Entity Framework's Include()?

Possible Duplicate:

  Entity Framework Include() strongly typed

Ok, I've got an entity framework query where I use Include to tell it I want a related object loaded:

var employees = _entities.Employees.Include("Manager").ToList()

By using include I avoid generating a query for every single employee's manager record (Instead a friendly JOIN is used in the query and the database is never bothered again).

But the use of a magic string "Manager" is unsettling, especially after coming from the supposedly more primitive, quick and dirty Linq2SQL. From a coding stand point it's like a loaded gun, ready to throw a run time exception that should have been caught at compile time. It also puts a big damper on refactoring.

Are there any built in properties or methods to get around this? For example I see Manager.EntityKeyPropertyName as a static string property, but this does not seem to be what I want. I'd rather not manually add a hard coded list of constants somewhere, but it would be better then the naked intellisense blind magic strings.

答: No there is not any build-in strong typed version of Include in EF 4 (I think it is in EF Features CTP4 and CTP5). I'm using this and I'm quite happy with it.</p>


问:
"ValueError: I/O operation on closed file." in nested loop
I'm trying to create an link scraper which worked so far. I only had problems when I was copying multiple lines, then it never stoped inserting these lines. So I wanted to split the mutliple lines into single lines but after creating the for loop which is iterating over the multilines I always get this error: ValueError: I/O operation on closed file.</p>

```<code>import pyperclip
import datetime

while True:
    with open("text.txt", "r+") as textfile:
        text = str(pyperclip.paste())
        liste = text.split("\r\n")

        for element in liste:
            for line in textfile:

                if element in line:
                    break
            else:
                now = datetime.datetime.now()
                textfile.write(str(now.day) + "." + str(now.month) + "." +
                               str(now.year) + " " + str(now. hour) + ":" +
                               str(now.minute) + " | ")
                textfile.write(element + "\n")
                textfile.close()
                print(element)
</code>```

答:
Read the error! It says:

ValueError: I/O operation on closed file

So clearly, you are trying to do something with a file that you have already closed! You are closing it on this line:

```<code>textfile.close()
</code>```

and then continuing the loop and trying to do more operations on it. Therefore, to fix this, just remove that line and the file will be closed anyway due to the with statement.

Body:
I'm trying to create an link scraper which worked so far. I only had problems when I was copying multiple lines, then it never stoped inserting these lines. So I wanted to split the mutliple lines into single lines but after creating the for loop which is iterating over the multilines I always get this error: ValueError: I/O operation on closed file.

import pyperclip
import datetime

while True:
    with open("text.txt", "r+") as textfile:
        text = str(pyperclip.paste())
        liste = text.split("\r\n")

        for element in liste:
            for line in textfile:

                if element in line:
                    break
            else:
                now = datetime.datetime.now()
                textfile.write(str(now.day) + "." + str(now.month) + "." +
                               str(now.year) + " " + str(now. hour) + ":" +
                               str(now.minute) + " | ")
                textfile.write(element + "\n")
                textfile.close()
                print(element)

Body:
Read the error! It says:

ValueError: I/O operation on closed file

So clearly, you are trying to do something with a file that you have already closed! You are closing it on this line:

textfile.close()

and then continuing the loop and trying to do more operations on it. Therefore, to fix this, just remove that line and the file will be closed anyway due to the with statement.


答: You can make a min heap, and call the ExtractMin function (len(arr) - x) times to get Xth largest value.

Title: How to get X largest values from array


问:
FileUpload error - "The form field fileInput did not contain a file" (CFML - FW/1)
I'm trying to upload a file on a ColdFusion site and am receiving the following error:

"The form field fileInput did not contain a file."

The file along with some text values are submitted through a form on an Edit page. The form is submitted to the "save" method in the controller, which sends two calls to fileService. The text values are passed as expected and updating them works fine. When I dump the RC Scope struct "fileInput" (the name of the input I am using to get the file) shows as [empty string]. It is not shown in the Form scope at all. Does anyone have an idea on what could be causing the issue with this? There are a couple of answered questions that are related to forms that use cffile (tags), but everything on the site I'm working on uses FileUpload (cfscript), so I'm not sure how to apply those answers here.

FYI The site uses Framework One (FW/1 version 4.1) as its MVC framework. I'm using ColdFusion 2016. Following are snippets of the code being used.

View: Edit.cfm

```<code><form action="#BuildURL( action='file.save' )#" name="filesForm" method="post" enctype="multipart/form-data">
  <input id="file_id" name="file_id" type="hidden" value="#rc.file_id#">
  <div class="form-group">
    <label for="name">File Name</label>
    <input type="text" class="form-control" id="name" name="name" placeholder="Enter File Name" value="#rc.name#">
  </div>
  <div class="form-group">
    <label for="fileInput">File Upload</label>
    <input type="file" id="fileInput" name"fileInput">
  </div>
  <div class="form-group">
    <button type="submit" class="btn btn-primary" name="Submit">Save</button>
  </div>
</form>
</code>```

Controller: file.cfc

```<code>public void function edit(rc){
  if (StructKeyExists(rc, 'file_id') && rc.file_id > 0){
    var q = fileService.getFile(rc.file_id);
    rc.file_id = q.file_id;
    rc.name = q.name;
  }
}

public void function save(required struct rc){
  rc.file_id = variables.fileService.save(rc.file_id, rc.name);

  param name = "rc.fileInput" default="";
  rc.result = variables.fileService.uploadFile(file = "fileInput");

  variables.fw.redirect(action='file.edit', append='file_id', queryString = "msg=updated");
}
</code>```

Service: file.cfc

```<code>struct function uploadFile(required string file){
  fileUploadResult = FileUpload(getTempDirectory(), arguments.file, "application/pdf", "MakeUnique");
}
</code>```

答: Did you try dumping the rc scope variable and what file are you trying to upload make sure it isnt an empty text file. </p>

Body:
I'm trying to upload a file on a ColdFusion site and am receiving the following error:

"The form field fileInput did not contain a file."

The file along with some text values are submitted through a form on an Edit page. The form is submitted to the "save" method in the controller, which sends two calls to fileService. The text values are passed as expected and updating them works fine. When I dump the RC Scope struct "fileInput" (the name of the input I am using to get the file) shows as [empty string]. It is not shown in the Form scope at all. Does anyone have an idea on what could be causing the issue with this? There are a couple of answered questions that are related to forms that use cffile (tags), but everything on the site I'm working on uses FileUpload (cfscript), so I'm not sure how to apply those answers here.

FYI The site uses Framework One (FW/1 version 4.1) as its MVC framework. I'm using ColdFusion 2016. Following are snippets of the code being used.

View: Edit.cfm

<form action="#BuildURL( action='file.save' )#" name="filesForm" method="post" enctype="multipart/form-data">
  <input id="file_id" name="file_id" type="hidden" value="#rc.file_id#">

    File Name
    <input type="text" class="form-control" id="name" name="name" placeholder="Enter File Name" value="#rc.name#">

    File Upload
    <input type="file" id="fileInput" name"fileInput">

    <button type="submit" class="btn btn-primary" name="Submit">Save</button>

</form>

Controller: file.cfc

public void function edit(rc){
  if (StructKeyExists(rc, 'file_id') && rc.file_id > 0){
    var q = fileService.getFile(rc.file_id);
    rc.file_id = q.file_id;
    rc.name = q.name;
  }
}

public void function save(required struct rc){
  rc.file_id = variables.fileService.save(rc.file_id, rc.name);

  param name = "rc.fileInput" default="";
  rc.result = variables.fileService.uploadFile(file = "fileInput");

  variables.fw.redirect(action='file.edit', append='file_id', queryString = "msg=updated");
}

Service: file.cfc

struct function uploadFile(required string file){
  fileUploadResult = FileUpload(getTempDirectory(), arguments.file, "application/pdf", "MakeUnique");
}


问:
How to merge office documents?
The situation is a handful office documents in different formats and with different layouts/contents:

{A,B,C}.odt

{D,E,F}.doc

{G,H,I}.docx

I cannot find a good way to merge all documents of either format, because there is no commandline option/tool [0,1,2] or the layout is messed up [3], e.g. ooo_cat.

The expected result should be one single file that contains the contents of the other three files without breaking the layout or other unwanted side effects. Merging the base template files into one big template is unfortunately not an option.

What is the best way to smoothly merge several documents programmatically/linux commandline?

[0] https://ask.libreoffice.org/en/question/19222/how-to-merge-multiple-documents-into-single-merged-document/

[1] https://forum.openoffice.org/en/forum/viewtopic.php?f=7&t=57435

[2] https://support.microsoft.com/en-us/help/2665750/how-to-merge-multiple-word-documents-into-one---eeekb

[3] https://askubuntu.com/questions/482277/how-to-merge-odt-documents-from-the-command-line

答:
Start LibreOffice listening with --headless.

Use Python interactively in a shell and start with import uno.  Or this can be done with a Python script.  A good tutorial is at http://christopher5106.github.io/office/2015/12/06/openoffice-libreoffice-automate-your-office-tasks-with-python-macros.html.

Based on link [1] in the question, call Insert -> Document like this recorded Basic code.

dim args(1) as new com.sun.star.beans.PropertyValue
args(0).Name = "Name"
args(0).Value = "file:///path/to/the_document.odt"
args(1).Name = "Filter"
args(1).Value = "writer8"
dispatcher.executeDispatch(document, ".uno:InsertDoc", "", 0, args())
```

Title: How to merge office documents?


问:
Passing parameter in crystal report using C#.NET
How to pass the parameter in Crystal report?</p>

答:
we can give a more detailed answer if the question is more detailed.

but in a nutshell, you can use ParameterField object to contain your parameter(s), add it to a ParameterFields object, and pass this to the ParameterFieldInfo property of you Crystal Report Viewer.