问:
Android: How do you have multiple attr with same enum?
I have an attr defined as an enum with a list of values:

```<code><attr name="font" format="enum">
    <enum name="AvenirMedium" value="1" />
    <enum name="AvenirBlack" value="2" />
</attr>
</code>```

I would like to use multiple attr with different names within the same .

For example:

```<code><declare-styleable name="CustomView">
    <attr name="font" />
    <attr name="leftFont" />
    <attr name="rightFont" />
</declare-styleable>
</code>```

Instead of defining the enum multiple times, I am trying to find a way to have the enum defined once, but to have font, leftFont, rightFont all using the same enum list.

Does anyone know how this can be accomplished?

Edit: I am well aware of how to define the attr globally and reference it in multiple declare-styleable. This question is to use the enum in multiple attr with different names.

答:
As the name is only parameter of attr that serves as key, the answer is:
no.. umfortunetly it is not possible..

You have to make identical enums with different names.

Body:
I have an attr defined as an enum with a list of values:

<attr name="font" format="enum">
    <enum name="AvenirMedium" value="1" />
    <enum name="AvenirBlack" value="2" />
</attr>

I would like to use multiple attr with different names within the same .

For example:

<declare-styleable name="CustomView">
    <attr name="font" />
    <attr name="leftFont" />
    <attr name="rightFont" />
</declare-styleable>

Instead of defining the enum multiple times, I am trying to find a way to have the enum defined once, but to have font, leftFont, rightFont all using the same enum list.

Does anyone know how this can be accomplished?

Edit: I am well aware of how to define the attr globally and reference it in multiple declare-styleable. This question is to use the enum in multiple attr with different names.


来源: stackexchange

问:
tag contents not returning in beautifulsoup
I have the following string I'm trying to extract:

```<code><item>
<dc:creator><![CDATA[Chris M]]></dc:creator>
<pubDate>Tue, 06 Jun 2017 07:38:23 +0000</pubDate>
</item>
</code>```

I'm trying to get the name Chris M and other authors with this:

```<code>soup = BeautifulSoup(response, "lxml")
items = soup.findAll("item")
            for i in items:
                 author = i.find('dc:creator')
                 print author
</code>```

This outputs:

```<code><dc:creator></dc:creator>
</code>```

How can I get the name contents from the tag?

答:
This worked for me using Python 3 - https://repl.it/languages/python3

Specifying parser as xml

```<code>import bs4 as bs
content="""
<collection>
    <item><dc:creator><![CDATA[Chris M]]></dc:creator></item>
    <item><dc:creator><![CDATA[Harris A]]></dc:creator></item>
</collection>
"""

soup = bs.BeautifulSoup(content, 'xml')

items = soup.findAll("item")
for i in items:
   author = i.find('creator')
   print(author.string)
</code>```

Output:

```<code>Chris M
Harris A
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have the following string I'm trying to extract:

<item>
<dc:creator><![CDATA[Chris M]]></dc:creator>
<pubDate>Tue, 06 Jun 2017 07:38:23 +0000</pubDate>
</item>

I'm trying to get the name Chris M and other authors with this:

soup = BeautifulSoup(response, "lxml")
items = soup.findAll("item")
            for i in items:
                 author = i.find('dc:creator')
                 print author

This outputs:

<dc:creator></dc:creator>

How can I get the name contents from the tag?

Body:
This worked for me using Python 3 - https://repl.it/languages/python3

Specifying parser as xml

import bs4 as bs
content="""
<collection>
    <item><dc:creator><![CDATA[Chris M]]></dc:creator></item>
    <item><dc:creator><![CDATA[Harris A]]></dc:creator></item>
</collection>
"""

soup = bs.BeautifulSoup(content, 'xml')

items = soup.findAll("item")
for i in items:
   author = i.find('creator')
   print(author.string)

Output:

Chris M
Harris A


问:
MongoDB: mongorestore failing for small database
I am setting up a Mongo DB database on mongolab. I have 2 small documents in a single collection in my local db server, that I want to upload. I used mongodump to export that to a collection.bson and collection.metadata.json file

When I use mongorestore I get an error:

Failed:database.collection: error restoring from /tmp/mongodump/database/collection.bson: insertion error: EOF

collection.bson is less than 2KB. My research shows that this error shows up when your database is huge, but not very small. I can't get anything for my situation. The common solution of using --batchSize 1 results in the same issue.

After I run mongorestore the collection does exist on the remote, but it is empty (0 documents)

How can I get my tiny local db up on my remote server (on MongoLab).

I am locally running mongo3.4, but my MongoLab instance is 3.2.13. I'm wondering if the problem is the mismatch of versions?

mongorestore command:

mongorestore -h ds111882.mlab.com:11882 -d database -u username -p password /tmp/mongodump/database

mongodump

mongodump -d database -o /tmp/mongodump

Additional info: I imported the mongodump I created into another local database (also running 3.4) and it worked just fine, but restoring to the mongolab server causes the error.

Also a bsondump of the generated collection.bson file creates a json file with the correct 2 documents.

答: Found the answer, it is an issue with versions. My schema was using the Decimal128 type, which isn't supported in 3.2. Downgrading to Double (didn't need Decimal128 anyway) fixed the issue.</p>


问:
Concept of functional interface
When I'm shooting a glance at lambda expressions, the book touches on a functional interface that has only one abstract method. My issue addresses on that quiz question

```<code>/* Which of these interfaces are functional interfaces? */
public interface Adder{
   int add(int a, int b);
}
public interface SmartAdder extends Adder{
   int add(double a, double b);
}
public interface Nothing{
}
</code>```

I know the last one is not, but I think the first and second ones should be functional interface. But the book says second one is not. Why? Doesn't it overrides add method? So even in second, isn't there only one abstract method?

答: SmartAdder has two methods. The method signatures are different. Functional Interface can have only one method.</p>

Title: Concept of functional interface

Body:
When I'm shooting a glance at lambda expressions, the book touches on a functional interface that has only one abstract method. My issue addresses on that quiz question

/* Which of these interfaces are functional interfaces? */
public interface Adder{
   int add(int a, int b);
}
public interface SmartAdder extends Adder{
   int add(double a, double b);
}
public interface Nothing{
}

I know the last one is not, but I think the first and second ones should be functional interface. But the book says second one is not. Why? Doesn't it overrides add method? So even in second, isn't there only one abstract method?


问:
Julia LightGraphs weakly_connected_components
Isn't it true that the weakly_connected_components in julia LightGraphs should provide connected components where if The DiGraph is turned into an undirected graph, then each component should be connected?
I have tried this and I do not receive such components? As an example I have tried this on the political blogs data as an undirected network

```<code>data=readdlm(path,',',Int64) #contains edges in each row
N_ = length(unique(vcat(data[:,1],data[:,2]))) ##to get number of vertices
network  = LightGraphs.DiGraph(N_)
#construct the network
for i in 1:size(data,1)
    add_edge!(network, Edge(data[i,1], data[i,2]))
end
#largest weakly connected component
net = weakly_connected_components(network)[1]
temp_net,vmap = induced_subgraph(network, net)
</code>```

and after getting the largest weakly connected component, I see the following:

```<code>isempty([i for i in vertices(temp_net) if isempty(edges(temp_net).adj[i])])

julia>false
</code>```

which signigies some nodes have no incoming or outgoing edges.
What can be the problem? I am using the latest release 6, but the LightGraphs package tests seem to be working.

答:
In addition to what @dan-getz said, I must implore you not to access any internal data fields of structures - we have accessors for everything that's "public". Specifically, edges(temp_net).adj is not guaranteed to be available. It's currently the same as fadj(g), the forward adjacency list of g, for both directed and undirected graphs, but it's not intended to be used except to help keep edge iteration state.

If you use .adj, your code will break on you without warning at some point.

Body:
Isn't it true that the weakly_connected_components in julia LightGraphs should provide connected components where if The DiGraph is turned into an undirected graph, then each component should be connected?
I have tried this and I do not receive such components? As an example I have tried this on the political blogs data as an undirected network

data=readdlm(path,',',Int64) #contains edges in each row
N_ = length(unique(vcat(data[:,1],data[:,2]))) ##to get number of vertices
network  = LightGraphs.DiGraph(N_)
#construct the network
for i in 1:size(data,1)
    add_edge!(network, Edge(data[i,1], data[i,2]))
end
#largest weakly connected component
net = weakly_connected_components(network)[1]
temp_net,vmap = induced_subgraph(network, net)

and after getting the largest weakly connected component, I see the following:

isempty([i for i in vertices(temp_net) if isempty(edges(temp_net).adj[i])])

julia>false

which signigies some nodes have no incoming or outgoing edges.
What can be the problem? I am using the latest release 6, but the LightGraphs package tests seem to be working.


问:
parse selective table rows in python with lxml and xpath
below is the structure of the html file that i wish to parse

```<code><tr data-mod-primary="true">
    <td>'some text'
<tr>
    <td>'some text'
<tr>
    <td>'some text'
<tr data-mod-primary="true">
    <td>'some text'
</code>```

I am interested in parsing only the text under
 and ignore other
's

I get all
 text through .xpath('//tr/td/text()') but this is not what I want. I have tried the below code after researching for solution for sometime:

```<code>.xpath('//tr[contains(@data-mod-primary="true",None)]/td/text()')
</code>```

but this too gets me the text under all
 basically same result as .xpath('//tr/td/text()')

Any help is appreciated. thank you.

答:
You can use @attr=value to extract specific tr tags:

```<code>//tr[@data-mod-primary='true']/td/text()
</code>```

Or if you use contains, it would be something like:

```<code>//tr[contains(@data-mod-primary, 'true')]/td/text()
</code>```

Body:
below is the structure of the html file that i wish to parse

    'some text'

    'some text'

    'some text'

    'some text'

I am interested in parsing only the text under
 and ignore other
's

I get all
 text through .xpath('//tr/td/text()') but this is not what I want. I have tried the below code after researching for solution for sometime:

.xpath('//tr[contains(@data-mod-primary="true",None)]/td/text()')

but this too gets me the text under all
 basically same result as .xpath('//tr/td/text()')

Any help is appreciated. thank you.

Body:
You can use @attr=value to extract specific tr tags:

//tr[@data-mod-primary='true']/td/text()

Or if you use contains, it would be something like:

//tr[contains(@data-mod-primary, 'true')]/td/text()


答:
An easy way to find out would be to try to define a class that implements SmartAdder. The compiler will tell you you need to implement both add(int, int) and add(double, double).

It's understandable that you thought add(double, double) would override add(int, int), but they are in fact separate methods, and could potentially have totally unrelated implementations.

If SmartAdder had defined a default implementation of add(int, int) it would be a functional interface still:

```<code>public interface SmartAdder extends Adder {
   int add(double a, double b);

   default int add(int a, int b) {
     return add((double)a, (double)b); // this calls the double method instead
  }
}
</code>```

You may also have come across the @FunctionalInterface annotation - this can be placed on an interface to enforce at compile-time that the interface has exactly one abstract method. If SmartAdder was annotated with @FunctionalInterface the interface itself would not compile.

Title: Concept of functional interface

Body:
An easy way to find out would be to try to define a class that implements SmartAdder. The compiler will tell you you need to implement both add(int, int) and add(double, double).

It's understandable that you thought add(double, double) would override add(int, int), but they are in fact separate methods, and could potentially have totally unrelated implementations.

If SmartAdder had defined a default implementation of add(int, int) it would be a functional interface still:

public interface SmartAdder extends Adder {
   int add(double a, double b);

   default int add(int a, int b) {
     return add((double)a, (double)b); // this calls the double method instead
  }
}

You may also have come across the @FunctionalInterface annotation - this can be placed on an interface to enforce at compile-time that the interface has exactly one abstract method. If SmartAdder was annotated with @FunctionalInterface the interface itself would not compile.


答:
interface SmartAdder overloads, not overrides interface Adder. That's because the name is the same name, but parameters types are different. Therefore, it has 2 functions. To be a functional interface it needs to have only one function.

==> Only interface Adder is a functional interface.

Title: Concept of functional interface


问:
How do I make Matlab help properly display web links for weird URLs?
Usually if I include, in the file foo.m, a comment of the form:

```<code>% See also: <a href="http://en.wikipedia.org/etc">link name</a>
</code>```

the link appears in the help browswer, i.e. in Matlab, I issue

```<code>>> help foo
</code>```

and I get something like

See also: link name

so far so good. However, there are some web addresses that have funny characters, for example:

```<code>% See also: <a href="http://en.wikipedia.org/wiki/Kernel_(statistics)">http://en.wikipedia.org/wiki/Kernel_(statistics)</a>
</code>```

Matlab does not render this correctly in the help browser. When I view the help, it looks like this:

See also:
statistics)">http://en.wikipedia.org/wiki/Kernel_(statistics)

where the link is to the local directory named 'statistics'. I have tried all kinds of quote escapes and backslashes, but cannot get the help browser to work properly.

答:
Url-escape the funny characters with character codes.

```<code>function foo
%FOO Function with funny help links
%
% Link to <a href="http://en.wikipedia.org/wiki/Kernel_%28statistics%29">some page</a>.
</code>```

The Matlab urlencode() function will show you what codes to use. But keep the colon and slashes as is.

```<code>>> disp(urlencode('Kernel_(statistics)'))
Kernel_%28statistics%29
</code>```

Here's a function that will quote the URL path elements, preserving the parts you need to leave intact.

```<code>function escapedUrl = escape_url_for_helptext(url)

ixColon = find(url == ':', 1);
if isempty(ixColon)
    [proto,rest] = deal('', url);
else
    [proto,rest] = deal(url(1:ixColon), url(ixColon+1:end));
end

parts = regexp(rest, '/', 'split');
encodedParts = cellfun(@urlencode, parts, 'UniformOutput', false);
escapedUrl = [proto join(encodedParts, '/')];

function out = join(strs, glue)

strs(1:end-1) = strcat(strs(1:end-1), {glue});
out = cat(2, strs{:});
</code>```

To use it, just pass in your whole URL.

```<code>>> escape_url_for_helptext('http://en.wikipedia.org/wiki/Kernel_(statistics)')
ans =
http://en.wikipedia.org/wiki/Kernel_%28statistics%29
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Usually if I include, in the file foo.m, a comment of the form:

% See also: link name

the link appears in the help browswer, i.e. in Matlab, I issue

>> help foo

and I get something like

See also: link name

so far so good. However, there are some web addresses that have funny characters, for example:

% See also: http://en.wikipedia.org/wiki/Kernel_(statistics)

Matlab does not render this correctly in the help browser. When I view the help, it looks like this:

See also:
statistics)">http://en.wikipedia.org/wiki/Kernel_(statistics)

where the link is to the local directory named 'statistics'. I have tried all kinds of quote escapes and backslashes, but cannot get the help browser to work properly.

Body:
Url-escape the funny characters with character codes.

function foo
%FOO Function with funny help links
%
% Link to <a href="http://en.wikipedia.org/wiki/Kernel_%28statistics%29">some page</a>.

The Matlab urlencode() function will show you what codes to use. But keep the colon and slashes as is.

>> disp(urlencode('Kernel_(statistics)'))
Kernel_%28statistics%29

Here's a function that will quote the URL path elements, preserving the parts you need to leave intact.

function escapedUrl = escape_url_for_helptext(url)

ixColon = find(url == ':', 1);
if isempty(ixColon)
    [proto,rest] = deal('', url);
else
    [proto,rest] = deal(url(1:ixColon), url(ixColon+1:end));
end

parts = regexp(rest, '/', 'split');
encodedParts = cellfun(@urlencode, parts, 'UniformOutput', false);
escapedUrl = [proto join(encodedParts, '/')];

function out = join(strs, glue)

strs(1:end-1) = strcat(strs(1:end-1), {glue});
out = cat(2, strs{:});

To use it, just pass in your whole URL.

>> escape_url_for_helptext('http://en.wikipedia.org/wiki/Kernel_(statistics)')
ans =
http://en.wikipedia.org/wiki/Kernel_%28statistics%29


问:
Countdown to zero instead of 1?
```<code>a = int(input("Enter a numeber: "))

for i in range(a):
    x = a - i
    print(x)
</code>```

How can I make this count down to zero instead of 1?

答:
Just add 1 to your range.

Your program now looks like:

```<code>a = int(input("Enter a number: "))

for i in range(a+1):
    x = a - i
    print(x)
</code>```

This is because range(n) goes from 0 to n-1, and so as you have it, your final iteration runs a - (a-1) = 1. To make your range go until a ( to calculate a - a ) you need to use range(a+1).

Title: Countdown to zero instead of 1?

Body:
a = int(input("Enter a numeber: "))

for i in range(a):
    x = a - i
    print(x)

How can I make this count down to zero instead of 1?

Body:
Just add 1 to your range.

Your program now looks like:

a = int(input("Enter a number: "))

for i in range(a+1):
    x = a - i
    print(x)

This is because range(n) goes from 0 to n-1, and so as you have it, your final iteration runs a - (a-1) = 1. To make your range go until a ( to calculate a - a ) you need to use range(a+1).


答:
You could use the three-argument form of range:

```<code>for i in range(a, -1, -1):
     print(i)
</code>```

It will start with a and then (because the step [third argument] is -1) count down to 0 because the stop value (-1 [second argument]) is excluded.

Title: Countdown to zero instead of 1?

Body:
You could use the three-argument form of range:

for i in range(a, -1, -1):
     print(i)

It will start with a and then (because the step [third argument] is -1) count down to 0 because the stop value (-1 [second argument]) is excluded.


问:
AWS Cost Management and Starting Multiple Instances based on tag
I am trying to accomplish two things: 1. Power management, 2. The ability to start groups of servers based on a common tag or other feature.

Power Management: I did look at EC2 Scheduler for shutting down and starting up systems, the problem the development shop here is very flexible and might work at spurious times throughout the day or night.  Weekends are probably solid to shut down instances, but I am thinking CloudWatch alarms (maybe deployed through cloudformation) are a better solution; just shut down servers when they idle for a long enough period?

Startup is the one I'm still not sure of.  If everything is shut down via CloudWatch Alarms, then I need it to be easy for developers to bring up groups of servers without much trouble - so a simple command at most.  Is there a way to accomplish this based on tagging or something of that nature?

Note This is for the development environment, production will use different power management.

Thanks!

答:
It is a common practice to stop/start Amazon EC2 instances based on a tag.

Here is an example in Python: stopinator.py

Or, you could do it with the AWS Command-Line Interface (CLI).

This command lists all instances with a given tag:

```<code>aws ec2 describe-instances --filter Name=tag:Department,Values=HR --query Reservations[*].Instances[*].InstanceId --output text
</code>```

It can be inserted into a command to stop instances:

```<code>aws ec2 stop-instances --instance-ids `aws ec2 describe-instances --filter Name=tag:cleanup,Values=ignore --query Reservations[*].Instances[*].InstanceId --output text`
</code>```

You could provide this as a script that your Developers could run when they want to stop/start instances. Or, you could write a small web-app that they access via a web page, that calls it on their behalf. (More secure, since you don't need to provide them with credentials.)

Body:
It is a common practice to stop/start Amazon EC2 instances based on a tag.

Here is an example in Python: stopinator.py

Or, you could do it with the AWS Command-Line Interface (CLI).

This command lists all instances with a given tag:

aws ec2 describe-instances --filter Name=tag:Department,Values=HR --query Reservations[*].Instances[*].InstanceId --output text

It can be inserted into a command to stop instances:

aws ec2 stop-instances --instance-ids `aws ec2 describe-instances --filter Name=tag:cleanup,Values=ignore --query Reservations[*].Instances[*].InstanceId --output text`

You could provide this as a script that your Developers could run when they want to stop/start instances. Or, you could write a small web-app that they access via a web page, that calls it on their behalf. (More secure, since you don't need to provide them with credentials.)


问:
Scanner not recognized by Microsoft POS
I have a barcode scanner from Metro Technologies and I am using Microsoft POS
to detect the input from the scanner. It is connected to my system using USB
port. But the scanner is not getting identified by the POS.</p>

```<code>public Form1()
{
InitializeComponent();
explorer = new PosExplorer(this);
explorer.DeviceAddedEvent += new
DeviceChangedEventHandler(explorer_DeviceAddedEvent);
}

void explorer_DeviceAddedEvent(object sender, DeviceChangedEventArgs e)
{
if (e.Device.Type == "Scanner")
{
scanner = (Scanner)explorer.CreateInstance(e.Device);
scanner.Open();
scanner.Claim(1000);
scanner.DeviceEnabled = true;
scanner.DataEvent += new
DataEventHandler(activeScanner_DataEvent);
scanner.DataEventEnabled = true;
scanner.DecodeData = true;
}
}

void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
txtbScanDataLabel.Text =
encoder.GetString(activeScanner.ScanDataLabel);
// Display the encoding type
txtbScanDataType.Text = activeScanner.ScanDataType.ToString();

// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}
</code>```

答:
From some forums and also in POS SDK documentation:

You have to add this in an xml file in the directory:

```<code>C:\Program Files\Common Files\microsoft shared\Point Of Service\Control Configurations\
</code>```

```<code><PointOfServiceConfig Version="1.0">
 <ServiceObject Type="Scanner" Name="Example scanner">
  <HardwareId From="HID\VID_04B4&PID_0100&REV_0001" To="HID\VID_04B4&PID_0100&REV_0001" />
 </ServiceObject>
</PointOfServiceConfig>
</code>```

You have to check the Hardware Id of your device and replace it inside the <HardwareId> tag

This is plug and play configuration.

Title: Scanner not recognized by Microsoft POS

Body:
I have a barcode scanner from Metro Technologies and I am using Microsoft POS
to detect the input from the scanner. It is connected to my system using USB
port. But the scanner is not getting identified by the POS.

public Form1()
{
InitializeComponent();
explorer = new PosExplorer(this);
explorer.DeviceAddedEvent += new
DeviceChangedEventHandler(explorer_DeviceAddedEvent);
}

void explorer_DeviceAddedEvent(object sender, DeviceChangedEventArgs e)
{
if (e.Device.Type == "Scanner")
{
scanner = (Scanner)explorer.CreateInstance(e.Device);
scanner.Open();
scanner.Claim(1000);
scanner.DeviceEnabled = true;
scanner.DataEvent += new
DataEventHandler(activeScanner_DataEvent);
scanner.DataEventEnabled = true;
scanner.DecodeData = true;
}
}

void activeScanner_DataEvent(object sender, DataEventArgs e)
{
UpdateEventHistory("Data Event");
ASCIIEncoding encoder = new ASCIIEncoding();
try
{
// Display the ASCII encoded label text
txtbScanDataLabel.Text =
encoder.GetString(activeScanner.ScanDataLabel);
// Display the encoding type
txtbScanDataType.Text = activeScanner.ScanDataType.ToString();

// re-enable the data event for subsequent scans
activeScanner.DataEventEnabled = true;
}
catch (PosControlException)
{
// Log any errors
UpdateEventHistory("DataEvent Operation Failed");
}
}

Body:
From some forums and also in POS SDK documentation:

You have to add this in an xml file in the directory:

C:\Program Files\Common Files\microsoft shared\Point Of Service\Control Configurations\

<PointOfServiceConfig Version="1.0">
 <ServiceObject Type="Scanner" Name="Example scanner">
  <HardwareId From="HID\VID_04B4&amp;PID_0100&amp;REV_0001" To="HID\VID_04B4&amp;PID_0100&amp;REV_0001" />
 </ServiceObject>
</PointOfServiceConfig>

You have to check the Hardware Id of your device and replace it inside the <HardwareId> tag

This is plug and play configuration.


答:
You can also use a while-loop like:

```<code>a = int(input("Enter a numeber: "))
while a >= 0:
    print(a)
    a -= 1
</code>```

output:

```<code>Enter a numeber: 10
10
9
8
7
6
5
4
3
2
1
0
</code>```

if you want to use a for loop you just need to use a+1 in the range:

```<code>a = int(input("Enter a numeber: "))
for i in range(a+1):
    print(a-i)
</code>```

Title: Countdown to zero instead of 1?

Body:
You can also use a while-loop like:

a = int(input("Enter a numeber: "))
while a >= 0:
    print(a)
    a -= 1

output:

Enter a numeber: 10
10
9
8
7
6
5
4
3
2
1
0

if you want to use a for loop you just need to use a+1 in the range:

a = int(input("Enter a numeber: "))
for i in range(a+1):
    print(a-i)


问:
Using VS2017 can I compile the DB structure and data into an SQL file, then upload it into another DB?
Using VS2017. Can I compile the DB structure and data into an SQL file, then upload it into another DB?

I'm thinking the SQL file will have the Create Table Statements and all that. Then later in that same file the statements to build the data.

答:
I took each table individually then each table data script, put them in a file and uploaded it. Took a bit of time but it worked.

basically it was :

```<code>CREATE DATABASE TMSProgram;

CREATE TABLE [dbo].[Billing] (
    [ordernumber]  INT             NOT NULL,
    [billto]       NVARCHAR (50)   NULL,
...
);

INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (2, N'ABC Fruits', CAST(50.00 AS Decimal(10, 2)), N'y', N'y', CAST(15.00 AS Decimal(10, 2)), N'y', N'none', 20045)
INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (3, N'Steveggg', CAST(36.00 AS Decimal(10, 2)), N'y', N'y', CAST(40.00 AS Decimal(10, 2)), N'y', N'none', 20045)
INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (4, N'Dan''s Tackle Shop', NULL, N'y', N'y', NULL, N'y', N'none', 20045)
...
</code>```

Body:
I took each table individually then each table data script, put them in a file and uploaded it. Took a bit of time but it worked.

basically it was :

CREATE DATABASE TMSProgram;

CREATE TABLE [dbo].[Billing] (
    [ordernumber]  INT             NOT NULL,
    [billto]       NVARCHAR (50)   NULL,
...
);

INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (2, N'ABC Fruits', CAST(50.00 AS Decimal(10, 2)), N'y', N'y', CAST(15.00 AS Decimal(10, 2)), N'y', N'none', 20045)
INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (3, N'Steveggg', CAST(36.00 AS Decimal(10, 2)), N'y', N'y', CAST(40.00 AS Decimal(10, 2)), N'y', N'none', 20045)
INSERT INTO [dbo].[Billing] ([ordernumber], [billto], [totalcharges], [tcposted], [paid], [driverpay], [dpposted], [paperwork], [compid]) VALUES (4, N'Dan''s Tackle Shop', NULL, N'y', N'y', NULL, N'y', N'none', 20045)
...


问:
PANDAS how to drop columns that have numbers and combine the rest of the columns
I have a DataFrame:

```<code>     A          B       C
  0 PQ          None    None
  1 Chieti      None    None
  2 Gainesville None    None
  3 Wenzhou     325027  None
  4 Boston      None    None
  5 D-53127     Bonn    None
  6 SE-11282    Stockholm None
  7 Birmingham  None    None
  8 Miami       None    None
  9 Los         Angeles None
</code>```

I want to combine the text in all columns  and create a new column which is column 'D' here .However I do not want to include the column if there are numbers or digits in that column . My final output should look like this:

```<code>     A          B       C       D
  0 PQ          None    None    PQ
  1 Chieti      None    None    Chieti
  2 Gainesville None    None    Gainesville
  3 Wenzhou     325027  None    Wenzhou
  4 Boston      None    None    Boston
  5 D-53127     Bonn    None    Bonn
  6 SE-11282    Stockholm None  Stockholm
  7 Birmingham  None    None    Birmingham
  8 Miami       None    None    Miami
  9 Los         Angeles None    LosAngeles
</code>```

Could the knowledgeable folks in Stackoverflow give me an insight into solving this using PANDAS/python

答:
You could do this by applying a function over the rows with apply(...,axis=1).

```<code>import pandas as pd

def row_func(row):
    def num_there(s):
        return any(i.isdigit() for i in s)
    result = []
    for x in row:
        if x and not num_there(str(x)):
            result.append(str(x))
    return ''.join(result)

df['D'] = df.apply(row_func, axis=1)
</code>```

Body:
I have a DataFrame:

     A          B       C
  0 PQ          None    None
  1 Chieti      None    None
  2 Gainesville None    None
  3 Wenzhou     325027  None
  4 Boston      None    None
  5 D-53127     Bonn    None
  6 SE-11282    Stockholm None
  7 Birmingham  None    None
  8 Miami       None    None
  9 Los         Angeles None

I want to combine the text in all columns  and create a new column which is column 'D' here .However I do not want to include the column if there are numbers or digits in that column . My final output should look like this:

     A          B       C       D
  0 PQ          None    None    PQ
  1 Chieti      None    None    Chieti
  2 Gainesville None    None    Gainesville
  3 Wenzhou     325027  None    Wenzhou
  4 Boston      None    None    Boston
  5 D-53127     Bonn    None    Bonn
  6 SE-11282    Stockholm None  Stockholm
  7 Birmingham  None    None    Birmingham
  8 Miami       None    None    Miami
  9 Los         Angeles None    LosAngeles

Could the knowledgeable folks in Stackoverflow give me an insight into solving this using PANDAS/python

Body:
You could do this by applying a function over the rows with apply(...,axis=1).

import pandas as pd

def row_func(row):
    def num_there(s):
        return any(i.isdigit() for i in s)
    result = []
    for x in row:
        if x and not num_there(str(x)):
            result.append(str(x))
    return ''.join(result)

df['D'] = df.apply(row_func, axis=1)


问:
Using Python to search google and store the websites into variables
I looking for a way to search google with python and store each website into a slot in an data list. Im looking for something like the example code below.

```<code>search=input('->')
results=google.search((search),(10))
print results
</code>```

In this case i want it to search google for whatever is in the variable "search", 10 is the amount of results I want to store in the variable and finally putting them on the screen with the "print results".

I would appreciate any help or anything similar to what I want. Thanks.

答:
As mentioned above google does provide an api for completing searches (https://developers.google.com/custom-search/json-api/v1/overview), and as mentioned depending on what you are trying to accomplish can get quite expensive. Another option is to scrap the google page. Below is an example I created using Beautiful Soup (https://www.crummy.com/software/BeautifulSoup/bs4/doc/#) to scrap the google result.

import urllib2
    import xml.etree.ElementTree
    from bs4 import BeautifulSoup #install using 'pip install beautifulsoup4'

```<code>'''
Since spaces will not work in url parameters, the spaces have to be converted int '+'
ex) "example text" -> "example+text"
'''
def spacesToPluses(string):
    words = string.split(" ")
    convertedString = ""
    for i in range(0, len(words)):
        convertedString += words[i] + "+"
    return convertedString[0:len(convertedString)-1]

'''
Opens the url with the parameter included and reads it as a string
'''
def getRawGoogleResponse(url):
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    headers={'User-Agent':user_agent,} #Required for google to allow url request

    request=urllib2.Request(url,None,headers)
    response = urllib2.urlopen(request)
    rawResponse = response.read()
    return rawResponse

'''
Takes in the raw string representation and converts it into an easier to navigate object (Beautiful Soup)
'''
def getParsedGoogleResponse(url):
    rawResponse = getRawGoogleResponse(url)
    fullPage = BeautifulSoup(rawResponse, 'html.parser')
    return fullPage

'''
Finds all of the urls on a single page
'''
def getGoogleResultsOnPage(fullPage):
    searchResultContainers = fullPage.find_all("h3", {"class": "r"}) #the results are contained in an h3 element with the class 'r'
    pageUrls = []
    for container in searchResultContainers: #get each link in the container
        fullUrl = container.find('a')['href']
        beginningOfUrl = fullUrl.index('http')
        pageUrls.append(fullUrl[beginningOfUrl:])#Chops off the extra bits google adds to the url
    return pageUrls

'''
Returns number of pages (max of 10)
'''
def getNumPages(basePage):
    navTable = basePage.find("table", {"id" : "nav"}) #The nav table contains the number of pages (up to 10)
    pageNumbers = navTable.find_all("a", {"class" : "fl"})
    lastPageNumber = int(pageNumbers[len(pageNumbers)-2].text)
    return lastPageNumber

'''
Loops through pages gathering url from each page
'''
def getAllGoogleSearchResults(search, numResults):
    baseUrl = "https://www.google.com/search?q=" + spacesToPluses(search)
    basePage = getParsedGoogleResponse(baseUrl)
    numPages = getNumPages(basePage)
    allUrls = []
    for i in range(0, numPages):
        completeUrl = baseUrl + "&start=" + str(i * 10) #google uses the parameter 'start' to represent the url to start at (10 urls pre page)
        page = getParsedGoogleResponse(completeUrl)
        for url in getGoogleResultsOnPage(page):
            allUrls.append(url)
    return allUrls[0:numResults]#return just the number of results

def main():
    print(getAllGoogleSearchResults("even another test", 1))

main()
</code>```

The solution works for the first 10 pages (or next highest) of google results. The urls are returned in an array of string objects. The information is scrapped by getting the response using urllib2. Hope this helps.

Body:
I looking for a way to search google with python and store each website into a slot in an data list. Im looking for something like the example code below.

search=input('->')
results=google.search((search),(10))
print results

In this case i want it to search google for whatever is in the variable "search", 10 is the amount of results I want to store in the variable and finally putting them on the screen with the "print results".

I would appreciate any help or anything similar to what I want. Thanks.

Body:
As mentioned above google does provide an api for completing searches (https://developers.google.com/custom-search/json-api/v1/overview), and as mentioned depending on what you are trying to accomplish can get quite expensive. Another option is to scrap the google page. Below is an example I created using Beautiful Soup (https://www.crummy.com/software/BeautifulSoup/bs4/doc/#) to scrap the google result.

import urllib2
    import xml.etree.ElementTree
    from bs4 import BeautifulSoup #install using 'pip install beautifulsoup4'

'''
Since spaces will not work in url parameters, the spaces have to be converted int '+'
ex) "example text" -> "example+text"
'''
def spacesToPluses(string):
    words = string.split(" ")
    convertedString = ""
    for i in range(0, len(words)):
        convertedString += words[i] + "+"
    return convertedString[0:len(convertedString)-1]

'''
Opens the url with the parameter included and reads it as a string
'''
def getRawGoogleResponse(url):
    user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
    headers={'User-Agent':user_agent,} #Required for google to allow url request

    request=urllib2.Request(url,None,headers)
    response = urllib2.urlopen(request)
    rawResponse = response.read()
    return rawResponse

'''
Takes in the raw string representation and converts it into an easier to navigate object (Beautiful Soup)
'''
def getParsedGoogleResponse(url):
    rawResponse = getRawGoogleResponse(url)
    fullPage = BeautifulSoup(rawResponse, 'html.parser')
    return fullPage

'''
Finds all of the urls on a single page
'''
def getGoogleResultsOnPage(fullPage):
    searchResultContainers = fullPage.find_all("h3", {"class": "r"}) #the results are contained in an h3 element with the class 'r'
    pageUrls = []
    for container in searchResultContainers: #get each link in the container
        fullUrl = container.find('a')['href']
        beginningOfUrl = fullUrl.index('http')
        pageUrls.append(fullUrl[beginningOfUrl:])#Chops off the extra bits google adds to the url
    return pageUrls

'''
Returns number of pages (max of 10)
'''
def getNumPages(basePage):
    navTable = basePage.find("table", {"id" : "nav"}) #The nav table contains the number of pages (up to 10)
    pageNumbers = navTable.find_all("a", {"class" : "fl"})
    lastPageNumber = int(pageNumbers[len(pageNumbers)-2].text)
    return lastPageNumber

'''
Loops through pages gathering url from each page
'''
def getAllGoogleSearchResults(search, numResults):
    baseUrl = "https://www.google.com/search?q=" + spacesToPluses(search)
    basePage = getParsedGoogleResponse(baseUrl)
    numPages = getNumPages(basePage)
    allUrls = []
    for i in range(0, numPages):
        completeUrl = baseUrl + "&start=" + str(i * 10) #google uses the parameter 'start' to represent the url to start at (10 urls pre page)
        page = getParsedGoogleResponse(completeUrl)
        for url in getGoogleResultsOnPage(page):
            allUrls.append(url)
    return allUrls[0:numResults]#return just the number of results

def main():
    print(getAllGoogleSearchResults("even another test", 1))

main()

The solution works for the first 10 pages (or next highest) of google results. The urls are returned in an array of string objects. The information is scrapped by getting the response using urllib2. Hope this helps.


问:
Cross-thread exception after async call
The code block below causes cross-thread invalid operation exception only with Npgsql (not sqlclient, sqlite, mysql, file read async).

```<code>private async void button1_Click(object sender, EventArgs e)
{
   var strBuilder = new Npgsql.NpgsqlConnectionStringBuilder()
   {
        Host = "localhost",
        Username = "postgres",
        Password = "password"
   };
   using (var conn = new Npgsql.NpgsqlConnection(strBuilder.ConnectionString))
   {
      try
      {
          await conn.OpenAsync();
          if (conn.State ==ConnectionState.Open)
          {
             MessageBox.Show("Connected");
             this.button1.Text = "CROSS-THREAD-With-NPGSQL";
          }
       }
    }
}
</code>```

I looked at the code from Npgsql and found this link:
https://github.com/npgsql/npgsql/blob/2dd46e7c544caf3302ca7b89dd888a16dccf5c2c/src/Npgsql/PGUtil.cs

At the bottom of the file, it said:

This mechanism is used to temporarily set the current synchronization
  context to null while executing Npgsql code, making all await
  continuations execute on the thread pool. This replaces the need to
  place ConfigureAwait(false) everywhere, and should be used in all
  surface async methods, without exception.

I have got quite an explanation from Roji (owner of the Npgsql repos) but I need to understand why I don't see similar issue with other drivers. Is the way npgsql temporary disabling the SynchronizationContext considered best practice? I am trying to look at the source code from other drivers but it will take a while so I hope I can get some help to head in the right direction.

Edit 1:
Stephen Cleary gave a very detailed answer below but I want to post some of my findings here as well. It may help others.
On 09/24/16, npgsql replaced all ConfigureAwait(false) by NoSynchronizationContextScope. As Stephen explained, the NoSynchronizationContextScope temporary cleared the caller context, thus causing such behavior. ConfigureAwait(false), on the other hand, doesn't do such thing and that should not have been replaced. To verify, I installed npgsql 3.1.7 (the version right before 09/24/16) and I didn't see the cross-thread exception anymore.

答:
Is the way npgsql temporary disabling the SynchronizationContext considered best practice?

No. The idea is not a bad one: to null out SynchronizationContext.Current for internal methods. However, their implementation is buggy because it does clear the caller's SynchronizationContext.Current.

This is because the original SynchronizationContext must be restored synchronously, not after an await. NoSynchronizationContextScope.Disposable must be disposed before the surface async method returns an incomplete task to its caller.

Thus, using this simple example:

```<code>public async Task<NpgsqlLargeObjectStream> OpenReadAsync(uint oid, CancellationToken cancellationToken)
{
  cancellationToken.ThrowIfCancellationRequested();
  using (NoSynchronizationContextScope.Enter())
    return await OpenRead(oid, true);
}
</code>```

The order of operations is:

Some thread calls OpenReadAsync.

The cancellationToken is checked.

NoSynchronizationContextScope.Enter saves and then clears SynchronizationContext.Current.

OpenRead is called and returns an incomplete task.

The task is awaited, which causes OpenReadAsync to return to its caller.

The calling thread has lost its SynchronizationContext.

Later, when the task returned from OpenRead completes:

A thread pool thread is picked up to resume executing OpenReadAsync.

The NoSynchronizationContextScope.Disposable is disposed, which sets SynchronizationContext.Current to its original value.

The task returned from OpenReadAsync is completed.

A thread pool thread now has an incorrect SynchronizationContext.

So, no, I would say that is totally buggy.

This is why my SynchronizationContextSwitcher.NoContext forces you to pass in a delegate: so it can force the disposal to occur synchronously. Its usage is more awkward, but it's forced to have correct semantics:

```<code>public Task<NpgsqlLargeObjectStream> OpenReadAsync(uint oid, CancellationToken cancellationToken) =>
  SynchronizationContextSwitcher.NoContext(async () =>
  {
    cancellationToken.ThrowIfCancellationRequested();
    return await OpenRead(oid, true);
  });
</code>```

Title: Cross-thread exception after async call

Body:
The code block below causes cross-thread invalid operation exception only with Npgsql (not sqlclient, sqlite, mysql, file read async).

private async void button1_Click(object sender, EventArgs e)
{
   var strBuilder = new Npgsql.NpgsqlConnectionStringBuilder()
   {
        Host = "localhost",
        Username = "postgres",
        Password = "password"
   };
   using (var conn = new Npgsql.NpgsqlConnection(strBuilder.ConnectionString))
   {
      try
      {
          await conn.OpenAsync();
          if (conn.State ==ConnectionState.Open)
          {
             MessageBox.Show("Connected");
             this.button1.Text = "CROSS-THREAD-With-NPGSQL";
          }
       }
    }
}

I looked at the code from Npgsql and found this link:
https://github.com/npgsql/npgsql/blob/2dd46e7c544caf3302ca7b89dd888a16dccf5c2c/src/Npgsql/PGUtil.cs

At the bottom of the file, it said:

This mechanism is used to temporarily set the current synchronization
  context to null while executing Npgsql code, making all await
  continuations execute on the thread pool. This replaces the need to
  place ConfigureAwait(false) everywhere, and should be used in all
  surface async methods, without exception.

I have got quite an explanation from Roji (owner of the Npgsql repos) but I need to understand why I don't see similar issue with other drivers. Is the way npgsql temporary disabling the SynchronizationContext considered best practice? I am trying to look at the source code from other drivers but it will take a while so I hope I can get some help to head in the right direction.

Edit 1:
Stephen Cleary gave a very detailed answer below but I want to post some of my findings here as well. It may help others.
On 09/24/16, npgsql replaced all ConfigureAwait(false) by NoSynchronizationContextScope. As Stephen explained, the NoSynchronizationContextScope temporary cleared the caller context, thus causing such behavior. ConfigureAwait(false), on the other hand, doesn't do such thing and that should not have been replaced. To verify, I installed npgsql 3.1.7 (the version right before 09/24/16) and I didn't see the cross-thread exception anymore.

Body:
Is the way npgsql temporary disabling the SynchronizationContext considered best practice?

No. The idea is not a bad one: to null out SynchronizationContext.Current for internal methods. However, their implementation is buggy because it does clear the caller's SynchronizationContext.Current.

This is because the original SynchronizationContext must be restored synchronously, not after an await. NoSynchronizationContextScope.Disposable must be disposed before the surface async method returns an incomplete task to its caller.

Thus, using this simple example:

public async Task<NpgsqlLargeObjectStream> OpenReadAsync(uint oid, CancellationToken cancellationToken)
{
  cancellationToken.ThrowIfCancellationRequested();
  using (NoSynchronizationContextScope.Enter())
    return await OpenRead(oid, true);
}

The order of operations is:

Some thread calls OpenReadAsync.

The cancellationToken is checked.

NoSynchronizationContextScope.Enter saves and then clears SynchronizationContext.Current.

OpenRead is called and returns an incomplete task.

The task is awaited, which causes OpenReadAsync to return to its caller.

The calling thread has lost its SynchronizationContext.

Later, when the task returned from OpenRead completes:

A thread pool thread is picked up to resume executing OpenReadAsync.

The NoSynchronizationContextScope.Disposable is disposed, which sets SynchronizationContext.Current to its original value.

The task returned from OpenReadAsync is completed.

A thread pool thread now has an incorrect SynchronizationContext.

So, no, I would say that is totally buggy.

This is why my SynchronizationContextSwitcher.NoContext forces you to pass in a delegate: so it can force the disposal to occur synchronously. Its usage is more awkward, but it's forced to have correct semantics:

public Task<NpgsqlLargeObjectStream> OpenReadAsync(uint oid, CancellationToken cancellationToken) =>
  SynchronizationContextSwitcher.NoContext(async () =>
  {
    cancellationToken.ThrowIfCancellationRequested();
    return await OpenRead(oid, true);
  });


问:
Class duplicates input objects
I have two python class objects that I use to extract data from Oracle to ArcMap.  The various activities in the process cause me to start with a list of 'column' objects and build a pyTable object.  The pyTable object has a list of insert Fields by name.  During __init__ I use the getSelect() function to populate the list of insert Fields.

I have added a bunch of statements to make sure that each time I call pyTable I get a newly created object, but I'm still seeing a strange result.  The first time I use the class, all is fine.  The second time I issue the same statement, the colList is new, but the field list is duplicated.  My apologies for not cleaning out the extraneous code sections.

Where am I messing up my object references?

Here are the execution results.  myList has 8 column objects.

>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
16
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> newTable = pyTable(myList)
>>> len(newTable.getTuple())
8
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
16
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
24
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
8
>>>
```

<p>Here are the two classes:</p>

```import arcpy, cx_Oracle

class column:
    # Add to the arcType and cxType functions to support more Oracle data types.
    # BLOB and CLOB fields will need additional support in Read and Write fx's.
      name = ''
      dataType = ''
      dataLen = 1
      dataPrecision = 0
      dataScale = 0
      query = ''
      isShape = False
      isLOB = False

      def __init__(self, Name, DataType, DataLen, DataPrecision, DataScale):
          self.name = Name
          self.dataType = DataType
          self.dataLen = DataLen
          self.dataPrecision = DataPrecision
          self.dataScale = DataScale
          if DataType == 'WKT':
              self.query = 'sdo_util.to_wktgeometry(t.' + Name + ') wkb, '
          else:
              self.query = 't.' + Name
          if DataType == 'SDO_GEOMETRY':
              self.isShape = True
          if DataType == 'BLOB' or DataType == 'CLOB' or DataType == 'WKT':
              self.isLOB = True

      def getArcType(self, *args):        # Data type translation 'Oracle_type':'ESRI_type'
          return {
#             'BINARY_DOUBLE':'DOUBLE',
#             'BINARY_FLOAT':'FLOAT',
#             'BLOB':'BLOB',
              'CHAR':'STRING',
              'CLOB':'CLOB',
              'DATE':'DATE',
#             'FLOAT':'FLOAT',
#             'LONG':'LONG',
#             'LONG RAW':'BLOB',
              'NUMBER':'DOUBLE',
#             'RAW':'BLOB',
#             'ROWID':'SHORT',
              'SDO_GEOMETRY':'GEOMETRY',
              'VARCHAR2':'STRING',
              'WKT':'WKT',
          }.get(self.dataType,"undefined")

      def getCxType(self, *args):        # Data type translation 'Oracle_type':'cx_Oracle.type'
          return {
              'BLOB':cx_Oracle.BLOB,
              'CHAR':cx_Oracle.STRING,
              'CLOB':cx_Oracle.CLOB,
              'DATE':cx_Oracle.DATETIME,
              'NUMBER':cx_Oracle.NUMBER,
              'SDO_GEOMETRY':cx_Oracle.CLOB,
              'VARCHAR2':cx_Oracle.STRING,
          }.get(self.dataType,"undefined")

class pyTable:
    # Create an object to track columns for read and write operations.
    # BLOB, CLOB and SDO_GEOMETRY types will need additional support in Read and Write fx's.
    length = 0
    # colList = []       # The original list of columns is coming from an Oracle query.
    # These two lists are different because of the way I treat shape.
    # I create a FC and then add attribute columns.  This puts the Shape column first in the list.
    __insCols = []       # I use insCols as a list of column type objects to write to ArcMap.
    __insertFields = []
    __colTuple = None
    __myData = []
    __pKey = 'P_KEY'     # The name of the primary key field should be
_CN
    __insBlobCols = []   # A list of column positions that contain BLOB data types.
    __insKeyCol = -1     # The position of the primary key column.

    def __init__(self, ColList):
        self.colList = ColList[:]
        self.length = len(ColList)
        self.isFC = self.__getShape()
        self.__select = self.getSelect()
        arcpy.AddMessage('New table class created with ' + str(self.length) + ' columns.')

    def __del__(self):
        self.colList = []
        del self.__insCols [:]
        del self.__insertFields [:]
        del self.__myData [:]
        del self.__insBlobCols [:]

    def addDataRow(self, inDataRow):
        self.__myData.append(inDataRow)

    def getInsCols(self):
        return self.__insCols

    def getTuple(self):
        return self.__colTuple

    def getPK(self):
        return self.__pKey

    def getInsBlobCols(self):
        return self.__insBlobCols

    def clearData(self):
        self.__myData = []

    def getData(self):
        return self.__myData

    def getKeyCol(self):
        return self.__insKeyCol

    def __getShape(self):
        isFeature = False
        featureName = ''
        for col in self.colList:
            if col.isShape:
                isFeature = True
                featureName = col.name
        if isFeature:
            wktShape = column(featureName, 'WKT', 0, 0, 0)
            self.__insCols.append(wktShape)
        for col in self.colList:
            if not col.isShape:
                self.__insCols.append(col)
        return isFeature

    def getSelect(self):
        # Build the select statement
        # Build the list of insert Field names
        # Build the Tuple of insert Field names
        # Identify the LOB columns by index number
        statement = 'select '
        del self.__insertFields[:]
        indx = 0
#        print ('Table has ', len(self.__insCols), ' insert columns.')
        for col in self.__insCols:
            if col.dataType == 'WKT':
                statement += 'sdo_util.to_wktgeometry(t.shape) wkb, '
                self.__insertFields.append('SHAPE@WKT')
            else:
                statement += 't.' + col.name + ', '
                self.__insertFields.append(col.name)
                if col.dataType == 'BLOB':
                    self.__insBlobCols.append(indx)
            #
            # ToDo: The key column should be
_CN
            #   But, the logic needs to work for views with different names.
            #
            if col.name == self.__pKey:
                self.__insKeyCol = indx
            indx += 1
        statement = statement[:statement.rfind(',')]  # Trim off the trailing comma
#        print ('Insert is composed of ', len(self.__insertFields), ' fields.' )
        self.__colTuple = tuple(self.__insertFields)
        return statement

    def createTemp(self, WorkSpace, tempFC):
        success = False
        insertCols = self.__insCols
        arcpy.AddMessage('Adding ' + tempFC + ' with ' + str(len(insertCols)) + ' columns.')
        try:
            if self.isFC:
                arcpy.CreateFeatureclass_management(WorkSpace, tempFC, 'POINT')
                arcpy.AddMessage(tempFC + ' feature class was successfully created.')
            else:
                arcpy.CreateTable_management(WorkSpace, tempFC)
                arcpy.AddMessage(tempFC + ' table was successfully created.')
            for col in insertCols:
                esriType = col.getArcType()
                if esriType == "undefined":
                    arcpy.AddError('Data type not currently supported, ' + col.dataType)
                    return success
                if col.dataType <> 'WKT':
                    arcpy.AddField_management(tempFC, col.name, esriType, col.dataPrecision, col.dataScale, col.dataLen)
                    arcpy.AddMessage('Created column: ' + col.name)
            success = True
        except:
            e = sys.exc_info()[1]
            arcpy.AddError('Create of ' + tempFC + ' failed with ' + str(e.args[0]))
        return success
```

答:
You are making a shallow copy of the list passed to your class in the init function.

See Shallow and deep copy operations in the Python documentation for some basic information.

self.colList = ColList[:] makes a new LIST, but inside that new list are references to the same objects that were in the original list (a shallow copy).

You need a deep copy:

```<code>import copy
...
self.colList = copy.deepcopy(ColList)
</code>```

A deep copy has a new list, as well as new objects initialized to match the objects in the original list.  So if the objects in one class' list change, they don't change in every class.

Title: Class duplicates input objects

Body:
I have two python class objects that I use to extract data from Oracle to ArcMap.  The various activities in the process cause me to start with a list of 'column' objects and build a pyTable object.  The pyTable object has a list of insert Fields by name.  During __init__ I use the getSelect() function to populate the list of insert Fields.

I have added a bunch of statements to make sure that each time I call pyTable I get a newly created object, but I'm still seeing a strange result.  The first time I use the class, all is fine.  The second time I issue the same statement, the colList is new, but the field list is duplicated.  My apologies for not cleaning out the extraneous code sections.

Where am I messing up my object references?

Here are the execution results.  myList has 8 column objects.

>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
16
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> arcTable = pyTable(myList)
>>> len(arcTable.getTuple())
8
>>> newTable = pyTable(myList)
>>> len(newTable.getTuple())
8
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
16
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
24
>>> thirdTable = pyTable(myList)
>>> len(thirdTable.getTuple())
8
>>>

Here are the two classes:

import arcpy, cx_Oracle

class column:
    # Add to the arcType and cxType functions to support more Oracle data types.
    # BLOB and CLOB fields will need additional support in Read and Write fx's.
      name = ''
      dataType = ''
      dataLen = 1
      dataPrecision = 0
      dataScale = 0
      query = ''
      isShape = False
      isLOB = False

      def __init__(self, Name, DataType, DataLen, DataPrecision, DataScale):
          self.name = Name
          self.dataType = DataType
          self.dataLen = DataLen
          self.dataPrecision = DataPrecision
          self.dataScale = DataScale
          if DataType == 'WKT':
              self.query = 'sdo_util.to_wktgeometry(t.' + Name + ') wkb, '
          else:
              self.query = 't.' + Name
          if DataType == 'SDO_GEOMETRY':
              self.isShape = True
          if DataType == 'BLOB' or DataType == 'CLOB' or DataType == 'WKT':
              self.isLOB = True

      def getArcType(self, *args):        # Data type translation 'Oracle_type':'ESRI_type'
          return {
#             'BINARY_DOUBLE':'DOUBLE',
#             'BINARY_FLOAT':'FLOAT',
#             'BLOB':'BLOB',
              'CHAR':'STRING',
              'CLOB':'CLOB',
              'DATE':'DATE',
#             'FLOAT':'FLOAT',
#             'LONG':'LONG',
#             'LONG RAW':'BLOB',
              'NUMBER':'DOUBLE',
#             'RAW':'BLOB',
#             'ROWID':'SHORT',
              'SDO_GEOMETRY':'GEOMETRY',
              'VARCHAR2':'STRING',
              'WKT':'WKT',
          }.get(self.dataType,"undefined")

      def getCxType(self, *args):        # Data type translation 'Oracle_type':'cx_Oracle.type'
          return {
              'BLOB':cx_Oracle.BLOB,
              'CHAR':cx_Oracle.STRING,
              'CLOB':cx_Oracle.CLOB,
              'DATE':cx_Oracle.DATETIME,
              'NUMBER':cx_Oracle.NUMBER,
              'SDO_GEOMETRY':cx_Oracle.CLOB,
              'VARCHAR2':cx_Oracle.STRING,
          }.get(self.dataType,"undefined")

class pyTable:
    # Create an object to track columns for read and write operations.
    # BLOB, CLOB and SDO_GEOMETRY types will need additional support in Read and Write fx's.
    length = 0
    # colList = []       # The original list of columns is coming from an Oracle query.
    # These two lists are different because of the way I treat shape.
    # I create a FC and then add attribute columns.  This puts the Shape column first in the list.
    __insCols = []       # I use insCols as a list of column type objects to write to ArcMap.
    __insertFields = []
    __colTuple = None
    __myData = []
    __pKey = 'P_KEY'     # The name of the primary key field should be
_CN
    __insBlobCols = []   # A list of column positions that contain BLOB data types.
    __insKeyCol = -1     # The position of the primary key column.

    def __init__(self, ColList):
        self.colList = ColList[:]
        self.length = len(ColList)
        self.isFC = self.__getShape()
        self.__select = self.getSelect()
        arcpy.AddMessage('New table class created with ' + str(self.length) + ' columns.')

    def __del__(self):
        self.colList = []
        del self.__insCols [:]
        del self.__insertFields [:]
        del self.__myData [:]
        del self.__insBlobCols [:]

    def addDataRow(self, inDataRow):
        self.__myData.append(inDataRow)

    def getInsCols(self):
        return self.__insCols

    def getTuple(self):
        return self.__colTuple

    def getPK(self):
        return self.__pKey

    def getInsBlobCols(self):
        return self.__insBlobCols

    def clearData(self):
        self.__myData = []

    def getData(self):
        return self.__myData

    def getKeyCol(self):
        return self.__insKeyCol

    def __getShape(self):
        isFeature = False
        featureName = ''
        for col in self.colList:
            if col.isShape:
                isFeature = True
                featureName = col.name
        if isFeature:
            wktShape = column(featureName, 'WKT', 0, 0, 0)
            self.__insCols.append(wktShape)
        for col in self.colList:
            if not col.isShape:
                self.__insCols.append(col)
        return isFeature

    def getSelect(self):
        # Build the select statement
        # Build the list of insert Field names
        # Build the Tuple of insert Field names
        # Identify the LOB columns by index number
        statement = 'select '
        del self.__insertFields[:]
        indx = 0
#        print ('Table has ', len(self.__insCols), ' insert columns.')
        for col in self.__insCols:
            if col.dataType == 'WKT':
                statement += 'sdo_util.to_wktgeometry(t.shape) wkb, '
                self.__insertFields.append('SHAPE@WKT')
            else:
                statement += 't.' + col.name + ', '
                self.__insertFields.append(col.name)
                if col.dataType == 'BLOB':
                    self.__insBlobCols.append(indx)
            #
            # ToDo: The key column should be
_CN
            #   But, the logic needs to work for views with different names.
            #
            if col.name == self.__pKey:
                self.__insKeyCol = indx
            indx += 1
        statement = statement[:statement.rfind(',')]  # Trim off the trailing comma
#        print ('Insert is composed of ', len(self.__insertFields), ' fields.' )
        self.__colTuple = tuple(self.__insertFields)
        return statement

    def createTemp(self, WorkSpace, tempFC):
        success = False
        insertCols = self.__insCols
        arcpy.AddMessage('Adding ' + tempFC + ' with ' + str(len(insertCols)) + ' columns.')
        try:
            if self.isFC:
                arcpy.CreateFeatureclass_management(WorkSpace, tempFC, 'POINT')
                arcpy.AddMessage(tempFC + ' feature class was successfully created.')
            else:
                arcpy.CreateTable_management(WorkSpace, tempFC)
                arcpy.AddMessage(tempFC + ' table was successfully created.')
            for col in insertCols:
                esriType = col.getArcType()
                if esriType == "undefined":
                    arcpy.AddError('Data type not currently supported, ' + col.dataType)
                    return success
                if col.dataType <> 'WKT':
                    arcpy.AddField_management(tempFC, col.name, esriType, col.dataPrecision, col.dataScale, col.dataLen)
                    arcpy.AddMessage('Created column: ' + col.name)
            success = True
        except:
            e = sys.exc_info()[1]
            arcpy.AddError('Create of ' + tempFC + ' failed with ' + str(e.args[0]))
        return success

Body:
You are making a shallow copy of the list passed to your class in the init function.

See Shallow and deep copy operations in the Python documentation for some basic information.

self.colList = ColList[:] makes a new LIST, but inside that new list are references to the same objects that were in the original list (a shallow copy).

You need a deep copy:

import copy
...
self.colList = copy.deepcopy(ColList)

A deep copy has a new list, as well as new objects initialized to match the objects in the original list.  So if the objects in one class' list change, they don't change in every class.


问:
Create new column with dplyr mutate and substring of existing column
I have a dataframe with a column of strings and want to extract substrings of those into a new column.

Here is some sample code and data showing I want to take the string after the final underscore character in the id column in order to create a new_id column.
The id column entry always has 2 underscore characters and it's always the final substring I would like.

```<code>df = data.frame( id = I(c("abcd_123_ABC","abc_5234_NHYK")), x = c(1.0,2.0) )

require(dplyr)

df = df %>% dplyr::mutate(new_id = strsplit(id, split="_")[[1]][3])
</code>```

I was expecting strsplit to act on each row in turn.

However, the new_id column only contains ABC in each row, whereas I would like ABC in row 1 and NHYK in row 2. Do you know why this fails and how to achieve what I want?

答:
An alternative without regex and keeping in the tidyverse style is to use tidyr::separate(). Note, this does remove the input column by default (remove=FALSE to prevent it).

```<code>## using your example data
df = data.frame( id = I(c("abcd_123_ABC","abc_5234_NHYK")), x = c(1.0,2.0) )

## separate knowing you will have three components
df %>% separate(id, c("first", "second", "new_id"), sep = "_") %>% select(-first, -second)
## returns
  new_id x
1    ABC 1
2   NHYK 2
</code>```

Body:
I have a dataframe with a column of strings and want to extract substrings of those into a new column.

Here is some sample code and data showing I want to take the string after the final underscore character in the id column in order to create a new_id column.
The id column entry always has 2 underscore characters and it's always the final substring I would like.

df = data.frame( id = I(c("abcd_123_ABC","abc_5234_NHYK")), x = c(1.0,2.0) )

require(dplyr)

df = df %>% dplyr::mutate(new_id = strsplit(id, split="_")[[1]][3])

I was expecting strsplit to act on each row in turn.

However, the new_id column only contains ABC in each row, whereas I would like ABC in row 1 and NHYK in row 2. Do you know why this fails and how to achieve what I want?

Body:
An alternative without regex and keeping in the tidyverse style is to use tidyr::separate(). Note, this does remove the input column by default (remove=FALSE to prevent it).

## using your example data
df = data.frame( id = I(c("abcd_123_ABC","abc_5234_NHYK")), x = c(1.0,2.0) )

## separate knowing you will have three components
df %>% separate(id, c("first", "second", "new_id"), sep = "_") %>% select(-first, -second)
## returns
  new_id x
1    ABC 1
2   NHYK 2


答:
BeautifulSoup recognizes CData as a subclass so you can have it check for instances of it.</p>

```<code>>>> from bs4 import BeautifulSoup, CData

>>> text = """<item>
<dc:creator><![CDATA[Chris M]]></dc:creator>
<pubDate>Tue, 06 Jun 2017 07:38:23 +0000</pubDate>
</item>"""
>>> soup = BeautifulSoup(text)
>>> for item in soup.findAll(text=True):
        if isinstance(item, CData):
            print(item)

Chris M
</code>```

Title: tag contents not returning in beautifulsoup

Body:
I have the following string I'm trying to extract:

<item>
<dc:creator><![CDATA[Chris M]]></dc:creator>
<pubDate>Tue, 06 Jun 2017 07:38:23 +0000</pubDate>
</item>

I'm trying to get the name Chris M and other authors with this:

soup = BeautifulSoup(response, "lxml")
items = soup.findAll("item")
            for i in items:
                 author = i.find('dc:creator')
                 print author

This outputs:

<dc:creator></dc:creator>

How can I get the name contents from the tag?

Body:
BeautifulSoup recognizes CData as a subclass so you can have it check for instances of it.

>>> from bs4 import BeautifulSoup, CData

>>> text = """<item>
<dc:creator><![CDATA[Chris M]]></dc:creator>
<pubDate>Tue, 06 Jun 2017 07:38:23 +0000</pubDate>
</item>"""
>>> soup = BeautifulSoup(text)
>>> for item in soup.findAll(text=True):
        if isinstance(item, CData):
            print(item)

Chris M


问:
How to save visible column state in bootstrap table toolbar?
I am using bootstrap table toolbar in my table list. Now while uncheck any column from toolbar it's hide that column from table heading,but now how i will save this visible column states to see after refreshing the page? </p>

答:
Not sure if the data attributes have been updated since @Martin's post, however the two fields:

```<code>data-state-save="true",
data-state-save-id-table="whateverIdYouLike"
</code>```

are not being used. Per current example: http://bootstrap-table.wenzhixin.net.cn/extensions/

View with debug tool:

Just utilize data-cookie-id-table instead and ensure it's value is unique if using multiple bootstrap tables on site.

Body:
Not sure if the data attributes have been updated since @Martin's post, however the two fields:

data-state-save="true",
data-state-save-id-table="whateverIdYouLike"

are not being used. Per current example: http://bootstrap-table.wenzhixin.net.cn/extensions/

View with debug tool:

Just utilize data-cookie-id-table instead and ensure it's value is unique if using multiple bootstrap tables on site.


问:
ListActivities setItemChecked in onListItemClick not working
I have this code here:

```<code>@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    if(l.isItemChecked(position))
        l.setItemChecked(position, false);
    else
        l.setItemChecked(position, true);
    Toast.makeText(mContext, "Mission: " + ((TreeNode)l.getItemAtPosition(position)).getTitle(), Toast.LENGTH_LONG).show();

}
</code>```

It works as far as the debugger goes, but the setItemChecked never seems to really set the item both graphically I do not see the check box appear and then on the next click through the isItemChecked still returns false.

Not sure what I am doing wrong here?

答:
have you tried refreshing the adapter of the list ? </p>

```<code>l.getAdapter().notifyDataSetChanged();
</code>```

Body:
I have this code here:

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    if(l.isItemChecked(position))
        l.setItemChecked(position, false);
    else
        l.setItemChecked(position, true);
    Toast.makeText(mContext, "Mission: " + ((TreeNode)l.getItemAtPosition(position)).getTitle(), Toast.LENGTH_LONG).show();

}

It works as far as the debugger goes, but the setItemChecked never seems to really set the item both graphically I do not see the check box appear and then on the next click through the isItemChecked still returns false.

Not sure what I am doing wrong here?

Body:
have you tried refreshing the adapter of the list ?

l.getAdapter().notifyDataSetChanged();


问:
Change bootstrap column order on different resolution
I'm using Boostrap and this is my html code:

```<code><div class="row">
    <div class="col-sm-7">A</div>
    <div class="col-sm-5">B</div>
</div>
</code>```

This is what appears in front-end:

A   | B

This is what obviously appears on mobile screen:

A

B

How can I change my code to have this?

B

A

**

SOLVED

**

I solved in this way. Please let me know if my solution is wrong even if it works:

```<code><div class="row">
    <div class="col-sm-5 col-right col-sm-push-7">B</div>
    <div class="col-sm-7 col-left col-sm-pull-5">A</div>
</div>
</code>```

答:
For web view you can set B before A and use fload: right; in css or pull-right class. Like this:

```<code><div class="row">
    <div class="col-sm-5 pull-right">B</div>
    <div class="col-sm-7">A</div>
</div>
</code>```

Body:
I'm using Boostrap and this is my html code:

A

B

This is what appears in front-end:

A   | B

This is what obviously appears on mobile screen:

A

B

How can I change my code to have this?

B

A

**

SOLVED

**

I solved in this way. Please let me know if my solution is wrong even if it works:

B

A

Body:
For web view you can set B before A and use fload: right; in css or pull-right class. Like this:

<div class="row">
    <div class="col-sm-5 pull-right">B</div>
    <div class="col-sm-7">A</div>
</div>


问:
ConfigureAwait(false) performance test
Everywhere I read that I should use ConfigureAwait(false) to avoid deadlocks and for performance reasons. We are using ConfigureAwait in our application. But might remove the ConfigureAwaits as it's causing a different thread's execution context.

The different thread's execution context is causing (sometimes) problems with translations. As the set culture in currentculture and currentUICulture is not accessible on a different execution context.

I have tested it a little bit with the code below. It did not make any performance difference. I understand it's not a good test as with this simple test there are not many threads used.

```<code>static async Task MyMethodAsync()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10).ConfigureAwait(continueOnCapturedContext: false);
  }
  stopwatch.Stop();
  Console.WriteLine("Await: " + stopwatch.Elapsed.ToString());
}

static async Task MyMethodAsyncNoAwait()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10);
  }
  stopwatch.Stop();
  Console.WriteLine(stopwatch.Elapsed.ToString());
}
</code>```

How should I test this properly? Is it a really bad idea of removing all ConfigureAwaits?

答:
What ever you do with async-await is not about performance but responsiveness and availability.

On client UIs like WinForms, WPF or UWP, it's about responsiveness. You use async-await on IO and CPU-bound operations to do work outside of the UI thread and ConfigureAwait(false) to explicitly avoid getting back to that UI thread.

On ASP.NET (.NET Framework, not .NET Core) it's about availability. You use async-await on IO operations to free the thread to handle other requests and use ConfigureAwait(false) to avoid setting up the returning to thread as the HTTP Context thread.

But because you're always doing more work, each logical operation will take longer.

On client UIs, the user will still be able to work with the application or, at least, not get that "not responding" phrase on the title bar and task manager.

On ASP.NET, because there are more threads available to handle requests, on heavy load, it will be faster because requests are allowed to start work right away instead of being blocked in the request queue.

Title: ConfigureAwait(false) performance test

Body:
Everywhere I read that I should use ConfigureAwait(false) to avoid deadlocks and for performance reasons. We are using ConfigureAwait in our application. But might remove the ConfigureAwaits as it's causing a different thread's execution context.

The different thread's execution context is causing (sometimes) problems with translations. As the set culture in currentculture and currentUICulture is not accessible on a different execution context.

I have tested it a little bit with the code below. It did not make any performance difference. I understand it's not a good test as with this simple test there are not many threads used.

static async Task MyMethodAsync()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10).ConfigureAwait(continueOnCapturedContext: false);
  }
  stopwatch.Stop();
  Console.WriteLine("Await: " + stopwatch.Elapsed.ToString());
}

static async Task MyMethodAsyncNoAwait()
{
  Stopwatch stopwatch = new Stopwatch();
  stopwatch.Start();
  for (int i = 0; i < 1000; i++)
  {
     await Task.Delay(10);
     await Task.Delay(10);
  }
  stopwatch.Stop();
  Console.WriteLine(stopwatch.Elapsed.ToString());
}

How should I test this properly? Is it a really bad idea of removing all ConfigureAwaits?


问:
Return string from Fortran to C++
I have the following function call in C++:

```<code>int strLength = 20;
char* name;

getName(name, strLength);

printf("name: %s\n", name);
</code>```

and in Fortran:

```<code>subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character, intent(out) :: name

name = 'Martin'
end subroutine getName
</code>```

When I execute the C++ routine the output is: name: M. Now, I suppose this happens because character, intent(out) :: name declares the name variable with size of 1, but if I change the declaration to this: character(len=6), intent(out) :: name I get this error message: Error: Character argument 'name' at (1) must be length 1 because procedure 'getname' is BIND(C). I've also tried this: character(len=6,kind=c_char), intent(out) :: name, with the same error message. Lastly, I tried this declaration: character(c_char),dimension(6), intent(out) :: name, which compiles but, yields this result: name: MMMMMM.

My question boils down to: How can I return a string from Fortran to C++?

答:
This Fortran function-based approach is neat and tidy, and is quite suitable when the string has not yet been set (or had memory allocated for it) in the C routine. Notice that you do not need to pass in a string length argument, or use an assumed-size array to build/return a string value.1

A Fortran allocatable character string constant is used, so that this function is reusable for any string.

An integer argument is also passed into the Fortran function to demonstrate, for example, how you may indicate what the desired response should be.

Notice that in this example "intent(out)" is used to indicate that the integer argument does not need to be defined before being passed in, but that it may be updated before it is returned. Therefore, you can modify its value and return it to the calling program so that it may instead be used as a "return code".

The Fortran Function

```<code>! f_string.f90
! Called from C routine as:  `myString = get_string(rc)`

function get_string(c_rc) bind(c, name='get_string')
    use, intrinsic :: iso_c_binding
    implicit none
    integer(c_int), intent(out) :: c_rc           ! <- Pass by reference; acts as return code in this example.
    type(c_ptr) :: get_string                     ! <- C_PTR to pass back to C
    character(len=:), allocatable, target, save :: fortstring   ! <- Allocatable/any length is fine

    fortstring = "Append C_NULL_CHAR to any Fortran string constant."//C_NULL_CHAR
    get_string = c_loc(fortstring)                ! <- C_LOC intrinsic gets loc of our string.
    c_rc = 1                                      ! <- Set the return code value.
end function get_string
</code>```

The C Program

```<code>// c_string.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *get_string(int *rc);              // <- The Fortran function signature.

int main(){
    int rc;                             // <- No value set.
    char *mynameptr;                    // <- Just a plain ol' char *, no memory allocation needed.

    mynameptr = get_string(&rc);

    printf("mynameptr=%s\n", mynameptr);
    printf("len =%d\n", strlen(mynameptr));
    printf("rc  =%d\n", rc);
    return rc;
}
</code>```

Compile, call, output:

```<code>ifort /c f_string.f90
icl c_string.c /link f_string.obj
c_string.exe
# example output:
# mynameptr=Append C_NULL_CHAR to any Fortran string constant.
# len =48
# rc  =1
</code>```

1 This also compiles cleanly without warnings (which do occur with the OP's solution without the modifications I suggested in its comments).

Title: Return string from Fortran to C++

Body:
I have the following function call in C++:

int strLength = 20;
char* name;

getName(name, strLength);

printf("name: %s\n", name);

and in Fortran:

subroutine getName(name) bind (c, name='GETNAME')
use,intrinsic :: iso_c_binding
implicit none
character, intent(out) :: name

name = 'Martin'
end subroutine getName

When I execute the C++ routine the output is: name: M. Now, I suppose this happens because character, intent(out) :: name declares the name variable with size of 1, but if I change the declaration to this: character(len=6), intent(out) :: name I get this error message: Error: Character argument 'name' at (1) must be length 1 because procedure 'getname' is BIND(C). I've also tried this: character(len=6,kind=c_char), intent(out) :: name, with the same error message. Lastly, I tried this declaration: character(c_char),dimension(6), intent(out) :: name, which compiles but, yields this result: name: MMMMMM.

My question boils down to: How can I return a string from Fortran to C++?

Body:
This Fortran function-based approach is neat and tidy, and is quite suitable when the string has not yet been set (or had memory allocated for it) in the C routine. Notice that you do not need to pass in a string length argument, or use an assumed-size array to build/return a string value.1

A Fortran allocatable character string constant is used, so that this function is reusable for any string.

An integer argument is also passed into the Fortran function to demonstrate, for example, how you may indicate what the desired response should be.

Notice that in this example "intent(out)" is used to indicate that the integer argument does not need to be defined before being passed in, but that it may be updated before it is returned. Therefore, you can modify its value and return it to the calling program so that it may instead be used as a "return code".

The Fortran Function

! f_string.f90
! Called from C routine as:  `myString = get_string(rc)`

function get_string(c_rc) bind(c, name='get_string')
    use, intrinsic :: iso_c_binding
    implicit none
    integer(c_int), intent(out) :: c_rc           ! <- Pass by reference; acts as return code in this example.
    type(c_ptr) :: get_string                     ! <- C_PTR to pass back to C
    character(len=:), allocatable, target, save :: fortstring   ! <- Allocatable/any length is fine

    fortstring = "Append C_NULL_CHAR to any Fortran string constant."//C_NULL_CHAR
    get_string = c_loc(fortstring)                ! <- C_LOC intrinsic gets loc of our string.
    c_rc = 1                                      ! <- Set the return code value.
end function get_string

The C Program

// c_string.c
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

char *get_string(int *rc);              // <- The Fortran function signature.

int main(){
    int rc;                             // <- No value set.
    char *mynameptr;                    // <- Just a plain ol' char *, no memory allocation needed.

    mynameptr = get_string(&rc);

    printf("mynameptr=%s\n", mynameptr);
    printf("len =%d\n", strlen(mynameptr));
    printf("rc  =%d\n", rc);
    return rc;
}

Compile, call, output:

ifort /c f_string.f90
icl c_string.c /link f_string.obj
c_string.exe
# example output:
# mynameptr=Append C_NULL_CHAR to any Fortran string constant.
# len =48
# rc  =1

1 This also compiles cleanly without warnings (which do occur with the OP's solution without the modifications I suggested in its comments).


问:
How are these two XPath expressions different?
I'm parsing a website using XPath. I've got two queries, one which finds the node I'm looking for:

```<code>//td[.//text()[contains(., "Date Filed:")]]
</code>```

And one which doesn't:

```<code>//td[contains(.//text(), "Date Filed:")]
</code>```

I don't understand how these are different. I'd read them both to mean, "Find td nodes which have a descendant text node containing Date Filed."

Can anybody explain how these are different?

Here's the HTML, though I don't think it's relevant to the question:

```<code><td width="40%" valign="top">
    <br><br><br><br><br>
    <b>Date Filed:</b> 11/13/2008<br>
    <b>Jury Demand: </b> No<br><br>
    <br><b>Date Terminated: </b><br>
    <br><b>Date Reopened: </b><br>
    <br><b>Does this action raise an issue of constitutionality?: </b>Y<br>
</td>
</code>```

(Don't look at me that way. I didn't make the website, the U.S. Gov't did.)

答:
That is how string conversion works in XPath:

In the second query contains(.//text(), "Date Filed:") you call contains function. It accepts two arguments of type string, you first parameter .//text() is node-set datatype, which means string function gets called internally to convert list of nodes to string. In this case string(.//text()) returns only first text node. If you change your second query to this: //td[contains(., "Date Filed:")] it will select the wanted td.

Body:
I'm parsing a website using XPath. I've got two queries, one which finds the node I'm looking for:

//td[.//text()[contains(., "Date Filed:")]]

And one which doesn't:

//td[contains(.//text(), "Date Filed:")]

I don't understand how these are different. I'd read them both to mean, "Find td nodes which have a descendant text node containing Date Filed."

Can anybody explain how these are different?

Here's the HTML, though I don't think it's relevant to the question:

    Date Filed: 11/13/2008

    Jury Demand:  No

Date Terminated:

Date Reopened:

Does this action raise an issue of constitutionality?: Y

(Don't look at me that way. I didn't make the website, the U.S. Gov't did.)


问:
SQL query convert it to Linq
```<code>select
    COUNT(prosold.Product_ID) as c,
    prosold.Product_ID,
    ProImg.ImagePath
from
    ProductSold as ProSold,
    ProductImages as ProImg
where
    ProSold.Product_ID = ProImg.Product_ID
group by
    ProSold.Product_ID, ProImg.ImagePath
order by
    c desc
</code>```

As I did it so but not working finally

```<code>var result = from p in db.Products
             join c in db.ProductSolds on p.Product_ID equals c.Product_ID into j1
             from j2 in j1.DefaultIfEmpty()
             group j2 by p.Product_ID into grouped
             select new { ParentId = grouped.Key, Count = grouped.Count(t => t.Product_ID != null) };
</code>```

答:
```<code>var ans = from ProSold in ProductSold
          join ProImg in ProductImages on ProSold.Product_ID equals ProImg.Product_ID
          group new { ProSold, ProImg } by new { ProSold.Product_ID, ProImg.ImagePath } into ppg
          let c = ppg.Count()
          orderby ppg descending
          select new { c, ppg.Key.Product_ID, ppg.Key.ImagePath };
</code>```

Title: SQL query convert it to Linq

Body:
select
    COUNT(prosold.Product_ID) as c,
    prosold.Product_ID,
    ProImg.ImagePath
from
    ProductSold as ProSold,
    ProductImages as ProImg
where
    ProSold.Product_ID = ProImg.Product_ID
group by
    ProSold.Product_ID, ProImg.ImagePath
order by
    c desc

As I did it so but not working finally

var result = from p in db.Products
             join c in db.ProductSolds on p.Product_ID equals c.Product_ID into j1
             from j2 in j1.DefaultIfEmpty()
             group j2 by p.Product_ID into grouped
             select new { ParentId = grouped.Key, Count = grouped.Count(t => t.Product_ID != null) };


问:
String Manipulation: Find the discount of a price/number while in a String in JavaScript
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

```<code>example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"
</code>```

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

答:
```<code>String input = "This person bought an iphone for $500 and a macbook for $1400";
        int index = input.indexOf('$');
        int inNumber = 0;
        String number = "";

        while (inNumber != -1) {
            inNumber++;
            char temp = input.charAt(index + inNumber);
            int value = Character.getNumericValue(temp);
            if (value >= 0 && value < 10) {
                number = number + value;
            } else
                break;
            if(temp==' ')
                break;
        }
</code>```

in variable number, you have got your first numeric, and again run the method to get the second, by  using String.subString(index)
and running the same process again, use Integer.parseInt() to get the int calcuate discounts and replace it with original index respectively , you know starting indexes of both strings
this is  a quick logic if you do not know the regex at the interview

Body:
I had a technical interview and this question was particularly hard for me to answer. Not sure how to go about this issue, would really appreciate if someone helped me figure out this question.

You have a string that states the price of an item. You want to return a string with the all the numbers 15% off the original number.

example.)

if an item was 15% off

input string:

str1 = "This person bought an iphone for $500 and a macbook for $1400"

output string:

str2 = "This person bought an iphone for $425 and a macbook for $1190"

I know I should split the string, and probably locate all the numbers that proceeds a "$" symbol but I am not sure how to go from there.

Body:
String input = "This person bought an iphone for $500 and a macbook for $1400";
        int index = input.indexOf('$');
        int inNumber = 0;
        String number = "";

        while (inNumber != -1) {
            inNumber++;
            char temp = input.charAt(index + inNumber);
            int value = Character.getNumericValue(temp);
            if (value >= 0 && value < 10) {
                number = number + value;
            } else
                break;
            if(temp==' ')
                break;
        }

in variable number, you have got your first numeric, and again run the method to get the second, by  using String.subString(index)
and running the same process again, use Integer.parseInt() to get the int calcuate discounts and replace it with original index respectively , you know starting indexes of both strings
this is  a quick logic if you do not know the regex at the interview


问:
Date and time change listener in Android?
In my application, there's a alarm service, and I find that if user change it's date or time to a passed time. My alarm will not be triggered at the time I expect.

So, I may have to reset all the alarms again. Is there an date and time change listener in android?

答:
In addition to the accepted answer

If you want to listen to time changes while your app is not running I would register in the manifest:

```<code><receiver android:name="com.your.pacakge.TimeChangeBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.TIME_SET"/>
        <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
    </intent-filter>
</receiver>
</code>```

If you do this, do not explicitly register the receiver in the code with registerReceiver and unregisterReceiver.

Again, this is just an addition to the accepted answer.

Body:
In addition to the accepted answer

If you want to listen to time changes while your app is not running I would register in the manifest:

<receiver android:name="com.your.pacakge.TimeChangeBroadcastReceiver">
    <intent-filter>
        <action android:name="android.intent.action.TIME_SET"/>
        <action android:name="android.intent.action.TIMEZONE_CHANGED"/>
    </intent-filter>
</receiver>

If you do this, do not explicitly register the receiver in the code with registerReceiver and unregisterReceiver.

Again, this is just an addition to the accepted answer.


问:
jQuery get rid of a:hover underline?
I'm just getting started with jQuery, having a little trouble.

Got a table of thumbnails, and I want each cell to be highlighted when I hover over the picture inside it. Got that part working. But I also want the picture inside the cell not to have an underline - this is inherited from the stylesheet a:hover{text-decoration:underline} . This is where I'm stuck, I don't think I'm setting the right thing.

I need to use inline styles, so my jQuery looks like:

```<code>$('[name*=thumb]').hover(
  function () {
    //as we hover over an item, change it's background, attempt to vaquish pesky underline
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#cccccc');
    $('#' + this).css('text-decoration', 'none');  //doesn't work : (
  },
  function () {
    //fix bgs of items we're not hovering on
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#ffffff');
  }
);
</code>```

My HTML looks like this :

```<code><td name="thumbcontainer8" id="thumbcontainer8"><a href="#" name="thumb8" id="thumb8"><img src="..." /></a></td>
<td name="thumbcontainer9" id="thumbcontainer9"><a href="#" name="thumb9" id="thumb9"><img src="..." /></a></td>
</code>```

答:
What about:</p>

```<code>  $(this).css('text-decoration', 'none');
</code>```

Title: jQuery get rid of a:hover underline?

Body:
I'm just getting started with jQuery, having a little trouble.

Got a table of thumbnails, and I want each cell to be highlighted when I hover over the picture inside it. Got that part working. But I also want the picture inside the cell not to have an underline - this is inherited from the stylesheet a:hover{text-decoration:underline} . This is where I'm stuck, I don't think I'm setting the right thing.

I need to use inline styles, so my jQuery looks like:

$('[name*=thumb]').hover(
  function () {
    //as we hover over an item, change it's background, attempt to vaquish pesky underline
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#cccccc');
    $('#' + this).css('text-decoration', 'none');  //doesn't work : (
  },
  function () {
    //fix bgs of items we're not hovering on
    $('#' + $(this).attr('id').replace('thumb', 'thumbcontainer')).css('background-color', '#ffffff');
  }
);

My HTML looks like this :

Body:
What about:

  $(this).css('text-decoration', 'none');


问:
IE screwiness (won't render empty cell in asp:listview)
I have an asp:listview using a css class.  On my dev system (VS2008), it renders correctly in Chrome, IE and FireFox.  On our production server (IIS 2.0), IE will not apply the style to an empty cell - but cells that contain text/whatever are fine.  Chrome and FireFox still render fine.  The style I want is a thin line on the bottom of each row, kind of like a row separator.  Any idea what I can try to fix this?

Here is the css I assign to the Item and AltItem templates

```<code>.itemtemplate
{
    background-color: White;
}
.itemtemplate TD
{
  border-bottom:solid 1px #eae9e1;
  border-right:solid 1px #eae9e1;
}
</code>```

Oh, one other thing.  If I change the background color in the css to say, orange, then the empty cells render with a border.

答:
Put   into your empty cell.

If I remember correctly, the  isn't supposed to be empty ever according to the HTML spec anyways, so you really should always have something in the cell.

Body:
I have an asp:listview using a css class.  On my dev system (VS2008), it renders correctly in Chrome, IE and FireFox.  On our production server (IIS 2.0), IE will not apply the style to an empty cell - but cells that contain text/whatever are fine.  Chrome and FireFox still render fine.  The style I want is a thin line on the bottom of each row, kind of like a row separator.  Any idea what I can try to fix this?

Here is the css I assign to the Item and AltItem templates

.itemtemplate
{
    background-color: White;
}
.itemtemplate TD
{
  border-bottom:solid 1px #eae9e1;
  border-right:solid 1px #eae9e1;
}

Oh, one other thing.  If I change the background color in the css to say, orange, then the empty cells render with a border.

Body:
Put &nbsp; into your empty cell.

If I remember correctly, the <td> isn't supposed to be empty ever according to the HTML spec anyways, so you really should always have something in the cell.