问:
ASP.NET Core 2.0 (Angular) to CloudFoundry
I am working on an app in CloudFoundry (CF) and I am getting an error when I push my code into CF saying that NodeJs is not installed.

```<code>[APP/PROC/WEB/0] ERR [1] Ensure that Node.js is installed and can be found in one of the PATH directories
Current PATH enviroment variable is: /home/vcap/deps/0/bin:/home/vcap/app/bin:/home/vcap/app/node_modules/.bin:/bin:/usr/bin
</code>```

I am using the latest CF .NET Core buildpack to push my app with the CLI command below;

```<code>cf push my-app -k 1GB -b https://github.com/cloudfoundry/dotnet-core-buildpack.git
</code>```

I can't find any information on how to install NodeJs into CF. They said that it should be included when I use the NodeJs buildpack but I can't do that because my app needs the .NET Core buildpack. Unless there's a way to use 2 buildpacks?

答:
While it's a workaround, you can remove the dependency on NodeJS unless you really need the server side pre-rendering functionality.

The issue stems from the inclusion of Microsoft.AspNetCore.SpaServices

See: Do I need to install Node.js on Production Server to host Angular 2? for further info.

The relevant code parts to remove are:

Views/_ViewImports.cshtml

remove @addTagHelper *, Microsoft.AspNetCore.SpaServices

Startup.cs

Remove using Microsoft.AspNetCore.SpaServices.Webpack;

Remove (from public void Configure(...))

```<code>app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
    HotModuleReplacement = true
});
</code>```

I was planning to log an issue on the dotnet-core-buildpack repo as well.

Also, You may be able to build your own buildpack that includes it, but I'm pretty green w/ PCF, so I haven't travelled that road yet.

Body:
I am working on an app in CloudFoundry (CF) and I am getting an error when I push my code into CF saying that NodeJs is not installed.

[APP/PROC/WEB/0] ERR [1] Ensure that Node.js is installed and can be found in one of the PATH directories
Current PATH enviroment variable is: /home/vcap/deps/0/bin:/home/vcap/app/bin:/home/vcap/app/node_modules/.bin:/bin:/usr/bin

I am using the latest CF .NET Core buildpack to push my app with the CLI command below;

cf push my-app -k 1GB -b https://github.com/cloudfoundry/dotnet-core-buildpack.git

I can't find any information on how to install NodeJs into CF. They said that it should be included when I use the NodeJs buildpack but I can't do that because my app needs the .NET Core buildpack. Unless there's a way to use 2 buildpacks?

Body:
While it's a workaround, you can remove the dependency on NodeJS unless you really need the server side pre-rendering functionality.

The issue stems from the inclusion of Microsoft.AspNetCore.SpaServices

See: Do I need to install Node.js on Production Server to host Angular 2? for further info.

The relevant code parts to remove are:

Views/_ViewImports.cshtml

remove @addTagHelper *, Microsoft.AspNetCore.SpaServices

Startup.cs

Remove using Microsoft.AspNetCore.SpaServices.Webpack;

Remove (from public void Configure(...))

app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
    HotModuleReplacement = true
});

I was planning to log an issue on the dotnet-core-buildpack repo as well.

Also, You may be able to build your own buildpack that includes it, but I'm pretty green w/ PCF, so I haven't travelled that road yet.


来源: stackexchange

问:
Java Large String compression safe approach
For a large string size ~15k, is any java recommended string compression and decompression techniques that are safe to implement.
The gzip format gives junk characters during compression and will it get corrupted when sent in the HTTP soap request. Please advise.</p>

答:
When you zip the text is not any more responding to an encoding as ASCII, UTF, or any other.

The compression will create a new table of conversion between characters and bits (not bytes). One byte could represent less than a character, one character, or more than one character.

The goal of compression is to represent the most repeated characters with the less amount of bits.

Once "compacted" the bytes may overlap with control characters, this why they are a pain to transmit as text.

When you don't have an alternative and have send something which is in binary format over http for example, you do the other way round, you take the bits and add extra bits to bring the binary data into the ASCII range, for example enconding in Base64.

That is why if you first remove extra bits by compressing, and after that you add bits to encode Base64, you might better off sending the original file as it is.

This is the reason why I sugested to send the data in binary format, of see if soap has any alternative to send binary data that doesn't imply reverting the compression process.

ContentLicense: CC BY-SA 3.0


问:
How do I read a data file with spaces in the row names into python?
In python I want to create a dictionary from a text file with two "columns". The first column contains names sometimes separated by spaces. The second column contains floats. Both columns are centered in the data file (why?). I don't know how to pythonically deal with the spaces. I am looking for a solution that I can use to iterate through many of these files.

What I see in the text file:

```<code>           value err     0.123
                value    3.000
</code>```

What the output from csv reader looks like:

```<code>with open('text.data') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
    print(row)
</code>```

[]

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', 'value', 'err', '', '', '',
'', '', '', '', '0.123']

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', 'value', '', '', '', '3.00']

What I want it to look like:

['value_err', 0.123]

['value', 3.00]

答:
You should use list comprehension :

```<code>with open('text.data') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
    formatted_row = [x for x in row if x != '']
</code>```

Now, in the question your csv file has value err as a value. This is kind of odd since it is two words. It is a typo in your question ?

Basically, my solution will strip any spaces in what you read.

Body:
In python I want to create a dictionary from a text file with two "columns". The first column contains names sometimes separated by spaces. The second column contains floats. Both columns are centered in the data file (why?). I don't know how to pythonically deal with the spaces. I am looking for a solution that I can use to iterate through many of these files.

What I see in the text file:

           value err     0.123
                value    3.000

What the output from csv reader looks like:

with open('text.data') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
    print(row)

[]

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', 'value', 'err', '', '', '',
'', '', '', '', '0.123']

['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '',
'', '', 'value', '', '', '', '3.00']

What I want it to look like:

['value_err', 0.123]

['value', 3.00]

Body:
You should use list comprehension :

with open('text.data') as f:
reader = csv.reader(f, delimiter=' ')
for row in reader:
    formatted_row = [x for x in row if x != '']

Now, in the question your csv file has value err as a value. This is kind of odd since it is two words. It is a typo in your question ?

Basically, my solution will strip any spaces in what you read.


问:
PHP mysql query issue when filtering from array and variables
On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.

Effective code that WORKS for filtering (very static, not practical to use obviously) is this:

```<code>$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\'  OR
                                          Joint_1=\'region2\'  OR
                                          Joint_1=\'region3\' OR
                                          Joint_1=\'region4\') AND
                                         (Position=\'position1\' OR
                                          Position=\'position2\' OR
                                          Position=\'position3\')";
$result = $conn->query($sql);

if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
      echo $row["Common_Name1"] . "<br>";
   }
} else {
  echo "0 results";
  }
</code>```

Below code is attempts at above code, but using arrays, which does NOT work.

```<code>$regions =
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');

$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\'  OR
                                          Joint_1=\'. $regions[1] .\'  OR
                                          Joint_1=\'. $regions[2] .\' OR
                                          Joint_1=\'. $regions[3] .\') AND
                                         (Position=\'. $position[0] .\' OR
                          Position=\'. $position[0] .\' OR
                      Position=\'. $position[0] .\')";
</code>```

Above code provides results of '0 results.'

I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).

```<code>$sqlregion = array();
foreach ($_POST['region'] as $reg) {
   $sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";
}
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",",
$sqlreg) . ");";

$result=$conn->query($sql);

if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
     echo $row["Common_Name1"] . "<br>";
   }
}
</code>```

Any help is appreciated! Thanks.

答:
You can construct this query from arrays, you can use the IN clause in mysql to specify multiple OR values

```<code>$regions = array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$regions = implode(",", $regions); // Converts array to string with comma as a separator
$position = implode(",", $position);
$sql = "SELECT * FROM `Table_Name` WHERE Joint_1 IN ($regions) AND Position IN ($position)";
echo $sql;
</code>```

This gives you a query like this

```<code>SELECT * FROM Table_Name WHERE Joint_1 IN (region1,region2,region3,region4) AND Position IN (position1,position2,position3)
</code>```

add in your own LIMIT GROUP BY or ORDER BY parameters to suit your needs

Body:
On my webpage (html, php), I'm trying to get it such that users may select multiple checkboxes, each checkbox effectively filters what results the users see. Info is pulled from the database (MySQL) based on the values in different columns. As shown below, one column is Joint_1, another column is Position.

Effective code that WORKS for filtering (very static, not practical to use obviously) is this:

$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'region1\'  OR
                                          Joint_1=\'region2\'  OR
                                          Joint_1=\'region3\' OR
                                          Joint_1=\'region4\') AND
                                         (Position=\'position1\' OR
                                          Position=\'position2\' OR
                                          Position=\'position3\')";
$result = $conn->query($sql);

if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
      echo $row["Common_Name1"] . "
";
   }
} else {
  echo "0 results";
  }

Below code is attempts at above code, but using arrays, which does NOT work.

$regions =
array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');

$sql = "SELECT * FROM `Table_Name` WHERE (Joint_1=\'. $regions[0] .\'  OR
                                          Joint_1=\'. $regions[1] .\'  OR
                                          Joint_1=\'. $regions[2] .\' OR
                                          Joint_1=\'. $regions[3] .\') AND
                                         (Position=\'. $position[0] .\' OR
                          Position=\'. $position[0] .\' OR
                      Position=\'. $position[0] .\')";

Above code provides results of '0 results.'

I've attempted to perform this numerous times, with additional NON-FUNCTIONAL CODE also below (below attempting to filter based on only 1 column as I have obviously not mastered the code to approach filtering based on 2 columns).

$sqlregion = array();
foreach ($_POST['region'] as $reg) {
   $sqlreg[] = "'" . mysql_real_escape_string($reg) . "'";
}
$sql = "SELECT * FROM 'Exercises' WHERE Joint_1 IN (" . implode(",",
$sqlreg) . ");";

$result=$conn->query($sql);

if($result->num_rows > 0) {
   while($row = $result->fetch_assoc()) {
     echo $row["Common_Name1"] . "
";
   }
}

Any help is appreciated! Thanks.

Body:
You can construct this query from arrays, you can use the IN clause in mysql to specify multiple OR values

$regions = array('region1', 'region2', 'region3', 'region4');
$position = array('position1', 'position2', 'position3');
$regions = implode(",", $regions); // Converts array to string with comma as a separator
$position = implode(",", $position);
$sql = "SELECT * FROM `Table_Name` WHERE Joint_1 IN ($regions) AND Position IN ($position)";
echo $sql;

This gives you a query like this

SELECT * FROM Table_Name WHERE Joint_1 IN (region1,region2,region3,region4) AND Position IN (position1,position2,position3)

add in your own LIMIT GROUP BY or ORDER BY parameters to suit your needs


问:
PHP Determine the starting characters of a string and length of a string then assign values to variable based upon the results
I have this if/elseif statement where if $DiscountDescription is not empty, then I search to see if it starts with an "e", "E", "A", and has either 12 characters, or 10 characters. Two other scenarios are 18 characters with 2 dashes, and 9 characters that are all numerical.

The code looks right to me, but it doesn't appear to be working. Any ideas?

```<code>$DiscountDescription = $_order->getDiscountDescription();

if ($DiscountDescription != '') {
    if (substr($DiscountDescription,0,1 == "e") && strlen($DiscountDescription == 12)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescription,0,1 == "E") && strlen($DiscountDescription == 10)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescription,0,1 == "A") && strlen($DiscountDescription == 10)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescription == 18) && substr_count($DiscountDescription,'-' == 2)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescription == 9) && ctype_digit($DiscountDescription)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }

    //$_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
}
</code>```

答:
As someone else said it looks like you are doing comparisons in the length check which won't work. You want to get the length and then compare it to an integer.

As a best practice you should also try to use strict comparisons === instead of ==.

Body:
I have this if/elseif statement where if $DiscountDescription is not empty, then I search to see if it starts with an "e", "E", "A", and has either 12 characters, or 10 characters. Two other scenarios are 18 characters with 2 dashes, and 9 characters that are all numerical.

The code looks right to me, but it doesn't appear to be working. Any ideas?

$DiscountDescription = $_order->getDiscountDescription();

if ($DiscountDescription != '') {
    if (substr($DiscountDescription,0,1 == "e") && strlen($DiscountDescription == 12)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescription,0,1 == "E") && strlen($DiscountDescription == 10)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (substr($DiscountDescription,0,1 == "A") && strlen($DiscountDescription == 10)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescription == 18) && substr_count($DiscountDescription,'-' == 2)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }
    elseif (strlen($DiscountDescription == 9) && ctype_digit($DiscountDescription)){
        $_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
    }

    //$_order->setDiscountDescription('Gift Cards ' . $DiscountDescription);
}


问:
Install older versions of postgres(7.x or 8.x) in ubuntu
I can only find installations for the latest stable version. Can someone provide me steps to install an older version of pg?

Thanks
Sithara

答:
I've installed Postgresql 8.4 on Ubuntu 16.4 using the following:

```<code>#Requirements
sudo apt-get install make
sudo apt-get install gcc
sudo apt-get install libreadline6 libreadline6-dev
sudo apt-get install zlib1g-dev
sudo apt-get install bison

#Download postgres
wget https://ftp.postgresql.org/pub/source/v8.4.22/postgresql-8.4.22.tar.gz
tar xfz postgresql-8.4.22.tar.gz
cd postgresql-8.4.22

#Installation
./configure
make
su
make install
adduser postgres
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data >logfile 2>&1 &
/usr/local/pgsql/bin/createdb test
/usr/local/pgsql/bin/psql test
</code>```

Look for documentation in order to install other version, in this case I've checked:

https://www.postgresql.org/docs/8.4/static/install-short.html

Body:
I've installed Postgresql 8.4 on Ubuntu 16.4 using the following:

#Requirements
sudo apt-get install make
sudo apt-get install gcc
sudo apt-get install libreadline6 libreadline6-dev
sudo apt-get install zlib1g-dev
sudo apt-get install bison

#Download postgres
wget https://ftp.postgresql.org/pub/source/v8.4.22/postgresql-8.4.22.tar.gz
tar xfz postgresql-8.4.22.tar.gz
cd postgresql-8.4.22

#Installation
./configure
make
su
make install
adduser postgres
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data
/usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data >logfile 2>&1 &
/usr/local/pgsql/bin/createdb test
/usr/local/pgsql/bin/psql test

Look for documentation in order to install other version, in this case I've checked:

https://www.postgresql.org/docs/8.4/static/install-short.html


问:
CSRF token for ajax
I have a problem with forms submitted with ajax. I do my forms with Zend Framework. Some are real forms so I add a Hash element. Others are for small operations (like upvote and downvote here) so I do them with links.

My problem is that I need to use ajax especially for the small forms (the links). I see a lot of questions but nothing comprehensive enough to solve the problem. Is there a detailed description on how to get csrf token working smoothly when forms are submitted via ajax? preferably with Zend Framework but general PHP answers will help too.

答: You don't need a CSRF token. You case use the HTTP_X_REQUESTED_WITH method (see e.g. here).

ContentLicense: CC BY-SA 2.5

Title: CSRF token for ajax


答:
Since there's only two columns, and the second shouldn't contain any internal spaces, this should work:

```<code>with open('text.data') as f:
    for line in f:
        line = line.split()
        print(['_'.join(line[:-1]), float(line[-1])])
</code>```

There's a number of things that could break this (additional columns, multiple internal spaces, blank lines, etc.), but absent a more complete definition of the file format, we have to make some guesses.

Title: How do I read a data file with spaces in the row names into python?

Body:
Since there's only two columns, and the second shouldn't contain any internal spaces, this should work:

with open('text.data') as f:
    for line in f:
        line = line.split()
        print(['_'.join(line[:-1]), float(line[-1])])

There's a number of things that could break this (additional columns, multiple internal spaces, blank lines, etc.), but absent a more complete definition of the file format, we have to make some guesses.


问:
How to remove specific substrings from a set of strings in Python?
I have a set of strings and all the strings have one of two specific substrings which I want to remove:

```<code>set1 = {'Apple.good', 'Orange.good', 'Pear.bad', 'Pear.good', 'Banana.bad', 'Potato.bad'}
</code>```

I want the ".good" and ".bad" substrings removed from all the strings. I tried this:

```<code>for x in set1:
    x.replace('.good', '')
    x.replace('.bad', '')
</code>```

but it doesn't seem to work, set1 stays exactly the same. I tried using for x in list(set1) instead but that doesn't change anything.

ContentLicense: CC BY-SA 4.0

Body:
I have a set of strings and all the strings have one of two specific substrings which I want to remove:

set1 = {'Apple.good', 'Orange.good', 'Pear.bad', 'Pear.good', 'Banana.bad', 'Potato.bad'}

I want the ".good" and ".bad" substrings removed from all the strings. I tried this:

for x in set1:
    x.replace('.good', '')
    x.replace('.bad', '')

but it doesn't seem to work, set1 stays exactly the same. I tried using for x in list(set1) instead but that doesn't change anything.

Body:
I did the test (but it is not your example) and the data does not return them orderly or complete

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = {x.replace('p','') for x in ind}
>>> newind
{'1', '2', '8', '5', '4'}

I proved that this works:

>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> newind = [x.replace('p','') for x in ind]
>>> newind
['5', '1', '8', '4', '2', '8']

or

>>> newind = []
>>> ind = ['p5','p1','p8','p4','p2','p8']
>>> for x in ind:
...     newind.append(x.replace('p',''))
>>> newind
['5', '1', '8', '4', '2', '8']


问:
Build an net461 app includ framework dlls in build
when I build a class library build of the 4.6.1 framework it includes in the build all the dll of the framework that I use, but I imagine that the dlls that already are of the framework should not be generated for the build folder, can help me ?

答:
Select the reference in the Solution Explorer in Visual Studio. When you slect it, the properties should appear below the solution explorer.

Change the 'Copy Local' to false.


问:
performance on xml column in sql server
I have normalized tables which keep data in the following format.

First Table name LogBook
columns are JourneyID, LocationID, PositionID, ID,

second table LogBookEvents
columns are LogBookID, LifeCodeID, LifeCode, LifeCodeValue, TotalValue

the first table has 3.4 million records
and the second table has 17.3 million records.

I found this the performance on these tables are big heavy even I have all the necessary indexes on the tables.

therefore I have designed a new table which has XML format

new table is.. LogbookLifeCodes,
columns are  JourneyID, LifeCode (XML Type)

by doing this, I have reduced the number of records to 900,000

and the LifeCode hold data in the following a format

```<code><LogBookLifeCodeEvents><LifeCodes>
<LogBookID>11</LogBookID>
<LocationID>0</LocationID>
<PositionID>0</PositionID>
<LifeCodeID>4</LifeCodeID>
<LifeCode>FH</LifeCode>
<LifeValue>0.0000</LifeValue>
<LifeTotal>0.0000</LifeTotal>
</code>```

and now am using the following query to return data in table format.

```<code>Select Tbl.Col.value('LogBookID[1]', 'int'),
   Tbl.Col.value('LocationID[1]', 'int'),
   Tbl.Col.value('LocationPositionID[1]', 'int'),
   Tbl.Col.value('LifeCodeID[1]', 'int'),
   Tbl.Col.value('LifeCode[1]', 'varchar(20)') from LogbookLifeCodes outer apply LogbookLifeCodes.LifeCode.nodes('//LogBookLifeCodeEvents/LifeCodes') Tbl(Col) where Tbl.Col.value('LogBookID[1]', 'int') = 11
</code>```

however this query takes 4 mins to run get the value for LogBookID = 11, this is not acceptable, returning 130,000 records.

but if I query the above-normalized tables only takes 01 seconds, same number of records

the XML columns on the second table having indexes, primary and secondary.

when I check the execution plan, the  normalized table index (clustered) cost 73%

but on the XML column index only cost 45 %

just would like to know, using XML column rather using relational tables better ?  or is any other way to improve the  performance of XML column as the second table has less records compare to the first structure ?

appreciate your commends and advices

many thanks

答:
Referencing this article (Performance tips of using XML data in SQL Server) note the three tips;

Promoting to relational columns by using persisted columns.

Typing the data.

Indexing the XML.

You may be indexing the XML, but indexing XML is (to me) even more difficult than indexing relational data based on query plans. The point of the article is that, if you work really, really hard, you may be able to approach relational levels of performance with XML data, not exceed it.

I understand why you might approach it this way conceptually, but SQL Server is a relational database. You will almost always get the best performance out of relational objects which are managed appropriately.

You note that, "I found this the performance on these tables are big heavy even I have all the necessary indexes on the tables", but later state that the relational query of note takes only 1 second where the XML based query takes four minutes.

Based on the information provided I do not understand the problem you are trying to solve, but you should not expect better performance on XML data than relational data in SQL Server.

Title: performance on xml column in sql server

Body:
I have normalized tables which keep data in the following format.

First Table name LogBook
columns are JourneyID, LocationID, PositionID, ID,

second table LogBookEvents
columns are LogBookID, LifeCodeID, LifeCode, LifeCodeValue, TotalValue

the first table has 3.4 million records
and the second table has 17.3 million records.

I found this the performance on these tables are big heavy even I have all the necessary indexes on the tables.

therefore I have designed a new table which has XML format

new table is.. LogbookLifeCodes,
columns are  JourneyID, LifeCode (XML Type)

by doing this, I have reduced the number of records to 900,000

and the LifeCode hold data in the following a format

<LogBookLifeCodeEvents><LifeCodes>
<LogBookID>11</LogBookID>
<LocationID>0</LocationID>
<PositionID>0</PositionID>
<LifeCodeID>4</LifeCodeID>
<LifeCode>FH</LifeCode>
<LifeValue>0.0000</LifeValue>
<LifeTotal>0.0000</LifeTotal>

and now am using the following query to return data in table format.

Select Tbl.Col.value('LogBookID[1]', 'int'),
   Tbl.Col.value('LocationID[1]', 'int'),
   Tbl.Col.value('LocationPositionID[1]', 'int'),
   Tbl.Col.value('LifeCodeID[1]', 'int'),
   Tbl.Col.value('LifeCode[1]', 'varchar(20)') from LogbookLifeCodes outer apply LogbookLifeCodes.LifeCode.nodes('//LogBookLifeCodeEvents/LifeCodes') Tbl(Col) where Tbl.Col.value('LogBookID[1]', 'int') = 11

however this query takes 4 mins to run get the value for LogBookID = 11, this is not acceptable, returning 130,000 records.

but if I query the above-normalized tables only takes 01 seconds, same number of records

the XML columns on the second table having indexes, primary and secondary.

when I check the execution plan, the  normalized table index (clustered) cost 73%

but on the XML column index only cost 45 %

just would like to know, using XML column rather using relational tables better ?  or is any other way to improve the  performance of XML column as the second table has less records compare to the first structure ?

appreciate your commends and advices

many thanks


问:
Error in Postgres TX
Trying to create a user in the database and it's telling me that cannot execute **** in a read-only transaction. I have no idea what's causing this? Is this a bad state in the database or connection? Why is this telling that it's not in a transaction but then telling me it's a read-only transaction? Does "transaction" refer to the same thing?

```<code>$ psql --host localhost --port 5432 --username **** postgres --no-password -v dbuser=root -t -X
psql (10.1, server 9.4.13)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=# set transaction read write;
WARNING:  SET TRANSACTION can only be used in transaction blocks
ERROR:  cannot set transaction read-write mode during recovery
postgres=# CREATE USER root WITH PASSWORD 'root';
ERROR:  cannot execute CREATE ROLE in a read-only transaction
</code>```

答:
Your database is in recovery.

Either it is a hot standby (most likely), or recovery was paused with SELECT pg_wal_replay_pause() or recovery_target_action = 'pause' in recovery.conf (check with SELECT pg_is_wal_replay_paused()), or a point-in-time-recovery is still running.

Use the primary or complete recovery.

Title: Error in Postgres TX

Body:
Trying to create a user in the database and it's telling me that cannot execute **** in a read-only transaction. I have no idea what's causing this? Is this a bad state in the database or connection? Why is this telling that it's not in a transaction but then telling me it's a read-only transaction? Does "transaction" refer to the same thing?

$ psql --host localhost --port 5432 --username **** postgres --no-password -v dbuser=root -t -X
psql (10.1, server 9.4.13)
SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
Type "help" for help.

postgres=# set transaction read write;
WARNING:  SET TRANSACTION can only be used in transaction blocks
ERROR:  cannot set transaction read-write mode during recovery
postgres=# CREATE USER root WITH PASSWORD 'root';
ERROR:  cannot execute CREATE ROLE in a read-only transaction


问:
Adding Social Media Share Logic From Firebase in Android
I am building an android instagram clone app with Firebase. I have enabled social media sharing buttons in my app to share the contents of a story via Facebook, email, WhatsApp, etc but don't know how to go about it.

Take a look at what I've tried:

```

    public class InstacloneApp extends AppCompatActivity {

    private RelativeLayout relativeLayout;

    private ImageView postCoverImg, userPhotoUrl;
    private TextView post_Title, post_Descpn, post_Author, postDate;

    private Button commentsBtn;
    private FloatingActionButton shareFAB;

    private String post_details = null;
    private FirebaseAuth mAuth;
    private DatabaseReference postRef;

    private Context mCtx = this;
    private String uid_post = null;

    private ScrollView scrollView;
    private Toolbar toolbar;

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

        relativeLayout = (RelativeLayout) findViewById(R.id.activity_blog_posts_view);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        post_details = getIntent().getExtras().getString("post+key");

        postCoverImg = (ImageView) findViewById(R.id.post_Backdrop);
        post_Title = (TextView) findViewById(R.id.post_title);
        post_Descpn = (TextView) findViewById(R.id.post_description_long);
        post_Author = (TextView) findViewById(R.id.authorTV);
        userPhotoUrl = (ImageView) findViewById(R.id.author_photo);
        postDate = (TextView) findViewById(R.id.post_date);
        shareFAB = (FloatingActionButton) findViewById(R.id.shareFAB);
        commentsBtn = (Button) findViewById(R.id.commentsBtn);

        mAuth = FirebaseAuth.getInstance();

        postRef = FirebaseDatabase.getInstance().getReference().child("Blog").child("All_Posts");
        postRef.keepSynced(true);

        postRef.child(post_details.toString()).addValueEventListener(new ValueEventListener() {  // this is to retrieve and view the blog post data
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String title_post = (String) dataSnapshot.child("postTitle").getValue();
                String desc_post = (String) dataSnapshot.child("full_postDesc").getValue();
                String backdrop_post = (String) dataSnapshot.child("postImage").getValue();
                String date_post = (String) dataSnapshot.child("postDate").getValue();

                uid_post =  (String) dataSnapshot.child("uid").getValue();

                post_Title.setText(title_post);
                post_Descpn.setText(desc_post);
                postDate.setText(date_post);
                Glide.with(mCtx).load(backdrop_post).into(postCoverImg);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        shareFAB.setOnClickListener(new View.OnClickListener() {  // my implemented share action
            @Override
            public void onClick(View view) {

                String content = post_details;

                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("*/*");
                shareIntent.putExtra(Intent.EXTRA_TEXT,content);
                startActivity(Intent.createChooser(shareIntent,"Share With"));

            }
        });

```

答:
Since your sharing the post content try changing your
from:

```<code>intent.setType("*/*");
</code>```

To:

```<code>intent.setType("text/plain");
</code>```

Body:
I am building an android instagram clone app with Firebase. I have enabled social media sharing buttons in my app to share the contents of a story via Facebook, email, WhatsApp, etc but don't know how to go about it.

Take a look at what I've tried:

    public class InstacloneApp extends AppCompatActivity {

    private RelativeLayout relativeLayout;

    private ImageView postCoverImg, userPhotoUrl;
    private TextView post_Title, post_Descpn, post_Author, postDate;

    private Button commentsBtn;
    private FloatingActionButton shareFAB;

    private String post_details = null;
    private FirebaseAuth mAuth;
    private DatabaseReference postRef;

    private Context mCtx = this;
    private String uid_post = null;

    private ScrollView scrollView;
    private Toolbar toolbar;

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

        relativeLayout = (RelativeLayout) findViewById(R.id.activity_blog_posts_view);
        scrollView = (ScrollView) findViewById(R.id.scrollView);
        toolbar = (Toolbar) findViewById(R.id.toolbar);

        toolbar.setTitle("");
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        post_details = getIntent().getExtras().getString("post+key");

        postCoverImg = (ImageView) findViewById(R.id.post_Backdrop);
        post_Title = (TextView) findViewById(R.id.post_title);
        post_Descpn = (TextView) findViewById(R.id.post_description_long);
        post_Author = (TextView) findViewById(R.id.authorTV);
        userPhotoUrl = (ImageView) findViewById(R.id.author_photo);
        postDate = (TextView) findViewById(R.id.post_date);
        shareFAB = (FloatingActionButton) findViewById(R.id.shareFAB);
        commentsBtn = (Button) findViewById(R.id.commentsBtn);

        mAuth = FirebaseAuth.getInstance();

        postRef = FirebaseDatabase.getInstance().getReference().child("Blog").child("All_Posts");
        postRef.keepSynced(true);

        postRef.child(post_details.toString()).addValueEventListener(new ValueEventListener() {  // this is to retrieve and view the blog post data
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {

                String title_post = (String) dataSnapshot.child("postTitle").getValue();
                String desc_post = (String) dataSnapshot.child("full_postDesc").getValue();
                String backdrop_post = (String) dataSnapshot.child("postImage").getValue();
                String date_post = (String) dataSnapshot.child("postDate").getValue();

                uid_post =  (String) dataSnapshot.child("uid").getValue();

                post_Title.setText(title_post);
                post_Descpn.setText(desc_post);
                postDate.setText(date_post);
                Glide.with(mCtx).load(backdrop_post).into(postCoverImg);

            }

            @Override
            public void onCancelled(DatabaseError databaseError) {

            }
        });

        shareFAB.setOnClickListener(new View.OnClickListener() {  // my implemented share action
            @Override
            public void onClick(View view) {

                String content = post_details;

                Intent shareIntent = new Intent();
                shareIntent.setAction(Intent.ACTION_SEND);
                shareIntent.setType("*/*");
                shareIntent.putExtra(Intent.EXTRA_TEXT,content);
                startActivity(Intent.createChooser(shareIntent,"Share With"));

            }
        });

Body:
Since your sharing the post content try changing your
from:

intent.setType("*/*");

To:

intent.setType("text/plain");


问:
How to reliably get all kafka topic messages via KafkaConsumer
The getMessages() method below sometimes gets all messages for a kafka topic.  This code is executed in a web application on page load.  Sometimes no messages come back and sometimes all messages come back.

Is there a way to set properties and/or change the code so that all messages come back every time?

```<code>public List<String> getMessages() {
    List<String> messages = new ArrayList<>();
    try {
        ConnectionKafka connection = ConstantsHome.connectionManager.getConnectionDef(getGuid(), ConnectionKafka.class);
        Properties props = new Properties();
        props.put("bootstrap.servers", connection.getProps().get("bootstrapServers"));
        props.put("group.id", getName());
        props.put("auto.offset.reset", "earliest");
        props.put("enable.auto.commit", "true");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Collections.singleton(getName()));
        consumer.poll(0);
        consumer.seekToBeginning(consumer.assignment());
        ConsumerRecords<String, String> records = consumer.poll(0);
        for (ConsumerRecord<String, String> record : records) {
            messages.add(
                String.format("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value())
            );
        }
        consumer.close(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        Utils.writeToLog(e, getClass().getName(), "", IErrorManager.ERROR);
    }
    Collections.sort(messages, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1.substring("offset = ".length(), o1.indexOf(","))) -
            Integer.valueOf(o2.substring("offset = ".length(), o2.indexOf(",")));
        }
    });
    return messages;
}
</code>```

答:
If your expectation is get all the messages for each call, you should be setting the following propertly

```<code>enable.auto.commit = false
</code>```

The other option is create a dynamic group ID for each  iteration, I would avoid  this option considering that the groups metadata is stored in the kafka side.

Body:
The getMessages() method below sometimes gets all messages for a kafka topic.  This code is executed in a web application on page load.  Sometimes no messages come back and sometimes all messages come back.

Is there a way to set properties and/or change the code so that all messages come back every time?

public List<String> getMessages() {
    List<String> messages = new ArrayList<>();
    try {
        ConnectionKafka connection = ConstantsHome.connectionManager.getConnectionDef(getGuid(), ConnectionKafka.class);
        Properties props = new Properties();
        props.put("bootstrap.servers", connection.getProps().get("bootstrapServers"));
        props.put("group.id", getName());
        props.put("auto.offset.reset", "earliest");
        props.put("enable.auto.commit", "true");
        props.put("key.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");
        props.put("value.deserializer", "org.apache.kafka.common.serialization.StringDeserializer");

        KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props);
        consumer.subscribe(Collections.singleton(getName()));
        consumer.poll(0);
        consumer.seekToBeginning(consumer.assignment());
        ConsumerRecords<String, String> records = consumer.poll(0);
        for (ConsumerRecord<String, String> record : records) {
            messages.add(
                String.format("offset = %d, key = %s, value = %s%n", record.offset(), record.key(), record.value())
            );
        }
        consumer.close(0, TimeUnit.MILLISECONDS);
    } catch (Exception e) {
        Utils.writeToLog(e, getClass().getName(), "", IErrorManager.ERROR);
    }
    Collections.sort(messages, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return Integer.valueOf(o1.substring("offset = ".length(), o1.indexOf(","))) -
            Integer.valueOf(o2.substring("offset = ".length(), o2.indexOf(",")));
        }
    });
    return messages;
}

Body:
If your expectation is get all the messages for each call, you should be setting the following propertly

enable.auto.commit = false

The other option is create a dynamic group ID for each  iteration, I would avoid  this option considering that the groups metadata is stored in the kafka side.


问:
Is it possible to post 360 Photos to Facebook from an iOS App?
I am looking for a way to post 360 photos on Facebook through my iOS app.

I have been searching on google and couldn't find any useful answer.

Could anyone please clarify about the possibility?

答:
I've created a framework that does exactly this.

Given that you've got the permission successfully, here's what you would do:

```<code>[[Facebook360Manager sharedInstance] shareImage:[UIImage imageNamed:@"cylindrical360.jpg"]
                                      userCaption:@"Example caption..."
                                    horizontalFOV:360.0
                                  sharePreference:FacebookShareManagerPreferenceCylindricalImage
                                  completionBlock:^(NSError * _Nullable error, NSString * _Nullable postID) {
                                    if (error) {
                                      NSLog(@"Error: %@",error);
                                    }else{
                                      NSLog(@"Shared successfully. Post ID: %@",postID);
                                    }
                                  }];
</code>```

Here's a link to the framework: https://github.com/AppCoders-io/Facebook360

Body:
I've created a framework that does exactly this.

Given that you've got the permission successfully, here's what you would do:

[[Facebook360Manager sharedInstance] shareImage:[UIImage imageNamed:@"cylindrical360.jpg"]
                                      userCaption:@"Example caption..."
                                    horizontalFOV:360.0
                                  sharePreference:FacebookShareManagerPreferenceCylindricalImage
                                  completionBlock:^(NSError * _Nullable error, NSString * _Nullable postID) {
                                    if (error) {
                                      NSLog(@"Error: %@",error);
                                    }else{
                                      NSLog(@"Shared successfully. Post ID: %@",postID);
                                    }
                                  }];

Here's a link to the framework: https://github.com/AppCoders-io/Facebook360


问:
How to create an reusable element similar to Selenium extend elements in Cypress.io?
In Selenium, it's possible to extend elements. This makes it possible to have a set of reusable custom elements for testing.

For example, we can have a getText method added.

```<code>public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}
</code>```

And re-use it as follows:

myElement.getText();

This example is detailed here: http://www.vcskicks.com/selenium-extensions.php

Is there a way to replicate this behavior in Cypress.io? Or do we need to query and call the same methods to get the data?

答:
You can accomplish this using simple functions. For example, you could move several functions into a utils.js.

```<code>export const getByText = (text) => cy.contains(text)
</code>```

And then import those methods into your spec file.

```<code>import { getByText } from './utils'

it('finds the element', () => {
  getByText('Jane Lane')
})
</code>```

You could alternatively create a custom command, but that's sometimes not necessary as noted in the best practices.

Body:
In Selenium, it's possible to extend elements. This makes it possible to have a set of reusable custom elements for testing.

For example, we can have a getText method added.

public static string GetText(this IWebDriver driver)
{
    return driver.FindElement(By.TagName("body")).Text;
}

And re-use it as follows:

myElement.getText();

This example is detailed here: http://www.vcskicks.com/selenium-extensions.php

Is there a way to replicate this behavior in Cypress.io? Or do we need to query and call the same methods to get the data?

Body:
You can accomplish this using simple functions. For example, you could move several functions into a utils.js.

export const getByText = (text) => cy.contains(text)

And then import those methods into your spec file.

import { getByText } from './utils'

it('finds the element', () => {
  getByText('Jane Lane')
})

You could alternatively create a custom command, but that's sometimes not necessary as noted in the best practices.


问:
Merging a common project with build variations in .NET MVC
I have a .net mvc site that should be published to a lot of different customers, and thus vary slightly depending on the target.

Is there any way to set up the core project structure, e.g. (simplified):

views

models

controllers

assets

bin

and make a merge at build time with whatever variations the current target might have. For example:

core project:

views

view1.cshtml

view2.cshtml

(removed rest of the folders for brevity)

customer 1 target:

views

view2.cshtml

view3.cshtml

desired merge result:

views

view1.cshtml (from core project)

view2.cshtml (from customer 1 target)

view3.cshtml (from customer 1 target)

The same rule should apply to controllers, binaries etc.

答:
First thing that comes in mind (and probably easiest because it does not require any additional tooling) is to create core project with core functionality, views and controllers. And for each customer create separate project with custom views and controllers. Then for customer-specific project simply link all required files from core project. It can be a little tedious to link the files depending on the number, but seems doable.

Another approach could be to use tools like CAKE or FAKE, with the help of which you can script the entire build process the way you want, but I never tried doing such custom scripting myself.

Third option that I can work as well is to conditionally include files based on defined constant, but that will require editing *.csproj files. The code can be something like:

```<code><Content Include="Views\View1.cshtml" />
<Content Include="Views\View2.cshtml" Condition="$(DefineConstants.Contains('CORE'))" />
<Content Include="Views\View2.cshtml" Condition="$(DefineConstants.Contains('CUSTOMER1'))" />
<Content Include="Views\View3.cshtml" Condition="$(DefineConstants.Contains('CORE'))" />
<Content Include="Views\View3.cshtml" Condition="$(DefineConstants.Contains('CUSTOMER1'))" />
</code>```

Not sure how easy it will be to maintain it though.

I would probably consider to split the application into independent components/projects that will contain all functionality related to the component. The during the build compose components with FAKE based on what components are needed for particular client.

Body:
First thing that comes in mind (and probably easiest because it does not require any additional tooling) is to create core project with core functionality, views and controllers. And for each customer create separate project with custom views and controllers. Then for customer-specific project simply link all required files from core project. It can be a little tedious to link the files depending on the number, but seems doable.

Another approach could be to use tools like CAKE or FAKE, with the help of which you can script the entire build process the way you want, but I never tried doing such custom scripting myself.

Third option that I can work as well is to conditionally include files based on defined constant, but that will require editing *.csproj files. The code can be something like:

<Content Include="Views\View1.cshtml" />
<Content Include="Views\View2.cshtml" Condition="$(DefineConstants.Contains('CORE'))" />
<Content Include="Views\View2.cshtml" Condition="$(DefineConstants.Contains('CUSTOMER1'))" />
<Content Include="Views\View3.cshtml" Condition="$(DefineConstants.Contains('CORE'))" />
<Content Include="Views\View3.cshtml" Condition="$(DefineConstants.Contains('CUSTOMER1'))" />

Not sure how easy it will be to maintain it though.

I would probably consider to split the application into independent components/projects that will contain all functionality related to the component. The during the build compose components with FAKE based on what components are needed for particular client.


问:
Find an element in a list of tuples
I have a list 'a'

```<code>a= [(1,2),(1,4),(3,5),(5,7)]
</code>```

I need to find all the tuples for a particular number. say for 1 it will be

```<code>result = [(1,2),(1,4)]
</code>```

How do I do that?

答:
The filter function can also provide an interesting solution:

```<code>result = list(filter(lambda x: x.count(1) > 0, a))
</code>```

which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

```<code>result = list(filter(lambda x: x[0] == 1, a))
</code>```

Title: Find an element in a list of tuples

Body:
I have a list 'a'

a= [(1,2),(1,4),(3,5),(5,7)]

I need to find all the tuples for a particular number. say for 1 it will be

result = [(1,2),(1,4)]

How do I do that?

Body:
The filter function can also provide an interesting solution:

result = list(filter(lambda x: x.count(1) > 0, a))

which searches the tuples in the list a for any occurrences of 1. If the search is limited to the first element, the solution can be modified into:

result = list(filter(lambda x: x[0] == 1, a))


问:
C++ code gets strangely skipped with no optimizations. Any ideas why?
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

```<code>...
short id;
...
</code>```

file.cc

```<code>id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}
</code>```

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

答:
Recall that during compiling, the C++ compiler looks through the code and determines what parts of the code execute in what order. If the compiler determines that a part of the code is never going to run, it will not optimize it.

For example:

```<code>int i = 0;
if( i == 1) {
    printf("This will never be printed\n");
}
</code>```

Here, there is no reason to optimize the if-statement, as it will never execute.

This sort of instance would be picked up if you compile with:

g++ -Wall mycode.c

where -Wall means show all warnings, and mycode.c is your project file.

As for execution, stepping through GDB shows the current flow of the program. If a branch (in an if-statement) is false, why would it ever go through that section of the code? You can only take one branch in an if-elseif-else statement.

I hope that helps you out.

Body:
I looked for an answer for two days to this with no success. I've never come across this problem before so I'll try my best. Please bear with me.

I returned to a C++ project I created over a year ago, which at the time ran without problems. I came across this interesting and incredibly annoying problem the other day as I was trying to get the same program to run. The code was something like:

file.h

...
short id;
...

file.cc

id = 0;
while (id < some_large_number)
{
   id = foo();
   if (id == 2)
   {
      //do something
   }
   else if (id == 2900)
   {
      //do something
   }
   else if (id == 30000)
   {
      //do something
   }
   else if (id == 40000)
   {
      //do something
   }
   else if (id == 45000)
   {
      //do something
   }
   else
   {
      //do something else
   }
}

The constant numbers were macros in hex notation that I expanded for this example. Turns out that this was truly a bug, but the debugger did not make it easy to discover. Heres what happened:

As I was trying to step through the code using GDB (with no optimizations), I noticed that GDB would jump straight to the else statement after reaching if (id == 30000), everytime. Because the numbers were c macros in hex notation, I did not notice at first that 40000 was beyond the limit of a signed short. This was very misleading, and spent hours trying to figure it out: I recompiled external libraries, reinstalled g++, among other things.

Obviously, making id an unsigned short fixed the problem. The other problem seems like a compiler issue. But I still don't understand, why were those sections of code completely skipped during execution, and with no optimizations? Why would it not go through each if statement and that way I could identify the real problem? Any ideas?

Thanks so much. I hope this is okay for a first question.

Body:
Recall that during compiling, the C++ compiler looks through the code and determines what parts of the code execute in what order. If the compiler determines that a part of the code is never going to run, it will not optimize it.

For example:

int i = 0;
if( i == 1) {
    printf("This will never be printed\n");
}

Here, there is no reason to optimize the if-statement, as it will never execute.

This sort of instance would be picked up if you compile with:

g++ -Wall mycode.c

where -Wall means show all warnings, and mycode.c is your project file.

As for execution, stepping through GDB shows the current flow of the program. If a branch (in an if-statement) is false, why would it ever go through that section of the code? You can only take one branch in an if-elseif-else statement.

I hope that helps you out.


问:
HTML Problems- Video Autoplay Playback Not working
I have started creating a website using HTML, however I want a video to play when I open the page and I have embedded the video as shown:

<!DOCTYPE HTML>

 Video HERE

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

  <video width="1920" height="1080" autoplay>
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

```

This is an example video, however, it doesn't work on a local PC. I use Notepad++ to code in, but it doesn't seem to work?

Please help

thanks

yg.swagness

答:
```<code><script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>
</code>```

This code is the issue- it changes the way your page works and the video doesn't autoplay

Body:
I have started creating a website using HTML, however I want a video to play when I open the page and I have embedded the video as shown:

<!DOCTYPE HTML>

 Video HERE

<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.indigo-pink.min.css">

  <video width="1920" height="1080" autoplay>
  <source src="http://techslides.com/demos/sample-videos/small.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>

This is an example video, however, it doesn't work on a local PC. I use Notepad++ to code in, but it doesn't seem to work?

Please help

thanks

yg.swagness

Body:
<script defer src="https://code.getmdl.io/1.3.0/material.min.js"></script>

This code is the issue- it changes the way your page works and the video doesn't autoplay


问:
jQuery tabs() function not displaying tabs
The following is my HTML code for creating a tabbed page.

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="jquery-ui-1.8.9.custom.min.js"></script>
  <title>Testing Tabs</title>
</head>
<body>
  <div id="tabs">
    <ul>
        <li><a href="#panel1">Panel 1</a></li>
        <li><a href="#panel2">Panel 2</a></li>
        <li><a href="#panel3">Panel 3</a></li>
    </ul>
    <div id="panel1">
        <p>This is the text of panel 1</p>
    </div>
    <div id="panel2">
        <p>This is the text of panel 2</p>
    </div>
    <div id="panel3">
        <p>This is the text of panel 3</p>
    </div>
  </div>
</body>
</code>```

When I execute the command $('#tabs').tabs() (or $('#tabs').tabs({})) at the Firebug CommandLine, nothing really happens i.e. the links remain links, and all the divs are displayed.

答:
Make sure you include the jQueryUI stylesheet as well.

```<code><link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/ui-lightness/jquery-ui.css" />
</code>```

Example: http://jsfiddle.net/6kg7k/

Body:
The following is my HTML code for creating a tabbed page.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

  <title>Testing Tabs</title>

Panel 1

Panel 2

Panel 3

This is the text of panel 1

This is the text of panel 2

This is the text of panel 3

When I execute the command $('#tabs').tabs() (or $('#tabs').tabs({})) at the Firebug CommandLine, nothing really happens i.e. the links remain links, and all the divs are displayed.

Body:
Make sure you include the jQueryUI stylesheet as well.

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/ui-lightness/jquery-ui.css" />

Example: http://jsfiddle.net/6kg7k/


问:
Use erb partials, in Rails, to append the DOM using JavaScript - not hitting controller
I have a form that has a variable number of line items, each having the same inputs and icons and lots of other elements. I have a _line_item.html.erb partial that gets used in a loop in the view to show existing line items.

I also have a button, at the bottom, that when clicked will add a new, blank line item to the page. Doing so, however, doesn't hit the controller and happens completely client side. Currently, I just have a variable in my javascript that is a big string equal to the same HTML in the partial. I have to edit and maintain the erb partial and the javascript string separately, though.

This is all kind of ugly, and not at all DRY, so I was wondering - is there any way to leverage the HTML present in the erb partial for appending new line items, WITHOUT having to hit the controller first? Or, is there a better client-side way of handling appending reusable blocks of HTML?

Also, cloning is not an option since at some point the user could remove all their line items. I guess I could leave a hidden one in the DOM somewhere, rendered via the erb partial, but that also feels not great.

答:
You could do it something like:

add a new form at the end of your line_item list (rendered when you are rending the list) that is hidden via display: none in your css

when you click the add button (or whatever it's called), show the new form (and probably hide the add button). For the form, I like to use a slideDown() function

when the user fills in the form and clicks submit (or however you submit the form), then do your create ajax call to the server. In your controller, render _line_item.html.erb

.on 'ajax:success', append the line_item html to your list (maybe sorting, if that floats your boat), re-hide your new form (similar to above, I use slideUp()), and re-show your add button.


问:
"INSERT IGNORE" vs "INSERT ... ON DUPLICATE KEY UPDATE"
While executing an INSERT statement with many rows, I want to skip duplicate entries that would otherwise cause failure. After some research, my options appear to be the use of either:

ON DUPLICATE KEY UPDATE which implies an unnecessary update at some cost, or

INSERT IGNORE implies an invitation for other kinds of failure to slip in unannounced.

Am I right in these assumptions? What's the best way to simply skip the rows that might cause duplicates and just continue on to the other rows?

答:
If you want to insert in the table and on the conflict of the primary key or unique index it will update the conflicting row instead of inserting that row.

Syntax:

```<code>insert into table1 set column1 = a, column2 = b on duplicate update column2 = c;
</code>```

Now here, this insert statement may look different what you have seen earlier. This insert statement trying to insert a row in table1 with the value of a and b into column column1 and column2 respectively.

Let's understand this statement in depth:

For example: here column1 is defined as the primary key in table1.

Now if in table1  there is no row having the value “a” in column1. So this statement will insert a row in the table1.

Now if in table1 there is a row having the value “a” in column2. So this statement will update the row’s column2  value with “c” where the column1 value is “a”.

So if you want to insert a new row otherwise update that row on the conflict of the primary key or unique index.

Read more on this link

OwnerDisplayName: ThomasGHenry

Body:
If you want to insert in the table and on the conflict of the primary key or unique index it will update the conflicting row instead of inserting that row.

Syntax:

insert into table1 set column1 = a, column2 = b on duplicate update column2 = c;

Now here, this insert statement may look different what you have seen earlier. This insert statement trying to insert a row in table1 with the value of a and b into column column1 and column2 respectively.

Let's understand this statement in depth:

For example: here column1 is defined as the primary key in table1.

Now if in table1  there is no row having the value “a” in column1. So this statement will insert a row in the table1.

Now if in table1 there is a row having the value “a” in column2. So this statement will update the row’s column2  value with “c” where the column1 value is “a”.

So if you want to insert a new row otherwise update that row on the conflict of the primary key or unique index.

Read more on this link


问:
Deleting elements from list depending on randomly generated number
This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list.  It should return a new list with the remaining viruses. Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining.

It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions.

```<code>def kill(viruses, mortalityProb):
    for i in viruses:
        if random.randint(0, 100) < (mortalityProb * 100):
            del i
    return viruses
</code>```

This does not quite work, but I can't get a grasp on why.

答:
One way to do this is viruses.remove(i). However, see the various postings on altering a list while you're iterating through it.

You can make this a one-liner; just call random for each virus, and include it if the "saving throw" works.

```<code>return [i for i in viruses if random.random() < mortalityProb]
</code>```

For instance:

```<code>>>> viruses = [x for x in range(20)]
>>> [i for i in viruses if random.random() < 0.75]
[0, 1, 3, 6, 7, 9, 10, 11, 12, 13, 15, 17, 18, 19]
</code>```

BTW, you have your variable misnamed: mortalityProb should describe the chance of the organism dying, not surviving.

Body:
This function should take a list of viruses like [ATCG, GTAC.....] and a mortalityProb (float between 0 and 1) that represents the chance of a virus to die / get deleted from the list.  It should return a new list with the remaining viruses. Each of the viruses has an individual chance to die, so with a mortalityProb of say 0.6, there should be around 60% of the viruses remaining.

It should be doable in 2 lines (including def kill(viruses, mortalityProb):) and my line of code using list comprehensions.

def kill(viruses, mortalityProb):
    for i in viruses:
        if random.randint(0, 100) < (mortalityProb * 100):
            del i
    return viruses

This does not quite work, but I can't get a grasp on why.

Body:
One way to do this is viruses.remove(i). However, see the various postings on altering a list while you're iterating through it.

You can make this a one-liner; just call random for each virus, and include it if the "saving throw" works.

return [i for i in viruses if random.random() < mortalityProb]

For instance:

>>> viruses = [x for x in range(20)]
>>> [i for i in viruses if random.random() < 0.75]
[0, 1, 3, 6, 7, 9, 10, 11, 12, 13, 15, 17, 18, 19]

BTW, you have your variable misnamed: mortalityProb should describe the chance of the organism dying, not surviving.


问:
SQL Conditional Join if Variable is Not NULL
I have some variable set that could look something like this:

```<code>SET @ItemID1 = 3
SET @ItemID2 = 26
SET @ItemID3 = NULL
SET @ItemRadius1 = 5000
SET @ItemRadius2 = 5000
SET @ItemRadius3 = NULL
</code>```

The ItemID is a lookup field and the radius is distance in meters. eg The query should return all Assets within 5000 meters of items with the ID of @ItemID1.

My query is currently joining on if the distance between the "Geo" field (which is a geography type) is less than whatever the radius is entetered.

```<code>SELECT DISTINCT
    a.AssetID,
    a.Name
    FROM Asset a
     JOIN Item i1 ON ((a.Geo.STDistance(i1.Geo) < @ItemRadius1) AND i1.TypeID = @ItemID1)
     JOIN Item i2 ON ((a.Geo.STDistance(i2.Geo) < @ItemRadius2) AND i2.TypeID = @ItemID2)
     JOIN Item i3 ON ((a.Geo.STDistance(i3.Geo) < @ItemRadius3) AND i3.TypeID = @ItemID3)
</code>```

My issue is that this is being set up as a procedure and the declared variables may be null. If they are my query will return no results. Is there a way to run the condition only if @ItemID3 IS NOT NULL AND @ItemRadius3 IS NOT NULL. I have tried selecting my results into a declared table then running the join on that declared table but my results were not filtering correctly. Any suggestions would be appreciated.

答:
I would suggest writing the query as:

```<code>SELECT a.*
FROM Asset a
WHERE (@ItemID1 IS NULL OR ItemRadius1 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i1
              WHERE a.Geo.STDistance(i1.Geo) < @ItemRadius1 AND i1.TypeID = @ItemID1)
      ) AND
      (@ItemID2 IS NULL OR ItemRadius2 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i2
              WHERE a.Geo.STDistance(i2.Geo) < @ItemRadius2 AND i2.TypeID = @ItemID1)
      ) AND
      (@ItemID3 IS NULL OR ItemRadius3 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i3
              WHERE a.Geo.STDistance(i3.Geo) < @ItemRadius3 AND i3.TypeID = @ItemID1)
      ) ;
</code>```

At the very least, this eliminates the overhead for the SELECT DISTINCT.

Body:
I have some variable set that could look something like this:

SET @ItemID1 = 3
SET @ItemID2 = 26
SET @ItemID3 = NULL
SET @ItemRadius1 = 5000
SET @ItemRadius2 = 5000
SET @ItemRadius3 = NULL

The ItemID is a lookup field and the radius is distance in meters. eg The query should return all Assets within 5000 meters of items with the ID of @ItemID1.

My query is currently joining on if the distance between the "Geo" field (which is a geography type) is less than whatever the radius is entetered.

SELECT DISTINCT
    a.AssetID,
    a.Name
    FROM Asset a
     JOIN Item i1 ON ((a.Geo.STDistance(i1.Geo) < @ItemRadius1) AND i1.TypeID = @ItemID1)
     JOIN Item i2 ON ((a.Geo.STDistance(i2.Geo) < @ItemRadius2) AND i2.TypeID = @ItemID2)
     JOIN Item i3 ON ((a.Geo.STDistance(i3.Geo) < @ItemRadius3) AND i3.TypeID = @ItemID3)

My issue is that this is being set up as a procedure and the declared variables may be null. If they are my query will return no results. Is there a way to run the condition only if @ItemID3 IS NOT NULL AND @ItemRadius3 IS NOT NULL. I have tried selecting my results into a declared table then running the join on that declared table but my results were not filtering correctly. Any suggestions would be appreciated.

Body:
I would suggest writing the query as:

SELECT a.*
FROM Asset a
WHERE (@ItemID1 IS NULL OR ItemRadius1 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i1
              WHERE a.Geo.STDistance(i1.Geo) < @ItemRadius1 AND i1.TypeID = @ItemID1)
      ) AND
      (@ItemID2 IS NULL OR ItemRadius2 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i2
              WHERE a.Geo.STDistance(i2.Geo) < @ItemRadius2 AND i2.TypeID = @ItemID1)
      ) AND
      (@ItemID3 IS NULL OR ItemRadius3 IS NULL OR
       EXISTS (SELECT 1
              FROM Item i3
              WHERE a.Geo.STDistance(i3.Geo) < @ItemRadius3 AND i3.TypeID = @ItemID1)
      ) ;

At the very least, this eliminates the overhead for the SELECT DISTINCT.


问:
Sorry, we're having trouble reaching the server
We have restore site from dev machine to staging. We have list in our site with people picker which is working fine on dev, but on staging it is showing message "Sorry, we're having trouble reaching the server.".

I have try to create one more people picker column in list(Stag), but new column also giving same error.

If i create new list on new column to other list(stag), it is working fine.

Can any one please help me in that.

答:
This worked for me
https://social.technet.microsoft.com/wiki/contents/articles/36583.sharepoint-2013-people-picker-error-sorry-were-having-trouble-reaching-the-server.aspx

```<code>$webApp = Get-SPWebApplication https://<web adderss>
$newdomain = new-object Microsoft.SharePoint.Administration.SPPeoplePickerSearchActiveDirectoryDomain
$newdomain.DomainName ='<Domain Name like domain.com>';
$newdomain.ShortDomainName ='<net bios name (optional)>';
$newdomain.LoginName ='domain\Farm Account'
$newdomain.IsForest='false'
$webapp.PeoplePickerSettings.SearchActiveDirectoryDomains.Add($newdomain)
$webapp.update()
</code>```

To verify

```<code>$webapp.PeoplePickerSettings.SearchActiveDirectoryDomains
</code>```

Body:
This worked for me
https://social.technet.microsoft.com/wiki/contents/articles/36583.sharepoint-2013-people-picker-error-sorry-were-having-trouble-reaching-the-server.aspx

$webApp = Get-SPWebApplication https://<web adderss>
$newdomain = new-object Microsoft.SharePoint.Administration.SPPeoplePickerSearchActiveDirectoryDomain
$newdomain.DomainName ='<Domain Name like domain.com>';
$newdomain.ShortDomainName ='<net bios name (optional)>';
$newdomain.LoginName ='domain\Farm Account'
$newdomain.IsForest='false'
$webapp.PeoplePickerSettings.SearchActiveDirectoryDomains.Add($newdomain)
$webapp.update()

To verify

$webapp.PeoplePickerSettings.SearchActiveDirectoryDomains


问:
Trying to understand the asynchrouny with a big amount of different function calls
I've started learing an asynchronous aproach, and
encountered a problem, help me with it.

The purpose is: get from somewhere a char data, and after that do something with it(using as text on the button, in my case). The code, that is pinned below is very slow. The most slowiest moment is a data getting: the fact is that the get(int id) function loads data from internet via WinInet(synchronously), sending the Post methods, and returning the answer.

```<code>void some_func()
{
for(int i(0);i<10;i++)
   for(int q(0);q<5;q++)
     {
       char data[100];
       strcpy(data, get(i,q)); // i, q - just some identifier data

       button[5*i+(q+1)]=new Button(data);
     }
}
</code>```

The first question:

How should it be solved(generaly, I mean, if get has nothing to do with the internet, but runs slow)? I have only one, stupid idea: run get in every separate thread. If it's the right way - how should I do that? Cause, it's wrong to, created 50 threads call from each the get function. 50 get functions?

Second Question

How to realize it with WinInet? Have red MSDN, but it too hardly for me, as for newer, maybe you explain it more simlier?

Thanks

答:
for asynchronous programming you need create some object which will be maintain state - in current case i and q must be not local variables of function but members of object, mandatory reference count to object. and usual file(socket) handle , etc.

function some_func() must have another pattern. it must be member function of object. and it must not call asynchronous get in loop. after call get it must just exit. when asynchronous operation, initiated by get, will be finished - some your callback must be called (if failed initiate asynchronous operation you need yourself just call this callback with error code). in callback you will be have pointer to your object  and using it - call some_func(). so some_func() must at begin handle result of previous get call - check for error, handle received data, if no error. than adjust object state (in your case i and q) and if need - call get again. and for initiated all this - need first time call get direct:

```<code>begin -> get() -> .. callback .. -> some_func() -> exit
          ^                             ┬
          └─────────────────────────────┘
</code>```

some demo example (with asynchronous read file)

```<code>struct SOME_OBJECT
{
    LARGE_INTEGER _ByteOffset;
    HANDLE _hFile;
    LONG _dwRef;
    int _i, _q;

    SOME_OBJECT()
    {
        _i = 0, _q = 0;
        _dwRef = 1;
        _ByteOffset.QuadPart = 0;
        _hFile = 0;
    }

    void beginGet();

    void DoSomething(PVOID pvData, DWORD_PTR cbData)
    {
        DbgPrint("DoSomething<%u,%u>(%x, %p)\n", _i, _q, cbData, pvData);
    }

    // some_func
    void OnComplete(DWORD dwErrorCode, PVOID pvData, DWORD_PTR cbData)
    {
        if (dwErrorCode == NOERROR)
        {
            DoSomething(pvData, cbData);

            if (++_q == 5)
            {
                _q = 0;

                if (++_i == 10)
                {
                    return ;
                }
            }

            _ByteOffset.QuadPart += cbData;

            beginGet();
        }
        else
        {
            DbgPrint("OnComplete - error=%u\n", dwErrorCode);
        }
    }

    ~SOME_OBJECT()
    {
        if (_hFile) CloseHandle(_hFile);
    }

    void AddRef() { InterlockedIncrement(&_dwRef); }

    void Release() { if (!InterlockedDecrement(&_dwRef)) delete this; }

    ULONG Create(PCWSTR FileName);
};

struct OPERATION_CTX : OVERLAPPED
{
    SOME_OBJECT* _pObj;
    BYTE _buf[];

    OPERATION_CTX(SOME_OBJECT* pObj) : _pObj(pObj)
    {
        pObj->AddRef();
        hEvent = 0;
    }

    ~OPERATION_CTX()
    {
        _pObj->Release();
    }

    VOID CALLBACK CompletionRoutine(DWORD dwErrorCode, DWORD_PTR dwNumberOfBytesTransfered)
    {
        _pObj->OnComplete(dwErrorCode, _buf, dwNumberOfBytesTransfered);

        delete this;
    }

    static VOID CALLBACK _CompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, OVERLAPPED* lpOverlapped)
    {
        static_cast<OPERATION_CTX*>(lpOverlapped)->CompletionRoutine(RtlNtStatusToDosError(dwErrorCode), dwNumberOfBytesTransfered);
    }

    void CheckResult(BOOL fOk)
    {
        if (!fOk)
        {
            ULONG dwErrorCode = GetLastError();

            if (dwErrorCode != ERROR_IO_PENDING)
            {
                CompletionRoutine(dwErrorCode, 0);
            }
        }
    }

    void* operator new(size_t cb, size_t ex)
    {
        return ::operator new(cb + ex);
    }

    void operator delete(PVOID pv)
    {
        ::operator delete(pv);
    }
};

ULONG SOME_OBJECT::Create(PCWSTR FileName)
{
    HANDLE hFile = CreateFile(FileName, FILE_READ_DATA, FILE_SHARE_READ, 0,
        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

    if (hFile != INVALID_HANDLE_VALUE)
    {
        _hFile = hFile;

        if (BindIoCompletionCallback(hFile, OPERATION_CTX::_CompletionRoutine, 0))
        {
            return NOERROR;
        }
    }

    return GetLastError();
}

void SOME_OBJECT::beginGet()
{
    const ULONG cbRead = 0x1000;

    if (OPERATION_CTX* ctx = new(cbRead) OPERATION_CTX(this))
    {
        ctx->Offset = _ByteOffset.LowPart;
        ctx->OffsetHigh = _ByteOffset.HighPart;
        ctx->CheckResult(ReadFile(_hFile, ctx->_buf, cbRead, 0, ctx));
    }
}

void ADemo(PCWSTR FileName)
{
    if (SOME_OBJECT* pObj = new SOME_OBJECT)
    {
        if (!pObj->Create(FileName))
        {
            pObj->beginGet();
        }
        pObj->Release();
    }
}
</code>```

Body:
I've started learing an asynchronous aproach, and
encountered a problem, help me with it.

The purpose is: get from somewhere a char data, and after that do something with it(using as text on the button, in my case). The code, that is pinned below is very slow. The most slowiest moment is a data getting: the fact is that the get(int id) function loads data from internet via WinInet(synchronously), sending the Post methods, and returning the answer.

void some_func()
{
for(int i(0);i<10;i++)
   for(int q(0);q<5;q++)
     {
       char data[100];
       strcpy(data, get(i,q)); // i, q - just some identifier data

       button[5*i+(q+1)]=new Button(data);
     }
}

The first question:

How should it be solved(generaly, I mean, if get has nothing to do with the internet, but runs slow)? I have only one, stupid idea: run get in every separate thread. If it's the right way - how should I do that? Cause, it's wrong to, created 50 threads call from each the get function. 50 get functions?

Second Question

How to realize it with WinInet? Have red MSDN, but it too hardly for me, as for newer, maybe you explain it more simlier?

Thanks

Body:
for asynchronous programming you need create some object which will be maintain state - in current case i and q must be not local variables of function but members of object, mandatory reference count to object. and usual file(socket) handle , etc.

function some_func() must have another pattern. it must be member function of object. and it must not call asynchronous get in loop. after call get it must just exit. when asynchronous operation, initiated by get, will be finished - some your callback must be called (if failed initiate asynchronous operation you need yourself just call this callback with error code). in callback you will be have pointer to your object  and using it - call some_func(). so some_func() must at begin handle result of previous get call - check for error, handle received data, if no error. than adjust object state (in your case i and q) and if need - call get again. and for initiated all this - need first time call get direct:

begin -> get() -> .. callback .. -> some_func() -> exit
          ^                             ┬
          └─────────────────────────────┘

some demo example (with asynchronous read file)

struct SOME_OBJECT
{
    LARGE_INTEGER _ByteOffset;
    HANDLE _hFile;
    LONG _dwRef;
    int _i, _q;

    SOME_OBJECT()
    {
        _i = 0, _q = 0;
        _dwRef = 1;
        _ByteOffset.QuadPart = 0;
        _hFile = 0;
    }

    void beginGet();

    void DoSomething(PVOID pvData, DWORD_PTR cbData)
    {
        DbgPrint("DoSomething<%u,%u>(%x, %p)\n", _i, _q, cbData, pvData);
    }

    // some_func
    void OnComplete(DWORD dwErrorCode, PVOID pvData, DWORD_PTR cbData)
    {
        if (dwErrorCode == NOERROR)
        {
            DoSomething(pvData, cbData);

            if (++_q == 5)
            {
                _q = 0;

                if (++_i == 10)
                {
                    return ;
                }
            }

            _ByteOffset.QuadPart += cbData;

            beginGet();
        }
        else
        {
            DbgPrint("OnComplete - error=%u\n", dwErrorCode);
        }
    }

    ~SOME_OBJECT()
    {
        if (_hFile) CloseHandle(_hFile);
    }

    void AddRef() { InterlockedIncrement(&_dwRef); }

    void Release() { if (!InterlockedDecrement(&_dwRef)) delete this; }

    ULONG Create(PCWSTR FileName);
};

struct OPERATION_CTX : OVERLAPPED
{
    SOME_OBJECT* _pObj;
    BYTE _buf[];

    OPERATION_CTX(SOME_OBJECT* pObj) : _pObj(pObj)
    {
        pObj->AddRef();
        hEvent = 0;
    }

    ~OPERATION_CTX()
    {
        _pObj->Release();
    }

    VOID CALLBACK CompletionRoutine(DWORD dwErrorCode, DWORD_PTR dwNumberOfBytesTransfered)
    {
        _pObj->OnComplete(dwErrorCode, _buf, dwNumberOfBytesTransfered);

        delete this;
    }

    static VOID CALLBACK _CompletionRoutine(DWORD dwErrorCode, DWORD dwNumberOfBytesTransfered, OVERLAPPED* lpOverlapped)
    {
        static_cast<OPERATION_CTX*>(lpOverlapped)->CompletionRoutine(RtlNtStatusToDosError(dwErrorCode), dwNumberOfBytesTransfered);
    }

    void CheckResult(BOOL fOk)
    {
        if (!fOk)
        {
            ULONG dwErrorCode = GetLastError();

            if (dwErrorCode != ERROR_IO_PENDING)
            {
                CompletionRoutine(dwErrorCode, 0);
            }
        }
    }

    void* operator new(size_t cb, size_t ex)
    {
        return ::operator new(cb + ex);
    }

    void operator delete(PVOID pv)
    {
        ::operator delete(pv);
    }
};

ULONG SOME_OBJECT::Create(PCWSTR FileName)
{
    HANDLE hFile = CreateFile(FileName, FILE_READ_DATA, FILE_SHARE_READ, 0,
        OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);

    if (hFile != INVALID_HANDLE_VALUE)
    {
        _hFile = hFile;

        if (BindIoCompletionCallback(hFile, OPERATION_CTX::_CompletionRoutine, 0))
        {
            return NOERROR;
        }
    }

    return GetLastError();
}

void SOME_OBJECT::beginGet()
{
    const ULONG cbRead = 0x1000;

    if (OPERATION_CTX* ctx = new(cbRead) OPERATION_CTX(this))
    {
        ctx->Offset = _ByteOffset.LowPart;
        ctx->OffsetHigh = _ByteOffset.HighPart;
        ctx->CheckResult(ReadFile(_hFile, ctx->_buf, cbRead, 0, ctx));
    }
}

void ADemo(PCWSTR FileName)
{
    if (SOME_OBJECT* pObj = new SOME_OBJECT)
    {
        if (!pObj->Create(FileName))
        {
            pObj->beginGet();
        }
        pObj->Release();
    }
}


问:
Evaluating a mathematical expression in a string form
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()
```

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

答:
For completion sake, posting @Jim Mischel solution as working Python 3 code.</p>

```<code>import re

class Solution:
    def evalExpression(self, s):
        operator_stack, operand_stack = [], []
        tokens = [i for i in re.split(r'(\d+|\W+)', s) if i]
        for token in tokens:
            if token.isdigit():
                operand_stack.append(int(token))
            else:
                while len(operator_stack) > 0 and self.has_higher_precedence(operator_stack[-1], token):
                    val = self.evaluate(operand_stack.pop(), operator_stack.pop(), operand_stack.pop())
                    operand_stack.append(val)
                operator_stack.append(token)
        while len(operator_stack) > 0:
            val = self.evaluate(operand_stack.pop(), operator_stack.pop(), operand_stack.pop())
            operand_stack.append(val)
        return operand_stack[-1]

    def has_higher_precedence(self, opr1, opr2):
        if opr1 == '/' or opr1 == '*' and opr2 == '+' or opr2 == '-':
            return True
        return False

    def evaluate(self, a, b, c):
        if b == '/':
            return c/a
        elif b == '*':
            return c*a
        elif b == '-':
            return c-a
        else:
            return c+a

if __name__ == '__main__':
    solution = Solution()
    print(solution.evalExpression('3+3-6*2'))
</code>```

Body:
This is a standard interview question, evaluate a mathematical expression given in the form of a string.

So provided, '3+3-6*2'
The answer should be -6

Now if the expressions only support four operations +,-,*,/
Then is there a simple way to do it using a stack.

I've solved it by converting the infix notation to postfix and then solving it using a stack - but I'm looking for a different approach that supports only these four operations. This is my solution,

def evaluate(self, s: str) -> int:
    expr = [i for i in re.split(r'(\d+|\W+)', s) if i]
    rpn = self.convertToPostfix(expr)
    return self.evalPostfix(rpn)

def convertToPostfix(self, infix: list) -> list:
    stack = collections.deque()
    result = []
    for item in infix:
        if item.isdigit():
            result.append(item)
        else:
            while len(stack) > 0 and self.has_higher_precedence(stack[-1], item):
                result.append(stack[-1])
                stack.pop()
            stack.append(item)
    while len(stack) > 0:
        result.append(stack.pop())
    return result

def has_higher_precedence(self, a: str, b: str) -> bool:
    if a == '/' and b == '*' or b == '+' or b == '-':
        return True
    if a == '*' and b == '+' or '-':
        return True
    if a == '+' and b == '-':
        return True
    return False

def evalPostfix(self, p: list) -> int:
    stack = collections.deque()
    for item in p:
        if item.isdigit():
            stack.append(int(item))
        elif item[1:].isdigit():
            stack.append(int(item))
        else:
            curr = stack.pop()
            prev = stack.pop()
            if item == '+':
                total = prev + curr
            elif item == '-':
                total = prev - curr
            elif item == '*':
                total = prev * curr
            else:
                total = prev / curr
            stack.append(total)
    return stack.pop()

Also I'm aware that this can be solved by designing a recursive lexical parser but that's beyond the scope of this question.

So my question is, is there a simple way to do this in O(n) time using a stack if there are only four operators

Body:
For completion sake, posting @Jim Mischel solution as working Python 3 code.

import re

class Solution:
    def evalExpression(self, s):
        operator_stack, operand_stack = [], []
        tokens = [i for i in re.split(r'(\d+|\W+)', s) if i]
        for token in tokens:
            if token.isdigit():
                operand_stack.append(int(token))
            else:
                while len(operator_stack) > 0 and self.has_higher_precedence(operator_stack[-1], token):
                    val = self.evaluate(operand_stack.pop(), operator_stack.pop(), operand_stack.pop())
                    operand_stack.append(val)
                operator_stack.append(token)
        while len(operator_stack) > 0:
            val = self.evaluate(operand_stack.pop(), operator_stack.pop(), operand_stack.pop())
            operand_stack.append(val)
        return operand_stack[-1]

    def has_higher_precedence(self, opr1, opr2):
        if opr1 == '/' or opr1 == '*' and opr2 == '+' or opr2 == '-':
            return True
        return False

    def evaluate(self, a, b, c):
        if b == '/':
            return c/a
        elif b == '*':
            return c*a
        elif b == '-':
            return c-a
        else:
            return c+a

if __name__ == '__main__':
    solution = Solution()
    print(solution.evalExpression('3+3-6*2'))


问:
Smallest Java SVG Engine
What is the smallest Java SVG engine (least/smallest jars) that actually works?  If your answer is Batik, what is the minimal dep. graph for getting this to work in a simple Java application?

I've looked at the dependency graph on the Batik site, but it looks like a typical Apache mess.  Are there better alternatives?

答: SVG Salamander claims to be much smaller thank Batik. It's hard not to believe them. Whether it's as full featured, I can't say, but a co-worker said good things about it.</p>

OwnerDisplayName: jsight

Title: Smallest Java SVG Engine

OwnerDisplayName: Dave Ray


问:
Delete line containing pattern found anywhere in another file
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

file2

```<code>these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words
</code>```

Expected output:

```<code>10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion
</code>```

Body:
I'd like to compare two files and delete lines in file1 if they contain a pattern found anywhere in file2. I did some searching and the closest answers I've been able to find were how to delete lines that appear in another file.

I'd like a simple grep, awk, sed, etc one-liner if possible. I'm matching on IP addresses, as shown below.

file1

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.2 00:00:12:34 1234.56AB.CDEF Vlan2
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

file2

these-are some_words 10.10.50.2 andmaybe some-other words
theseare somewords 10.10.50.99 and-maybe some_other words

Expected output:

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion

Body:
awk to the rescue!

$ awk 'NR==FNR{a[$3];next} !($1 in a)' file2 file1

10.10.50.1 00:00:10:23 0000.0012.3456 Vlan1
10.10.50.3 00:00:23:10 ABCD.EF12.345 Vlan3billion


问:
Python dict with list to dataframe
I have a python dict with a few key/value pairs, one value being a list, that I'm trying to convert the a Pandas dataframe. Converting the generic dict is rather straight forward with df = pd.DataFrame(dict), however the list is throwing off the conversion and I'm seeking help on the best practice on how to deal with it.

For example, below in a sample dict that I'm working with:

```<code>{'foo': 123.0, 'ctr': 0.03, 'bar': 2.3, 'keys': ['2015-05-01', 'us', 'find foo', 'find bar', 'DESKTOP'], 'super': 5.0}
</code>```

However below is the return of the dataframe --note that the list created multiple rows within the dataframe.

```<code>   super   ctr     foo    keys        bar
0     5.0  0.03    123.0  2015-05-01  2.3
1     5.0  0.03    123.0  tha         2.3
2     5.0  0.03    123.0  find foo    2.3
3     5.0  0.03    123.0  find bar    2.3
4     5.0  0.03    123.0  DESKTOP     2.3
</code>```

Is there a better way to convert a python dict like this than simply passing it through pd.DataFrame() to have it return one row with all data within the dict?

Many thanks in advance!

答:
Brackets around dict will do the trick

```<code>pd.DataFrame([dict])
</code>```

Title: Python dict with list to dataframe

Body:
I have a python dict with a few key/value pairs, one value being a list, that I'm trying to convert the a Pandas dataframe. Converting the generic dict is rather straight forward with df = pd.DataFrame(dict), however the list is throwing off the conversion and I'm seeking help on the best practice on how to deal with it.

For example, below in a sample dict that I'm working with:

{'foo': 123.0, 'ctr': 0.03, 'bar': 2.3, 'keys': ['2015-05-01', 'us', 'find foo', 'find bar', 'DESKTOP'], 'super': 5.0}

However below is the return of the dataframe --note that the list created multiple rows within the dataframe.

   super   ctr     foo    keys        bar
0     5.0  0.03    123.0  2015-05-01  2.3
1     5.0  0.03    123.0  tha         2.3
2     5.0  0.03    123.0  find foo    2.3
3     5.0  0.03    123.0  find bar    2.3
4     5.0  0.03    123.0  DESKTOP     2.3

Is there a better way to convert a python dict like this than simply passing it through pd.DataFrame() to have it return one row with all data within the dict?

Many thanks in advance!

Body:
Brackets around dict will do the trick

pd.DataFrame([dict])