qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
269,436 |
<p>I have set a canvas' background to an image of a company logo. I would like for this image to be aligned to the bottom right corner of the canvas.<br>
Is it possible to do this, or would it require for the image to be added into the canvas as a child? That would not work with this program as all children of the canvas are handled differently.</p>
<p>Thank You</p>
|
[
{
"answer_id": 269514,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 0,
"selected": false,
"text": "<p>AFAIK The WPF Canvas needs child UI elements to be positioned using absolute co-ordinates. \nTo achieve the right-bottom-anchored effect, I think you'd need to <strong>handle the window resize event, recalculate and apply the Top,Left co-ordinates</strong> for the child Image element to always stick to the right buttom corner.</p>\n\n<pre><code><Window x:Class=\"HelloWPF.Window1\" xmlns...\n Title=\"Window1\" Height=\"300\" Width=\"339\">\n <Canvas>\n <Image Canvas.Left=\"195\" Canvas.Top=\"175\" Height=\"87\" Name=\"image1\" Stretch=\"Fill\" Width=\"122\" Source=\"dilbert2666700071126ni1.gif\"/>\n </Canvas>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 270871,
"author": "Alan Le",
"author_id": 1133,
"author_profile": "https://Stackoverflow.com/users/1133",
"pm_score": 0,
"selected": false,
"text": "<p>How about containing the canvas and image inside of a Grid control like so?</p>\n\n<pre><code><Window ...>\n <Grid>\n <Canvas/>\n <Image HorizontalAlignment=\"Right\" VerticalAlignment=\"Bottom\" .../>\n <Grid>\n</Window>\n</code></pre>\n"
},
{
"answer_id": 270883,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 5,
"selected": true,
"text": "<p>Will this work? (It worked for me, anyway.)</p>\n\n<pre><code> <Canvas>\n <Canvas.Background>\n <ImageBrush ImageSource=\"someimage.jpg\" AlignmentX=\"Right\" \n AlignmentY=\"Bottom\" Stretch=\"None\" />\n </Canvas.Background>\n </Canvas>\n</code></pre>\n"
},
{
"answer_id": 15619342,
"author": "Enrique Marco",
"author_id": 2208251,
"author_profile": "https://Stackoverflow.com/users/2208251",
"pm_score": 0,
"selected": false,
"text": "<p>This is my solution using a border inside the canvas to align the image. This solution works well when canvas is resized:</p>\n\n<pre><code><Canvas x:Name=\"MiCanvas\" Height=\"250\" Width=\"500\" Background=\"Aqua\">\n <Border x:Name=\"MiBorderImage\" \n Width=\"{Binding ElementName=MiCanvas, Path=ActualWidth}\"\n Height=\"{Binding ElementName=MiCanvas, Path=ActualHeight}\"\n Background=\"Transparent\">\n <Image x:Name=\"MiImage\" Source=\"/GraphicsLibrary/Logos/MiLogo.png\"\n HorizontalAlignment=\"Right\" \n VerticalAlignment=\"Bottom\" \n Stretch=\"None\" />\n </Border>\n </Canvas>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30838/"
] |
I have set a canvas' background to an image of a company logo. I would like for this image to be aligned to the bottom right corner of the canvas.
Is it possible to do this, or would it require for the image to be added into the canvas as a child? That would not work with this program as all children of the canvas are handled differently.
Thank You
|
Will this work? (It worked for me, anyway.)
```
<Canvas>
<Canvas.Background>
<ImageBrush ImageSource="someimage.jpg" AlignmentX="Right"
AlignmentY="Bottom" Stretch="None" />
</Canvas.Background>
</Canvas>
```
|
269,440 |
<p>I have the following query:</p>
<pre><code>UPDATE lessonstatus
INNER JOIN user ON lessonstatus.user_id = user.user_id
SET user_id = (SELECT user_id FROM user WHERE username = 'too_many_accounts')
WHERE last_name = 'stupid'
AND first_name = 'user'
AND username != 'too_many_accounts'
AND lessonstatus.lesson_id NOT IN (SELECT lesson_id FROM lessonstatus WHERE user_id = 1);
</code></pre>
<p>However, I get the following error when trying to execute it:</p>
<pre><code>Error Code : 1093
You can't specify target table 'lessonstatus_rtab' for update in FROM clause
</code></pre>
<p>How would I fix this query so that it works?</p>
|
[
{
"answer_id": 269471,
"author": "Arvo",
"author_id": 35777,
"author_profile": "https://Stackoverflow.com/users/35777",
"pm_score": 0,
"selected": false,
"text": "<p>There are more errors (\"user\" table and \"user_rtab\" alias do not match, use of non-qualified field names is not recommended), but UPDATE syntax itself should be similar:</p>\n\n<pre><code>UPDATE lessonstatus\nSET user_id = (SELECT TOP 1 user_id FROM user WHERE username = 'too_many_accounts')\nFROM lessonstatus\n INNER JOIN user ON lessonstatus.user_id = user_rtab.user_id\nWHERE last_name = 'stupid' \n AND first_name = 'user'\n AND username != 'too_many_accounts'\n AND lessonstatus.lesson_id NOT IN (\n SELECT lesson_id FROM lessonstatus WHERE user_id = 1\n );\n</code></pre>\n"
},
{
"answer_id": 269546,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 3,
"selected": true,
"text": "<p>You can't <code>SELECT</code> from a table (even in a subquery) that you're updating in the same query. That's what the error \"can't specify target table\" means.</p>\n\n<p>But you can join <code>user</code> and <code>lessonstatus</code> multiple times in the <code>UPDATE</code> statement, and use the join criteria creatively to pick out the individual row you want.</p>\n\n<p>The way to simulate <code>NOT IN</code> with a join is to do a <code>LEFT OUTER JOIN</code>. Where the right side of that join is not matched, that's where <code>NOT IN</code> would be true.</p>\n\n<pre><code>UPDATE lessonstatus l1\n INNER JOIN user u1 ON (l1.user_id = u1.user_id)\n INNER JOIN user u2 ON (u2.username = 'too_many_accounts')\n LEFT OUTER JOIN lessonstatus l2 \n ON (l1.lesson_id = l2.lesson_id AND l2.user_id = 1)\nSET l1.user_id = u2.user_id\nWHERE u1.last_name = 'stupid' AND u1.first_name = 'user'\n AND u1.username != 'too_many_accounts'\n AND l2.lesson_id IS NULL; -- equivalent to \"l NOT IN l2\"\n</code></pre>\n\n<p><strong>nb:</strong> I have tested this query for syntax, but not with real data. Anyway, it should get you started.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
I have the following query:
```
UPDATE lessonstatus
INNER JOIN user ON lessonstatus.user_id = user.user_id
SET user_id = (SELECT user_id FROM user WHERE username = 'too_many_accounts')
WHERE last_name = 'stupid'
AND first_name = 'user'
AND username != 'too_many_accounts'
AND lessonstatus.lesson_id NOT IN (SELECT lesson_id FROM lessonstatus WHERE user_id = 1);
```
However, I get the following error when trying to execute it:
```
Error Code : 1093
You can't specify target table 'lessonstatus_rtab' for update in FROM clause
```
How would I fix this query so that it works?
|
You can't `SELECT` from a table (even in a subquery) that you're updating in the same query. That's what the error "can't specify target table" means.
But you can join `user` and `lessonstatus` multiple times in the `UPDATE` statement, and use the join criteria creatively to pick out the individual row you want.
The way to simulate `NOT IN` with a join is to do a `LEFT OUTER JOIN`. Where the right side of that join is not matched, that's where `NOT IN` would be true.
```
UPDATE lessonstatus l1
INNER JOIN user u1 ON (l1.user_id = u1.user_id)
INNER JOIN user u2 ON (u2.username = 'too_many_accounts')
LEFT OUTER JOIN lessonstatus l2
ON (l1.lesson_id = l2.lesson_id AND l2.user_id = 1)
SET l1.user_id = u2.user_id
WHERE u1.last_name = 'stupid' AND u1.first_name = 'user'
AND u1.username != 'too_many_accounts'
AND l2.lesson_id IS NULL; -- equivalent to "l NOT IN l2"
```
**nb:** I have tested this query for syntax, but not with real data. Anyway, it should get you started.
|
269,458 |
<p>Ages ago when I was a java developer I could make separate ant scripts that I would call from my main ant script. I would put properties unique to each environment where my main script would run. I want to do the same thing in MSBuild but I can't find out how to chain MSBuild scripts together.</p>
|
[
{
"answer_id": 269482,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 3,
"selected": true,
"text": "<p>You need to <a href=\"http://msdn.microsoft.com/en-us/library/92x05xfs.aspx\" rel=\"nofollow noreferrer\">Import</a> them.</p>\n\n<pre><code> <Import Project=\"MyTargets\" Condition=\"Exists('MyTargets')\"/>\n</code></pre>\n"
},
{
"answer_id": 269498,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 1,
"selected": false,
"text": "<p>The import is definitely useful, you can also actively invoke other projects:</p>\n\n<pre><code><MSBuild Projects=\"Other.proj\" Properties=\"SomeProp=$(MyProperty)\" />\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
Ages ago when I was a java developer I could make separate ant scripts that I would call from my main ant script. I would put properties unique to each environment where my main script would run. I want to do the same thing in MSBuild but I can't find out how to chain MSBuild scripts together.
|
You need to [Import](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx) them.
```
<Import Project="MyTargets" Condition="Exists('MyTargets')"/>
```
|
269,462 |
<p>I'm doing some small changes to C++ MFC project. I'm .NET developer so Windows programming is new to me.</p>
<p>I need to launch some method right after CDialog is completely shown (painted) for the first time, but only once.</p>
<p>How can I do this? In .NET I would handle <strong>Form.Shown</strong> event.</p>
<p>Do I need to handle some message? Which?
Do I need to override some CDialog method?
Or is there no easy way? I'm thinking of handling WM_ACTIVATE and then using a flag to ensure I call another method only once.</p>
|
[
{
"answer_id": 269850,
"author": "Sumrak",
"author_id": 19124,
"author_profile": "https://Stackoverflow.com/users/19124",
"pm_score": 3,
"selected": true,
"text": "<p>Found the answer here: <a href=\"https://web.archive.org/web/20190119124649/https://blogs.msdn.microsoft.com/oldnewthing/20060925-02/?p=29603\" rel=\"nofollow noreferrer\">Waiting until the dialog box is displayed before doing something</a></p>\n<pre><code>Short story:\nINT_PTR CALLBACK\nDlgProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)\n{\n switch (uiMsg) {\n\n case WM_INITDIALOG:\n return TRUE;\n\n case WM_WINDOWPOSCHANGED:\n if ((((WINDOWPOS*)lParam)->flags & SWP_SHOWWINDOW) &&\n !g_fShown) {\n g_fShown = TRUE;\n PostMessage(hwnd, WM_APP, 0, 0);\n }\n break;\n\n\n case WM_APP:\n MessageBox(hwnd,\n IsWindowVisible(hwnd) ? TEXT("Visible")\n : TEXT("Not Visible"),\n TEXT("Title"), MB_OK);\n break;\n\n case WM_CLOSE:\n EndDialog(hwnd, 0);\n break;\n }\n\n return FALSE;\n}\n</code></pre>\n<p>If you're using MFC like I am you'll need to map WM_WINDOWPOSCHANGED and then use ON_MESSAGE to map WM_APP. See <a href=\"http://www.codeproject.com/KB/dialog/messagehandling2.aspx?fid=789&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26\" rel=\"nofollow noreferrer\">this CodeProject article</a> for more details.</p>\n"
},
{
"answer_id": 271162,
"author": "Joel Lucsy",
"author_id": 645,
"author_profile": "https://Stackoverflow.com/users/645",
"pm_score": 0,
"selected": false,
"text": "<p>Another approach I've used a number of times with great success is to use a timer. Set it for 10m0s. It'll only fire after the dialog is shown. </p>\n"
},
{
"answer_id": 326763,
"author": "baash05",
"author_id": 31325,
"author_profile": "https://Stackoverflow.com/users/31325",
"pm_score": 0,
"selected": false,
"text": "<p>Hell put the code in OnPaint() and thow a bool m_fullyInitilized in your class.\nI like the timer too.. Though I usually go with 100ms. I also move all my initilization code out of the oninit, in these cases.. Just to protect against too much processing in there. </p>\n"
},
{
"answer_id": 60402071,
"author": "SteveH",
"author_id": 12962350,
"author_profile": "https://Stackoverflow.com/users/12962350",
"pm_score": 1,
"selected": false,
"text": "<p>For reference you don't need to override DlgProc to intercept WM_WINDOWPOSCHANGED.</p>\n\n<pre><code> ON_WM_WINDOWPOSCHANGED()\n ON_MESSAGE(MyCDialog::MY_USER_MSG, OnDialogShown)\n\nvoid MyCDialog::OnWindowPosChanged(WINDOWPOS *wndpos)\n{\n __super::OnWindowPosChanged(wndpos);\n\n if (!mDialogShown && (wndpos->flags & SWP_SHOWWINDOW)) {\n PostMessage(MY_USER_MSG);\n mDialogShown = true;\n }\n}\n\nLRESULT MyCDialog::OnDialogShown(WPARAM, LPARAM)\n{\n ...\n}\n\n</code></pre>\n\n<p>You can implement the handling inline instead of posting another message if appropriate.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269462",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19124/"
] |
I'm doing some small changes to C++ MFC project. I'm .NET developer so Windows programming is new to me.
I need to launch some method right after CDialog is completely shown (painted) for the first time, but only once.
How can I do this? In .NET I would handle **Form.Shown** event.
Do I need to handle some message? Which?
Do I need to override some CDialog method?
Or is there no easy way? I'm thinking of handling WM\_ACTIVATE and then using a flag to ensure I call another method only once.
|
Found the answer here: [Waiting until the dialog box is displayed before doing something](https://web.archive.org/web/20190119124649/https://blogs.msdn.microsoft.com/oldnewthing/20060925-02/?p=29603)
```
Short story:
INT_PTR CALLBACK
DlgProc(HWND hwnd, UINT uiMsg, WPARAM wParam, LPARAM lParam)
{
switch (uiMsg) {
case WM_INITDIALOG:
return TRUE;
case WM_WINDOWPOSCHANGED:
if ((((WINDOWPOS*)lParam)->flags & SWP_SHOWWINDOW) &&
!g_fShown) {
g_fShown = TRUE;
PostMessage(hwnd, WM_APP, 0, 0);
}
break;
case WM_APP:
MessageBox(hwnd,
IsWindowVisible(hwnd) ? TEXT("Visible")
: TEXT("Not Visible"),
TEXT("Title"), MB_OK);
break;
case WM_CLOSE:
EndDialog(hwnd, 0);
break;
}
return FALSE;
}
```
If you're using MFC like I am you'll need to map WM\_WINDOWPOSCHANGED and then use ON\_MESSAGE to map WM\_APP. See [this CodeProject article](http://www.codeproject.com/KB/dialog/messagehandling2.aspx?fid=789&df=90&mpp=25&noise=3&sort=Position&view=Quick&fr=26) for more details.
|
269,466 |
<p>I am having trouble with a very simple Perl process. I am basically querying an Oracle database and I want to load it into Excel. I have been able to use DBIx::Dump and it works. However, I need to be able to use a variety of Excel formatting tools. And I think <a href="http://search.cpan.org/dist/Spreadsheet::WriteExcel" rel="nofollow noreferrer">Spreadsheet::WriteExcel</a> is the best module that outputs to Excel that allows me do more formatting. </p>
<p>Below is the code and the error I am getting. I basically query Oracle, fetch the data, load into an array and try to write to Excel. For some reason it is doing some kind of comparison and it does not like the data types. For example, the date is '25-OCT-08'. The SVP is 'S01'. It seems to be saying that they are not numeric. </p>
<p>Error:</p>
<pre><code>Argument "01-NOV-08" isn't numeric in numeric ge <>=> at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 3414.
Argument "01-NOV-08" isn't numeric in pack ge <>=> ge <>=> at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 2157.
</code></pre>
<p>Code:</p>
<pre><code>#!/usr/bin/perl -w
#Set the Perl Modules
use strict;
use DBI;
use Spreadsheet::WriteExcel;
# Connect to the oracle database
my $dbh = DBI->connect( 'dbi:Oracle:xxxx',
'xxxx',
'xxxx',
) || die "Database connection not made: $DBI::errstr";
#Set up Query
my $stmt = "select
week_end_date, SVP, RD,
DM, store, wtd_smrr_gain,QTD_SMRR_GAIN,
wtd_bor_gain,QTD_BOR_GAIN,
wtd_cust_gain,QTD_CUST_GAIN,
wtd_CARD_CLOSED_OCT25,QTD_AVG_CARD_CL
from
bonus_4Q_store
order by
store";
#Prepare Query
my $sth = $dbh->prepare($stmt);
#Execute Query
$sth->execute() or die $dbh->errstr;
my( $week_end_date,$SVP,$RD,$DM,$store,
$wtd_smrr_gain,$QTD_SMRR_GAIN,
$wtd_bor_gain,$QTD_BOR_GAIN,
$wtd_cust_gain,$QTD_CUST_GAIN,
$wtd_CARD_CLOSED_OCT25,$QTD_AVG_CARD_CL);
#binds each column to a scalar reference
$sth->bind_columns(undef,\$week_end_date,\$SVP,\$RD,\$DM,\$store,
\$wtd_smrr_gain,\$QTD_SMRR_GAIN,
\$wtd_bor_gain,\$QTD_BOR_GAIN,
\$wtd_cust_gain,\$QTD_CUST_GAIN,
\$wtd_CARD_CLOSED_OCT25,\$QTD_AVG_CARD_CL,);
#create a new instance
my $Excelfile = "/Test_Report.xls";
my $excel = Spreadsheet::WriteExcel->new("$Excelfile");
my $worksheet = $excel->addworksheet("WOW_SHEET");
#Create array shell
my @data;
#Call data and Write to Excel
while ( @data = $sth->fetchrow_array()){
my $week_end_date = $data[0];
my $SVP = $data[1];
my $RD = $data[2];
my $DM = $data[3];
my $store = $data[1];
my $wtd_smrr_gain = $data[2];
my $QTD_SMRR_GAIN = $data[3];
my $wtd_bor_gain = $data[4];
my $QTD_BOR_GAIN = $data[5];
my $wtd_cust_gain = $data[6];
my $QTD_CUST_GAIN = $data[7];
my $wtd_CARD_CLOSED_OCT25 = $data[8];
my $QTD_AVG_CARD_CL = $data[9];
my $row = 0;
my $col = 0;
foreach my $stmt (@data)
{
$worksheet->write($row++, @data);
last;
}
}
print "DONE \n";
$sth->finish();
$dbh->disconnect();
</code></pre>
|
[
{
"answer_id": 269497,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 2,
"selected": false,
"text": "<p>I would guess that it is coming out as a string, and when you try to insert it into the date column, there is no implicit conversion for it.</p>\n\n<p>Try selecting the date like this, and it will turn it into a char that you can use to do compares.</p>\n\n<pre><code>to_char(date, 'YYYY/MM/DD HH24:MI:SS')\n</code></pre>\n\n<p>then </p>\n\n<pre><code>to_date(date, 'YYYY/MM/DD HH24:MI:SS') \n</code></pre>\n\n<p>to convert it back to a date on insert. That is generally what you need to do in SQL.</p>\n\n<p>As I recall, perl has a trace facility for DBI that might giver a better picture as to what is going on.</p>\n"
},
{
"answer_id": 270591,
"author": "jmcnamara",
"author_id": 10238,
"author_profile": "https://Stackoverflow.com/users/10238",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is here:</p>\n\n<pre><code>foreach my $stmt (@data) \n{ \n $worksheet->write($row++, @data); # !!\n last; \n} \n</code></pre>\n\n<p>The correct syntax for <code>write()</code> is:</p>\n\n<pre><code>write($row, $column, $token, $format)\n</code></pre>\n\n<p>You are missing the <code>$column</code> argument, which in this case is probably 0.</p>\n\n<p>If <code>$stmt</code> is an array ref then you can write it in one go as follows:</p>\n\n<pre><code>$worksheet->write($row++, 0, $stmt); \n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269466",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am having trouble with a very simple Perl process. I am basically querying an Oracle database and I want to load it into Excel. I have been able to use DBIx::Dump and it works. However, I need to be able to use a variety of Excel formatting tools. And I think [Spreadsheet::WriteExcel](http://search.cpan.org/dist/Spreadsheet::WriteExcel) is the best module that outputs to Excel that allows me do more formatting.
Below is the code and the error I am getting. I basically query Oracle, fetch the data, load into an array and try to write to Excel. For some reason it is doing some kind of comparison and it does not like the data types. For example, the date is '25-OCT-08'. The SVP is 'S01'. It seems to be saying that they are not numeric.
Error:
```
Argument "01-NOV-08" isn't numeric in numeric ge <>=> at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 3414.
Argument "01-NOV-08" isn't numeric in pack ge <>=> ge <>=> at C:/Perl/site/lib/Spreadsheet/WriteExcel/Worksheet.pm line 2157.
```
Code:
```
#!/usr/bin/perl -w
#Set the Perl Modules
use strict;
use DBI;
use Spreadsheet::WriteExcel;
# Connect to the oracle database
my $dbh = DBI->connect( 'dbi:Oracle:xxxx',
'xxxx',
'xxxx',
) || die "Database connection not made: $DBI::errstr";
#Set up Query
my $stmt = "select
week_end_date, SVP, RD,
DM, store, wtd_smrr_gain,QTD_SMRR_GAIN,
wtd_bor_gain,QTD_BOR_GAIN,
wtd_cust_gain,QTD_CUST_GAIN,
wtd_CARD_CLOSED_OCT25,QTD_AVG_CARD_CL
from
bonus_4Q_store
order by
store";
#Prepare Query
my $sth = $dbh->prepare($stmt);
#Execute Query
$sth->execute() or die $dbh->errstr;
my( $week_end_date,$SVP,$RD,$DM,$store,
$wtd_smrr_gain,$QTD_SMRR_GAIN,
$wtd_bor_gain,$QTD_BOR_GAIN,
$wtd_cust_gain,$QTD_CUST_GAIN,
$wtd_CARD_CLOSED_OCT25,$QTD_AVG_CARD_CL);
#binds each column to a scalar reference
$sth->bind_columns(undef,\$week_end_date,\$SVP,\$RD,\$DM,\$store,
\$wtd_smrr_gain,\$QTD_SMRR_GAIN,
\$wtd_bor_gain,\$QTD_BOR_GAIN,
\$wtd_cust_gain,\$QTD_CUST_GAIN,
\$wtd_CARD_CLOSED_OCT25,\$QTD_AVG_CARD_CL,);
#create a new instance
my $Excelfile = "/Test_Report.xls";
my $excel = Spreadsheet::WriteExcel->new("$Excelfile");
my $worksheet = $excel->addworksheet("WOW_SHEET");
#Create array shell
my @data;
#Call data and Write to Excel
while ( @data = $sth->fetchrow_array()){
my $week_end_date = $data[0];
my $SVP = $data[1];
my $RD = $data[2];
my $DM = $data[3];
my $store = $data[1];
my $wtd_smrr_gain = $data[2];
my $QTD_SMRR_GAIN = $data[3];
my $wtd_bor_gain = $data[4];
my $QTD_BOR_GAIN = $data[5];
my $wtd_cust_gain = $data[6];
my $QTD_CUST_GAIN = $data[7];
my $wtd_CARD_CLOSED_OCT25 = $data[8];
my $QTD_AVG_CARD_CL = $data[9];
my $row = 0;
my $col = 0;
foreach my $stmt (@data)
{
$worksheet->write($row++, @data);
last;
}
}
print "DONE \n";
$sth->finish();
$dbh->disconnect();
```
|
I would guess that it is coming out as a string, and when you try to insert it into the date column, there is no implicit conversion for it.
Try selecting the date like this, and it will turn it into a char that you can use to do compares.
```
to_char(date, 'YYYY/MM/DD HH24:MI:SS')
```
then
```
to_date(date, 'YYYY/MM/DD HH24:MI:SS')
```
to convert it back to a date on insert. That is generally what you need to do in SQL.
As I recall, perl has a trace facility for DBI that might giver a better picture as to what is going on.
|
269,486 |
<p>I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it possible to achieve this through JVM configuration instead of adding this piece of code?</p>
<pre><code>cal.setFirstDayOfWeek(Calendar.MONDAY);
</code></pre>
|
[
{
"answer_id": 269501,
"author": "ricafeal",
"author_id": 34598,
"author_profile": "https://Stackoverflow.com/users/34598",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried to invoke the JVM with a different locale? But you should be careful with side effects...</p>\n"
},
{
"answer_id": 269506,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 2,
"selected": false,
"text": "<p>According to the API:</p>\n\n<blockquote>\n <p>Calendar defines a locale-specific seven day week using two parameters: the first day of the week and the minimal days in first week (from 1 to 7). These numbers are taken from the locale resource data when a Calendar is constructed. They may also be specified explicitly through the methods for setting their values. </p>\n</blockquote>\n\n<p>So if you ensure that your locale is appropriately configured, this will be implicitly set. Personally, I would prefer explicitly setting this...</p>\n\n<p>See <a href=\"https://stackoverflow.com/questions/64038/setting-java-locale-settings\">#64038</a> for ways to set a locale from the command line.</p>\n"
},
{
"answer_id": 269538,
"author": "Kariem",
"author_id": 12039,
"author_profile": "https://Stackoverflow.com/users/12039",
"pm_score": 5,
"selected": true,
"text": "<p>The first day of the week is derived from the current locale. If you don't set the locale of the calendar (<a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)\" rel=\"noreferrer\">Calendar.getInstance(Locale)</a>, or <a href=\"http://java.sun.com/j2se/1.5.0/docs/api/java/util/GregorianCalendar.html#GregorianCalendar(java.util.Locale)\" rel=\"noreferrer\">new GregorianCalendar(Locale)</a>), it will use the system's default. The system's default can be overridden by a JVM parameter:</p>\n\n<pre><code>public static void main(String[] args) {\n Calendar c = new GregorianCalendar();\n System.out.println(Locale.getDefault() + \": \" + c.getFirstDayOfWeek());\n}\n</code></pre>\n\n<p>This should show a different output with different JVM parameters for language/country:</p>\n\n<ul>\n<li><em><code>-Duser.language=en -Duser.country=US</code></em> -> <strong><code>en_US: 1</code></strong> <em>(Sunday)</em></li>\n<li><em><code>-Duser.language=en -Duser.country=GB</code></em> -> <strong><code>en_GB: 2</code></strong> <em>(Monday)</em></li>\n</ul>\n\n<p>Don't forget that this could change other behavio(u)r too.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269486",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35172/"
] |
I'm trying to change default firstDayOfWeek for java.util.Calendar from SUNDAY to MONDAY. Is it possible to achieve this through JVM configuration instead of adding this piece of code?
```
cal.setFirstDayOfWeek(Calendar.MONDAY);
```
|
The first day of the week is derived from the current locale. If you don't set the locale of the calendar ([Calendar.getInstance(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Calendar.html#getInstance(java.util.Locale)), or [new GregorianCalendar(Locale)](http://java.sun.com/j2se/1.5.0/docs/api/java/util/GregorianCalendar.html#GregorianCalendar(java.util.Locale))), it will use the system's default. The system's default can be overridden by a JVM parameter:
```
public static void main(String[] args) {
Calendar c = new GregorianCalendar();
System.out.println(Locale.getDefault() + ": " + c.getFirstDayOfWeek());
}
```
This should show a different output with different JVM parameters for language/country:
* *`-Duser.language=en -Duser.country=US`* -> **`en_US: 1`** *(Sunday)*
* *`-Duser.language=en -Duser.country=GB`* -> **`en_GB: 2`** *(Monday)*
Don't forget that this could change other behavio(u)r too.
|
269,496 |
<p>There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:</p>
<ol>
<li><p>Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.</p></li>
<li><p>Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.</p></li>
</ol>
<p>What are the benefits, costs, and consequences of each? Are there other alternatives?</p>
<p>I see this debate come up on a regular basis, but I don't think it's been asked on
Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it. </p>
|
[
{
"answer_id": 269526,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 5,
"selected": false,
"text": "<p>The difference is typically expressed as the difference between \"is a\" and \"has a\". Inheritance, the \"is a\" relationship, is summed up nicely in the <a href=\"http://en.wikipedia.org/wiki/Liskov_substitution_principle\" rel=\"noreferrer\">Liskov Substitution Principle</a>. Aggregation, the \"has a\" relationship, is just that - it shows that the aggregating object <em>has</em> one of the aggregated objects.</p>\n\n<p>Further distinctions exist as well - private inheritance in C++ indicates a \"is implemented in terms of\" relationship, which can also be modeled by the aggregation of (non-exposed) member objects as well.</p>\n"
},
{
"answer_id": 269533,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 5,
"selected": false,
"text": "<p>At the beginning of <a href=\"https://rads.stackoverflow.com/amzn/click/com/0201633612\" rel=\"noreferrer\" rel=\"nofollow noreferrer\">GOF</a> they state</p>\n\n<blockquote>\n <p>Favor object composition over class inheritance.</p>\n</blockquote>\n\n<p>This is further discussed <a href=\"http://www.artima.com/lejava/articles/designprinciples4.html\" rel=\"noreferrer\">here</a></p>\n"
},
{
"answer_id": 269535,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 9,
"selected": true,
"text": "<p>It's not a matter of which is the best, but of when to use what.</p>\n\n<p>In the 'normal' cases a simple question is enough to find out if we need inheritance or aggregation.</p>\n\n<ul>\n<li>If The new class <strong>is</strong> more or less as the original class. Use inheritance. The new class is now a subclass of the original class.</li>\n<li>If the new class must <strong>have</strong> the original class. Use aggregation. The new class has now the original class as a member.</li>\n</ul>\n\n<p>However, there is a big gray area. So we need several other tricks.</p>\n\n<ul>\n<li>If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we have a big nasty smell that indicates that we had to use aggregation.</li>\n<li>If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.</li>\n</ul>\n\n<p>To cut it short. We should use aggregation if part of the interface is not used or has to be changed to avoid an illogical situation. We only need to use inheritance, if we need almost all of the functionality without major changes. And when in doubt, use Aggregation.</p>\n\n<p>An other possibility for, the case that we have an class that needs part of the functionality of the original class, is to split the original class in a root class and a sub class. And let the new class inherit from the root class. But you should take care with this, not to create an illogical separation.</p>\n\n<p>Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark', 'Play'. </p>\n\n<pre><code>class Dog\n Eat;\n Walk;\n Bark;\n Play;\nend;\n</code></pre>\n\n<p>We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try to extend it from a Dog.</p>\n\n<pre><code>class Cat is Dog\n Purr; \nend;\n</code></pre>\n\n<p>Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a barking cat violates the principles of the universe. So we need to override the Bark method so that it does nothing.</p>\n\n<pre><code>class Cat is Dog\n Purr; \n Bark = null;\nend;\n</code></pre>\n\n<p>Ok, this works, but it smells bad. So lets try an aggregation:</p>\n\n<pre><code>class Cat\n has Dog;\n Eat = Dog.Eat;\n Walk = Dog.Walk;\n Play = Dog.Play;\n Purr;\nend;\n</code></pre>\n\n<p>Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an internal dog that wants out. So lets try solution number three:</p>\n\n<pre><code>class Pet\n Eat;\n Walk;\n Play;\nend;\n\nclass Dog is Pet\n Bark;\nend;\n\nclass Cat is Pet\n Purr;\nend;\n</code></pre>\n\n<p>This is much cleaner. No internal dogs. And cats and dogs are at the same level. We can even introduce other pets to extend the model. Unless it is a fish, or something that does not walk. In that case we again need to refactor. But that is something for an other time.</p>\n"
},
{
"answer_id": 269537,
"author": "Salman Kasbati",
"author_id": 33931,
"author_profile": "https://Stackoverflow.com/users/33931",
"pm_score": 2,
"selected": false,
"text": "<p>I'll cover the where-these-might-apply part. Here's an example of both, in a game scenario. Suppose, there's a game which has different types of soldiers. Each soldier can have a knapsack which can hold different things.</p>\n\n<p><strong>Inheritance here?</strong>\nThere's a marine, green beret & a sniper. These are types of soldiers. So, there's a base class Soldier with Marine, Green Beret & Sniper as derived classes</p>\n\n<p><strong>Aggregation here?</strong>\nThe knapsack can contain grenades, guns (different types), knife, medikit, etc. A soldier can be equipped with any of these at any given point in time, plus he can also have a bulletproof vest which acts as armor when attacked and his injury decreases to a certain percentage. The soldier class contains an object of bulletproof vest class and the knapsack class which contains references to these items.</p>\n"
},
{
"answer_id": 269539,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 0,
"selected": false,
"text": "<p>Both approaches are used to solve different problems. You don't always need to aggregate over two or more classes when inheriting from one class.</p>\n\n<p>Sometimes you do have to aggregate a single class because that class is sealed or has otherwise non-virtual members you need to intercept so you create a proxy layer that obviously isn't valid in terms of inheritance but so long as the class you are proxying has an interface you can subscribe to this can work out fairly well.</p>\n"
},
{
"answer_id": 269548,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's not an either/or debate. It's just that:</p>\n\n<ol>\n<li>is-a (inheritance) relationships occur less often than has-a (composition) relationships. </li>\n<li>Inheritance is harder to get right, even when it's appropriate to use it, so due diligence has to be taken because it can break encapsulation, encourage tight coupling by exposing implementation and so forth.</li>\n</ol>\n\n<p>Both have their place, but inheritance is riskier. </p>\n\n<p>Although of course it wouldn't make sense to have a class Shape 'having-a' Point and a Square classes. Here inheritance is due.</p>\n\n<p>People tend to think about inheritance first when trying to design something extensible, that is what's wrong.</p>\n"
},
{
"answer_id": 269549,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 2,
"selected": false,
"text": "<p>The question is normally phrased as <a href=\"https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance\">Composition vs. Inheritance</a>, and it has been asked here before.</p>\n"
},
{
"answer_id": 269553,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 4,
"selected": false,
"text": "<p>Here's my most common argument:</p>\n\n<p>In any object-oriented system, there are two parts to any class:</p>\n\n<ol>\n<li><p>Its <em>interface</em>: the \"public face\" of the object. This is the set of capabilities it announces to the rest of the world. In a lot of languages, the set is well defined into a \"class\". Usually these are the method signatures of the object, though it varies a bit by language.</p></li>\n<li><p>Its <em>implementation</em>: the \"behind the scenes\" work that the object does to satisfy its interface and provide functionality. This is typically the code and member data of the object. </p></li>\n</ol>\n\n<p>One of the fundamental principles of OOP is that the implementation is <em>encapsulated</em> (ie:hidden) within the class; the only thing that outsiders should see is the interface.</p>\n\n<p>When a subclass inherits from a subclass, it typically inherits <em>both</em> the implementation and the interface. This, in turn, means that you're <em>forced</em> to accept both as constraints on your class. </p>\n\n<p>With aggregation, you get to choose either implementation or interface, or both -- but you're not forced into either. The functionality of an object is left up to the object itself. It can defer to other objects as it likes, but it's ultimately responsible for itself. In my experience, this leads to a more flexible system: one that's easier to modify.</p>\n\n<p>So, whenever I'm developing object-oriented software, I almost always prefer aggregation over inheritance.</p>\n"
},
{
"answer_id": 269600,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": false,
"text": "<p>I gave an answer to <a href=\"https://stackoverflow.com/questions/263355/is-a-vs-has-a-which-one-is-better\">\"Is a\" vs \"Has a\" : which one is better?</a>.</p>\n\n<p>Basically I agree with other folks: use inheritance only if your derived class truly <em>is</em> the type you're extending, not merely because it <em>contains</em> the same data. Remember that inheritance means the subclass gains the methods as well as the data.</p>\n\n<p>Does it make sense for your derived class to have all the methods of the superclass? Or do you just quietly promise yourself that those methods should be ignored in the derived class? Or do you find yourself overriding methods from the superclass, making them no-ops so no one calls them inadvertently? Or giving hints to your API doc generation tool to omit the method from the doc? </p>\n\n<p>Those are strong clues that aggregation is the better choice in that case.</p>\n"
},
{
"answer_id": 269700,
"author": "Craig Walker",
"author_id": 3488,
"author_profile": "https://Stackoverflow.com/users/3488",
"pm_score": 3,
"selected": false,
"text": "<p>I see a lot of \"is-a vs. has-a; they're conceptually different\" responses on this and the related questions. </p>\n\n<p>The one thing I've found in my experience is that trying to determine whether a relationship is \"is-a\" or \"has-a\" is bound to fail. Even if you can correctly make that determination for the objects now, changing requirements mean that you'll probably be wrong at some point in the future.</p>\n\n<p>Another thing I've found is that it's <em>very</em> hard to convert from inheritance to aggregation once there's a lot of code written around an inheritance hierarchy. Just switching from a superclass to an interface means changing nearly every subclass in the system.</p>\n\n<p>And, as I mentioned elsewhere in this post, aggregation tends to be less flexible than inheritance.</p>\n\n<p>So, you have a perfect storm of arguments against inheritance whenever you have to choose one or the other:</p>\n\n<ol>\n<li>Your choice will likely be the wrong one at some point</li>\n<li>Changing that choice is difficult once you've made it.</li>\n<li>Inheritance tends to be a worse choice as it's more constraining.</li>\n</ol>\n\n<p>Thus, I tend to choose aggregation -- even when there appears to be a strong is-a relationship.</p>\n"
},
{
"answer_id": 269947,
"author": "orcmid",
"author_id": 33810,
"author_profile": "https://Stackoverflow.com/users/33810",
"pm_score": 2,
"selected": false,
"text": "<p>I wanted to make this a comment on the original question, but 300 characters bites [;<).</p>\n\n<p>I think we need to be careful. First, there are more flavors than the two rather specific examples made in the question. </p>\n\n<p>Also, I suggest that it is valuable not to confuse the objective with the instrument. One wants to make sure that the chosen technique or methodology supports achievement of the primary objective, but I don't thing out-of-context which-technique-is-best discussion is very useful. It does help to know the pitfalls of the different approaches along with their clear sweet spots.</p>\n\n<p>For example, what are you out to accomplish, what do you have available to start with, and what are the constraints?</p>\n\n<p>Are you creating a component framework, even a special purpose one? Are interfaces separable from implementations in the programming system or is it accomplished by a practice using a different sort of technology? Can you separate the inheritance structure of interfaces (if any) from the inheritance structure of classes that implement them? Is it important to hide the class structure of an implementation from the code that relies on the interfaces the implementation delivers? Are there multiple implementations to be usable at the same time or is the variation more over-time as a consequence of maintenance and enhancememt? This and more needs to be considered before you fixate on a tool or a methodology.</p>\n\n<p>Finally, is it that important to lock distinctions in the abstraction and how you think of it (as in is-a versus has-a) to different features of the OO technology? Perhaps so, if it keeps the conceptual structure consistent and manageable for you and others. But it is wise not to be enslaved by that and the contortions you might end up making. Maybe it is best to stand back a level and not be so rigid (but leave good narration so others can tell what's up). [I look for what makes a particular portion of a program explainable, but some times I go for elegance when there is a bigger win. Not always the best idea.]</p>\n\n<p>I'm an interface purist, and I am drawn to the kinds of problems and approaches where interface purism is appropriate, whether building a Java framework or organizing some COM implementations. That doesn't make it appropriate for everything, not even close to everything, even though I swear by it. (I have a couple of projects that appear to provide serious counter-examples against interface purism, so it will be interesting to see how I manage to cope.)</p>\n"
},
{
"answer_id": 7485960,
"author": "Blue Clouds",
"author_id": 1501191,
"author_profile": "https://Stackoverflow.com/users/1501191",
"pm_score": 1,
"selected": false,
"text": "<p>Favour happens when both candidate qualifies. A and B are options and you favour A. The reason is that composition offers more extension/flexiblity possiblities than generalization. This extension/flexiblity refers mostly to runtime/dynamic flexibility. </p>\n\n<p>The benefit is not immediately visible. To see the benefit you need to wait for the next unexpected change request. So in most cases those sticked to generlalization fails when compared to those who embraced composition(except one obvious case mentioned later). Hence the rule. From a learning point of view if you can implement a dependency injection successfully then you should know which one to favour and when. The rule helps you in making a decision as well; if you are not sure then select composition.</p>\n\n<p>Summary: Composition :The coupling is reduced by just having some smaller things you plug into something bigger, and the bigger object just calls the smaller object back. Generlization: From an API point of view defining that a method can be overridden is a stronger commitment than defining that a method can be called. (very few occassions when Generalization wins). And never forget that with composition you are using inheritance too, from a interface instead of a big class</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3488/"
] |
There are two schools of thought on how to best extend, enhance, and reuse code in an object-oriented system:
1. Inheritance: extend the functionality of a class by creating a subclass. Override superclass members in the subclasses to provide new functionality. Make methods abstract/virtual to force subclasses to "fill-in-the-blanks" when the superclass wants a particular interface but is agnostic about its implementation.
2. Aggregation: create new functionality by taking other classes and combining them into a new class. Attach an common interface to this new class for interoperability with other code.
What are the benefits, costs, and consequences of each? Are there other alternatives?
I see this debate come up on a regular basis, but I don't think it's been asked on
Stack Overflow yet (though there is some related discussion). There's also a surprising lack of good Google results for it.
|
It's not a matter of which is the best, but of when to use what.
In the 'normal' cases a simple question is enough to find out if we need inheritance or aggregation.
* If The new class **is** more or less as the original class. Use inheritance. The new class is now a subclass of the original class.
* If the new class must **have** the original class. Use aggregation. The new class has now the original class as a member.
However, there is a big gray area. So we need several other tricks.
* If we have used inheritance (or we plan to use it) but we only use part of the interface, or we are forced to override a lot of functionality to keep the correlation logical. Then we have a big nasty smell that indicates that we had to use aggregation.
* If we have used aggregation (or we plan to use it) but we find out we need to copy almost all of the functionality. Then we have a smell that points in the direction of inheritance.
To cut it short. We should use aggregation if part of the interface is not used or has to be changed to avoid an illogical situation. We only need to use inheritance, if we need almost all of the functionality without major changes. And when in doubt, use Aggregation.
An other possibility for, the case that we have an class that needs part of the functionality of the original class, is to split the original class in a root class and a sub class. And let the new class inherit from the root class. But you should take care with this, not to create an illogical separation.
Lets add an example. We have a class 'Dog' with methods: 'Eat', 'Walk', 'Bark', 'Play'.
```
class Dog
Eat;
Walk;
Bark;
Play;
end;
```
We now need a class 'Cat', that needs 'Eat', 'Walk', 'Purr', and 'Play'. So first try to extend it from a Dog.
```
class Cat is Dog
Purr;
end;
```
Looks, alright, but wait. This cat can Bark (Cat lovers will kill me for that). And a barking cat violates the principles of the universe. So we need to override the Bark method so that it does nothing.
```
class Cat is Dog
Purr;
Bark = null;
end;
```
Ok, this works, but it smells bad. So lets try an aggregation:
```
class Cat
has Dog;
Eat = Dog.Eat;
Walk = Dog.Walk;
Play = Dog.Play;
Purr;
end;
```
Ok, this is nice. This cat does not bark anymore, not even silent. But still it has an internal dog that wants out. So lets try solution number three:
```
class Pet
Eat;
Walk;
Play;
end;
class Dog is Pet
Bark;
end;
class Cat is Pet
Purr;
end;
```
This is much cleaner. No internal dogs. And cats and dogs are at the same level. We can even introduce other pets to extend the model. Unless it is a fish, or something that does not walk. In that case we again need to refactor. But that is something for an other time.
|
269,523 |
<p>I've got a Page class in my .edmx ADO.NET Entity Data Model file with with Parent and Children properties. It's for a hierarchy of Pages.</p>
<p><em>removed dead ImageShack link - ADO.NET Entity Framework Hierarchical Page Class</em></p>
<p>This is handled in my SQL database with a ParentId foreign key in the Page table bound to the Id primary key of that same Page table.</p>
<p>How do I display this hierarchy in a WPF TreeView?</p>
|
[
{
"answer_id": 273535,
"author": "Zack Peterson",
"author_id": 83,
"author_profile": "https://Stackoverflow.com/users/83",
"pm_score": 5,
"selected": true,
"text": "<p>I got this working with help from <a href=\"https://stackoverflow.com/users/9268/abe-heidebrecht\">Abe Heidebrecht</a>. Much thanks to him.</p>\n\n<p>Here's my XAML...</p>\n\n<pre><code><Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:local=\"clr-namespace:PageManager\"\n Title=\"Window1\" Height=\"300\" Width=\"300\" Name=\"Window1\">\n <Grid>\n <TreeView Margin=\"12\" Name=\"TreeViewPages\" ItemsSource=\"{Binding}\" TreeViewItem.Expanded=\"TreeViewPages_Expanded\">\n <TreeView.Resources>\n <HierarchicalDataTemplate DataType=\"{x:Type local:Page}\" ItemsSource=\"{Binding Children}\">\n <TextBlock Text=\"{Binding Path=ShortTitle}\" />\n </HierarchicalDataTemplate>\n </TreeView.Resources>\n </TreeView>\n </Grid>\n</Window>\n</code></pre>\n\n<p>Here's my Visual Basic code...</p>\n\n<pre class=\"lang-vb prettyprint-override\"><code>Class Window1\n\n Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded\n Dim db As New PageEntities\n Dim RootPage = From p In db.Page.Include(\"Children\") _\n Where (p.Parent Is Nothing) _\n Select p\n TreeViewPages.ItemsSource = RootPage\n End Sub\n\n Private Sub TreeViewPages_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n Dim ExpandedTreeViewItem As TreeViewItem = DirectCast(e.OriginalSource, TreeViewItem)\n Dim PageId As Guid = DirectCast(ExpandedTreeViewItem.DataContext, Page).Id\n Dim db As New PageEntities\n Dim ChildPages = From p In db.Page.Include(\"Children\") _\n Where p.Parent.Id = PageId _\n Select p\n ExpandedTreeViewItem.ItemsSource = ChildPages\n End Sub\nEnd Class\n</code></pre>\n\n<p>When the window loads, the root node and its children are queried from the database and inserted into the tree.</p>\n\n<p>Each time a node is expanded, that node's children and grandchildren are queried from the database and inserted into the tree.</p>\n"
},
{
"answer_id": 652762,
"author": "Mike Christiansen",
"author_id": 29249,
"author_profile": "https://Stackoverflow.com/users/29249",
"pm_score": 3,
"selected": false,
"text": "<p>A different way: (well, very similar, but slightly different)</p>\n\n<p>In your Window Load function:</p>\n\n<pre><code>PageEntities db = new PageEntities();\nTreeViewPages.ItemsSource = db.Page.Where(u=>u.Parent==null);\n</code></pre>\n\n<p>Create a new file Page.cs</p>\n\n<pre><code>public partial class Page {\n public ObjectQuery<Page> LoadedChildren {\n get {\n var ret = Children;\n if(ret.IsLoaded==false) ret.Load();\n return ret;\n }\n }\n}\n</code></pre>\n\n<p>In your XAML:</p>\n\n<pre><code><TreeView Name=\"TreeViewPages\">\n <TreeView.ItemTemplate>\n <HierarchicalDataTemplate ItemSource=\"{Binding LoadedChildren}\">\n <TextBlock Text=\"{Binding ShortTitle}\" />\n </HierarchicalDataTemplate>\n </TreeView.ItemTemplate>\n</TreeView>\n</code></pre>\n\n<p>Its not tested, but you should get the general idea.</p>\n"
},
{
"answer_id": 4839274,
"author": "Nathan R",
"author_id": 584878,
"author_profile": "https://Stackoverflow.com/users/584878",
"pm_score": 1,
"selected": false,
"text": "<p>Second solution worked best for me. I have a list of recursive objects, so this is the XAML that I used:</p>\n\n<pre><code><TreeView Height=\"Auto\" HorizontalAlignment=\"Stretch\" Name=\"trvVaults\" VerticalAlignment=\"Stretch\" Width=\"Auto\" Grid.Column=\"0\" Margin=\"5\">\n <!-- Treeview ItemsSource is loaded programmatically -->\n <TreeView.ItemTemplate>\n <HierarchicalDataTemplate ItemsSource=\"{Binding Vaults}\">\n <TextBlock Text=\"{Binding Name}\" />\n </HierarchicalDataTemplate>\n </TreeView.ItemTemplate>\n</TreeView>\n</code></pre>\n\n<p>Each 'Vault' object has several properties (name, location, etc) and a generic list of 'Vaults'.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/83/"
] |
I've got a Page class in my .edmx ADO.NET Entity Data Model file with with Parent and Children properties. It's for a hierarchy of Pages.
*removed dead ImageShack link - ADO.NET Entity Framework Hierarchical Page Class*
This is handled in my SQL database with a ParentId foreign key in the Page table bound to the Id primary key of that same Page table.
How do I display this hierarchy in a WPF TreeView?
|
I got this working with help from [Abe Heidebrecht](https://stackoverflow.com/users/9268/abe-heidebrecht). Much thanks to him.
Here's my XAML...
```
<Window x:Class="Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:PageManager"
Title="Window1" Height="300" Width="300" Name="Window1">
<Grid>
<TreeView Margin="12" Name="TreeViewPages" ItemsSource="{Binding}" TreeViewItem.Expanded="TreeViewPages_Expanded">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Page}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Path=ShortTitle}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</Grid>
</Window>
```
Here's my Visual Basic code...
```vb
Class Window1
Private Sub Window1_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
Dim db As New PageEntities
Dim RootPage = From p In db.Page.Include("Children") _
Where (p.Parent Is Nothing) _
Select p
TreeViewPages.ItemsSource = RootPage
End Sub
Private Sub TreeViewPages_Expanded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
Dim ExpandedTreeViewItem As TreeViewItem = DirectCast(e.OriginalSource, TreeViewItem)
Dim PageId As Guid = DirectCast(ExpandedTreeViewItem.DataContext, Page).Id
Dim db As New PageEntities
Dim ChildPages = From p In db.Page.Include("Children") _
Where p.Parent.Id = PageId _
Select p
ExpandedTreeViewItem.ItemsSource = ChildPages
End Sub
End Class
```
When the window loads, the root node and its children are queried from the database and inserted into the tree.
Each time a node is expanded, that node's children and grandchildren are queried from the database and inserted into the tree.
|
269,541 |
<p>I'm trying to build a HQL that can left join values from a collection, in order to give me the chance of checking "is null" on it.</p>
<p>Taken from the example from hibernate manual:</p>
<pre>
from Cat as cat
left join cat.kittens as kitten
with kitten.bodyWeight > 10.0
</pre>
<p>doesn't seem to work in NHibernate, since it doesn't recognize the "with" keyword. How else are you supposed to left join and check for no-matching entries if you cannot specify join-clauses directly in your join as opposed to in your WHERE-statement?</p>
<p>I'm running NHibernate 2.0.0.</p>
|
[
{
"answer_id": 269709,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 3,
"selected": true,
"text": "<p>Unfortunately, this is not supported in NHibernate. It was <a href=\"http://jira.nhibernate.org/browse/NH-514\" rel=\"nofollow noreferrer\">first requested in 2005</a> and is by far the most popular requested feature.</p>\n"
},
{
"answer_id": 494894,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can workaround it by using an outer join, and then do this:</p>\n\n<pre><code>from Cat c\nleft join c.Kittens as kitten\nwhere kitten.bodyweight > 10 or kitten.bodyweight is null\n</code></pre>\n"
},
{
"answer_id": 782331,
"author": "Frederik Gheysels",
"author_id": 55774,
"author_profile": "https://Stackoverflow.com/users/55774",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently they're working on it ...\n<a href=\"https://nhibernate.jira.com/browse/NH-514\" rel=\"nofollow noreferrer\">https://nhibernate.jira.com/browse/NH-514</a></p>\n\n<p>I've received an update report from the NHibernate JIRA yesterday, and this issue should be fixed in NHibernate v2.1.0 Alpha 3 :)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33663/"
] |
I'm trying to build a HQL that can left join values from a collection, in order to give me the chance of checking "is null" on it.
Taken from the example from hibernate manual:
```
from Cat as cat
left join cat.kittens as kitten
with kitten.bodyWeight > 10.0
```
doesn't seem to work in NHibernate, since it doesn't recognize the "with" keyword. How else are you supposed to left join and check for no-matching entries if you cannot specify join-clauses directly in your join as opposed to in your WHERE-statement?
I'm running NHibernate 2.0.0.
|
Unfortunately, this is not supported in NHibernate. It was [first requested in 2005](http://jira.nhibernate.org/browse/NH-514) and is by far the most popular requested feature.
|
269,545 |
<p>With the jQuery datepicker, how does one change the year range that is displayed? On the jQuery UI site it says the default is "10 years before and after the current year are shown". I want to use this for a birthday selection and 10 years before today is no good. Can this be done with the jQuery datepicker or will I have to use a different solution?</p>
<p>link to datepicker demo: <a href="http://jqueryui.com/demos/datepicker/#dropdown-month-year" rel="noreferrer">http://jqueryui.com/demos/datepicker/#dropdown-month-year</a></p>
|
[
{
"answer_id": 269561,
"author": "Shog9",
"author_id": 811,
"author_profile": "https://Stackoverflow.com/users/811",
"pm_score": 8,
"selected": true,
"text": "<p>If you look down the demo page a bit, you'll see a \"Restricting Datepicker\" section. Use the dropdown to specify the \"<code>Year dropdown shows last 20 years</code>\" demo , and hit view source:</p>\n\n<pre><code>$(\"#restricting\").datepicker({ \n yearRange: \"-20:+0\", // this is the option you're looking for\n showOn: \"both\", \n buttonImage: \"templates/images/calendar.gif\", \n buttonImageOnly: true \n});\n</code></pre>\n\n<p>You'll want to do the same (obviously changing <code>-20</code> to <code>-100</code> or something).</p>\n"
},
{
"answer_id": 269573,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 3,
"selected": false,
"text": "<p>Adding to what @Shog9 posted, you can also restrict dates individually in the beforeShowDay: callback function.</p>\n\n<p>You supply a function that takes a date and returns a boolean array:</p>\n\n<pre><code>\"$(\".selector\").datepicker({ beforeShowDay: nationalDays}) \nnatDays = [[1, 26, 'au'], [2, 6, 'nz'], [3, 17, 'ie'], [4, 27, 'za'], \n[5, 25, 'ar'], [6, 6, 'se'], [7, 4, 'us'], [8, 17, 'id'], [9, 7, \n'br'], [10, 1, 'cn'], [11, 22, 'lb'], [12, 12, 'ke']]; \nfunction nationalDays(date) { \n for (i = 0; i < natDays.length; i++) { \n if (date.getMonth() == natDays[i][0] - 1 && date.getDate() == \nnatDays[i][1]) { \n return [false, natDays[i][2] + '_day']; \n } \n } \n return [true, '']; \n} \n</code></pre>\n"
},
{
"answer_id": 419283,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>au, nz, ie, etc. are the country codes for the countries whose national days are being displayed (Australia, New Zealand, Ireland, ...). As seen in the code, these values are combined with '_day' and passed back to be applied to that day as a CSS style. The corresponding styles are of the form show below, which moves the text for that day out of the way and replaces it with an image of the country's flag.</p>\n\n<pre><code>.au_day {\n text-indent: -9999px;\n background: #eee url(au.gif) no-repeat center;\n}\n</code></pre>\n\n<p>The 'false' value that is passed back with the new style indicates that these days may not be selected.</p>\n"
},
{
"answer_id": 4068478,
"author": "Plippie",
"author_id": 344117,
"author_profile": "https://Stackoverflow.com/users/344117",
"pm_score": 5,
"selected": false,
"text": "<p>Why not show the year or month selection boxes?</p>\n\n<pre><code>$( \".datefield\" ).datepicker({\n changeMonth: true,\n changeYear: true,\n yearRange:'-90:+0'\n});\n</code></pre>\n"
},
{
"answer_id": 11734244,
"author": "Warren Sergent",
"author_id": 800505,
"author_profile": "https://Stackoverflow.com/users/800505",
"pm_score": 3,
"selected": false,
"text": "<p>what no one else has put is that you can also set hard-coded date ranges:</p>\n\n<p>for example:</p>\n\n<pre><code>yearRange: \"1901:2012\"\n</code></pre>\n\n<p>whilst it may be advisable to not do this, it is however, an option that is perfectly valid (and useful if you are legitimately looking for say a specific year in a catalogue - such as \"1963:1984\" ).</p>\n"
},
{
"answer_id": 15961162,
"author": "Maverick",
"author_id": 1500491,
"author_profile": "https://Stackoverflow.com/users/1500491",
"pm_score": 3,
"selected": false,
"text": "<p>Perfect for date of birth fields (and what I use) is similar to what Shog9 said, although I'm going to give a more specific DOB example:</p>\n\n<pre><code>$(\".datePickerDOB\").datepicker({ \n yearRange: \"-122:-18\", //18 years or older up to 122yo (oldest person ever, can be sensibly set to something much smaller in most cases)\n maxDate: \"-18Y\", //Will only allow the selection of dates more than 18 years ago, useful if you need to restrict this\n minDate: \"-122Y\"\n});\n</code></pre>\n\n<p>Hope future googlers find this useful :).</p>\n"
},
{
"answer_id": 21726498,
"author": "Manish",
"author_id": 1917951,
"author_profile": "https://Stackoverflow.com/users/1917951",
"pm_score": 2,
"selected": false,
"text": "<pre><code> $(\"#DateOfBirth\").datepicker({\n yearRange: \"-100:+0\",\n changeMonth: true,\n changeYear: true,\n });\n</code></pre>\n\n<p>yearRange: '1950:2013', // specifying a hard coded year range\nor this way</p>\n\n<p>yearRange: \"-100:+0\", // last hundred years</p>\n\n<p>It will help to show drop down for year and month selection.</p>\n"
},
{
"answer_id": 23677495,
"author": "Himansz",
"author_id": 3328204,
"author_profile": "https://Stackoverflow.com/users/3328204",
"pm_score": 1,
"selected": false,
"text": "<p>i think this may work as well </p>\n\n<pre><code>$(function () {\n $(\".DatepickerInputdob\").datepicker({\n dateFormat: \"d M yy\",\n changeMonth: true,\n changeYear: true,\n yearRange: '1900:+0',\n defaultDate: '01 JAN 1900'\n });\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847/"
] |
With the jQuery datepicker, how does one change the year range that is displayed? On the jQuery UI site it says the default is "10 years before and after the current year are shown". I want to use this for a birthday selection and 10 years before today is no good. Can this be done with the jQuery datepicker or will I have to use a different solution?
link to datepicker demo: <http://jqueryui.com/demos/datepicker/#dropdown-month-year>
|
If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "`Year dropdown shows last 20 years`" demo , and hit view source:
```
$("#restricting").datepicker({
yearRange: "-20:+0", // this is the option you're looking for
showOn: "both",
buttonImage: "templates/images/calendar.gif",
buttonImageOnly: true
});
```
You'll want to do the same (obviously changing `-20` to `-100` or something).
|
269,566 |
<p>I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote:</p>
<pre><code><a href="secondpage.html#one"></a>
<a href="secondpage.html#two"></a>
<a href="secondpage.html#three"></a>
</code></pre>
<p>I'm expecting to see two.html load the text with id "one", but it doesn't work, does anyone know what I did wrong? </p>
<p>Here's the code on second page:</p>
<pre><code><ul id="menu" class="aaa">
<li><a id="one" href="#">one</a></li>
<li><a id="two" href="#">two</a></li>
<li><a id="three" href="#">three</a></li>
</ul>
</code></pre>
<p>And I have a JS file to modify each id:</p>
<pre><code>$("one").observe('click', function() {
$('Pic').writeAttribute('src',"picone.jpg");
$('Bio').update("texthere!");
});
</code></pre>
<p>Same for two and three.</p>
<p>Right now if I click on a button on the first page, it will always show
the text and pic for "one", no matter which button I click.</p>
<p>But I want to see the pic and text for "two" if i click on it.</p>
|
[
{
"answer_id": 269592,
"author": "Keltex",
"author_id": 28260,
"author_profile": "https://Stackoverflow.com/users/28260",
"pm_score": 0,
"selected": false,
"text": "<p>When you say \"different ids\" how are you setting up your anchors on the 2nd page? The anchor on the 2nd page should look like this:</p>\n\n<pre><code><a name='one'></a>\n</code></pre>\n\n<p>Put this right above the text that you want to mark on the 2nd page.</p>\n"
},
{
"answer_id": 269595,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 1,
"selected": false,
"text": "<p>the #blastuffbla is not an ID but the location hash.\nYou can acces it by using:</p>\n\n<pre><code>self.document.location.hash\n</code></pre>\n\n<p>which would return #hash, if you would only want hash you would use:</p>\n\n<pre><code>self.document.location.hash.substring(1)\n</code></pre>\n\n<p>Hope this helps</p>\n"
},
{
"answer_id": 269604,
"author": "Leonel Martins",
"author_id": 26673,
"author_profile": "https://Stackoverflow.com/users/26673",
"pm_score": 0,
"selected": false,
"text": "<p>Do you want to scroll the page to the positon of the id \"one\"? Maybe the content of the page is too small that you cant scroll there. I mean sometimes the browser cant move the element marked with the id to the top of the canvas and looks like it doenst scrolled there. Try to include enough space after the element to make it scrollable to the top of the browser.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 269619,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 3,
"selected": true,
"text": "<p>What you want to do is simulate a click on your anchor when the page loads. Since you're using jQuery, the simplest approach (but far form best) would be the following:</p>\n\n<pre>\n$(window).observe('domready', function () {\n $(location.hash).click();\n});\n</pre>\n\n<p>attach ondomready-event to window. Fetch element with id=one (with jQuery this would be '#one', same as your location.hash would be, very handy in this case), trigger a click on it.</p>\n\n<p>You might need to replace $(location.hash).click(); with $(location.hash).get(0).click() since jQuery tend to return arrays of jQuery-objects. </p>\n\n<p>But a better solution in your case would be to have an event-handler that you can trigger manually, thus circumvent the need of firing events, aswell as drop the anchors and put onclick directly on your li's.</p>\n\n<p>And furthermore, why do you load a second page when all you seem to want to do is to show/hide content dynamically? Do it on the same page...</p>\n"
},
{
"answer_id": 269938,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 1,
"selected": false,
"text": "<p> tags do not have id's but names to handle the anchors in Urls, you will still need the ID to manage them in JS though.\nSo your list should be:</p>\n\n<pre><code><ul id=\"menu\" class=\"aaa\">\n<li><a id=\"one\" name=\"one\" href=\"#\">one</a></li>\n<li><a id=\"two\" name=\"two\" href=\"#\">two</a></li>\n<li><a id=\"three\" name=\"three\" href=\"#\">three</a></li></ul>\n</code></pre>\n\n<p>Your javascript seemed correct though.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34797/"
] |
I have two html pages, when you click on something on the first html, it will go to the second one. What I want to do is to show text according to what you clicked on the first html. different texts are wrapped with different ids. Here's how I wrote:
```
<a href="secondpage.html#one"></a>
<a href="secondpage.html#two"></a>
<a href="secondpage.html#three"></a>
```
I'm expecting to see two.html load the text with id "one", but it doesn't work, does anyone know what I did wrong?
Here's the code on second page:
```
<ul id="menu" class="aaa">
<li><a id="one" href="#">one</a></li>
<li><a id="two" href="#">two</a></li>
<li><a id="three" href="#">three</a></li>
</ul>
```
And I have a JS file to modify each id:
```
$("one").observe('click', function() {
$('Pic').writeAttribute('src',"picone.jpg");
$('Bio').update("texthere!");
});
```
Same for two and three.
Right now if I click on a button on the first page, it will always show
the text and pic for "one", no matter which button I click.
But I want to see the pic and text for "two" if i click on it.
|
What you want to do is simulate a click on your anchor when the page loads. Since you're using jQuery, the simplest approach (but far form best) would be the following:
```
$(window).observe('domready', function () {
$(location.hash).click();
});
```
attach ondomready-event to window. Fetch element with id=one (with jQuery this would be '#one', same as your location.hash would be, very handy in this case), trigger a click on it.
You might need to replace $(location.hash).click(); with $(location.hash).get(0).click() since jQuery tend to return arrays of jQuery-objects.
But a better solution in your case would be to have an event-handler that you can trigger manually, thus circumvent the need of firing events, aswell as drop the anchors and put onclick directly on your li's.
And furthermore, why do you load a second page when all you seem to want to do is to show/hide content dynamically? Do it on the same page...
|
269,577 |
<p>I am working on a small parser that should accept input in a number of languages. I am going to have maybe 50 strings that will serve as keywords/anchors in parsing the input. In PHP, what would be the best way to organize these translated keywords? </p>
<p>One possible solution that comes to my mind is to use an associative array. Like this:</p>
<pre><code>$lang = array('us' => array('totalDebt' => 'Total Debt', 'color' => 'Color'),
'gb' => array('totalDebt' => 'Total Debt', 'color' => 'Colour'))
</code></pre>
<p>which I could then access using the following:</p>
<pre><code>$langCode = 'en';
$debtPos = strpos($lang[$langCode]['totalDebt']);
</code></pre>
<p>Are there any better, proven methods for dealing with a bunch of short strings translated into a bunch of languages?</p>
|
[
{
"answer_id": 269865,
"author": "Seamus",
"author_id": 30443,
"author_profile": "https://Stackoverflow.com/users/30443",
"pm_score": 0,
"selected": false,
"text": "<p>Generally people use l10n (or something similar) in their application because it allows for additional languages by adding a localization file which means the programmers do not have to change code. But if it is a simple script, then <a href=\"http://codeutopia.net/blog/2007/11/22/localize-your-site-in-3-easy-steps/\" rel=\"nofollow noreferrer\">full on localization</a> would be overkill. </p>\n"
},
{
"answer_id": 269902,
"author": "user27987",
"author_id": 27987,
"author_profile": "https://Stackoverflow.com/users/27987",
"pm_score": 2,
"selected": false,
"text": "<p>For a complete translation solution, you can look on a solution like <a href=\"http://www.php.net/manual/en/intro.gettext.php\" rel=\"nofollow noreferrer\">gettext</a>.</p>\n\n<p>you solution is good enough (fast, cheap on resources) for small dictionaries.\nI didn't understand what you tried to do using the strpos() function.</p>\n\n<p>Don't forget to use some kind of fallback if the term you want to translate doesn't exists in the language, usually the fallback is to the English.</p>\n"
},
{
"answer_id": 270850,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 0,
"selected": false,
"text": "<p>I have seen your solution used in other OS projects, however the <code>$lang</code> array is usually constructed in different files. For example:</p>\n\n<pre><code><?php // lang.us.php\n$LANG['us'] = array(\n 'totalDebt' => 'Total Debt',\n 'color' => 'Color',\n );\n</code></pre>\n\n<p>and so on for lang.gb.php, lang.de.php, etc.</p>\n"
},
{
"answer_id": 270888,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<p>As Peter said, you've got the right idea, but separate your languages into different files. It means that PHP won't have to store the array of every single word in every single language. Because you only are going to be loading one language at a time, you can skip the <code>$lang['us']</code> level of nesting too.</p>\n\n<p>You could even \"extend\" languages:</p>\n\n<pre><code><?php // lang.en-gb.php\n$lang = array(\n 'color' => \"Colour\",\n 'totalDebt' => \"Total Debt\",\n ...\n);\n?>\n\n<?php // lang.en-us.php\ninclude('lang.en-gb.php');\n\n$lang['color'] = \"Color\";\n// don't need to redefine \"totalDebt\"\n?>\n</code></pre>\n\n<p>You might even consider creating a basic class which handles all this for you: detect the locale, choose the correct file, have \"error\" handling, if a term isn't defined in a particular language, etc.</p>\n"
},
{
"answer_id": 270954,
"author": "jcampbell1",
"author_id": 20512,
"author_profile": "https://Stackoverflow.com/users/20512",
"pm_score": 0,
"selected": false,
"text": "<p>You probably don't want 'totaldebt' => 'Total Debt' as that will ultimately obfuscate your code, and is slower than just storing 'Total Debt' as the hash key. The gettext way of doing things is to just wrap the strings in a function.</p>\n\n<p>so rather than:</p>\n\n<pre><code>echo \"Color\";\n</code></pre>\n\n<p>You do:</p>\n\n<pre><code>echo t(\"Color\");\n</code></pre>\n\n<p>the t() function will look at the globally defined language, and make the substitution if possible. At some point, you may want to use gettext and doing it this way will be compatible. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269577",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am working on a small parser that should accept input in a number of languages. I am going to have maybe 50 strings that will serve as keywords/anchors in parsing the input. In PHP, what would be the best way to organize these translated keywords?
One possible solution that comes to my mind is to use an associative array. Like this:
```
$lang = array('us' => array('totalDebt' => 'Total Debt', 'color' => 'Color'),
'gb' => array('totalDebt' => 'Total Debt', 'color' => 'Colour'))
```
which I could then access using the following:
```
$langCode = 'en';
$debtPos = strpos($lang[$langCode]['totalDebt']);
```
Are there any better, proven methods for dealing with a bunch of short strings translated into a bunch of languages?
|
For a complete translation solution, you can look on a solution like [gettext](http://www.php.net/manual/en/intro.gettext.php).
you solution is good enough (fast, cheap on resources) for small dictionaries.
I didn't understand what you tried to do using the strpos() function.
Don't forget to use some kind of fallback if the term you want to translate doesn't exists in the language, usually the fallback is to the English.
|
269,578 |
<p>I want to get the method <code>System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)</code> method, but I keep coming up with nulls.</p>
<pre><code>var type = typeof(T);
var propertyInfo = type.GetProperty(group.PropertyName);
var propertyType = propertyInfo.PropertyType;
var sorterType = typeof(Func<,>).MakeGenericType(type, propertyType);
var expressionType = typeof(Expression<>).MakeGenericType(sorterType);
var queryType = typeof(IQueryable<T>);
var orderBy = typeof(System.Linq.Queryable).GetMethod("OrderBy", new[] { queryType, expressionType }); /// is always null.
</code></pre>
<p>Does anyone have any insight? I would prefer to not loop through the <code>GetMethods</code> result.</p>
|
[
{
"answer_id": 269606,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>I don't believe there's an easy way of doing this - it's basically a missing feature from reflection, IIRC. You have to loop through the methods to find the one you want :(</p>\n"
},
{
"answer_id": 269908,
"author": "David",
"author_id": 21909,
"author_profile": "https://Stackoverflow.com/users/21909",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var orderBy =\n (from methodInfo in typeof(System.Linq.Queryable).GetMethods()\n where methodInfo.Name == \"OrderBy\"\n let parameterInfo = methodInfo.GetParameters()\n where parameterInfo.Length == 2\n && parameterInfo[0].ParameterType.GetGenericTypeDefinition() == typeof(IQueryable<>)\n && parameterInfo[1].ParameterType.GetGenericTypeDefinition() == typeof(Expression<>)\n select\n methodInfo\n ).Single();\n</code></pre>\n"
},
{
"answer_id": 269992,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>A variant of your solution, as an extension method:</p>\n\n<pre><code>public static class TypeExtensions\n{\n private static readonly Func<MethodInfo, IEnumerable<Type>> ParameterTypeProjection = \n method => method.GetParameters()\n .Select(p => p.ParameterType.GetGenericTypeDefinition());\n\n public static MethodInfo GetGenericMethod(this Type type, string name, params Type[] parameterTypes)\n {\n return (from method in type.GetMethods()\n where method.Name == name\n where parameterTypes.SequenceEqual(ParameterTypeProjection(method))\n select method).SingleOrDefault();\n }\n}\n</code></pre>\n"
},
{
"answer_id": 373396,
"author": "Neil",
"author_id": 24315,
"author_profile": "https://Stackoverflow.com/users/24315",
"pm_score": 5,
"selected": true,
"text": "<p>Solved (by hacking LINQ)!</p>\n\n<p>I saw your question while researching the same problem. After finding no good solution, I had the idea to look at the LINQ expression tree. Here's what I came up with:</p>\n\n<pre><code>public static MethodInfo GetOrderByMethod<TElement, TSortKey>()\n{\n Func<TElement, TSortKey> fakeKeySelector = element => default(TSortKey);\n\n Expression<Func<IEnumerable<TElement>, IOrderedEnumerable<TElement>>> lamda\n = list => list.OrderBy(fakeKeySelector);\n\n return (lamda.Body as MethodCallExpression).Method;\n}\n\nstatic void Main(string[] args)\n{\n List<int> ints = new List<int>() { 9, 10, 3 };\n MethodInfo mi = GetOrderByMethod<int, string>(); \n Func<int,string> keySelector = i => i.ToString();\n IEnumerable<int> sortedList = mi.Invoke(null, new object[] { ints, \n keySelector }\n ) as IEnumerable<int>;\n\n foreach (int i in sortedList)\n {\n Console.WriteLine(i);\n }\n}\n</code></pre>\n\n<p>output: 10 3 9</p>\n\n<p>EDIT: Here is how to get the method if you don't know the type at compile-time:</p>\n\n<pre><code>public static MethodInfo GetOrderByMethod(Type elementType, Type sortKeyType)\n{\n MethodInfo mi = typeof(Program).GetMethod(\"GetOrderByMethod\", Type.EmptyTypes);\n\n var getOrderByMethod = mi.MakeGenericMethod(new Type[] { elementType,\n sortKeyType });\n return getOrderByMethod.Invoke(null, new object[] { }) as MethodInfo;\n}\n</code></pre>\n\n<p>Be sure to replace typeof(Program) with typeof(WhateverClassYouDeclareTheseMethodsIn).</p>\n"
},
{
"answer_id": 3453666,
"author": "Kyle",
"author_id": 259594,
"author_profile": "https://Stackoverflow.com/users/259594",
"pm_score": 1,
"selected": false,
"text": "<p>Using lambda expressions you can get the generic method easily</p>\n\n<pre><code> var method = type.GetGenericMethod\n (c => c.Validate((IValidator<object>)this, o, action));\n</code></pre>\n\n<p>Read more about it here:</p>\n\n<p><s><a href=\"http://www.nerdington.com/2010/08/calling-generic-method-without-magic.html\" rel=\"nofollow noreferrer\">http://www.nerdington.com/2010/08/calling-generic-method-without-magic.html</a></s></p>\n\n<p><a href=\"http://web.archive.org/web/20100911074123/http://www.nerdington.com/2010/08/calling-generic-method-without-magic.html\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20100911074123/http://www.nerdington.com/2010/08/calling-generic-method-without-magic.html</a></p>\n"
},
{
"answer_id": 3628713,
"author": "qube",
"author_id": 438137,
"author_profile": "https://Stackoverflow.com/users/438137",
"pm_score": 3,
"selected": false,
"text": "<p>I think the following extension method would be a solution to the problem:</p>\n\n<pre><code>public static MethodInfo GetGenericMethod(\n this Type type, string name, Type[] generic_type_args, Type[] param_types, bool complain = true)\n{\n foreach (MethodInfo m in type.GetMethods())\n if (m.Name == name)\n {\n ParameterInfo[] pa = m.GetParameters();\n if (pa.Length == param_types.Length)\n {\n MethodInfo c = m.MakeGenericMethod(generic_type_args);\n if (c.GetParameters().Select(p => p.ParameterType).SequenceEqual(param_types))\n return c;\n }\n }\n if (complain)\n throw new Exception(\"Could not find a method matching the signature \" + type + \".\" + name +\n \"<\" + String.Join(\", \", generic_type_args.AsEnumerable()) + \">\" +\n \"(\" + String.Join(\", \", param_types.AsEnumerable()) + \").\");\n return null;\n}\n</code></pre>\n\n<p>The call would be something like (just changing the last line of your original code):</p>\n\n<pre><code>var type = typeof(T); \nvar propertyInfo = type.GetProperty(group.PropertyName); \nvar propertyType = propertyInfo.PropertyType; \n\nvar sorterType = typeof(Func<,>).MakeGenericType(type, propertyType); \nvar expressionType = typeof(Expression<>).MakeGenericType(sorterType); \n\nvar queryType = typeof(IQueryable<T>); \n\nvar orderBy = typeof(Queryable).GetGenericMethod(\"OrderBy\",\n new Type[] { type, propertyType },\n new[] { queryType, expressionType });\n</code></pre>\n\n<p>What is different to the other solutions: the resulting method matches the parameter types exactly, not only their generic base types.</p>\n"
},
{
"answer_id": 12117133,
"author": "Konstantin Isaev",
"author_id": 1026676,
"author_profile": "https://Stackoverflow.com/users/1026676",
"pm_score": 0,
"selected": false,
"text": "<p>I think that it mabe be made with class like so:</p>\n\n<pre><code>public static class SortingUtilities<T, TProperty>\n{\n public static IOrderedQueryable<T> ApplyOrderBy(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.OrderBy(selector);\n }\n\n\n public static IOrderedQueryable<T> ApplyOrderByDescending(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.OrderByDescending(selector);\n }\n\n public static IQueryable<T> Preload(IQueryable<T> query, Expression<Func<T, TProperty>> selector)\n {\n return query.Include(selector);\n }\n}\n</code></pre>\n\n<p>And you can use this even like so:</p>\n\n<pre><code>public class SortingOption<T> where T: class\n{\n private MethodInfo ascendingMethod;\n private MethodInfo descendingMethod;\n private LambdaExpression lambda;\n public string Name { get; private set; }\n\n public SortDirection DefaultDirection { get; private set; }\n\n public bool ApplyByDefault { get; private set; }\n\n public SortingOption(PropertyInfo targetProperty, SortableAttribute options)\n {\n Name = targetProperty.Name;\n DefaultDirection = options.Direction;\n ApplyByDefault = options.IsDefault;\n var utilitiesClass = typeof(SortingUtilities<,>).MakeGenericType(typeof(T), targetProperty.PropertyType);\n ascendingMethod = utilitiesClass.GetMethod(\"ApplyOrderBy\", BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase);\n descendingMethod = utilitiesClass.GetMethod(\"ApplyOrderByDescending\", BindingFlags.Static | BindingFlags.Public | BindingFlags.IgnoreCase);\n var param = Expression.Parameter(typeof(T));\n var getter = Expression.MakeMemberAccess(param, targetProperty);\n lambda = Expression.Lambda(typeof(Func<,>).MakeGenericType(typeof(T), targetProperty.PropertyType), getter, param);\n }\n\n public IQueryable<T> Apply(IQueryable<T> query, SortDirection? direction = null)\n {\n var dir = direction.HasValue ? direction.Value : DefaultDirection;\n var method = dir == SortDirection.Ascending ? ascendingMethod : descendingMethod;\n return (IQueryable<T>)method.Invoke(null, new object[] { query, lambda });\n }\n}\n</code></pre>\n\n<p>with attribute like this:</p>\n\n<pre><code>public class SortableAttribute : Attribute \n{\n public SortDirection Direction { get; set; }\n public bool IsDefault { get; set; }\n}\n</code></pre>\n\n<p>and this enum:</p>\n\n<pre><code>public enum SortDirection\n{\n Ascending,\n Descending\n}\n</code></pre>\n"
},
{
"answer_id": 15695892,
"author": "PaulWh",
"author_id": 2221700,
"author_profile": "https://Stackoverflow.com/users/2221700",
"pm_score": 2,
"selected": false,
"text": "<p>If you do know the types at compile time, you can do this with less code without using the Expression type, or depending on Linq at all, like so:</p>\n\n<pre><code>public static MethodInfo GetOrderByMethod<TElement, TSortKey>() {\n IEnumerable<TElement> col = null;\n return new Func<Func<TElement, TSortKey>, IOrderedEnumerable<TElement>>(col.OrderBy).Method;\n}\n</code></pre>\n"
},
{
"answer_id": 19499360,
"author": "MBoros",
"author_id": 280562,
"author_profile": "https://Stackoverflow.com/users/280562",
"pm_score": 0,
"selected": false,
"text": "<p>Just another comment (it should be, but since its too long, i have to post it as an answer) following up @NeilWhitaker -s answer (here using Enumerable.Count), since we are in the middle of clearing the strings out :) \nwhy not use the Expression trees in your bytype method too? \nSomething like :</p>\n\n<pre><code> #region Count\n /// <summary>\n /// gets the \n /// public static int Count&lt;TSource>(this IEnumerable&lt;TSource> source);\n /// methodinfo\n /// </summary>\n /// <typeparam name=\"TSource\">type of the elements</typeparam>\n /// <returns></returns>\n public static MethodInfo GetCountMethod<TSource>()\n {\n Expression<Func<IEnumerable<TSource>, int>> lamda = list => list.Count();\n return (lamda.Body as MethodCallExpression).Method;\n }\n\n /// <summary>\n /// gets the \n /// public static int Count&lt;TSource>(this IEnumerable&lt;TSource> source);\n /// methodinfo\n /// </summary>\n /// <param name=\"elementType\">type of the elements</param>\n /// <returns></returns>\n public static MethodInfo GetCountMethodByType(Type elementType)\n {\n // to get the method name, we use lambdas too\n Expression<Action> methodNamer = () => GetCountMethod<object>();\n var gmi = ((MethodCallExpression)methodNamer.Body).Method.GetGenericMethodDefinition();\n var mi = gmi.MakeGenericMethod(new Type[] { elementType });\n return mi.Invoke(null, new object[] { }) as MethodInfo;\n }\n #endregion Disctinct\n</code></pre>\n"
},
{
"answer_id": 68642630,
"author": "t.ouvre",
"author_id": 5658778,
"author_profile": "https://Stackoverflow.com/users/5658778",
"pm_score": 2,
"selected": false,
"text": "<p>Today there is a good alternative with the method <code>Type.MakeGenericMethodParameter</code>. The following snippet retrieve the <code>Queryable.OrderBy</code> method:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>var TSource = Type.MakeGenericMethodParameter(0);\nvar TKey = Type.MakeGenericMethodParameter(1);\nvar orderBy = typeof(Queryable).GetMethod(nameof(Queryable.OrderBy), 2, BindingFlags.Static | BindingFlags.Public, null, CallingConventions.Standard\n , new[] { typeof(IQueryable<>).MakeGenericType(TSource), typeof(Expression<>).MakeGenericType(typeof(Func<,>).MakeGenericType(TSource, TKey)) }\n , null);\nAssert.NotNull(orderBy);\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269578",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21909/"
] |
I want to get the method `System.Linq.Queryable.OrderyBy<T, TKey>(the IQueryable<T> source, Expression<Func<T,TKey>> keySelector)` method, but I keep coming up with nulls.
```
var type = typeof(T);
var propertyInfo = type.GetProperty(group.PropertyName);
var propertyType = propertyInfo.PropertyType;
var sorterType = typeof(Func<,>).MakeGenericType(type, propertyType);
var expressionType = typeof(Expression<>).MakeGenericType(sorterType);
var queryType = typeof(IQueryable<T>);
var orderBy = typeof(System.Linq.Queryable).GetMethod("OrderBy", new[] { queryType, expressionType }); /// is always null.
```
Does anyone have any insight? I would prefer to not loop through the `GetMethods` result.
|
Solved (by hacking LINQ)!
I saw your question while researching the same problem. After finding no good solution, I had the idea to look at the LINQ expression tree. Here's what I came up with:
```
public static MethodInfo GetOrderByMethod<TElement, TSortKey>()
{
Func<TElement, TSortKey> fakeKeySelector = element => default(TSortKey);
Expression<Func<IEnumerable<TElement>, IOrderedEnumerable<TElement>>> lamda
= list => list.OrderBy(fakeKeySelector);
return (lamda.Body as MethodCallExpression).Method;
}
static void Main(string[] args)
{
List<int> ints = new List<int>() { 9, 10, 3 };
MethodInfo mi = GetOrderByMethod<int, string>();
Func<int,string> keySelector = i => i.ToString();
IEnumerable<int> sortedList = mi.Invoke(null, new object[] { ints,
keySelector }
) as IEnumerable<int>;
foreach (int i in sortedList)
{
Console.WriteLine(i);
}
}
```
output: 10 3 9
EDIT: Here is how to get the method if you don't know the type at compile-time:
```
public static MethodInfo GetOrderByMethod(Type elementType, Type sortKeyType)
{
MethodInfo mi = typeof(Program).GetMethod("GetOrderByMethod", Type.EmptyTypes);
var getOrderByMethod = mi.MakeGenericMethod(new Type[] { elementType,
sortKeyType });
return getOrderByMethod.Invoke(null, new object[] { }) as MethodInfo;
}
```
Be sure to replace typeof(Program) with typeof(WhateverClassYouDeclareTheseMethodsIn).
|
269,581 |
<p>I am attempting to return a collection of departments from a .NET assembly to be consumed by ASP via COM Interop. Using .NET I would just return a generic collection, e.g. <code>List<Department></code>, but it seems that generics don't work well with COM Interop. So, what are my options?</p>
<p>I would like to both iterate over the list and be able to access an item by index. Should I inherit from <code>List<Department></code>, implement an <code>IList</code>, <code>IList<Department></code> or another interface, or is there a better way? Ideally I would prefer not to have to implement a custom collection for every type of list I need. Also, will <code>List[index]</code> even work with COM Interop?</p>
<p>Thanks,
Mike</p>
<h2>Example .NET components (C#):</h2>
<pre><code>public class Department {
public string Code { get; private set; }
public string Name { get; private set; }
// ...
}
public class MyLibrary {
public List<Department> GetDepartments() {
// return a list of Departments from the database
}
}
</code></pre>
<h2>Example ASP code:</h2>
<pre><code><%
Function PrintDepartments(departments)
Dim department
For Each department In departments
Response.Write(department.Code & ": " & department.Name & "<br />")
Next
End Function
Dim myLibrary, departments
Set myLibrary = Server.CreateObject("MyAssembly.MyLibrary")
Set departments = myLibrary.GetDepartments()
%>
<h1>Departments</h1>
<% Call PrintDepartments(departments) %>
<h1>The third department</h1>
<%= departments(2).Name %>
</code></pre>
<h2>Related questions:</h2>
<ul>
<li><a href="https://stackoverflow.com/questions/161704/using-generic-lists-on-serviced-component">Using Generic lists on serviced component</a></li>
<li><a href="https://stackoverflow.com/questions/56375/are-non-generic-collections-in-net-obsolete">Are non-generic collections in .NET obsolete?</a></li>
</ul>
|
[
{
"answer_id": 270025,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 5,
"selected": true,
"text": "<p>After some more research and trial-and-error, I think I found a solution by using <code>System.Collections.ArrayList</code>. However, this does not work with getting a value by index. To do so, I created a new class <code>ComArrayList</code> that inherits from <code>ArrayList</code> and adds new methods <code>GetByIndex</code> and <code>SetByIndex</code>.</p>\n\n<h2>COM Interop compatible collection:</h2>\n\n<pre><code>public class ComArrayList : System.Collections.ArrayList {\n public virtual object GetByIndex(int index) {\n return base[index];\n }\n\n public virtual void SetByIndex(int index, object value) {\n base[index] = value;\n }\n}\n</code></pre>\n\n<h2>Updated .NET component MyLibrary.GetDepartments:</h2>\n\n<pre><code>public ComArrayList GetDepartments() {\n // return a list of Departments from the database\n}\n</code></pre>\n\n<h2>Updated ASP:</h2>\n\n<pre><code><h1>The third department</h1>\n<%= departments.GetByIndex(2).Name %>\n</code></pre>\n"
},
{
"answer_id": 1860558,
"author": "Christian Hayter",
"author_id": 115413,
"author_profile": "https://Stackoverflow.com/users/115413",
"pm_score": 3,
"selected": false,
"text": "<p>Since you are only consuming the data in ASP, I would suggest returning <code>Department[]</code>. This should map directly to a SAFEARRAY in COM. It supports enumeration and indexed access too.</p>\n\n<pre><code>public Department[] GetDepartments() {\n var departments = new List<Department>();\n // populate list from database\n return departments.ToArray();\n}\n</code></pre>\n"
},
{
"answer_id": 4631789,
"author": "Jeremy Prine",
"author_id": 567669,
"author_profile": "https://Stackoverflow.com/users/567669",
"pm_score": 1,
"selected": false,
"text": "<p>In your ASP code, could you not do this?</p>\n\n<pre><code><h1>The third department</h1>\n<%= departments.Item(2).Name %>\n</code></pre>\n\n<p>I know that in VB .NET, C# indexers are supported via the \"Item\" property, so the same idea may work in ASP.</p>\n"
},
{
"answer_id": 9362837,
"author": "akc42",
"author_id": 438737,
"author_profile": "https://Stackoverflow.com/users/438737",
"pm_score": 1,
"selected": false,
"text": "<p>I've been trying to address this same problem in vb.net (not fluent in C#).</p>\n\n<p>Since List(Of T) supports the IList interface, for the COM interface for my objects I have tried specifying</p>\n\n<pre><code>Public Class MyClass\n...\n Private _MyList As List(of MyObject)\n Public ReadOnly Property MyList As IList Implements IMyClass.MyList\n Get\n Return _MyList\n End Get\n End Property\n</code></pre>\n\n<p>and then specifying in the Public Interface that COM sees</p>\n\n<pre><code>ReadOnly Property MyList As IList\n</code></pre>\n\n<p>This seems to work fine from a classic ASP client that instantiates the object, calls a generator function and then reads MyList property like an array.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269581",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14934/"
] |
I am attempting to return a collection of departments from a .NET assembly to be consumed by ASP via COM Interop. Using .NET I would just return a generic collection, e.g. `List<Department>`, but it seems that generics don't work well with COM Interop. So, what are my options?
I would like to both iterate over the list and be able to access an item by index. Should I inherit from `List<Department>`, implement an `IList`, `IList<Department>` or another interface, or is there a better way? Ideally I would prefer not to have to implement a custom collection for every type of list I need. Also, will `List[index]` even work with COM Interop?
Thanks,
Mike
Example .NET components (C#):
-----------------------------
```
public class Department {
public string Code { get; private set; }
public string Name { get; private set; }
// ...
}
public class MyLibrary {
public List<Department> GetDepartments() {
// return a list of Departments from the database
}
}
```
Example ASP code:
-----------------
```
<%
Function PrintDepartments(departments)
Dim department
For Each department In departments
Response.Write(department.Code & ": " & department.Name & "<br />")
Next
End Function
Dim myLibrary, departments
Set myLibrary = Server.CreateObject("MyAssembly.MyLibrary")
Set departments = myLibrary.GetDepartments()
%>
<h1>Departments</h1>
<% Call PrintDepartments(departments) %>
<h1>The third department</h1>
<%= departments(2).Name %>
```
Related questions:
------------------
* [Using Generic lists on serviced component](https://stackoverflow.com/questions/161704/using-generic-lists-on-serviced-component)
* [Are non-generic collections in .NET obsolete?](https://stackoverflow.com/questions/56375/are-non-generic-collections-in-net-obsolete)
|
After some more research and trial-and-error, I think I found a solution by using `System.Collections.ArrayList`. However, this does not work with getting a value by index. To do so, I created a new class `ComArrayList` that inherits from `ArrayList` and adds new methods `GetByIndex` and `SetByIndex`.
COM Interop compatible collection:
----------------------------------
```
public class ComArrayList : System.Collections.ArrayList {
public virtual object GetByIndex(int index) {
return base[index];
}
public virtual void SetByIndex(int index, object value) {
base[index] = value;
}
}
```
Updated .NET component MyLibrary.GetDepartments:
------------------------------------------------
```
public ComArrayList GetDepartments() {
// return a list of Departments from the database
}
```
Updated ASP:
------------
```
<h1>The third department</h1>
<%= departments.GetByIndex(2).Name %>
```
|
269,590 |
<p>I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:</p>
<p>It should be (jQuery):</p>
<pre><code>$("asd").bla();
</code></pre>
<p>It was:</p>
<pre><code>("asd").bla();
</code></pre>
<p>(Dollar sign gone missing)</p>
<p>Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"?</p>
<hr>
<p>Update:
I'm using the current version of Firefox (3.0.3).</p>
<p>To reproduce, just use this HTML code:</p>
<pre><code><html><head><title>test</title>
<script>
("asd").bla();
</script>
</head><body></body></html>
</code></pre>
<p>To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...</p>
|
[
{
"answer_id": 269635,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": -1,
"selected": false,
"text": "<p>Assuming it's CodeIngiter, it can't find the js file.</p>\n"
},
{
"answer_id": 269636,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": true,
"text": "<p>I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that <code>bla()</code> is not a function available on the String object. Since you were missing the <code>$</code>, which means you were missing a function, <code>(\"asd\")</code> would evaluate to a string, and then the JavaScript interpreter would try to call <code>bla()</code> on that object. So, if you had the following code in your project:</p>\n\n<pre><code>String.prototype.bla = function() {};\n\n// now this next line will execute without any problems:\n(\"asd\").bla();\n</code></pre>\n\n<p>So, it is possible that <code>Ci</code> is some internal Firefox symbol that simply refers to the idea of a function. That is my guess, I imagine you are going to need someone that knows something about Firefox's internals to get a better answer to this question...</p>\n\n<hr>\n\n<p>UPDATE: I am running your example code in the <em>exact</em> same version of FF as you are, but it reports the error as:</p>\n\n<blockquote>\n <p>Error: \"asd\".bla is not a function<br>\n Source File: file:///C:/test.html<br>\n Line: 3</p>\n</blockquote>\n\n<p>Perhaps you have an extension/plug-in running that does something with this? Maybe some Greasemonkey script or something?</p>\n"
},
{
"answer_id": 269831,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 2,
"selected": false,
"text": "<p>Jason seems to be right. Many plugins (e.g. Firebug, Geode) use Ci as a shortcut:</p>\n\n<pre><code>const Ci = Components.interfaces; \n</code></pre>\n\n<p>So the plugins seem to cause that strange error message.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269590",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
I just spent half an one our to find out what caused the Error-Message "Ci is not defined" in my JavaScript code. I finally found the reason:
It should be (jQuery):
```
$("asd").bla();
```
It was:
```
("asd").bla();
```
(Dollar sign gone missing)
Now after having fixed the problem I'd like to understand the message itself: What does Firefox mean when it tells me that "Ci" is not defined. What's "Ci"?
---
Update:
I'm using the current version of Firefox (3.0.3).
To reproduce, just use this HTML code:
```
<html><head><title>test</title>
<script>
("asd").bla();
</script>
</head><body></body></html>
```
To make it clear: I know what caused the error message. I'd just like to know what Firefox tries to tell me with "Ci"...
|
I don't know which version of FF you are using, but regardless, the message is probably referring to the fact that `bla()` is not a function available on the String object. Since you were missing the `$`, which means you were missing a function, `("asd")` would evaluate to a string, and then the JavaScript interpreter would try to call `bla()` on that object. So, if you had the following code in your project:
```
String.prototype.bla = function() {};
// now this next line will execute without any problems:
("asd").bla();
```
So, it is possible that `Ci` is some internal Firefox symbol that simply refers to the idea of a function. That is my guess, I imagine you are going to need someone that knows something about Firefox's internals to get a better answer to this question...
---
UPDATE: I am running your example code in the *exact* same version of FF as you are, but it reports the error as:
>
> Error: "asd".bla is not a function
>
> Source File: file:///C:/test.html
>
> Line: 3
>
>
>
Perhaps you have an extension/plug-in running that does something with this? Maybe some Greasemonkey script or something?
|
269,594 |
<p>I have a website built using Asp.net and LinqToSql for Data Access. In a certain section of the site, LinqToSql produces a query that looks like this (from my dev machine):</p>
<pre><code>select ...
from table1
left outer join table2 on table1 where ...
left outer join table3 on table2 where ...
</code></pre>
<p>Since the connection between table2 and table1 is not always there, the left outer join is appropriate in this situation. And since the link between table3 and table1 goes through table2, it also needs a left outer join. This sql returns the correct recordset.</p>
<p>I just put the code up to a server. Running the identical code in the same scenario, LinqToSql produces the following query:</p>
<pre><code>select ...
from table1
left outer join table2 on table1 where ...
join table3 on table2 where ...
</code></pre>
<p>For some reason, it renders the join between table2 and table3 as an inner join, instead of an outer join. This results in zero records being returned from the query.</p>
<p>Both dev machine and server are using .Net 3.5 SP1. Dev machine is Vista64, Server is Windows Server 2003 SP2. A colleague of mine using Windows XP PRO also confirmed the same correct behavior on their dev machine. </p>
<p>Can anyone think of a reason why the server would create different sql? How can I fix this? It seems to be something tied into the way that Linq and .Net is running on the server. However, I can't think of any way to confirm and fix this.</p>
<hr>
<p>Linq Code (I am only including the parts that are relevant to the section where the sql changed):</p>
<pre><code>from Import_Table t in db.Import_Tables
select new {
CheckedOutUser = (!t.IsCheckedOut) ? "--" : t.Import_CheckoutHistory.System_User.FirstName + " " + t.Import_CheckoutHistory.System_User.LastName,
CheckedOutUserID = (!t.IsCheckedOut) ? 0 : t.Import_CheckoutHistory.System_UserID};
</code></pre>
<p>In the context of the description above, table1 = Import_Table, table2 = Import_CheckoutHistory, table3 = System_User. If I comment out the line here that begins with "CheckedOutUser = ..." then it works on the server - so this is definitely the culprit.</p>
<p>Actual sql returned:</p>
<pre><code>SELECT
(CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN CONVERT(NVarChar(401),'--') ELSE ([t2].[FirstName] + ' ') + [t2].[LastName] END) AS [CheckedOutUser],
(CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN 0 ELSE [t1].[system_UserID] END) AS [CheckedOutUserID]
FROM [dbo].[import_Table] AS [t0]
LEFT OUTER JOIN [dbo].[import_CheckoutHistory] AS [t1] ON [t1].[import_CheckoutHistoryID] = [t0].[import_CheckoutHistoryID]
LEFT OUTER/INNER JOIN [dbo].[system_User] AS [t2] ON [t2].[system_UserID] = [t1].[system_UserID]
</code></pre>
<p>On the dev machines, the last line begins with "Left outer". On the server, the last line begins with "Inner"</p>
<p><strong>Update:</strong> My solution is <a href="https://stackoverflow.com/questions/269594/linqtosql-producing-different-sql-queries-on-different-machines-for-identical-c#275751">below</a></p>
|
[
{
"answer_id": 269928,
"author": "DamienG",
"author_id": 5720,
"author_profile": "https://Stackoverflow.com/users/5720",
"pm_score": 0,
"selected": false,
"text": "<p>Sounds like the LINQ to SQL classes (DBML and/or associated code generation) between the two is not the same - specifically how the association is defined between these two tables.</p>\n"
},
{
"answer_id": 270015,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Is your production database different to your development one, e.g. SQL Server 2008 instead of 2005? I believe LINQ to SQL will vary the SQL it generates based on the actual execution-time database it's talking to.</p>\n\n<p>Also, are the schemas exactly the same on both databases?</p>\n"
},
{
"answer_id": 275751,
"author": "Yaakov Ellis",
"author_id": 51,
"author_profile": "https://Stackoverflow.com/users/51",
"pm_score": -1,
"selected": true,
"text": "<p>I have checked the following:</p>\n\n<ol>\n<li>Both use the same database</li>\n<li>Both have the identical code</li>\n<li>Both have the identical dbml file</li>\n</ol>\n\n<p>I know that something has to be out of synch somewhere, but I can't find it.</p>\n\n<p>So I have implemented the following workaround: I added a view to my database that includes both left outer joins. This view is now in my dbml file, and in the query above, I reference the view instead of the table. This is working fine.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269594",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/51/"
] |
I have a website built using Asp.net and LinqToSql for Data Access. In a certain section of the site, LinqToSql produces a query that looks like this (from my dev machine):
```
select ...
from table1
left outer join table2 on table1 where ...
left outer join table3 on table2 where ...
```
Since the connection between table2 and table1 is not always there, the left outer join is appropriate in this situation. And since the link between table3 and table1 goes through table2, it also needs a left outer join. This sql returns the correct recordset.
I just put the code up to a server. Running the identical code in the same scenario, LinqToSql produces the following query:
```
select ...
from table1
left outer join table2 on table1 where ...
join table3 on table2 where ...
```
For some reason, it renders the join between table2 and table3 as an inner join, instead of an outer join. This results in zero records being returned from the query.
Both dev machine and server are using .Net 3.5 SP1. Dev machine is Vista64, Server is Windows Server 2003 SP2. A colleague of mine using Windows XP PRO also confirmed the same correct behavior on their dev machine.
Can anyone think of a reason why the server would create different sql? How can I fix this? It seems to be something tied into the way that Linq and .Net is running on the server. However, I can't think of any way to confirm and fix this.
---
Linq Code (I am only including the parts that are relevant to the section where the sql changed):
```
from Import_Table t in db.Import_Tables
select new {
CheckedOutUser = (!t.IsCheckedOut) ? "--" : t.Import_CheckoutHistory.System_User.FirstName + " " + t.Import_CheckoutHistory.System_User.LastName,
CheckedOutUserID = (!t.IsCheckedOut) ? 0 : t.Import_CheckoutHistory.System_UserID};
```
In the context of the description above, table1 = Import\_Table, table2 = Import\_CheckoutHistory, table3 = System\_User. If I comment out the line here that begins with "CheckedOutUser = ..." then it works on the server - so this is definitely the culprit.
Actual sql returned:
```
SELECT
(CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN CONVERT(NVarChar(401),'--') ELSE ([t2].[FirstName] + ' ') + [t2].[LastName] END) AS [CheckedOutUser],
(CASE WHEN NOT ([t0].[IsCheckedOut] = 1) THEN 0 ELSE [t1].[system_UserID] END) AS [CheckedOutUserID]
FROM [dbo].[import_Table] AS [t0]
LEFT OUTER JOIN [dbo].[import_CheckoutHistory] AS [t1] ON [t1].[import_CheckoutHistoryID] = [t0].[import_CheckoutHistoryID]
LEFT OUTER/INNER JOIN [dbo].[system_User] AS [t2] ON [t2].[system_UserID] = [t1].[system_UserID]
```
On the dev machines, the last line begins with "Left outer". On the server, the last line begins with "Inner"
**Update:** My solution is [below](https://stackoverflow.com/questions/269594/linqtosql-producing-different-sql-queries-on-different-machines-for-identical-c#275751)
|
I have checked the following:
1. Both use the same database
2. Both have the identical code
3. Both have the identical dbml file
I know that something has to be out of synch somewhere, but I can't find it.
So I have implemented the following workaround: I added a view to my database that includes both left outer joins. This view is now in my dbml file, and in the query above, I reference the view instead of the table. This is working fine.
|
269,601 |
<p>I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need preserving and I don't want to have a copy of the new with its initial name sticking around. </p>
<p>I have commons lang and io already, so if there's a method I've missed, that would be great.</p>
|
[
{
"answer_id": 269641,
"author": "Michael Myers",
"author_id": 13531,
"author_profile": "https://Stackoverflow.com/users/13531",
"pm_score": 1,
"selected": false,
"text": "<p>Is there a problem with <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html#delete()\" rel=\"nofollow noreferrer\">deleting</a> the old one and <a href=\"http://java.sun.com/javase/6/docs/api/java/io/File.html#renameTo(java.io.File)\" rel=\"nofollow noreferrer\">renaming</a> the new one?</p>\n"
},
{
"answer_id": 269647,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 3,
"selected": true,
"text": "<p>You're going to need to create two <code>java.io.File</code> objects: one for the new file, one for the old file.</p>\n\n<p>Lets call these <code>oldFile</code> and <code>newFile</code>.</p>\n\n<pre><code>oldFile.delete()\nnewFile.renameTo(oldFile);\n</code></pre>\n\n<p>Edit: mmyers beat me to it.</p>\n"
},
{
"answer_id": 269649,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 2,
"selected": false,
"text": "<p><code>Java.io.File.renameTo(java.io.File)</code></p>\n\n<p>You might need to call <code>File.delete()</code> first on the original file first - some systems won't rename a file onto an existing file.</p>\n"
},
{
"answer_id": 269666,
"author": "James Van Huis",
"author_id": 31828,
"author_profile": "https://Stackoverflow.com/users/31828",
"pm_score": 2,
"selected": false,
"text": "<p>This should get you reasonably close:</p>\n\n<pre><code>public boolean replaceOldJar(String originalJarPath, java.io.File newJar) {\n java.io.File originalJar = new java.io.File(originalJarPath);\n if (!originalJar.isFile()) {\n return false;\n }\n boolean deleteOldJarSucceeded = originalJar.delete();\n if (!deleteOldJarSucceeded) {\n return false;\n }\n newJar.renameTo(originalJar);\n return originalJar.exists();\n}\n</code></pre>\n"
},
{
"answer_id": 269670,
"author": "kasperjj",
"author_id": 34240,
"author_profile": "https://Stackoverflow.com/users/34240",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not completely sure if you are asking simply how to rename the file in the filesystem or if you also want to reload this new version of your jar?</p>\n\n<p>The rename part sounds easy... just use File.renameTo... unfortunately, there are many platform specific problems related to doing this. Some platforms will not allow you to overwrite an existing file, others will not allow you to rename a file so it changes location onto another partition. If you want to make the process completely safe, you need to do the process yourself by removing the old file first and then renaming the new (or copying if a partition change is possible). This is naturally prone to problems if your application/machine crashes while doing this, since it is no longer an atomic operation. You will thus need to add a check to your applications startup process that looks for rename operations that were in the middle when the crash occured. If you are just updating a single file in this way, it should be pretty easy.</p>\n\n<p>However, if you actually want to reload the jar, there are a few more issues to thing about, but you would need to give a bit more detailed view of the situation to get proper advice on how to do it.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4893/"
] |
I have a file I need to rename to that of an existing file. This is a copy, modify, replace original operation on an existing JAR file. I've got the first two steps done, I just need help with the replace original bit. What's the best way to rename the new version of the JAR to that of the old. The old JAR doesn't need preserving and I don't want to have a copy of the new with its initial name sticking around.
I have commons lang and io already, so if there's a method I've missed, that would be great.
|
You're going to need to create two `java.io.File` objects: one for the new file, one for the old file.
Lets call these `oldFile` and `newFile`.
```
oldFile.delete()
newFile.renameTo(oldFile);
```
Edit: mmyers beat me to it.
|
269,605 |
<p>I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values.</p>
<p>In this case more than ever an example is worth thousands of words:</p>
<p>Table:</p>
<pre><code>A B C
1 x q
2 y w
3 y e
4 z r
5 z t
6 z y
</code></pre>
<p><em>SQL magic</em></p>
<p>Result:</p>
<pre><code>B C
y w
y e
z r
z t
z y
</code></pre>
<p>Basically it removes all unique values of column B but keeps the multiple rows of the
data kept. I can "group by b" and then "count>1" to get the not distinct but the result will only list one row of B not the 2 or more that I need.</p>
<p>Any help?</p>
<p>Thanks.</p>
|
[
{
"answer_id": 269620,
"author": "a2800276",
"author_id": 27408,
"author_profile": "https://Stackoverflow.com/users/27408",
"pm_score": 2,
"selected": false,
"text": "<pre><code>select \n * \nfrom \n my_table t1, \n my_table t2\nwhere \n t1.B = t2.B\nand\n t1.C != t2.C\n\n-- apparently you need to use <> instead of != in Access\n-- Thanks, Dave!\n</code></pre>\n\n<p>Something like that?</p>\n"
},
{
"answer_id": 269622,
"author": "Paul Morgan",
"author_id": 16322,
"author_profile": "https://Stackoverflow.com/users/16322",
"pm_score": 1,
"selected": false,
"text": "<p>join the unique values of B you determined with group by b and count > 1 back to the original table to retrieve the C values from the table.</p>\n"
},
{
"answer_id": 269671,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 3,
"selected": false,
"text": "<p>Another way of returning the results you want would be this:</p>\n\n<pre><code>select *\nfrom\n my_table\nwhere \n B in \n (select B from my_table group by B having count(*) > 1)\n</code></pre>\n"
},
{
"answer_id": 269708,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 6,
"selected": true,
"text": "<pre><code>Select B, C\nFrom Table\nWhere B In\n (Select B From Table\n Group By B\n Having Count(*) > 1)\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've got an MS access database and I would need to create an SQL query that allows me to select all the not distinct entries in one column while still keeping all the values.
In this case more than ever an example is worth thousands of words:
Table:
```
A B C
1 x q
2 y w
3 y e
4 z r
5 z t
6 z y
```
*SQL magic*
Result:
```
B C
y w
y e
z r
z t
z y
```
Basically it removes all unique values of column B but keeps the multiple rows of the
data kept. I can "group by b" and then "count>1" to get the not distinct but the result will only list one row of B not the 2 or more that I need.
Any help?
Thanks.
|
```
Select B, C
From Table
Where B In
(Select B From Table
Group By B
Having Count(*) > 1)
```
|
269,611 |
<p>"Both DataSource and DataSourceID are defined on 'grdCommunication'. Remove one definition."</p>
<p>I just got this error today, the code has been working until this afternoon I published the latest version to our server and it broke with that error both locally and on the server. I don't use "DataSourceID", the application reads database queries into a datatable and sets the datatable as the DataSource on the GridViews. I did a search in Visual Studio, searching the entire solution and the string "DataSourceID" does not appear in even 1 line of code in the entire solution. This is the first thing that freaked me out. </p>
<p>I figure it had been working yesterday, so I reverted the code to yesterday's build. The error was still there. I kept going back a build, and still the issue is there. I went back a month, I am still getting the same error. This application was working fine this morning? There has really been no code changes, and no where in the application is the DataSourceID EVER set on any of the gridviews. Has anyone ever seen anything like this at all??</p>
<p>How can I get that error if DataSourceID is never set... and the word "DataSourceID" is not in my solution? I just did a wingrep on the entire tree doing a case insensitive search on datasourceid.... pulled up absolutely nothing. That word is absolutely no where in the entire application. </p>
<pre><code> <asp:GridView ID="grdCommunication" runat="server"
Height="130px" Width="100%"
AllowPaging="true" >
... standard grid view column setup here...
</asp:GridView>
// Code behind.. to set the datasource
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
</code></pre>
<p>// Updated: removed some confusing notes. </p>
|
[
{
"answer_id": 269701,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 4,
"selected": true,
"text": "<p>Try this:</p>\n\n<pre><code>DataSet dsActivity = objCompany.GetActivityDetails();\ngrdCommunication.DataSource = dsActivity.Tables[0];\ngrdCommunication.DataBind();\n</code></pre>\n"
},
{
"answer_id": 269718,
"author": "WillCodeForCoffee",
"author_id": 31197,
"author_profile": "https://Stackoverflow.com/users/31197",
"pm_score": 1,
"selected": false,
"text": "<p>tslib is right, don't do:\ngrdCommunication.DataSourceID = null;\nor the string.Empty version. You only use the DataSourceID if you're using a SqlDataSource or ObjectDataSource control for your binding.</p>\n\n<p>It's called \"declarative\" binding because you're using \"declared\" controls from on your page. Binding to controls does not require a call to the DataBind() method.</p>\n\n<p>Because you're DataBinding manually (calling grd.DataBind()) you only set the DataSourrce and then call DataBind().</p>\n"
},
{
"answer_id": 269743,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 2,
"selected": false,
"text": "<p>Holy smoke batman. The Table name was changed causing my Datasource to be no good. But that error message doesn't make any sense in this situation. So technically tsilb's solution will work if I call the table by index instead of by name, so I'll mark his solution as correct. </p>\n\n<p>After reading his post, I tried dsActivity.Tables[\"Activities\"] instead of passing the dataset to the Datasource and the table name to the Datamember, and obviously that didn't work, but If I pass the actual index, which I don't like doing because that index might change, then it is now working. But the messed up part, was that error.. That error was completely off base as to what the problem was. saying that I defined both and to remove one, when in reality, that was not the case. and another really messed up thing, was the table name was only changed to be all upper case... But hey, \"Activities\" is a different key than \"ACTIVITIES\". </p>\n"
},
{
"answer_id": 480840,
"author": "weffey",
"author_id": 13208,
"author_profile": "https://Stackoverflow.com/users/13208",
"pm_score": 0,
"selected": false,
"text": "<p>I ran into the same error, but a totally different problem and solution. In my case, I'm using LINQ to SQL to populate some dropdown lists, then caching the results for further page views. Everything would load fine with a clear cache, and then would error out on subsequent page views.</p>\n\n<pre><code>if (Cache[\"countries\"] != null)\n{\n lbCountries.Items.Clear();\n lbCountries.DataValueField = \"Code\";\n lbCountries.DataTextField = \"Name\";\n lbCountries.DataSource = (Cache[\"countries\"]);\n lbCountries.DataBind();}\nelse\n{\n var lstCountries = from Countries in db_read.Countries orderby Countries.Name select Countries;\n lbCountries.Items.Clear();\n lbCountries.DataValueField = \"Code\";\n lbCountries.DataTextField = \"Name\";\n lbCountries.DataSource = lstCountries.ToList();\n lbCountries.DataBind();\n\n Cache.Add(\"countries\", lstCountries, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);\n}\n</code></pre>\n\n<p>The issue came from:\nCache.Add(\"countries\", <strong>lstCountries</strong>, null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);</p>\n\n<p>When it should have been:\nCache.Add(\"countries\", <strong>lstCountries.ToList(),</strong> null, System.Web.Caching.Cache.NoAbsoluteExpiration, new TimeSpan(0, 240, 0), System.Web.Caching.CacheItemPriority.High, null);</p>\n"
},
{
"answer_id": 652604,
"author": "roman m",
"author_id": 3661,
"author_profile": "https://Stackoverflow.com/users/3661",
"pm_score": 0,
"selected": false,
"text": "<p>I got this error today, turns out that it had nothing to do with DataSourceID, and had everything to do with the DatasSource itself.</p>\n\n<p>I had a problem in my DatasSource , and instead of getting a DatasSource related error, I got this meaningless error.</p>\n\n<p>Make sure you're DatasSource is good, and this error should go away.</p>\n"
},
{
"answer_id": 2201804,
"author": "Jayant Bramhankar",
"author_id": 1439505,
"author_profile": "https://Stackoverflow.com/users/1439505",
"pm_score": 0,
"selected": false,
"text": "<p>always bind dataset with table index to gridview...</p>\n\n<p>ex. gridgrdCommunication.Table[0]; as metioned above by Tsilb</p>\n\n<p>second way you intentionally write..</p>\n\n<p>gridgrdCommunication.DataSourceID = String.Empty; \ngridgrdCommunication.DataSource=ds;\ngridgrdCommunication.DataBind();</p>\n"
},
{
"answer_id": 2638418,
"author": "a52",
"author_id": 52474,
"author_profile": "https://Stackoverflow.com/users/52474",
"pm_score": 0,
"selected": false,
"text": "<p>Check you database structure.... if you are acceding your data throw a dbml file, the table structure in your database it's different of the dbml file structure </p>\n"
},
{
"answer_id": 3522713,
"author": "kjpowers2",
"author_id": 233361,
"author_profile": "https://Stackoverflow.com/users/233361",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using the Object Data Source and want to conditionally reload the grid in code behind you can successfully do this: </p>\n\n<pre><code>Dim datatable As DataTable = dataset.Tables(0)\nDim dataSourceID As String = gvImageFiles.DataSourceID\ngvImageFiles.DataSourceID = Nothing\ngvImageFiles.DataSource = datatable.DefaultView\ngvImageFiles.DataBind()\ngvImageFiles.DataSource = Nothing\ngvImageFiles.DataSourceID = dataSourceID\n</code></pre>\n"
},
{
"answer_id": 12929357,
"author": "Eren",
"author_id": 1752377,
"author_profile": "https://Stackoverflow.com/users/1752377",
"pm_score": 2,
"selected": false,
"text": "<p>Replace this code before this grdCommunication.DataSource = dsActivity;</p>\n\n<pre><code>grdCommunication.DataBind();\ngrdCommunication.DataSourceID=\"\";\n</code></pre>\n"
},
{
"answer_id": 38585136,
"author": "Kristin Kabajwisa",
"author_id": 6414616,
"author_profile": "https://Stackoverflow.com/users/6414616",
"pm_score": 0,
"selected": false,
"text": "<p>You need to chose one way to bind the grid\n <strong>if it is from code behind means using c# code then remove the datasourceid property from grid view from design view of grid\nlike this</strong>\n</p>\n\n<p>//you have to make it like this</p>\n\n<p></p>\n"
},
{
"answer_id": 39211746,
"author": "Mr.Buntha Khin",
"author_id": 551920,
"author_profile": "https://Stackoverflow.com/users/551920",
"pm_score": 0,
"selected": false,
"text": "<p>Please try this:</p>\n\n<blockquote>\n <p>gvCustomerInvoiceList.DataSourceID = \"\"; \n gvCustomerInvoiceList.DataSource = ci_data; \n gvCustomerInvoiceList.DataBind();</p>\n</blockquote>\n"
},
{
"answer_id": 46094277,
"author": "amby",
"author_id": 6359807,
"author_profile": "https://Stackoverflow.com/users/6359807",
"pm_score": 0,
"selected": false,
"text": "<p>I got this error today. It turns out that my stored procedure did not return neither any record nor a structure. This was because I had an empty <code>try catch</code> without a <code>raiserror</code>.</p>\n"
},
{
"answer_id": 48396372,
"author": "aries",
"author_id": 9255449,
"author_profile": "https://Stackoverflow.com/users/9255449",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load\n Page.DataBind()\nEnd Sub\nFunction GetData()\n Dim dt As New DataTable\n Try\n\n dt.Columns.Add(\"ROOM_ID\", GetType(String))\n dt.Columns.Add(\"SCHED_ID\", GetType(String))\n dt.Columns.Add(\"TIME_START\", GetType(Date))\n dt.Columns.Add(\"TIME_END\", GetType(Date))\n\n\n Dim dr As DataRow = dt.NewRow\n\n dr(\"ROOM_ID\") = \"Indocin\"\n dr(\"SCHED_ID\") = \"David\"\n dr(\"TIME_START\") = \"2018-01-03 09:00:00.000\"\n dr(\"TIME_END\") = \"2018-01-03 12:00:00.000\"\n dt.Rows.Add(dr)\n\n\n Catch ex As Exception\n MsgBox(ex.ToString)\n End Try\n Return dt\nEnd Function\n</code></pre>\n\n<p>and add this to your item DataSource=\"<%# GetData() %>\" </p>\n"
},
{
"answer_id": 57583895,
"author": "David Nelson",
"author_id": 629472,
"author_profile": "https://Stackoverflow.com/users/629472",
"pm_score": 0,
"selected": false,
"text": "<p>In my case the connection string to the database was not working. Fixing the connection string got rid of this error.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18893/"
] |
"Both DataSource and DataSourceID are defined on 'grdCommunication'. Remove one definition."
I just got this error today, the code has been working until this afternoon I published the latest version to our server and it broke with that error both locally and on the server. I don't use "DataSourceID", the application reads database queries into a datatable and sets the datatable as the DataSource on the GridViews. I did a search in Visual Studio, searching the entire solution and the string "DataSourceID" does not appear in even 1 line of code in the entire solution. This is the first thing that freaked me out.
I figure it had been working yesterday, so I reverted the code to yesterday's build. The error was still there. I kept going back a build, and still the issue is there. I went back a month, I am still getting the same error. This application was working fine this morning? There has really been no code changes, and no where in the application is the DataSourceID EVER set on any of the gridviews. Has anyone ever seen anything like this at all??
How can I get that error if DataSourceID is never set... and the word "DataSourceID" is not in my solution? I just did a wingrep on the entire tree doing a case insensitive search on datasourceid.... pulled up absolutely nothing. That word is absolutely no where in the entire application.
```
<asp:GridView ID="grdCommunication" runat="server"
Height="130px" Width="100%"
AllowPaging="true" >
... standard grid view column setup here...
</asp:GridView>
// Code behind.. to set the datasource
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity;
grdCommunication.DataBind();
```
// Updated: removed some confusing notes.
|
Try this:
```
DataSet dsActivity = objCompany.GetActivityDetails();
grdCommunication.DataSource = dsActivity.Tables[0];
grdCommunication.DataBind();
```
|
269,632 |
<p>Upon a click on an IMG, I would like to get to the next subsequent DIV so that the DIVs content can either be displayed or hidden depending on its current display state.</p>
<p>This is an HTML snippet:</p>
<pre><code><div>
<span class="expand"><img src="images/plus.gif"></span>
<span>Subject Heading</span>
</div>
<div class="record hidden">Display or Hide this text</div>
</code></pre>
<p>I have some code (<a href="https://stackoverflow.com/questions/123401/using-jquery-to-find-the-next-table-row#123518">provided in another answer on this site</a>) for doing this in a table. Would I set an event listener for the img or the containing span? not sure how to use parent(), next(), sibling() functions to get around....</p>
<p>Also, how do you test if your navigation is getting to the right element? can you use an alert to display the id or value?</p>
<p>Any help is appreciated
Thanks</p>
|
[
{
"answer_id": 269681,
"author": "WillCodeForCoffee",
"author_id": 31197,
"author_profile": "https://Stackoverflow.com/users/31197",
"pm_score": 1,
"selected": false,
"text": "<p>One good place to look is in the Visual jQuery Docs under selectors: <a href=\"http://screencasts.visualjquery.com/\" rel=\"nofollow noreferrer\">http://screencasts.visualjquery.com/</a></p>\n\n<p>I think you're trying to do something like</p>\n\n<p>$(this).parent().next('.hidden');</p>\n\n<p>inside your onClick function?</p>\n\n<p>Hope that helps!</p>\n"
},
{
"answer_id": 269691,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 0,
"selected": false,
"text": "<p>You have several options:</p>\n\n<pre><code>$('.expand').click(function () {\n $(\".record\").toggle();\n});\n</code></pre>\n\n<p>or</p>\n\n<pre><code>$('.expand').click(function () {\n $(\".record\").slideToggle(\"slow\");\n});\n</code></pre>\n\n<p>Though if you're going to be targeting the next div based on it's relevance to the clicked img, then you'll need to target it with .parent('span').parent('div').next('record')</p>\n"
},
{
"answer_id": 269697,
"author": "Allain Lalonde",
"author_id": 2443,
"author_profile": "https://Stackoverflow.com/users/2443",
"pm_score": 2,
"selected": false,
"text": "<p>A cleaner approach is to toggle the image's parent's class between collapsed and expanded then in your css you can use contextual selectors to hide nested divs within collapsed ones.</p>\n\n<p>Just my 2 cents.</p>\n"
},
{
"answer_id": 269711,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 3,
"selected": true,
"text": "<p>Here's a working example:</p>\n\n<pre><code><script type=\"text/javascript\" src=\"../jquery-1.2.6.min.js\"></script>\n\n<div>\n <span class=\"expand\"><img src=\"x.jpg\"></span>\n <span>Subject Heading</span>\n</div>\n<div class=\"record hidden\">Display or Hide this text</div>\n\n<script type=\"text/javascript\">\n $(document).ready(function(){\n $('.expand img').toggle(\n function(){\n $(this).parent().parent().next().hide();\n },\n function(){\n $(this).parent().parent().next().show();\n });\n });\n</script>\n</code></pre>\n\n<p>Note that I'm using parent twice because the event is added to the image, whose parent is the span, whose parent is the div.</p>\n"
},
{
"answer_id": 269719,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 1,
"selected": false,
"text": "<p>Allain is correct, it is better to operate only on the parent, then use CSS selectors to show or hide the children, flip +/- images, etc. But anyway, <a href=\"http://rome.purepistos.net/tmp/sof-269632.html\" rel=\"nofollow noreferrer\">here</a> is functional code that does what you want in the way you were wondering:</p>\n\n<pre><code><html>\n\n<head>\n\n <script type=\"text/javascript\" src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js\"></script>\n <script type=\"text/javascript\">\n $( document ).ready( function() {\n $( '.expand img' ).click(\n function() {\n $(this).parents( 'div' ).eq( 0 ).siblings( '.record' ).eq( 0 ).toggleClass( 'hidden' );\n }\n );\n } );\n </script>\n\n <style type=\"text/css\">\n .hidden {\n display: none;\n }\n </style>\n\n</head>\n\n<body>\n\n <div>\n <span class=\"expand\"><img src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\"></span>\n <span>Subject Heading</span>\n </div>\n <div class=\"other\">Don't care about this</div>\n <div class=\"record hidden\">Display or Hide this text</div>\n\n</body>\n\n</html>\n</code></pre>\n"
},
{
"answer_id": 269815,
"author": "Jay Corbett",
"author_id": 2755,
"author_profile": "https://Stackoverflow.com/users/2755",
"pm_score": 1,
"selected": false,
"text": "<p>This is what I am using currently, thanks Adam...but I will explore Allain's suggestion as well.</p>\n\n<pre><code>$(function(){\n$('.expand img').toggle(\n function(){\n $(this).parent().parent().next().show();\n $(this).attr('src', 'images/minus.gif') ;\n },\n function(){\n $(this).parent().parent().next().hide();\n $(this).attr('src', 'images/plus.gif') ;\n });\n});\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269632",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2755/"
] |
Upon a click on an IMG, I would like to get to the next subsequent DIV so that the DIVs content can either be displayed or hidden depending on its current display state.
This is an HTML snippet:
```
<div>
<span class="expand"><img src="images/plus.gif"></span>
<span>Subject Heading</span>
</div>
<div class="record hidden">Display or Hide this text</div>
```
I have some code ([provided in another answer on this site](https://stackoverflow.com/questions/123401/using-jquery-to-find-the-next-table-row#123518)) for doing this in a table. Would I set an event listener for the img or the containing span? not sure how to use parent(), next(), sibling() functions to get around....
Also, how do you test if your navigation is getting to the right element? can you use an alert to display the id or value?
Any help is appreciated
Thanks
|
Here's a working example:
```
<script type="text/javascript" src="../jquery-1.2.6.min.js"></script>
<div>
<span class="expand"><img src="x.jpg"></span>
<span>Subject Heading</span>
</div>
<div class="record hidden">Display or Hide this text</div>
<script type="text/javascript">
$(document).ready(function(){
$('.expand img').toggle(
function(){
$(this).parent().parent().next().hide();
},
function(){
$(this).parent().parent().next().show();
});
});
</script>
```
Note that I'm using parent twice because the event is added to the image, whose parent is the span, whose parent is the div.
|
269,653 |
<p>Does anybody know if there is a way to make autocompletion work in MySQL Command Line Client under Windows? It's working nicely under Linux for me, but simply moves the cursor under Windows instead.</p>
|
[
{
"answer_id": 269750,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 5,
"selected": true,
"text": "<p>It ought to work this way:</p>\n\n<pre><code>C:\\> mysql --auto-rehash\n</code></pre>\n\n<p>Or configure your my.cnf:</p>\n\n<pre><code>[mysql]\nauto-rehash\n</code></pre>\n\n<p><strong>edit:</strong> My apologies. I have found some references that the tab-completion feature in mysql client works only on UNIX/Linux. It does not work on Windows.</p>\n\n<p><strong>update:</strong> The reason for this is mentioned briefly in MySQL <a href=\"http://bugs.mysql.com/bug.php?id=4731\" rel=\"noreferrer\">bug #4731</a>:</p>\n\n<blockquote>\n <p>[31 Jul 2004 12:47] Sergei Golubchik </p>\n \n <p>I just downloaded 4.0.15 - command\n completion in mysql.exe is NOT\n working, as expected. It was never\n working in mysql.exe because we were\n not able to make readline to compile\n with VC++. </p>\n \n <p>mysqlc.exe is a cygwin build, and it is linked with readline.</p>\n</blockquote>\n\n<p>Explanation: <a href=\"http://en.wikipedia.org/wiki/GNU_readline\" rel=\"noreferrer\">GNU readline</a> is a standard open-source library for handling user input. The MySQL team uses the readline library, but they are not its author. From the above comment, I understand that they were unsuccessful in compiling the readline library on Windows with Microsoft Visual C++, the tool they use to build the MySQL product. Some open-source projects have not been made fully compatible with the Microsoft Windows environment.</p>\n\n<p>At one time in the past, the MySQL product provided an alternative client they called <code>mysqlc.exe</code>, which they compiled with the <a href=\"http://www.cygwin.com/\" rel=\"noreferrer\">cygwin</a> toolset on Windows, but they don't provide this anymore. The cygwin toolset includes the readline library, so it was possible to compile the <code>mysqlc.exe</code> client with support for tab-completion.</p>\n\n<p>So in theory, if you are really intrepid, you could download the cygwin toolset including the readline library, then download the MySQL source code and build it using cygwin. Then you should have a mysql client program that can perform tab-completion. But this sounds like a lot of work even for someone who is familiar with building MySQL from source.</p>\n"
},
{
"answer_id": 270691,
"author": "AngryHacker",
"author_id": 9382,
"author_profile": "https://Stackoverflow.com/users/9382",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably not what you are looking for, but the enterprise version of SQLYog offers a somewhat limited schema auto-completion.</p>\n"
},
{
"answer_id": 48806454,
"author": "paka",
"author_id": 3708589,
"author_profile": "https://Stackoverflow.com/users/3708589",
"pm_score": 1,
"selected": false,
"text": "<p>If above dosen't work and you use widnows 10 you can install linux shell, then install mysql-client and connect like in terminal in linux where autocomplite works.</p>\n\n<p>Instruction:\n<a href=\"https://learn.microsoft.com/en-us/windows/wsl/install-win10\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/en-us/windows/wsl/install-win10</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9777/"
] |
Does anybody know if there is a way to make autocompletion work in MySQL Command Line Client under Windows? It's working nicely under Linux for me, but simply moves the cursor under Windows instead.
|
It ought to work this way:
```
C:\> mysql --auto-rehash
```
Or configure your my.cnf:
```
[mysql]
auto-rehash
```
**edit:** My apologies. I have found some references that the tab-completion feature in mysql client works only on UNIX/Linux. It does not work on Windows.
**update:** The reason for this is mentioned briefly in MySQL [bug #4731](http://bugs.mysql.com/bug.php?id=4731):
>
> [31 Jul 2004 12:47] Sergei Golubchik
>
>
> I just downloaded 4.0.15 - command
> completion in mysql.exe is NOT
> working, as expected. It was never
> working in mysql.exe because we were
> not able to make readline to compile
> with VC++.
>
>
> mysqlc.exe is a cygwin build, and it is linked with readline.
>
>
>
Explanation: [GNU readline](http://en.wikipedia.org/wiki/GNU_readline) is a standard open-source library for handling user input. The MySQL team uses the readline library, but they are not its author. From the above comment, I understand that they were unsuccessful in compiling the readline library on Windows with Microsoft Visual C++, the tool they use to build the MySQL product. Some open-source projects have not been made fully compatible with the Microsoft Windows environment.
At one time in the past, the MySQL product provided an alternative client they called `mysqlc.exe`, which they compiled with the [cygwin](http://www.cygwin.com/) toolset on Windows, but they don't provide this anymore. The cygwin toolset includes the readline library, so it was possible to compile the `mysqlc.exe` client with support for tab-completion.
So in theory, if you are really intrepid, you could download the cygwin toolset including the readline library, then download the MySQL source code and build it using cygwin. Then you should have a mysql client program that can perform tab-completion. But this sounds like a lot of work even for someone who is familiar with building MySQL from source.
|
269,660 |
<p>Does anyone know how to iterate over a generic list if the type of that list isn't known until runtime?</p>
<p>For example, assume <code>obj1</code> is passed into a function as an <code>Object</code>:</p>
<pre><code>Dim t As Type = obj1.GetType
If t.IsGenericType Then
Dim typeParameters() As Type = t.GetGenericArguments()
Dim typeParam As Type = typeParameters(0)
End If
</code></pre>
<p>If <code>obj</code> is passed as a <code>List(Of String)</code> then using the above I can determine that a generic list (<code>t</code>) was passed and that it's of type <code>String</code> (<code>typeParam</code>). I know I am making a big assumption that there is only one generic parameter, but that's fine for this simple example.</p>
<p>What I'd like to know is, based on the above, how do I do something like this:</p>
<pre><code>For Each item As typeParam In obj1
'do something with it here
Next
</code></pre>
<p>Or even something as simple as getting <code>obj1.Count()</code>.</p>
|
[
{
"answer_id": 269716,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": true,
"text": "<p>If you know that obj is a <a href=\"http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx\" rel=\"nofollow noreferrer\">Generic List</a>. Then you're in luck.</p>\n\n<p>Generic List implements IList and IEnumerable (both are non-generic). So you could cast to either of those interfaces and then For Each over them.</p>\n\n<ul>\n<li>IList has a count property.</li>\n<li>IList also has a Cast method. If you don't know the type to cast to, use object. This will give you an IEnumerable(Of object) that you can then start using Linq against.</li>\n</ul>\n"
},
{
"answer_id": 269807,
"author": "Todd",
"author_id": 2572,
"author_profile": "https://Stackoverflow.com/users/2572",
"pm_score": 2,
"selected": false,
"text": "<p>The method that iterates over your list can specify a generic type:</p>\n\n<pre><code>Public Sub Foo(Of T)(list As List(Of T))\n For Each obj As T In list\n ..do something with obj..\n Next\nEnd Sub\n</code></pre>\n\n<p>So then you can call:</p>\n\n<pre><code>Dim list As New List(Of String)\nFoo(Of String)(list)\n</code></pre>\n\n<p>This method makes the code look a little hairy, at least in VB.NET. </p>\n\n<p>The same thing can be accomplished if you have the objects that are in the list implement a specific interface. That way you can populate the list with any object type as long as they implement the interface, the iteration method would only work on the common values between the object types.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269660",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12842/"
] |
Does anyone know how to iterate over a generic list if the type of that list isn't known until runtime?
For example, assume `obj1` is passed into a function as an `Object`:
```
Dim t As Type = obj1.GetType
If t.IsGenericType Then
Dim typeParameters() As Type = t.GetGenericArguments()
Dim typeParam As Type = typeParameters(0)
End If
```
If `obj` is passed as a `List(Of String)` then using the above I can determine that a generic list (`t`) was passed and that it's of type `String` (`typeParam`). I know I am making a big assumption that there is only one generic parameter, but that's fine for this simple example.
What I'd like to know is, based on the above, how do I do something like this:
```
For Each item As typeParam In obj1
'do something with it here
Next
```
Or even something as simple as getting `obj1.Count()`.
|
If you know that obj is a [Generic List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx). Then you're in luck.
Generic List implements IList and IEnumerable (both are non-generic). So you could cast to either of those interfaces and then For Each over them.
* IList has a count property.
* IList also has a Cast method. If you don't know the type to cast to, use object. This will give you an IEnumerable(Of object) that you can then start using Linq against.
|
269,676 |
<p>I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.</p>
<p>Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?</p>
<p>system info:</p>
<ul>
<li>MySQL 5.0.19 </li>
<li>Client 5.1.11 </li>
<li>Windows XP</li>
<li>Python 2.4 / MySQLdb 1.2.1 p2</li>
</ul>
|
[
{
"answer_id": 270449,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 1,
"selected": false,
"text": "<p>you can always run LOCK TABLE tablename from another session (mysql CLI for instance). That might do the trick.</p>\n\n<p>It will remain locked until you release it or disconnect the session.</p>\n"
},
{
"answer_id": 270492,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not familar with Python, so excuse my incorrect language If I'm saying this wrong... but open two sessions (in separate windows, or from separate Python processes - from separate boxes would work ... ) Then ... </p>\n\n<p>. In Session A:</p>\n\n<pre><code> Begin Transaction \n Insert TableA() Values()... \n</code></pre>\n\n<p>. Then In Session B:</p>\n\n<pre><code>Begin Transaction\n Insert TableB() Values()... \n Insert TableA() Values() ...\n</code></pre>\n\n<p>. Then go back to session A</p>\n\n<pre><code> Insert TableB() Values () ...\n</code></pre>\n\n<p>You'll get a deadlock... </p>\n"
},
{
"answer_id": 271789,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 1,
"selected": false,
"text": "<p>You want something along the following lines.</p>\n\n<p><strong>parent.py</strong></p>\n\n<pre><code>import subprocess\nc1= subprocess.Popen( [\"python\", \"child.py\", \"1\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE )\nc2= subprocess.Popen( [\"python\", \"child.py\", \"2\"], stdin=subprocess.PIPE, stdout=subprocess.PIPE )\nout1, err1= c1.communicate( \"to 1: hit it!\" )\nprint \" 1:\", repr(out1)\nprint \"*1:\", repr(err1)\nout2, err2= c2.communicate( \"to 2: ready, set, go!\" )\nprint \" 2:\", repr(out2)\nprint \"*2:\", repr(err2)\nout1, err1= c1.communicate()\nprint \" 1:\", repr(out1)\nprint \"*1:\", repr(err1)\nout2, err2= c2.communicate()\nprint \" 2:\", repr(out2)\nprint \"*2:\", repr(err2)\nc1.wait()\nc2.wait()\n</code></pre>\n\n<p><strong>child.py</strong></p>\n\n<pre><code>import yourDBconnection as dbapi2\n\ndef child1():\n print \"Child 1 start\"\n conn= dbapi2.connect( ... )\n c1= conn.cursor()\n conn.begin() # turn off autocommit, start a transaction\n ra= c1.execute( \"UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'\" )\n print ra\n print \"Child1\", raw_input()\n rb= c1.execute( \"UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'\" )\n print rb\n c1.close()\n print \"Child 1 finished\"\n\ndef child2():\n print \"Child 2 start\"\n conn= dbapi2.connect( ... )\n c1= conn.cursor()\n conn.begin() # turn off autocommit, start a transaction\n rb= c1.execute( \"UPDATE B SET BC1='Bchgd' WHERE BC1='BC1-1'\" )\n print rb\n print \"Child2\", raw_input()\n ra= c1.execute( \"UPDATE A SET AC1='Achgd' WHERE AC1='AC1-1'\" )\n print ta\n c1.close()\n print \"Child 2 finish\"\n\ntry:\n if sys.argv[1] == \"1\":\n child1()\n else:\n child2()\nexcept Exception, e:\n print repr(e)\n</code></pre>\n\n<p>Note the symmetry. Each child starts out holding one resource. Then they attempt to get someone else's held resource. You can, for fun, have 3 children and 3 resources for a really vicious circle.</p>\n\n<p>Note that difficulty in contriving a situation in which deadlock occurs. If your transactions are short -- and consistent -- deadlock is very difficult to achieve. Deadlock requires (a) transaction which hold locks for a long time AND (b) transactions which acquire locks in an inconsistent order. I have found it easiest to prevent deadlocks by keeping my transactions short and consistent.</p>\n\n<p>Also note the non-determinism. You can't predict which child will die with a deadlock and which will continue after the other died. Only one of the two need to die to release needed resources for the other. Some RDBMS's claim that there's a rule based on number of resources held blah blah blah, but in general, you'll never know how the victim was chosen.</p>\n\n<p>Because of the two writes being in a specific order, you sort of expect child 1 to die first. However, you can't guarantee that. It's not deadlock until child 2 tries to get child 1's resources -- the sequence of who acquired first may not determine who dies.</p>\n\n<p>Also note that these are processes, not threads. Threads -- because of the Python GIL -- might be inadvertently synchronized and would require lots of calls to <code>time.sleep( 0.001 )</code> to give the other thread a chance to catch up. Processes -- for this -- are slightly simpler because they're fully independent.</p>\n"
},
{
"answer_id": 1468676,
"author": "noonex",
"author_id": 102484,
"author_profile": "https://Stackoverflow.com/users/102484",
"pm_score": 1,
"selected": false,
"text": "<p>Not sure if either above is correct.\nCheck out this:</p>\n\n<p><a href=\"http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/\" rel=\"nofollow noreferrer\">http://www.xaprb.com/blog/2006/08/08/how-to-deliberately-cause-a-deadlock-in-mysql/</a></p>\n"
},
{
"answer_id": 8100573,
"author": "leiavoia",
"author_id": 1042374,
"author_profile": "https://Stackoverflow.com/users/1042374",
"pm_score": 2,
"selected": false,
"text": "<p>Here's some pseudocode for how i do it in PHP:</p>\n\n<p>Script 1:</p>\n\n<pre><code>START TRANSACTION;\nINSERT INTO table <anything you want>;\nSLEEP(5);\nUPDATE table SET field = 'foo';\nCOMMIT;\n</code></pre>\n\n<p>Script 2:</p>\n\n<pre><code>START TRANSACTION;\nUPDATE table SET field = 'foo';\nSLEEP(5);\nINSERT INTO table <anything you want>;\nCOMMIT;\n</code></pre>\n\n<p>Execute script 1 and then immediately execute script 2 in another terminal. You'll get a deadlock if the database table already has some data in it (In other words, it starts deadlocking after the second time you try this).</p>\n\n<p>Note that if mysql won't honor the SLEEP() command, use Python's equivalent in the application itself.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13009/"
] |
I want to make my Python library working with MySQLdb be able to detect deadlocks and try again. I believe I've coded a good solution, and now I want to test it.
Any ideas for the simplest queries I could run using MySQLdb to create a deadlock condition would be?
system info:
* MySQL 5.0.19
* Client 5.1.11
* Windows XP
* Python 2.4 / MySQLdb 1.2.1 p2
|
Here's some pseudocode for how i do it in PHP:
Script 1:
```
START TRANSACTION;
INSERT INTO table <anything you want>;
SLEEP(5);
UPDATE table SET field = 'foo';
COMMIT;
```
Script 2:
```
START TRANSACTION;
UPDATE table SET field = 'foo';
SLEEP(5);
INSERT INTO table <anything you want>;
COMMIT;
```
Execute script 1 and then immediately execute script 2 in another terminal. You'll get a deadlock if the database table already has some data in it (In other words, it starts deadlocking after the second time you try this).
Note that if mysql won't honor the SLEEP() command, use Python's equivalent in the application itself.
|
269,692 |
<p>I have a clock feature in a VB.NET program that displays the time including the seconds. I currently have a timer constantly polling using NOW. I have to poll the system clock quite often because I need to have the second update in sync with the system clock.</p>
<p>Is there a more direct to access the time only when the seconds change?</p>
<p>Is there a more efficient way to write this code?</p>
<p>If you need more info let me know.</p>
|
[
{
"answer_id": 269738,
"author": "Jason Z",
"author_id": 2470,
"author_profile": "https://Stackoverflow.com/users/2470",
"pm_score": 4,
"selected": true,
"text": "<p>Why not use the timer component? This assumes that you are using a GUI and not building a service.</p>\n\n<p>You could call a synchronization routine that performed the polling to get the timer very close to the seconds changing, then delegate to the timer. You could call the sync routine once a minute or so to make sure that you aren't getting any OS drift.</p>\n\n<p>That being said, I'm sure there is a way to detect the seconds changing event, I just don't know how to do it.</p>\n\n<p>Update:</p>\n\n<p><a href=\"http://en.csharp-online.net/Delegates_and_Events%E2%80%94Events_and_Delegates\" rel=\"noreferrer\">This link</a> has an implementation similar to what I was envisioning. Just modify it so that you are not permanently stuck in a loop and voila! You have your sync routine.</p>\n\n<p>Update 2:</p>\n\n<p>Based on feedback from Shog9, I think this might be a better approach than polling:</p>\n\n<pre><code>Public Class Form1\n Private WithEvents clockTimer As New Timer\n Private currentTime As DateTime = DateTime.MinValue\n\n Private Sub ClockTick(ByVal sender As Object, _\n ByVal e As System.EventArgs) Handles clockTimer.Tick\n\n UpdateTimer()\n DisplayTimer()\n End Sub\n\n Private Sub UpdateTimer()\n currentTime = DateTime.Now\n\n clockTimer.Stop()\n clockTimer.Interval = 1000 - currentTime.Millisecond\n clockTimer.Start()\n End Sub\n\n Private Sub DisplayTimer()\n lblTime.Text = currentTime.ToString(\"T\")\n End Sub\n\n Private Sub Form1_Load(ByVal sender As System.Object, _\n ByVal e As System.EventArgs) Handles MyBase.Load\n\n UpdateTimer()\n DisplayTimer()\n End Sub\nEnd Class\n</code></pre>\n\n<p>Now, based on my preliminary tests, there is some sort of drift with each Tick event. On my machine, it varied between 12 and 20 milliseconds. If anyone has an idea on how to reliably correct the drift, I would be interested in learning.</p>\n"
},
{
"answer_id": 269867,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 0,
"selected": false,
"text": "<p>Use a Timer object, set it's \"interval\" to 0, set it's \"enabled\" to true. That will fire roughly every 15 milliseconds (based on your hardware configuration). In that method, set MyLabel.Text = DateTime.Now.ToString() (or whatever you're doing).</p>\n\n<p>That is perfectly performant.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4856/"
] |
I have a clock feature in a VB.NET program that displays the time including the seconds. I currently have a timer constantly polling using NOW. I have to poll the system clock quite often because I need to have the second update in sync with the system clock.
Is there a more direct to access the time only when the seconds change?
Is there a more efficient way to write this code?
If you need more info let me know.
|
Why not use the timer component? This assumes that you are using a GUI and not building a service.
You could call a synchronization routine that performed the polling to get the timer very close to the seconds changing, then delegate to the timer. You could call the sync routine once a minute or so to make sure that you aren't getting any OS drift.
That being said, I'm sure there is a way to detect the seconds changing event, I just don't know how to do it.
Update:
[This link](http://en.csharp-online.net/Delegates_and_Events%E2%80%94Events_and_Delegates) has an implementation similar to what I was envisioning. Just modify it so that you are not permanently stuck in a loop and voila! You have your sync routine.
Update 2:
Based on feedback from Shog9, I think this might be a better approach than polling:
```
Public Class Form1
Private WithEvents clockTimer As New Timer
Private currentTime As DateTime = DateTime.MinValue
Private Sub ClockTick(ByVal sender As Object, _
ByVal e As System.EventArgs) Handles clockTimer.Tick
UpdateTimer()
DisplayTimer()
End Sub
Private Sub UpdateTimer()
currentTime = DateTime.Now
clockTimer.Stop()
clockTimer.Interval = 1000 - currentTime.Millisecond
clockTimer.Start()
End Sub
Private Sub DisplayTimer()
lblTime.Text = currentTime.ToString("T")
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
UpdateTimer()
DisplayTimer()
End Sub
End Class
```
Now, based on my preliminary tests, there is some sort of drift with each Tick event. On my machine, it varied between 12 and 20 milliseconds. If anyone has an idea on how to reliably correct the drift, I would be interested in learning.
|
269,713 |
<p>We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.</p>
<p>These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password':</p>
<blockquote>
<p>joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA=</p>
</blockquote>
<p>I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format:</p>
<p>[algo]$[salt]$[hash]</p>
<p>Where the salt is a plain string and the hash is the hex digest of an SHA1 hash.</p>
<p>So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings.</p>
<p>We've used reflector to glean how ASP authenticates against these values:</p>
<pre><code>internal string EncodePassword(string pass, int passwordFormat, string salt)
{
if (passwordFormat == 0)
{
return pass;
}
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
byte[] inArray = null;
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
if (passwordFormat == 1)
{
HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
if ((algorithm == null) && Membership.IsHashAlgorithmFromMembershipConfig)
{
RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException();
}
inArray = algorithm.ComputeHash(dst);
}
else
{
inArray = this.EncryptPassword(dst);
}
return Convert.ToBase64String(inArray);
}
</code></pre>
<p>Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first.</p>
<p>It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database.</p>
<p>I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing:</p>
<pre><code>import hashlib
from base64 import b64decode, b64encode
b64salt = "kDP0Py2QwEdJYtUX9cJABg=="
b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA="
binsalt = b64decode(b64salt)
password_string = 'password'
m1 = hashlib.sha1()
# Pass in salt
m1.update(binsalt)
# Pass in password
m1.update(password_string)
# B64 encode the binary digest
if b64encode(m1.digest()) == b64hash:
print "Logged in!"
else:
print "Didn't match"
print b64hash
print b64encode(m1.digest())
</code></pre>
<p>I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?</p>
|
[
{
"answer_id": 269888,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 0,
"selected": false,
"text": "<p>Two thoughts as to what could be going wrong.</p>\n\n<p>First the code from the reflection has three paths:</p>\n\n<ul>\n<li>If passwordFormat is 0 it returns the password as is.</li>\n<li>If passwordFormat is 1 it creates the hash as your python code does.</li>\n<li>If passwordFormat is anything other than 0 or 1 it calls this.EncryptPassword()</li>\n</ul>\n\n<p>How do you know you are hashing the password, and not encrypting the password with this.EncryptPassword()? You may need to reverse the EncryptPassword() member function and replicate that. That is unless you have some information which ensures that you are hashing the password and not encrypting it.</p>\n\n<p>Second if it is indeed hashing the password you may want to see what the Encoding.Unicode.GetBytes() function returns for the string \"password\", as you may be getting something back like:</p>\n\n<pre><code>0x00 0x70 0x00 0x61 0x00 0x73 0x00 0x73 0x00 0x77 0x00 0x6F 0x00 0x72 0x00 0x64\n</code></pre>\n\n<p>instead of:</p>\n\n<pre><code>0x70 0x61 0x73 0x73 0x77 0x6F 0x72 0x64\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 270670,
"author": "MrKurt",
"author_id": 35296,
"author_profile": "https://Stackoverflow.com/users/35296",
"pm_score": 4,
"selected": true,
"text": "<p>It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary.</p>\n\n<p>There may be a better way to rip out the BOM, but this works for me!</p>\n\n<p>Here's one that passes:</p>\n\n<pre><code>import hashlib\nfrom base64 import b64decode, b64encode\n\ndef utf16tobin(s):\n return s.encode('hex')[4:].decode('hex')\n\nb64salt = \"kDP0Py2QwEdJYtUX9cJABg==\"\nb64hash = \"OJF6H4KdxFLgLu+oTDNFodCEfMA=\"\nbinsalt = b64decode(b64salt)\npassword_string = 'password'.encode(\"utf16\")\npassword_string = utf16tobin(password_string)\n\nm1 = hashlib.sha1()\n# Pass in salt\nm1.update(binsalt + password_string)\n# Pass in password\n# B64 encode the binary digest\nif b64encode(m1.digest()) == b64hash:\n print \"Logged in!\"\nelse:\n print \"Didn't match\"\n print b64hash\n print b64encode(m1.digest())\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269713",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13668/"
] |
We have a current application where user login credentials are stored in a SQL Server DB. These are, basically, stored as a plain text username, a password hash, and an associated salt for this hash.
These were all created by built in functions in ASP.NET's membership/role system. Here's a row for a user named 'joe' and a password of 'password':
>
> joe,kDP0Py2QwEdJYtUX9cJABg==,OJF6H4KdxFLgLu+oTDNFodCEfMA=
>
>
>
I've dumped this stuff into a CSV file and I'm attempting to get it into a usable format for Django which stores its passwords in this format:
[algo]$[salt]$[hash]
Where the salt is a plain string and the hash is the hex digest of an SHA1 hash.
So far I've been able to ascertain that ASP is storing these hashes and salts in a base64 format. Those values above decode into binary strings.
We've used reflector to glean how ASP authenticates against these values:
```
internal string EncodePassword(string pass, int passwordFormat, string salt)
{
if (passwordFormat == 0)
{
return pass;
}
byte[] bytes = Encoding.Unicode.GetBytes(pass);
byte[] src = Convert.FromBase64String(salt);
byte[] dst = new byte[src.Length + bytes.Length];
byte[] inArray = null;
Buffer.BlockCopy(src, 0, dst, 0, src.Length);
Buffer.BlockCopy(bytes, 0, dst, src.Length, bytes.Length);
if (passwordFormat == 1)
{
HashAlgorithm algorithm = HashAlgorithm.Create(Membership.HashAlgorithmType);
if ((algorithm == null) && Membership.IsHashAlgorithmFromMembershipConfig)
{
RuntimeConfig.GetAppConfig().Membership.ThrowHashAlgorithmException();
}
inArray = algorithm.ComputeHash(dst);
}
else
{
inArray = this.EncryptPassword(dst);
}
return Convert.ToBase64String(inArray);
}
```
Eseentially, pulls in the salt from the DB and b64 decodes it into a binary representation. It does a "GetBytes" on the raw password and then it concatinates them, salt first.
It then runs the SHA1 algorithm on this new string, base64 encodes it, and compares it against the value stored in the database.
I've attempted to write some code to try and reproduce these hashes in Python and I'm failing. I won't be able to use them in Django until I can figure out how this translates over. Here's how I'm testing:
```
import hashlib
from base64 import b64decode, b64encode
b64salt = "kDP0Py2QwEdJYtUX9cJABg=="
b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA="
binsalt = b64decode(b64salt)
password_string = 'password'
m1 = hashlib.sha1()
# Pass in salt
m1.update(binsalt)
# Pass in password
m1.update(password_string)
# B64 encode the binary digest
if b64encode(m1.digest()) == b64hash:
print "Logged in!"
else:
print "Didn't match"
print b64hash
print b64encode(m1.digest())
```
I'm wondering if anyone can see any flaws in my approach or can suggest an alternate method. Perhaps you can take the algorithms above and the known password and salt above and produce the hash on your system?
|
It appears python is inserting a byte order marker when you convert a UTF16 string to binary. The .NET byte array contains no BOM, so I did some ghetto python that turns the UTF16 into hex, removes the first 4 characters, then decodes it to binary.
There may be a better way to rip out the BOM, but this works for me!
Here's one that passes:
```
import hashlib
from base64 import b64decode, b64encode
def utf16tobin(s):
return s.encode('hex')[4:].decode('hex')
b64salt = "kDP0Py2QwEdJYtUX9cJABg=="
b64hash = "OJF6H4KdxFLgLu+oTDNFodCEfMA="
binsalt = b64decode(b64salt)
password_string = 'password'.encode("utf16")
password_string = utf16tobin(password_string)
m1 = hashlib.sha1()
# Pass in salt
m1.update(binsalt + password_string)
# Pass in password
# B64 encode the binary digest
if b64encode(m1.digest()) == b64hash:
print "Logged in!"
else:
print "Didn't match"
print b64hash
print b64encode(m1.digest())
```
|
269,720 |
<p>I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.</p>
<p>I start the server like this:</p>
<pre><code>/**
* starts the network server
* @return true if sucessfull
*/
public boolean start()
{
try
{
// just to be sure that we don't start two servers
this.stop();
server = new NetworkServerControl();
server.start( null );
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>And stop it like this:</p>
<pre><code>/**
* stops the server
*
* @return true if there were no problems stopping the server
*/
public boolean stop()
{
try
{
if ( server == null )
{
server = new NetworkServerControl();
}
server.shutdown();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>On the main() I have this so the process doesn't die while the server is running</p>
<pre><code>(...)
clsDB.start();
while( clsDB.testForConnection() )
{
Thread.sleep( 60000 );
}
</code></pre>
<p>testForConnection() looks like this:</p>
<pre><code>/**
* Try to test for a connection
*
* @return true if the server is alive
*/
public boolean testForConnection()
{
try
{
server.ping();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
</code></pre>
<p>My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started).</p>
<p>I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.</p>
|
[
{
"answer_id": 269765,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 2,
"selected": false,
"text": "<p>I did a project awhile ago with derby (including running in network mode), and I seem to remember that there is some SQL you can execute on the server which shuts derby down.</p>\n\n<p>So, assuming that's the case (no time to google for it atm sorry) you could, on start up, look for your network instance. If it exists, run this SQL on it. Once you have determined that it's finally shut down (polling that it exists I suppose) you can then start it up again.</p>\n\n<p><strong>Edit:</strong> Oh, it wasn't SQL, it's connecting to the DB with 'shutdown=true' as a parameter. See <a href=\"http://db.apache.org/derby/docs/dev/devguide/tdevdvlp40464.html\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>DriverManager.getConnection(\n \"jdbc:derby:sample;shutdown=true\");\n</code></pre>\n"
},
{
"answer_id": 269801,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 1,
"selected": false,
"text": "<p>The other solution I raised does not interact with your JAR, which you may not enjoy.</p>\n\n<p>An alternative is to have your JAR that starts the derby instance open a TCP port that it monitors when it starts derby. You can then send your own shutdown commands to that from your new JAR instance (obviously before opening up your own TCP port).</p>\n\n<p>Startup of an instance of your derby JAR would be:</p>\n\n<ul>\n<li>See if agreed upon TCP port was open.</li>\n<li>If so, send the shutdown command.\n\n<ul>\n<li>The JAR you send the command to would then shut down derby using the <code>stop()</code> method.</li>\n<li>Once it's done shutting derby down it would send a <code>success</code> of whatever back and close the connection.</li>\n</ul></li>\n<li>We listen on the agreed upon TCP port.</li>\n<li>We call <code>start()</code> and start Derby.</li>\n</ul>\n\n<p>This is more work than my other solution but is theorectically a better one, since as part of your restart your JAR may want to do other things as well (clean / restart other resources, log the fact that it's being shutdown, stuff like that).</p>\n"
},
{
"answer_id": 726826,
"author": "ferro",
"author_id": 2216428,
"author_profile": "https://Stackoverflow.com/users/2216428",
"pm_score": 2,
"selected": true,
"text": "<p>We ended up with using a file that is created when the server is to be killed, then on the server process we periodically check if the file exists, if it's there we kill the server.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2216428/"
] |
I'm looking for a good way to run a Apache Derby server in network mode. I'm using the NetworkServerControl to start the server and it's working great.
I start the server like this:
```
/**
* starts the network server
* @return true if sucessfull
*/
public boolean start()
{
try
{
// just to be sure that we don't start two servers
this.stop();
server = new NetworkServerControl();
server.start( null );
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
```
And stop it like this:
```
/**
* stops the server
*
* @return true if there were no problems stopping the server
*/
public boolean stop()
{
try
{
if ( server == null )
{
server = new NetworkServerControl();
}
server.shutdown();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
```
On the main() I have this so the process doesn't die while the server is running
```
(...)
clsDB.start();
while( clsDB.testForConnection() )
{
Thread.sleep( 60000 );
}
```
testForConnection() looks like this:
```
/**
* Try to test for a connection
*
* @return true if the server is alive
*/
public boolean testForConnection()
{
try
{
server.ping();
return true;
}
catch ( Exception ex )
{
this.logLogger.debug( ex );
return false;
}
}
```
My problem is that when a new instace of my JAR is called the old one will still be running (unless I'm really really lucky and the test is made before the new server is started).
I know I could just test if the server is already running and then I wouldn't start again, but I would like for start to work like a restart if the server is already there.
|
We ended up with using a file that is created when the server is to be killed, then on the server process we periodically check if the file exists, if it's there we kill the server.
|
269,761 |
<p>Please consider the following:</p>
<pre><code><td style="width: 500px;">
<div style="width: 400px;">SomeContent</div>
</td>
</code></pre>
<p>For some reason, the column that contains a div will not expand to 500px as the style suggests.</p>
<p>Do you know how to get the td to honor the width that I am specifying in the style?</p>
|
[
{
"answer_id": 269776,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 3,
"selected": true,
"text": "<p>In theory, you can use the min-width and max-width styles. In practice, some popular browsers ignore these styles. In this case you have explicitly declared a width of 400, so it should always equal 400 unless acted upon by a child growing or a parent shrinking. You could runat-\"server\" and programatically determine the width attribute based on content size, or you could play with the overflow style, or put it in a Panel with a horizontal scrollbar.</p>\n"
},
{
"answer_id": 269793,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 0,
"selected": false,
"text": "<p>is there a width on the table and other tds within the table? Also, have you got a doc type going on?</p>\n\n<p>However, that said, here's your solution:</p>\n\n<pre><code><td style=\"width: 500px\">\n <div style=\"padding: 0 50px\">SomeContent</div>\n</td>\n</code></pre>\n\n<p>Setting your padding appropriately.</p>\n\n<hr>\n\n<p>Having reread your question, I feel that this might not be the answer you're looking for. Could you elaborate a little more?</p>\n"
},
{
"answer_id": 269975,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code><td style=\"width:500px;\">\n <div style=\"width:100%;\">SomeContent</div>\n</td>\n</code></pre>\n\n<p>if however you want the td to be the exact size of the div, to a MAX of 500px, then try:</p>\n\n<pre><code><td style=\"max-width:500px;\">\n <div style=\"width:100%;\">SomeContent</div>\n</td>\n</code></pre>\n\n<p>Keeping in mind that IE6 doesn't understand max-width, and will just force it to be 500px.</p>\n"
},
{
"answer_id": 789336,
"author": "Phunky",
"author_id": 95992,
"author_profile": "https://Stackoverflow.com/users/95992",
"pm_score": 0,
"selected": false,
"text": "<p>You have no reason to set a fixed width on the DIV within the TD, by default DIV's are block elements which means they will fill the full width of there containing element.</p>\n\n<p>Either set padding on the TD or margin on the DIV to achieve the same style.</p>\n\n<p>Without seeing futher markup or css i can't see any reason why the TD would not be 500px, if you added two different background colors to the elements you will indeed noticed that the TD will be 100px wider than the div.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10589/"
] |
Please consider the following:
```
<td style="width: 500px;">
<div style="width: 400px;">SomeContent</div>
</td>
```
For some reason, the column that contains a div will not expand to 500px as the style suggests.
Do you know how to get the td to honor the width that I am specifying in the style?
|
In theory, you can use the min-width and max-width styles. In practice, some popular browsers ignore these styles. In this case you have explicitly declared a width of 400, so it should always equal 400 unless acted upon by a child growing or a parent shrinking. You could runat-"server" and programatically determine the width attribute based on content size, or you could play with the overflow style, or put it in a Panel with a horizontal scrollbar.
|
269,773 |
<p>I am using a custom item renderer in a combobox to display a custom drawing instead of the default text label.</p>
<p>This works fine for the dropdown list but the displayed item ( when the list is closed) is still the textual representation of my object.</p>
<p>Is there a way to have the displayed item rendered the same way as the one in the dropdown?</p>
|
[
{
"answer_id": 280859,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 4,
"selected": true,
"text": "<p>By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.</p>\n\n<pre><code>package\n{\n import mx.controls.ComboBox;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n\n override protected function createChildren():void {\n super.createChildren();\n\n if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n addChild(textInputReplacement);\n }\n }\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth;\n textInputReplacement.height = unscaledHeight;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1782090,
"author": "Maurits de Boer",
"author_id": 94870,
"author_profile": "https://Stackoverflow.com/users/94870",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the above solution, but found that the selectedItem did not display when the combobox was closed. A extra line of code was required to bind the itemRenderer data property to the selectedItem:</p>\n\n<pre><code> if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 2446068,
"author": "Dane",
"author_id": 238751,
"author_profile": "https://Stackoverflow.com/users/238751",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you maclema and Maurits de Boer. I added a couple more things to this class to make it fit my needs:</p>\n\n<ul>\n<li><p>I overrode set itemRenderer so that this will work if you set the itemRenderer through AS instead of mxml. I moved the text input replacement code to its own function to avoid duplication.</p></li>\n<li><p>I added setters for 'increaseW' and 'increaseH' to resize the combobox if necessary because my renderer was too big for the combobox at first. </p></li>\n<li><p>I subtracted 25 from the textInputReplacement width so it doesn't ever overlap the dropdown button... may be better to use something more proportional to accommodate different skins and such.</p></li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>package\n{\n import mx.binding.utils.BindingUtils;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n public function set increaseW(val:Number):void\n {\n _increaseW = val;\n }\n\n public function set increaseH(val:Number):void\n {\n _increaseH = val;\n }\n\n override public function set itemRenderer(value:IFactory):void\n {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n override protected function createChildren():void \n {\n super.createChildren();\n replaceTextInput();\n\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n unscaledWidth += _increaseW;\n unscaledHeight += _increaseH;\n\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth - 25;\n textInputReplacement.height = unscaledHeight;\n }\n }\n\n protected function replaceTextInput():void\n {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n addChild(textInputReplacement);\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7744558,
"author": "sixtyfootersdude",
"author_id": 251589,
"author_profile": "https://Stackoverflow.com/users/251589",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for a way to do this using the Spark ComboBox. </p>\n\n<p>This thread was very useful to me but so far there have only been answers on how to do it using an mx:ComboBox. I thought that I should append my answer on how to do it using a spark ComboBox.</p>\n\n<ol>\n<li>Create a new skin of the ComboBox</li>\n<li>Hide and disable the textInput</li>\n<li>Insert your own component</li>\n</ol>\n\n<p>This is what the skin would look like:</p>\n\n<pre><code><s:SparkSkin>\n\n <... Lots of other stuff/>\n\n <s:BorderContainer height=\"25\">\n <WHATEVER YOU NEED HERE!/>\n </s:BorderContainer>\n\n <!-- Disable the textInput and hide it -->\n <s:TextInput id=\"textInput\"\n left=\"0\" right=\"18\" top=\"0\" bottom=\"0\" \n skinClass=\"spark.skins.spark.ComboBoxTextInputSkin\"\n\n visible=\"false\" enabled=\"false\"/> \n\n\n</s:SparkSkin>\n</code></pre>\n\n<p>With the Spark ComboBox this process is very easy and does not require you to extend ComboBox.</p>\n"
},
{
"answer_id": 11673604,
"author": "John",
"author_id": 1555289,
"author_profile": "https://Stackoverflow.com/users/1555289",
"pm_score": 2,
"selected": false,
"text": "<p>I've extended Dane's code a bit further. In some cases clicking did not open the drop box with my renderer and I noticed that the normal Flex ComboBox skins did not fire. Thus in <em>replaceTextInput()</em> I added some additional event listeners and save a reference to the ComboBox button used to display the skins. Now it behaves just like the normal ComboBox.</p>\n\n<p>Here's the code:</p>\n\n<pre>\n package\n {\n import flash.events.Event;\n import flash.events.KeyboardEvent;\n import flash.events.MouseEvent;\n\n import mx.binding.utils.BindingUtils;\n import mx.controls.Button;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n import mx.events.DropdownEvent;\n\n /**\n * Extension of the standard ComboBox that will use the assigned 'itemRenderer'\n * for both the list items and the selected item.\n * \n * Based on code from:\n * http://stackoverflow.com/questions/269773/flex-custom-item-renderer-for-the-displayed-item-in-the-combobox\n */\n public class ComboBoxFullRenderer extends ComboBox\n {\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n\n /**\n * Keeps track of the current open/close state of the drop down list. \n */\n protected var _isOpen:Boolean = false;\n\n /**\n * Stores a reference to the 'Button' which overlays the ComboBox. Allows\n * us to pass events to it so skins are properly triggered. \n */\n protected var _buttonRef:Button = null;\n\n\n /**\n * Constructor. \n */\n public function ComboBoxFullRenderer() {\n super();\n }\n\n\n /**\n * Sets a value to increase the width of our ComboBox to adjust sizing. \n * \n * @param val Number of pixels to increase the width of the ComboBox.\n */\n public function set increaseW(val:Number):void {\n _increaseW = val;\n }\n\n /**\n * Sets a value to increase the height of our ComboBox to adjust sizing. \n * \n * @param val Number of pixels to increase the height of the ComboBox.\n */\n public function set increaseH(val:Number):void {\n _increaseH = val;\n }\n\n\n /**\n * Override the 'itemRenderer' setter so we can also replace the selected\n * item renderer.\n * \n * @param value The renderer to be used to display the drop down list items\n * and the selected item.\n */\n override public function set itemRenderer(value:IFactory):void {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n\n /**\n * Override base 'createChildren()' routine to call our 'replaceTextInput()'\n * method to replace the standard selected item renderer.\n * \n * @see #replaceTextInput();\n */\n override protected function createChildren():void {\n super.createChildren();\n replaceTextInput();\n }\n\n\n /**\n * Routine to replace the ComboBox 'textInput' child with our own child\n * that will render the selected data element. Will create an instance of\n * the 'itemRenderer' set for this ComboBox. \n */\n protected function replaceTextInput():void {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null && textInput != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer instance to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n // Listen for clicks so we can open/close the drop down when\n // renderer components are clicked. \n textInputReplacement.addEventListener(MouseEvent.CLICK, _onClick);\n // Listen to the mouse events on our renderer so we can feed them to\n // the ComboBox overlay button. This will make sure the button skins\n // are activated. See ComboBox::commitProperties() code.\n textInputReplacement.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.MOUSE_UP, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.ROLL_OVER, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.ROLL_OUT, _onMouseEvent);\n textInputReplacement.addEventListener(KeyboardEvent.KEY_DOWN, _onMouseEvent);\n\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n // Add our renderer as a child.\n addChild(textInputReplacement);\n\n // Listen for open close so we can maintain state. The\n // 'isShowingDropdown' property is mx_internal so we don't\n // have access to it. \n this.addEventListener(DropdownEvent.OPEN, _onOpen);\n this.addEventListener(DropdownEvent.CLOSE, _onClose);\n\n // Save a reference to the mx_internal button for the combo box.\n // We will need this so we can call its dispatchEvent() method.\n for (var i:int = 0; i < this.numChildren; i++) {\n var temp:Object = this.getChildAt(i);\n if (temp is Button) {\n _buttonRef = temp as Button;\n break;\n } \n }\n }\n }\n }\n\n\n /**\n * Detect open events on the drop down list to keep track of the current\n * drop down state so we can react properly to a click on our selected\n * item renderer.\n * \n * @param event The DropdownEvent.OPEN event for the combo box.\n */\n protected function _onOpen(event:DropdownEvent) : void {\n _isOpen = true;\n }\n\n\n /**\n * Detect close events on the drop down list to keep track of the current\n * drop down state so we can react properly to a click on our selected\n * item renderer.\n * \n * @param event The DropdownEvent.CLOSE event for the combo box.\n */\n protected function _onClose(event:DropdownEvent) : void {\n _isOpen = false;\n }\n\n\n /**\n * When we detect a click on our renderer open or close the drop down list\n * based on whether the drop down is currently open/closed.\n * \n * @param event The CLICK event from our selected item renderer.\n */\n protected function _onClick(event:MouseEvent) : void {\n if (_isOpen) {\n this.close(event);\n } else {\n this.open();\n }\n }\n\n\n /**\n * React to certain mouse/keyboard events on our selected item renderer and\n * pass the events to the ComboBox 'button' so that the skins are properly\n * applied.\n * \n * @param event A mouse or keyboard event to send to the ComboBox button.\n * \n */\n protected function _onMouseEvent(event:Event) : void {\n if (_buttonRef != null) {\n _buttonRef.dispatchEvent(event);\n }\n }\n } // end class\n } // end package\n</pre>\n"
},
{
"answer_id": 32511399,
"author": "Paulo Enmanuel",
"author_id": 1541093,
"author_profile": "https://Stackoverflow.com/users/1541093",
"pm_score": 0,
"selected": false,
"text": "<p>I found an easier way of changing the renderer for the selected element. This one only works if your element inherits from the <code>TextInput</code> class, in Flex 4.0 or above.</p>\n\n<p>In Flex v4.5, in <code>ComboBase.createChildren</code> at line 1177, you will find that the class definable for the <code>textInput</code> can be passed using the style key <code>textInputClass</code>: </p>\n\n<pre><code>// Mechanism to use MXFTETextInput. \nvar textInputClass:Class = getStyle(\"textInputClass\"); \nif (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)\n{\n textInput = new TextInput();\n}\nelse\n{\n textInput = new textInputClass();\n}\n</code></pre>\n\n<p>Just change the value of this key in the constructor of your combo and now you have your own renderer for the <code>selectedItem</code>. </p>\n\n<pre><code>public function ComboAvailableProfessor()\n{\n super();\n\n itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );\n setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );\n}\n</code></pre>\n\n<p>Finally you must bind the <code>data</code> property to the <code>selectedItem</code> property in your combo in order to get data displayed.</p>\n\n<pre><code>override protected function createChildren():void\n{\n super.createChildren();\n\n BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2011/"
] |
I am using a custom item renderer in a combobox to display a custom drawing instead of the default text label.
This works fine for the dropdown list but the displayed item ( when the list is closed) is still the textual representation of my object.
Is there a way to have the displayed item rendered the same way as the one in the dropdown?
|
By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.
```
package
{
import mx.controls.ComboBox;
import mx.core.UIComponent;
public class ComboBox2 extends ComboBox
{
public function ComboBox2()
{
super();
}
protected var textInputReplacement:UIComponent;
override protected function createChildren():void {
super.createChildren();
if ( !textInputReplacement ) {
if ( itemRenderer != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer to use in place of the text input
textInputReplacement = itemRenderer.newInstance();
addChild(textInputReplacement);
}
}
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
if ( textInputReplacement ) {
textInputReplacement.width = unscaledWidth;
textInputReplacement.height = unscaledHeight;
}
}
}
}
```
|
269,774 |
<p>I've got a solution which I setup / cleanup using batch files ...
- there are a pair of MSMQ ports, send and receive, with another application on the end of the queues</p>
<p>I'm finding I can't properly stop the orchestration in the batch file ... the error is the send port is unenlisted
- I'm using the StopOrch.vbs script from the SDK samples</p>
<p>But I can go into BizTalk Admin Console and manually stop the orchestration with Full Terminate Ok</p>
<p>The setup / cleanup works Ok if I don't actually push any messages down the MSMQ queues</p>
|
[
{
"answer_id": 280859,
"author": "Matt MacLean",
"author_id": 22,
"author_profile": "https://Stackoverflow.com/users/22",
"pm_score": 4,
"selected": true,
"text": "<p>By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.</p>\n\n<pre><code>package\n{\n import mx.controls.ComboBox;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n\n override protected function createChildren():void {\n super.createChildren();\n\n if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n addChild(textInputReplacement);\n }\n }\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth;\n textInputReplacement.height = unscaledHeight;\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 1782090,
"author": "Maurits de Boer",
"author_id": 94870,
"author_profile": "https://Stackoverflow.com/users/94870",
"pm_score": 3,
"selected": false,
"text": "<p>I tried the above solution, but found that the selectedItem did not display when the combobox was closed. A extra line of code was required to bind the itemRenderer data property to the selectedItem:</p>\n\n<pre><code> if ( !textInputReplacement ) {\n if ( itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = itemRenderer.newInstance();\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 2446068,
"author": "Dane",
"author_id": 238751,
"author_profile": "https://Stackoverflow.com/users/238751",
"pm_score": 0,
"selected": false,
"text": "<p>Thank you maclema and Maurits de Boer. I added a couple more things to this class to make it fit my needs:</p>\n\n<ul>\n<li><p>I overrode set itemRenderer so that this will work if you set the itemRenderer through AS instead of mxml. I moved the text input replacement code to its own function to avoid duplication.</p></li>\n<li><p>I added setters for 'increaseW' and 'increaseH' to resize the combobox if necessary because my renderer was too big for the combobox at first. </p></li>\n<li><p>I subtracted 25 from the textInputReplacement width so it doesn't ever overlap the dropdown button... may be better to use something more proportional to accommodate different skins and such.</p></li>\n</ul>\n\n<p>Code:</p>\n\n<pre><code>package\n{\n import mx.binding.utils.BindingUtils;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n\n public class ComboBox2 extends ComboBox\n {\n public function ComboBox2()\n {\n super();\n }\n\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n public function set increaseW(val:Number):void\n {\n _increaseW = val;\n }\n\n public function set increaseH(val:Number):void\n {\n _increaseH = val;\n }\n\n override public function set itemRenderer(value:IFactory):void\n {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n override protected function createChildren():void \n {\n super.createChildren();\n replaceTextInput();\n\n }\n\n override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {\n\n unscaledWidth += _increaseW;\n unscaledHeight += _increaseH;\n\n super.updateDisplayList(unscaledWidth, unscaledHeight);\n\n if ( textInputReplacement ) {\n textInputReplacement.width = unscaledWidth - 25;\n textInputReplacement.height = unscaledHeight;\n }\n }\n\n protected function replaceTextInput():void\n {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n addChild(textInputReplacement);\n\n // ADD THIS BINDING:\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n addChild(textInputReplacement);\n\n }\n }\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 7744558,
"author": "sixtyfootersdude",
"author_id": 251589,
"author_profile": "https://Stackoverflow.com/users/251589",
"pm_score": 0,
"selected": false,
"text": "<p>I was looking for a way to do this using the Spark ComboBox. </p>\n\n<p>This thread was very useful to me but so far there have only been answers on how to do it using an mx:ComboBox. I thought that I should append my answer on how to do it using a spark ComboBox.</p>\n\n<ol>\n<li>Create a new skin of the ComboBox</li>\n<li>Hide and disable the textInput</li>\n<li>Insert your own component</li>\n</ol>\n\n<p>This is what the skin would look like:</p>\n\n<pre><code><s:SparkSkin>\n\n <... Lots of other stuff/>\n\n <s:BorderContainer height=\"25\">\n <WHATEVER YOU NEED HERE!/>\n </s:BorderContainer>\n\n <!-- Disable the textInput and hide it -->\n <s:TextInput id=\"textInput\"\n left=\"0\" right=\"18\" top=\"0\" bottom=\"0\" \n skinClass=\"spark.skins.spark.ComboBoxTextInputSkin\"\n\n visible=\"false\" enabled=\"false\"/> \n\n\n</s:SparkSkin>\n</code></pre>\n\n<p>With the Spark ComboBox this process is very easy and does not require you to extend ComboBox.</p>\n"
},
{
"answer_id": 11673604,
"author": "John",
"author_id": 1555289,
"author_profile": "https://Stackoverflow.com/users/1555289",
"pm_score": 2,
"selected": false,
"text": "<p>I've extended Dane's code a bit further. In some cases clicking did not open the drop box with my renderer and I noticed that the normal Flex ComboBox skins did not fire. Thus in <em>replaceTextInput()</em> I added some additional event listeners and save a reference to the ComboBox button used to display the skins. Now it behaves just like the normal ComboBox.</p>\n\n<p>Here's the code:</p>\n\n<pre>\n package\n {\n import flash.events.Event;\n import flash.events.KeyboardEvent;\n import flash.events.MouseEvent;\n\n import mx.binding.utils.BindingUtils;\n import mx.controls.Button;\n import mx.controls.ComboBox;\n import mx.core.IFactory;\n import mx.core.UIComponent;\n import mx.events.DropdownEvent;\n\n /**\n * Extension of the standard ComboBox that will use the assigned 'itemRenderer'\n * for both the list items and the selected item.\n * \n * Based on code from:\n * http://stackoverflow.com/questions/269773/flex-custom-item-renderer-for-the-displayed-item-in-the-combobox\n */\n public class ComboBoxFullRenderer extends ComboBox\n {\n protected var textInputReplacement:UIComponent;\n private var _increaseW:Number = 0;\n private var _increaseH:Number = 0;\n\n\n /**\n * Keeps track of the current open/close state of the drop down list. \n */\n protected var _isOpen:Boolean = false;\n\n /**\n * Stores a reference to the 'Button' which overlays the ComboBox. Allows\n * us to pass events to it so skins are properly triggered. \n */\n protected var _buttonRef:Button = null;\n\n\n /**\n * Constructor. \n */\n public function ComboBoxFullRenderer() {\n super();\n }\n\n\n /**\n * Sets a value to increase the width of our ComboBox to adjust sizing. \n * \n * @param val Number of pixels to increase the width of the ComboBox.\n */\n public function set increaseW(val:Number):void {\n _increaseW = val;\n }\n\n /**\n * Sets a value to increase the height of our ComboBox to adjust sizing. \n * \n * @param val Number of pixels to increase the height of the ComboBox.\n */\n public function set increaseH(val:Number):void {\n _increaseH = val;\n }\n\n\n /**\n * Override the 'itemRenderer' setter so we can also replace the selected\n * item renderer.\n * \n * @param value The renderer to be used to display the drop down list items\n * and the selected item.\n */\n override public function set itemRenderer(value:IFactory):void {\n super.itemRenderer = value;\n replaceTextInput();\n }\n\n\n /**\n * Override base 'createChildren()' routine to call our 'replaceTextInput()'\n * method to replace the standard selected item renderer.\n * \n * @see #replaceTextInput();\n */\n override protected function createChildren():void {\n super.createChildren();\n replaceTextInput();\n }\n\n\n /**\n * Routine to replace the ComboBox 'textInput' child with our own child\n * that will render the selected data element. Will create an instance of\n * the 'itemRenderer' set for this ComboBox. \n */\n protected function replaceTextInput():void {\n if ( !textInputReplacement ) {\n if ( this.itemRenderer != null && textInput != null ) {\n //remove the default textInput\n removeChild(textInput);\n\n //create a new itemRenderer instance to use in place of the text input\n textInputReplacement = this.itemRenderer.newInstance();\n // Listen for clicks so we can open/close the drop down when\n // renderer components are clicked. \n textInputReplacement.addEventListener(MouseEvent.CLICK, _onClick);\n // Listen to the mouse events on our renderer so we can feed them to\n // the ComboBox overlay button. This will make sure the button skins\n // are activated. See ComboBox::commitProperties() code.\n textInputReplacement.addEventListener(MouseEvent.MOUSE_DOWN, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.MOUSE_UP, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.ROLL_OVER, _onMouseEvent);\n textInputReplacement.addEventListener(MouseEvent.ROLL_OUT, _onMouseEvent);\n textInputReplacement.addEventListener(KeyboardEvent.KEY_DOWN, _onMouseEvent);\n\n // Bind the data of the textInputReplacement to the selected item\n BindingUtils.bindProperty(textInputReplacement, \"data\", this, \"selectedItem\", true);\n\n // Add our renderer as a child.\n addChild(textInputReplacement);\n\n // Listen for open close so we can maintain state. The\n // 'isShowingDropdown' property is mx_internal so we don't\n // have access to it. \n this.addEventListener(DropdownEvent.OPEN, _onOpen);\n this.addEventListener(DropdownEvent.CLOSE, _onClose);\n\n // Save a reference to the mx_internal button for the combo box.\n // We will need this so we can call its dispatchEvent() method.\n for (var i:int = 0; i < this.numChildren; i++) {\n var temp:Object = this.getChildAt(i);\n if (temp is Button) {\n _buttonRef = temp as Button;\n break;\n } \n }\n }\n }\n }\n\n\n /**\n * Detect open events on the drop down list to keep track of the current\n * drop down state so we can react properly to a click on our selected\n * item renderer.\n * \n * @param event The DropdownEvent.OPEN event for the combo box.\n */\n protected function _onOpen(event:DropdownEvent) : void {\n _isOpen = true;\n }\n\n\n /**\n * Detect close events on the drop down list to keep track of the current\n * drop down state so we can react properly to a click on our selected\n * item renderer.\n * \n * @param event The DropdownEvent.CLOSE event for the combo box.\n */\n protected function _onClose(event:DropdownEvent) : void {\n _isOpen = false;\n }\n\n\n /**\n * When we detect a click on our renderer open or close the drop down list\n * based on whether the drop down is currently open/closed.\n * \n * @param event The CLICK event from our selected item renderer.\n */\n protected function _onClick(event:MouseEvent) : void {\n if (_isOpen) {\n this.close(event);\n } else {\n this.open();\n }\n }\n\n\n /**\n * React to certain mouse/keyboard events on our selected item renderer and\n * pass the events to the ComboBox 'button' so that the skins are properly\n * applied.\n * \n * @param event A mouse or keyboard event to send to the ComboBox button.\n * \n */\n protected function _onMouseEvent(event:Event) : void {\n if (_buttonRef != null) {\n _buttonRef.dispatchEvent(event);\n }\n }\n } // end class\n } // end package\n</pre>\n"
},
{
"answer_id": 32511399,
"author": "Paulo Enmanuel",
"author_id": 1541093,
"author_profile": "https://Stackoverflow.com/users/1541093",
"pm_score": 0,
"selected": false,
"text": "<p>I found an easier way of changing the renderer for the selected element. This one only works if your element inherits from the <code>TextInput</code> class, in Flex 4.0 or above.</p>\n\n<p>In Flex v4.5, in <code>ComboBase.createChildren</code> at line 1177, you will find that the class definable for the <code>textInput</code> can be passed using the style key <code>textInputClass</code>: </p>\n\n<pre><code>// Mechanism to use MXFTETextInput. \nvar textInputClass:Class = getStyle(\"textInputClass\"); \nif (!textInputClass || FlexVersion.compatibilityVersion < FlexVersion.VERSION_4_0)\n{\n textInput = new TextInput();\n}\nelse\n{\n textInput = new textInputClass();\n}\n</code></pre>\n\n<p>Just change the value of this key in the constructor of your combo and now you have your own renderer for the <code>selectedItem</code>. </p>\n\n<pre><code>public function ComboAvailableProfessor()\n{\n super();\n\n itemRenderer = new ClassFactory( ProfessorAvailableListItemRenderer );\n setStyle( 'textInputClass', ProfessorAvailableSelectedListItemRenderer );\n}\n</code></pre>\n\n<p>Finally you must bind the <code>data</code> property to the <code>selectedItem</code> property in your combo in order to get data displayed.</p>\n\n<pre><code>override protected function createChildren():void\n{\n super.createChildren();\n\n BindingUtils.bindProperty( textInput, 'data', this, 'selectedItem', true );\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269774",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27756/"
] |
I've got a solution which I setup / cleanup using batch files ...
- there are a pair of MSMQ ports, send and receive, with another application on the end of the queues
I'm finding I can't properly stop the orchestration in the batch file ... the error is the send port is unenlisted
- I'm using the StopOrch.vbs script from the SDK samples
But I can go into BizTalk Admin Console and manually stop the orchestration with Full Terminate Ok
The setup / cleanup works Ok if I don't actually push any messages down the MSMQ queues
|
By default you cannot do this. However, if you extend ComboBox you can add this functionality easily. Here is a quick example, it is a rough version and probably needs testing / tweaking but it shows how you could accomplish this.
```
package
{
import mx.controls.ComboBox;
import mx.core.UIComponent;
public class ComboBox2 extends ComboBox
{
public function ComboBox2()
{
super();
}
protected var textInputReplacement:UIComponent;
override protected function createChildren():void {
super.createChildren();
if ( !textInputReplacement ) {
if ( itemRenderer != null ) {
//remove the default textInput
removeChild(textInput);
//create a new itemRenderer to use in place of the text input
textInputReplacement = itemRenderer.newInstance();
addChild(textInputReplacement);
}
}
}
override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void {
super.updateDisplayList(unscaledWidth, unscaledHeight);
if ( textInputReplacement ) {
textInputReplacement.width = unscaledWidth;
textInputReplacement.height = unscaledHeight;
}
}
}
}
```
|
269,781 |
<p>Is there an easy way to convert a string that contains this:</p>
<pre><code>Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)
</code></pre>
<p>into a string that contains this:</p>
<pre><code>20081105_131212
</code></pre>
<p><strong>UPDATE:</strong><br>
I ended up using date.tryparse which is similar to tryParseExact except you don't have to specify the format string. I did have to eliminate the () and the EST for this to work. The date string will always be EST because the date string comes from 1 web server.</p>
<p>Original string: <br></p>
<pre><code>Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)
</code></pre>
<p>Using this code: <br></p>
<pre><code>buff1.Remove(0, 6).Replace("(", "").Replace(")", "").Replace("EST", "").Trim()
</code></pre>
<p>Becomes this string: <br></p>
<pre><code>Wed, 5 Nov 2008 13:12:12 -0500
</code></pre>
<p>Then I can format appropriately to generate my filename date using this:</p>
<pre><code> If Date.TryParse(buff1, dateValue) Then
MsgBox(Format(dateValue, "yyyyMMdd_HHmmss"))
Else
MsgBox("nope")
End If
</code></pre>
|
[
{
"answer_id": 269841,
"author": "Salman Kasbati",
"author_id": 33931,
"author_profile": "https://Stackoverflow.com/users/33931",
"pm_score": 0,
"selected": false,
"text": "<p><code>Format(date, \"yyyyMMdd_HHmmss\")</code></p>\n\n<p>More help on <a href=\"http://msdn.microsoft.com/en-us/library/59bz1f0h(VS.71).aspx\" rel=\"nofollow noreferrer\">format</a> function.</p>\n"
},
{
"answer_id": 269883,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p>If by VB you mean VB.NET you could use <code>Date.Parse</code> followed by <code>ToString()</code> with a format string:</p>\n\n<pre><code>Date.Parse(YourDateString).ToString(\"yyyyMMdd_HHmmss\")\n</code></pre>\n\n<p>Note: Remove the initial \"Date: \" before you parse the string.</p>\n"
},
{
"answer_id": 269915,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": true,
"text": "<p>Even better than <code>Date.Parse</code> in this case would be <code>Date.TryParseExact()</code>. That would let you tell the framework what format you expect and return a boolean rather than throwing an exception if the parse fails.</p>\n\n<p>Then use <code>.ToString(\"yyyyMMdd_HHmmss\")</code> to get the desired new string format.</p>\n\n<p>Here's the format string reference, in case you need it:<br>\n<a href=\"http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx</a></p>\n\n<p>Finally, I noticed you're ignoring the -500 timezone offset. Are you sure that all your strings are really from the same time zone?</p>\n"
},
{
"answer_id": 269942,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>Like @splattne's solution in VB.NET, but with the cleanup as well...</p>\n\n<pre><code>Dim strDateVal As String = \"Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)\"\nstrDateVal = strDateVal.Substring(strDateVal.IndexOf(\", \") + 2, strDateVal.Length - strDateVal.IndexOf(\", \") - 2)\nstrDateVal = strDateVal.Substring(0, strDateVal.LastIndexOf(\" \")).TrimEnd\nDim DateVal As Date = Date.Parse(strDateVal)\nDim NewStringVal As String = Format(DateVal, \"yyyyMMdd_HHmmss\")\n</code></pre>\n\n<p>NOTE: This ignores the timezone in order to match your expected result (per the example data in the question)</p>\n"
},
{
"answer_id": 269956,
"author": "RS Conley",
"author_id": 7890,
"author_profile": "https://Stackoverflow.com/users/7890",
"pm_score": 1,
"selected": false,
"text": "<p>For a pure VB solution I would go</p>\n\n<pre><code>Function ConvertDateString(ByVal Original As String) As String\n Dim Elements As String() = Split(Original, \" \")\n Dim DateString As String = Elements(3) & \" \" & Elements(2) & \" \" & Elements(4) & \" \" & Elements(5)\n Return Date.Parse(DateString).ToString(\"yyyyMMdd_HHmmsss\")\nEnd Function\n</code></pre>\n\n<p>You could eliminate DateString by just using the concatenated string in the Parase. It will fit on one line if your resolution is 1024 by 768 or bigger.</p>\n"
},
{
"answer_id": 1480998,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Dim strDateVal As String = \"Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)\"\n\nstrDateVal = strDateVal.Substring(strDateVal.IndexOf(\", \") + 2, \nstrDateVal.Length - strDateVal.IndexOf(\", \") - 2)\n\nstrDateVal = strDateVal.Substring(0, strDateVal.LastIndexOf(\" \")).TrimEnd\n\nDim DateVal As Date = Date.Parse(strDateVal)\nDim NewStringVal As String = Format(DateVal, \"ddMMyyyy_HHmmss\")\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24721/"
] |
Is there an easy way to convert a string that contains this:
```
Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)
```
into a string that contains this:
```
20081105_131212
```
**UPDATE:**
I ended up using date.tryparse which is similar to tryParseExact except you don't have to specify the format string. I did have to eliminate the () and the EST for this to work. The date string will always be EST because the date string comes from 1 web server.
Original string:
```
Date: Wed, 5 Nov 2008 13:12:12 -0500 (EST)
```
Using this code:
```
buff1.Remove(0, 6).Replace("(", "").Replace(")", "").Replace("EST", "").Trim()
```
Becomes this string:
```
Wed, 5 Nov 2008 13:12:12 -0500
```
Then I can format appropriately to generate my filename date using this:
```
If Date.TryParse(buff1, dateValue) Then
MsgBox(Format(dateValue, "yyyyMMdd_HHmmss"))
Else
MsgBox("nope")
End If
```
|
Even better than `Date.Parse` in this case would be `Date.TryParseExact()`. That would let you tell the framework what format you expect and return a boolean rather than throwing an exception if the parse fails.
Then use `.ToString("yyyyMMdd_HHmmss")` to get the desired new string format.
Here's the format string reference, in case you need it:
<http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx>
Finally, I noticed you're ignoring the -500 timezone offset. Are you sure that all your strings are really from the same time zone?
|
269,782 |
<p>I have a really simple WPF UserControl:</p>
<pre><code><UserControl x:Class="dr.SitecoreCompare.WPF.ConnectionEntry"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="connEntry"
BorderBrush="Navy" BorderThickness="1" Margin="5,0,0,5" >
<StackPanel Margin="0,10,0,0" >
<Label FontWeight="ExtraBold" Content="{Binding ElementName=connEntry, Path=Title}"></Label>
<Label Margin="0,5,0,0">Server:</Label>
<TextBox x:Name="txtServer" TabIndex="1" Text="{Binding Path=ServerName}" ></TextBox>
<Label>Database:</Label>
<TextBox x:Name="txtDatabase" TabIndex="2" Text="{Binding Path=DatabaseName}"></TextBox>
</StackPanel>
</code></pre>
<p></p>
<p>This is used twice in the same window. Now, I can select the first TextBox on both th instances of my UserControl, but the second ("txtDatabase") textbox cannot be selected, neither by tabbing or clicking. Why is this ? Am I missing something with regards to creating WPF usercontrols ? </p>
<p>EDIT:
DatabaseName is not readonly, it is a simple property. The XAML for the window the usercontrol is placed on looks like this:</p>
<pre><code><Window x:Class="dr.SitecoreCompare.WPF.ProjectDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:dr.SitecoreCompare.WPF"
Title="Choose project" Height="280" Width="500"
WindowStartupLocation="CenterOwner" WindowStyle="SingleBorderWindow" HorizontalAlignment="Center" ShowInTaskbar="False" ShowActivated="True" ResizeMode="NoResize" VerticalContentAlignment="Top" VerticalAlignment="Center">
<StackPanel>
<Label>Choose databases</Label>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<c:ConnectionEntry Grid.Column="0" x:Name="connMaster" Title="Master:" Padding="5" />
<c:ConnectionEntry Grid.Column="1" x:Name="connSlave" Title="Slave:" Padding="5" />
</Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0" >
<Button x:Name="btnCancel" Click="btnCancel_Click">Cancel</Button>
<Button x:Name="btnOK" Click="btnOK_Click">OK</Button>
</StackPanel>
</StackPanel>
</Window>
</code></pre>
|
[
{
"answer_id": 269813,
"author": "dmo",
"author_id": 1807,
"author_profile": "https://Stackoverflow.com/users/1807",
"pm_score": 0,
"selected": false,
"text": "<p>This works in XamlPad, so I think there is something outside the code you posted that is causing the problem. Is DatabaseName readonly?</p>\n"
},
{
"answer_id": 280095,
"author": "Geoff Cox",
"author_id": 30505,
"author_profile": "https://Stackoverflow.com/users/30505",
"pm_score": 3,
"selected": true,
"text": "<p>Try Mode=TwoWay in your binding. I've seen this where the initialization sets the value and the control can not set the the value.</p>\n\n<pre><code><TextBox x:Name=\"txtDatabase\" TabIndex=\"2\" Text=\"{Binding Path=DatabaseName, Mode=TwoWay}\"></TextBox>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269782",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13627/"
] |
I have a really simple WPF UserControl:
```
<UserControl x:Class="dr.SitecoreCompare.WPF.ConnectionEntry"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
x:Name="connEntry"
BorderBrush="Navy" BorderThickness="1" Margin="5,0,0,5" >
<StackPanel Margin="0,10,0,0" >
<Label FontWeight="ExtraBold" Content="{Binding ElementName=connEntry, Path=Title}"></Label>
<Label Margin="0,5,0,0">Server:</Label>
<TextBox x:Name="txtServer" TabIndex="1" Text="{Binding Path=ServerName}" ></TextBox>
<Label>Database:</Label>
<TextBox x:Name="txtDatabase" TabIndex="2" Text="{Binding Path=DatabaseName}"></TextBox>
</StackPanel>
```
This is used twice in the same window. Now, I can select the first TextBox on both th instances of my UserControl, but the second ("txtDatabase") textbox cannot be selected, neither by tabbing or clicking. Why is this ? Am I missing something with regards to creating WPF usercontrols ?
EDIT:
DatabaseName is not readonly, it is a simple property. The XAML for the window the usercontrol is placed on looks like this:
```
<Window x:Class="dr.SitecoreCompare.WPF.ProjectDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:c="clr-namespace:dr.SitecoreCompare.WPF"
Title="Choose project" Height="280" Width="500"
WindowStartupLocation="CenterOwner" WindowStyle="SingleBorderWindow" HorizontalAlignment="Center" ShowInTaskbar="False" ShowActivated="True" ResizeMode="NoResize" VerticalContentAlignment="Top" VerticalAlignment="Center">
<StackPanel>
<Label>Choose databases</Label>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition />
<ColumnDefinition />
</Grid.ColumnDefinitions>
<c:ConnectionEntry Grid.Column="0" x:Name="connMaster" Title="Master:" Padding="5" />
<c:ConnectionEntry Grid.Column="1" x:Name="connSlave" Title="Slave:" Padding="5" />
</Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,0" >
<Button x:Name="btnCancel" Click="btnCancel_Click">Cancel</Button>
<Button x:Name="btnOK" Click="btnOK_Click">OK</Button>
</StackPanel>
</StackPanel>
</Window>
```
|
Try Mode=TwoWay in your binding. I've seen this where the initialization sets the value and the control can not set the the value.
```
<TextBox x:Name="txtDatabase" TabIndex="2" Text="{Binding Path=DatabaseName, Mode=TwoWay}"></TextBox>
```
|
269,794 |
<p>I have this code:</p>
<pre><code>CCalcArchive::CCalcArchive() : m_calcMap()
{
}
</code></pre>
<p><code>m_calcMap</code> is defined as this:</p>
<pre><code>typedef CTypedPtrMap<CMapStringToPtr, CString, CCalculation*> CCalcMap;
CCalcMap& m_calcMap;
</code></pre>
<p>When I compile in Visual Studio 2008, I get this error:</p>
<pre><code>error C2440: 'initializing' : cannot convert from 'int' to 'CCalcArchive::CCalcMap &'
</code></pre>
<p>I don't even understand where it gets the "int" error from, and also why this doesn't work? It feels like I'm actually having some sort of syntax error, but isn't this how member initialization lists are supposed to be used? Also, AFAIK, the MFC class <code>CTypedPtrMap</code> has no constructor taking arguments.</p>
|
[
{
"answer_id": 269809,
"author": "Torlack",
"author_id": 5243,
"author_profile": "https://Stackoverflow.com/users/5243",
"pm_score": 2,
"selected": false,
"text": "<p>Unless I'm missing something, since it is a reference, it needs to be initialized to point to something. Reference variables, by definition, can't be initialized to NULL.</p>\n\n<p>As far as the int, I don't know why it is saying that.</p>\n"
},
{
"answer_id": 269811,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure where it's getting the <code>int</code> from, but you <strong>must</strong> initialize all references in the initializer list. <code>m_calcMap</code> is declared as a reference, and so it must be initialized to refer to some instance of a <code>CCalcMap</code> object - you can't leave it uninitialized. If there's no way for you to pass the referred-to object into the constructor, or there's a possibility that you need it to not refer to an object, then use a pointer instead of a reference.</p>\n"
},
{
"answer_id": 269836,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "<p>It's a common MO for C++ compilers, when they can't figure out what a type is, to spit out an error message and assume that the user meant 'int' in order to be able to continue (...and generate even more error messages ;-)</p>\n\n<p>You do need to initialize all references in a class in your constructors, though.</p>\n"
},
{
"answer_id": 270160,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 3,
"selected": true,
"text": "<p>The <code>int</code> is coming from the fact that <code>CTypedPtrMap</code> has a constructor that takes an <code>int</code> argument that is defaulted to 10.</p>\n\n<p>The real problem that you're running into is that the <code>m_calcMap</code> reference initalization you have there is trying to default construct a temporary <code>CTypedPtrMap</code> object to bind the reference to. However, only <code>const</code> references can be bound to temporary objects. No doubt the error message is not very informative.</p>\n\n<p>But even if the <code>m_calcMap</code> member were a <code>const</code> refernce, you'd still have a problem binding it to a temporary. in this case, the MSVC 2008 compiler gives a pretty clear warning:</p>\n\n<pre><code>mfctest.cpp(72) : warning C4413: '' : reference member is initialized to a temporary \n that doesn't persist after the constructor exits\n</code></pre>\n"
},
{
"answer_id": 271482,
"author": "Jonas",
"author_id": 9744,
"author_profile": "https://Stackoverflow.com/users/9744",
"pm_score": 0,
"selected": false,
"text": "<p>Ah, yes my idea was that I intended to run its constructor in the initializer list, and thus have the object be constructed at all times. It's getting more clear now after especially Mike B's reply and now makes perfect sense that the constructed object would immediately be destructed after going out of scope. That's what I never considered first. :S I thought that was OK with references, along with initializing it with a reference to an existing object.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269794",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9744/"
] |
I have this code:
```
CCalcArchive::CCalcArchive() : m_calcMap()
{
}
```
`m_calcMap` is defined as this:
```
typedef CTypedPtrMap<CMapStringToPtr, CString, CCalculation*> CCalcMap;
CCalcMap& m_calcMap;
```
When I compile in Visual Studio 2008, I get this error:
```
error C2440: 'initializing' : cannot convert from 'int' to 'CCalcArchive::CCalcMap &'
```
I don't even understand where it gets the "int" error from, and also why this doesn't work? It feels like I'm actually having some sort of syntax error, but isn't this how member initialization lists are supposed to be used? Also, AFAIK, the MFC class `CTypedPtrMap` has no constructor taking arguments.
|
The `int` is coming from the fact that `CTypedPtrMap` has a constructor that takes an `int` argument that is defaulted to 10.
The real problem that you're running into is that the `m_calcMap` reference initalization you have there is trying to default construct a temporary `CTypedPtrMap` object to bind the reference to. However, only `const` references can be bound to temporary objects. No doubt the error message is not very informative.
But even if the `m_calcMap` member were a `const` refernce, you'd still have a problem binding it to a temporary. in this case, the MSVC 2008 compiler gives a pretty clear warning:
```
mfctest.cpp(72) : warning C4413: '' : reference member is initialized to a temporary
that doesn't persist after the constructor exits
```
|
269,795 |
<p>How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?</p>
<p>I'm trying to look for the source of the <code>datetime</code> module in particular, but I'm interested in a more general answer as well.</p>
|
[
{
"answer_id": 269803,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>sys.path</code> list contains the list of directories which will be searched for modules at runtime:</p>\n\n<pre><code>python -v\n>>> import sys\n>>> sys.path\n['', '/usr/local/lib/python25.zip', '/usr/local/lib/python2.5', ... ]\n</code></pre>\n"
},
{
"answer_id": 269806,
"author": "jblocksom",
"author_id": 20626,
"author_profile": "https://Stackoverflow.com/users/20626",
"pm_score": 8,
"selected": false,
"text": "<p>Running <code>python -v</code> from the command line should tell you what is being imported and from where. This works for me on Windows and Mac OS X.</p>\n\n<pre><code>C:\\>python -v\n# installing zipimport hook\nimport zipimport # builtin\n# installed zipimport hook\n# C:\\Python24\\lib\\site.pyc has bad mtime\nimport site # from C:\\Python24\\lib\\site.py\n# wrote C:\\Python24\\lib\\site.pyc\n# C:\\Python24\\lib\\os.pyc has bad mtime\nimport os # from C:\\Python24\\lib\\os.py\n# wrote C:\\Python24\\lib\\os.pyc\nimport nt # builtin\n# C:\\Python24\\lib\\ntpath.pyc has bad mtime\n...\n</code></pre>\n\n<p>I'm not sure what those bad mtime's are on my install!</p>\n"
},
{
"answer_id": 269810,
"author": "Bjarke Ebert",
"author_id": 31890,
"author_profile": "https://Stackoverflow.com/users/31890",
"pm_score": 5,
"selected": false,
"text": "<p><code>datetime</code> is a builtin module, so there is no (Python) source file.</p>\n\n<p>For modules coming from <code>.py</code> (or <code>.pyc</code>) files, you can use <code>mymodule.__file__</code>, e.g.</p>\n\n<pre><code>> import random\n> random.__file__\n'C:\\\\Python25\\\\lib\\\\random.pyc'\n</code></pre>\n"
},
{
"answer_id": 269814,
"author": "JimB",
"author_id": 32880,
"author_profile": "https://Stackoverflow.com/users/32880",
"pm_score": 1,
"selected": false,
"text": "<p>Not all python modules are written in python. Datetime happens to be one of them that is not, and (on linux) is datetime.so.</p>\n\n<p>You would have to download the source code to the python standard library to get at it.</p>\n"
},
{
"answer_id": 269825,
"author": "Moe",
"author_id": 3051,
"author_profile": "https://Stackoverflow.com/users/3051",
"pm_score": 10,
"selected": true,
"text": "<p>For a pure python module you can find the source by looking at <code>themodule.__file__</code>.\nThe datetime module, however, is written in C, and therefore <code>datetime.__file__</code> points to a .so file (there is no <code>datetime.__file__</code> on Windows), and therefore, you can't see the source.</p>\n<p>If you download a python source tarball and extract it, the modules' code can be found in the <strong>Modules</strong> subdirectory.</p>\n<p>For example, if you want to find the datetime code for python 2.6, you can look at</p>\n<pre><code>Python-2.6/Modules/datetimemodule.c\n</code></pre>\n<p>You can also find the latest version of this file on github on the web at\n<a href=\"https://github.com/python/cpython/blob/main/Modules/_datetimemodule.c\" rel=\"noreferrer\">https://github.com/python/cpython/blob/main/Modules/_datetimemodule.c</a></p>\n"
},
{
"answer_id": 2723437,
"author": "Daryl Spitzer",
"author_id": 4766,
"author_profile": "https://Stackoverflow.com/users/4766",
"pm_score": 3,
"selected": false,
"text": "<p>Check out this <a href=\"http://chris-lamb.co.uk/2010/04/22/locating-source-any-python-module/\" rel=\"noreferrer\">nifty \"cdp\" command</a> to cd to the directory containing the source for the indicated Python module:</p>\n\n<pre><code>cdp () {\n cd \"$(python -c \"import os.path as _, ${1}; \\\n print _.dirname(_.realpath(${1}.__file__[:-1]))\"\n )\"\n}\n</code></pre>\n"
},
{
"answer_id": 5089930,
"author": "evdama",
"author_id": 440041,
"author_profile": "https://Stackoverflow.com/users/440041",
"pm_score": 4,
"selected": false,
"text": "<p>New in Python 3.2, you can now use e.g. <code>code_info()</code> from the dis module:\n<a href=\"http://docs.python.org/dev/whatsnew/3.2.html#dis\">http://docs.python.org/dev/whatsnew/3.2.html#dis</a></p>\n"
},
{
"answer_id": 5740458,
"author": "Vijay",
"author_id": 684799,
"author_profile": "https://Stackoverflow.com/users/684799",
"pm_score": 4,
"selected": false,
"text": "<p>In the python interpreter you could import the particular module and then type help(module). This gives details such as Name, File, Module Docs, Description et al.</p>\n\n<p>Ex:</p>\n\n<pre><code>import os\n\nhelp(os)\n\n\nHelp on module os:\n\nNAME\n\nos - OS routines for Mac, NT, or Posix depending on what system we're on.\n\nFILE\n\n/usr/lib/python2.6/os.py\n\nMODULE DOCS\n\nhttp://docs.python.org/library/os\n\nDESCRIPTION\n\nThis exports:\n\n- all functions from posix, nt, os2, or ce, e.g. unlink, stat, etc.\n\n- os.path is one of the modules posixpath, or ntpath\n\n- os.name is 'posix', 'nt', 'os2', 'ce' or 'riscos'\n</code></pre>\n\n<p>et al</p>\n"
},
{
"answer_id": 13888157,
"author": "abarnert",
"author_id": 908494,
"author_profile": "https://Stackoverflow.com/users/908494",
"pm_score": 7,
"selected": false,
"text": "<p>I realize this answer is 4 years late, but the existing answers are misleading people.</p>\n\n<p>The right way to do this is never <code>__file__</code>, or trying to walk through <code>sys.path</code> and search for yourself, etc. (unless you need to be backward compatible beyond 2.1).</p>\n\n<p>It's the <a href=\"http://docs.python.org/library/inspect.html\"><code>inspect</code></a> module—in particular, <code>getfile</code> or <code>getsourcefile</code>.</p>\n\n<p>Unless you want to learn and implement the rules (which are documented, but painful, for CPython 2.x, and not documented at all for other implementations, or 3.x) for mapping <code>.pyc</code> to <code>.py</code> files; dealing with .zip archives, eggs, and module packages; trying different ways to get the path to <code>.so</code>/<code>.pyd</code> files that don't support <code>__file__</code>; figuring out what Jython/IronPython/PyPy do; etc. In which case, go for it.</p>\n\n<p>Meanwhile, every Python version's source from 2.0+ is available online at <code>http://hg.python.org/cpython/file/X.Y/</code> (e.g., <a href=\"http://hg.python.org/cpython/file/2.7/\">2.7</a> or <a href=\"http://hg.python.org/cpython/file/3.3/\">3.3</a>). So, once you discover that <code>inspect.getfile(datetime)</code> is a <code>.so</code> or <code>.pyd</code> file like <code>/usr/local/lib/python2.7/lib-dynload/datetime.so</code>, you can look it up inside the Modules directory. Strictly speaking, there's no way to be sure of which file defines which module, but nearly all of them are either <code>foo.c</code> or <code>foomodule.c</code>, so it shouldn't be hard to guess that <a href=\"http://hg.python.org/cpython/file/2.7/Modules/datetimemodule.c\">datetimemodule.c</a> is what you want.</p>\n"
},
{
"answer_id": 15211581,
"author": "Ernest",
"author_id": 408885,
"author_profile": "https://Stackoverflow.com/users/408885",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a one-liner to get the filename for a module, suitable for shell aliasing:</p>\n\n<pre><code>echo 'import sys; t=__import__(sys.argv[1],fromlist=[\\\".\\\"]); print(t.__file__)' | python - \n</code></pre>\n\n<p>Set up as an alias:</p>\n\n<pre><code>alias getpmpath=\"echo 'import sys; t=__import__(sys.argv[1],fromlist=[\\\".\\\"]); print(t.__file__)' | python - \"\n</code></pre>\n\n<p>To use:</p>\n\n<pre><code>$ getpmpath twisted\n/usr/lib64/python2.6/site-packages/twisted/__init__.pyc\n$ getpmpath twisted.web\n/usr/lib64/python2.6/site-packages/twisted/web/__init__.pyc\n</code></pre>\n"
},
{
"answer_id": 16370057,
"author": "Codespaced",
"author_id": 765049,
"author_profile": "https://Stackoverflow.com/users/765049",
"pm_score": 6,
"selected": false,
"text": "<p>from the standard library try <a href=\"http://docs.python.org/2/library/imp.html#imp.find_module\">imp.find_module</a></p>\n\n<pre><code>>>> import imp\n>>> imp.find_module('fontTools')\n(None, 'C:\\\\Python27\\\\lib\\\\site-packages\\\\FontTools\\\\fontTools', ('', '', 5))\n>>> imp.find_module('datetime')\n(None, 'datetime', ('', '', 6))\n</code></pre>\n"
},
{
"answer_id": 24117914,
"author": "Dun0523",
"author_id": 1945240,
"author_profile": "https://Stackoverflow.com/users/1945240",
"pm_score": 4,
"selected": false,
"text": "<p>On windows you can find the location of the python module as shown below:i.e find rest_framework module\n<img src=\"https://i.stack.imgur.com/TsWpv.png\" alt=\"enter image description here\"></p>\n"
},
{
"answer_id": 27230006,
"author": "Anon",
"author_id": 3995094,
"author_profile": "https://Stackoverflow.com/users/3995094",
"pm_score": 1,
"selected": false,
"text": "<p>For those who prefer a GUI solution: if you're using a gui such as Spyder (part of the Anaconda installation) you can just right-click the module name (such as \"csv\" in \"import csv\") and select \"go to definition\" - this will open the file, but also on the top you can see the exact file location (\"C:....csv.py\") </p>\n"
},
{
"answer_id": 32784452,
"author": "James Mark Mackenzie",
"author_id": 4045979,
"author_profile": "https://Stackoverflow.com/users/4045979",
"pm_score": 7,
"selected": false,
"text": "<p>If you're using pip to install your modules, just <code>pip show $module</code> the location is returned.</p>\n"
},
{
"answer_id": 37970790,
"author": "nexayq",
"author_id": 2450748,
"author_profile": "https://Stackoverflow.com/users/2450748",
"pm_score": 3,
"selected": false,
"text": "<p>On Ubuntu 12.04, for example numpy package for python2, can be found at:</p>\n\n<pre><code>/usr/lib/python2.7/dist-packages/numpy\n</code></pre>\n\n<p>Of course, this is not generic answer</p>\n"
},
{
"answer_id": 59930926,
"author": "Supradeep",
"author_id": 6281259,
"author_profile": "https://Stackoverflow.com/users/6281259",
"pm_score": 1,
"selected": false,
"text": "<p>If you are not using interpreter then you can run the code below:</p>\n\n<pre><code>import site\nprint (site.getsitepackages())\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>['C:\\\\Users\\\\<your username>\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37', 'C:\\\\Users\\\\<your username>\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37\\\\lib\\\\site-packages']\n</code></pre>\n\n<p>The second element in Array will be your package location. In this case:</p>\n\n<pre><code>C:\\Users\\<your username>\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages\n</code></pre>\n"
},
{
"answer_id": 61061257,
"author": "Anirudh Sharma",
"author_id": 13238270,
"author_profile": "https://Stackoverflow.com/users/13238270",
"pm_score": 0,
"selected": false,
"text": "<p>In an IDE like Spyder, import the module and then run the module individually. \n<a href=\"https://i.stack.imgur.com/3cXpx.png\" rel=\"nofollow noreferrer\">enter image description here</a></p>\n"
},
{
"answer_id": 61095592,
"author": "vub",
"author_id": 9932834,
"author_profile": "https://Stackoverflow.com/users/9932834",
"pm_score": 3,
"selected": false,
"text": "<p>Another way to check if you have multiple python versions installed, from the terminal.</p>\n<p><code>$ python3 -m pip show pyperclip</code></p>\n<p>Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/site-</p>\n<p><code>$ python -m pip show pyperclip</code></p>\n<p>Location: /Users/umeshvuyyuru/Library/Python/2.7/lib/python/site-packages</p>\n"
},
{
"answer_id": 67790109,
"author": "Ritik Attri",
"author_id": 14652528,
"author_profile": "https://Stackoverflow.com/users/14652528",
"pm_score": 3,
"selected": false,
"text": "<p>Just updating the answer in case anyone needs it now, I'm at Python 3.9 and using Pip to manage packages. Just use <code>pip show</code>, e.g.:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>pip show numpy\n</code></pre>\n<p>It will give you all the details with the location of where pip is storing all your other packages.</p>\n"
},
{
"answer_id": 72396307,
"author": "Harry P",
"author_id": 19175859,
"author_profile": "https://Stackoverflow.com/users/19175859",
"pm_score": -1,
"selected": false,
"text": "<p>as written above\nin python just use help(module)\nie</p>\n<p>import fractions</p>\n<p>help(fractions)</p>\n<p>if your module, in the example fractions, is installed then it will tell you location and info about it, if its not installed it says module not available</p>\n<p>if its not available it doesn't come by default with python in which case you can check where you found it for download info</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4766/"
] |
How do I learn where the source file for a given Python module is installed? Is the method different on Windows than on Linux?
I'm trying to look for the source of the `datetime` module in particular, but I'm interested in a more general answer as well.
|
For a pure python module you can find the source by looking at `themodule.__file__`.
The datetime module, however, is written in C, and therefore `datetime.__file__` points to a .so file (there is no `datetime.__file__` on Windows), and therefore, you can't see the source.
If you download a python source tarball and extract it, the modules' code can be found in the **Modules** subdirectory.
For example, if you want to find the datetime code for python 2.6, you can look at
```
Python-2.6/Modules/datetimemodule.c
```
You can also find the latest version of this file on github on the web at
<https://github.com/python/cpython/blob/main/Modules/_datetimemodule.c>
|
269,805 |
<p>I have been trying to parse Java exceptions that appear in a log for some code I'm working with. My question is, do you parse the exception trace from the top down, or the bottom up? It looks something like this:</p>
<pre><code>ERROR [main]</b> Nov/04 11:03:19,440 [localhost].[/BookmarksPortlet].[] - Exception sending context...
org.springframework.beans.factory.BeanCreationException: Error creating bean...: Cannot Resolve reference...: Error creating bean... nested exception... nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.Oracle10gDialect
Caused by:
... [similar exceptions and nested exceptions]
...
at [start of stack trace]
</code></pre>
<p>Something like that. Obviously, I'm not looking for the answer to this specific exception, but how do you go about parsing an exception trace like this? Do you start at the top level error, or do you start at the inner most error (under the "caused by" clauses)?</p>
<p>The problem is more difficult for me because I'm not working with code I wrote. I'm editing the XML configurations, so I'm not really even looking the Java code. In my own code, I would recognize locations in the trace and would know what sort of things to look for. So how do you approach an exception like this in general?</p>
|
[
{
"answer_id": 269816,
"author": "SCdF",
"author_id": 1666,
"author_profile": "https://Stackoverflow.com/users/1666",
"pm_score": 2,
"selected": false,
"text": "<p>This stuff is a little hard to explain, but my first step is nearly always starting from the top and skimming down until I see the familiar <code>com.mycompany.myproject</code>.</p>\n\n<p>Given the line number attached to that you have a place to work from in your own code, which is often a good start.</p>\n\n<p><strong>Edit:</strong> But, re-reading your question you say it's not your code.. so this may not be a useful answer at all..</p>\n"
},
{
"answer_id": 269846,
"author": "Elie",
"author_id": 23249,
"author_profile": "https://Stackoverflow.com/users/23249",
"pm_score": 2,
"selected": true,
"text": "<p>In your particular example, there's a class missing. As soon as you see an error like that, you know what needs fixing (either correcting the class name, or updating the classpath so that the class can be found).</p>\n\n<p>In general, though, I look from my code toward the generated code until I find the error. If I get a NullPointerException, for example, I check to see if it's being caused by one of my classes. If it's a missing class, though, I won't find anything wrong with my own classes, so I'll start at the other end of the stack trace and look for a recognizable error.</p>\n"
},
{
"answer_id": 270366,
"author": "bpapa",
"author_id": 543,
"author_profile": "https://Stackoverflow.com/users/543",
"pm_score": 1,
"selected": false,
"text": "<p>In your example, it looks like you need to add some Oracle JDBC driver or something to your project's classpath. </p>\n\n<p>But in the spirit of the question, I think it depends. In this example Spring isn't being very helpful on it's own - error creating bean. Gee, thanks for that information. However, it tells you exactly WHY there was an error creating a bean. The \"inner most\" exception. </p>\n\n<p>I've seen other examples where the inner most exception will be too specific (like an NPE) while on the outside the exception that was actually thrown had the most useful error message. It varies from project to project.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269805",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8092/"
] |
I have been trying to parse Java exceptions that appear in a log for some code I'm working with. My question is, do you parse the exception trace from the top down, or the bottom up? It looks something like this:
```
ERROR [main]</b> Nov/04 11:03:19,440 [localhost].[/BookmarksPortlet].[] - Exception sending context...
org.springframework.beans.factory.BeanCreationException: Error creating bean...: Cannot Resolve reference...: Error creating bean... nested exception... nested exception is org.hibernate.HibernateException: Dialect class not found: org.hibernate.dialect.Oracle10gDialect
Caused by:
... [similar exceptions and nested exceptions]
...
at [start of stack trace]
```
Something like that. Obviously, I'm not looking for the answer to this specific exception, but how do you go about parsing an exception trace like this? Do you start at the top level error, or do you start at the inner most error (under the "caused by" clauses)?
The problem is more difficult for me because I'm not working with code I wrote. I'm editing the XML configurations, so I'm not really even looking the Java code. In my own code, I would recognize locations in the trace and would know what sort of things to look for. So how do you approach an exception like this in general?
|
In your particular example, there's a class missing. As soon as you see an error like that, you know what needs fixing (either correcting the class name, or updating the classpath so that the class can be found).
In general, though, I look from my code toward the generated code until I find the error. If I get a NullPointerException, for example, I check to see if it's being caused by one of my classes. If it's a missing class, though, I won't find anything wrong with my own classes, so I'll start at the other end of the stack trace and look for a recognizable error.
|
269,837 |
<p>I have a class derived from <code>CTreeCtrl</code>. In <code>OnCreate()</code> I replace the default <code>CToolTipCtrl</code> object with a custom one:</p>
<pre><code>int CMyTreeCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTreeCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
// Replace tool tip with our own which will
// ask us for the text to display with a TTN_NEEDTEXT message
CTooltipManager::CreateToolTip(m_pToolTip, this, AFX_TOOLTIP_TYPE_DEFAULT);
m_pToolTip->AddTool(this, LPSTR_TEXTCALLBACK);
SetToolTips(m_pToolTip);
// Update: Added these two lines, which don't help either
m_pToolTip->Activate(TRUE);
EnableToolTips(TRUE);
return 0;
}
</code></pre>
<p>My message handler looks like this:</p>
<pre><code>ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &CMyTreeCtrl::OnTtnNeedText)
</code></pre>
<p>However I never receive a <code>TTN_NEEDTEXT</code> message. I had a look with Spy++ and it also looks like this message never gets sent.</p>
<p>What could be the problem here?</p>
<h2>Update</h2>
<p>I'm not sure whether this is relevant: The <code>CTreeCtrl</code>'s parent window is of type <code>CDockablePane</code>. Could there be some extra work needed for this to work?</p>
|
[
{
"answer_id": 269873,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you still have to enable the tooltip, even though you are replacing the builtin.</p>\n\n<pre><code>EnableToolTips(TRUE);\n</code></pre>\n\n<p>Well, since that did not work for you and since no-one more expert has offered any help, here a few more suggestions from me. Although they are lame, they might get you moving again:</p>\n\n<ul>\n<li>Make sure your OnCreate() rotine is actually being executed.</li>\n<li>Enable the tool tip BEFORE you replace it.</li>\n<li><p>The code I use to do this looks like this. ( I confess I do not understand all the details, I copied it from some sample code, it worked and so I never looked at it any more. )</p>\n\n<p>// Enable the standard tooltip</p>\n\n<p>EnableToolTips(TRUE);</p>\n\n<p>// Disable the builtin tooltip </p>\n\n<p>CToolTipCtrl* pToolTipCtrl = (CToolTipCtrl*)CWnd::FromHandle((HWND)::SendMessage(m_hWnd, LVM_GETTOOLTIPS, 0, 0L));</p></li>\n</ul>\n"
},
{
"answer_id": 274406,
"author": "skst",
"author_id": 4858,
"author_profile": "https://Stackoverflow.com/users/4858",
"pm_score": 0,
"selected": false,
"text": "<p>Try to specifically handle all tooltip ids:</p>\n\n<pre><code>ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, &CMyTreeCtrl::OnNeedTipText)\n</code></pre>\n\n<p>If that doesn't work, you may have to manually call RelayEvent() from PreTranslateMessage().</p>\n"
},
{
"answer_id": 275395,
"author": "Javier De Pedro",
"author_id": 14053,
"author_profile": "https://Stackoverflow.com/users/14053",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tried in a CTreeCtrl but I think you should call RelayEvent for the tooltip ctrl to know when the tooltip has to be displayed. Try this:</p>\n\n<p>MyTreeCtrl.h:</p>\n\n<pre><code>virtual BOOL PreTranslateMessage(MSG* pMsg);\n</code></pre>\n\n<p>MyTreeCtrl.cpp:</p>\n\n<pre><code>BOOL CMyTreeCtrl::PreTranslateMessage(MSG* pMsg) \n{\n m_pToolTip.Activate(TRUE);\n m_pToolTip.RelayEvent(pMsg);\n\n return CTreeCtrl::PreTranslateMessage(pMsg);\n}\n</code></pre>\n\n<p>I hope this help.</p>\n"
},
{
"answer_id": 799366,
"author": "JeffH",
"author_id": 73826,
"author_profile": "https://Stackoverflow.com/users/73826",
"pm_score": 1,
"selected": false,
"text": "<p>Don't you have to override OnToolHitTest()?</p>\n\n<p><a href=\"http://www.codeguru.com/forum/showthread.php?p=557485\" rel=\"nofollow noreferrer\">(old) Resource 1</a>\n<br/><br/>\n<a href=\"http://www.microsoft.com/msj/0397/c/c0397.aspx\" rel=\"nofollow noreferrer\">(old) Resource 2:</a></p>\n\n<blockquote>\n <p>In addition to returning the hit code (nHit), you also have to fill out the TOOLINFO struct. Here's how VIRGIL does it in CMainFrame::OnToolHitTest:</p>\n</blockquote>\n\n<pre><code> int nHit = MAKELONG(pt.x, pt.y);\n pTI->hwnd = m _ hWnd;\n pTI->uId = nHit;\n pTI->rect = CRect(CPoint(pt.x-1,pt.y-1),CSize(2,2));\n pTI->uFlags |= TTF _ NOTBUTTON;\n pTI->lpszText = LPSTR _ TEXTCALLBACK;\n</code></pre>\n\n<p>Most of this is obvious—like setting hwnd and uId—but some of it is less so. I set the rect member to a 2-pixel-wide, 2-pixel-high rectangle centered around the mouse location. The tooltip control uses this rectangle as the bounding rectangle of the \"tool,\" which I want to be tiny, so moving the mouse anywhere will constitute moving outside the tool. I set TTF _ NOTBUTTON in uFlags because the tooltip is not associated with a button. This is a special MFC flag defined in afxwin.h; MFC uses it to do help for tooltips. There's another MFC-extended flag for tooltips, TTF _ ALWAYSTIP. You can use it if you want MFC to display the tip even when your window is not active.\nYou may have noticed that so far I haven't told MFC or the tooltip or the TOOLINFO what the actual text of the tip is. That's what LPSTR _ TEXTCALLBACK is for. This special value tells the tooltip control (the internal, thread-global one that MFC uses) to call my window back to get the text. It does this by sending my window a WM _ NOTIFY message with notification code TTN _ NEEDTEXT. </p>\n"
},
{
"answer_id": 867675,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 4,
"selected": true,
"text": "<p>Finally! I (partially) solved it:</p>\n\n<p>It looks like the CDockablePane parent window indeed caused this problem...</p>\n\n<p>First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window.</p>\n\n<p>Then I edited the parent window's <code>OnCreate()</code> method:</p>\n\n<pre><code>int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n if (CDockablePane::OnCreate(lpCreateStruct) == -1)\n return -1;\n\nconst DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |\n TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |\n TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;\n\n// TREECTRL_ID is a custom member constant, set to 1\nif(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )\n{\n TRACE0(\"Failed to create trace tree list control.\\n\");\n return -1;\n}\n\n// m_pToolTip is a protected member of CDockablePane\nm_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);\nm_tree.SetToolTips(m_pToolTip);\n\n\nreturn 0;\n</code></pre>\n\n<p>}</p>\n\n<p>Unforunately we cannot simply call <code>AddTool()</code> with less parameters because the base class will complain in the form of an <code>ASSERT</code> about a <code>uFlag</code> member if there is no tool ID set.\nAnd since we need to set the ID, we also need to set a rectangle. I created a <code>CRect</code> member and set it to <code>(0, 0, 10000, 10000)</code> in the CTor. I have not yet found a working way to change the tool's rect size so this is my very ugly workaround. This is also why I call this solution partial. <strong>Update: <a href=\"https://stackoverflow.com/questions/867724/how-to-modify-the-tool-rect-of-a-ctooltipctrl\">I asked a question regarding this.</a></strong></p>\n\n<p>Finally there is the handler to get the tooltip info:</p>\n\n<pre><code>// Message map entry\nON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)\n\n\n// Handler\nvoid CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)\n{\n LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);\n\n // This is a CString member\n m_toolTipText.ReleaseBuffer();\n m_toolTipText.Empty();\n\n // Set your text here...\n\n pGetInfoTip->pszText = m_toolTipText.GetBuffer();\n\n *pResult = 0;\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27596/"
] |
I have a class derived from `CTreeCtrl`. In `OnCreate()` I replace the default `CToolTipCtrl` object with a custom one:
```
int CMyTreeCtrl::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CTreeCtrl::OnCreate(lpCreateStruct) == -1)
return -1;
// Replace tool tip with our own which will
// ask us for the text to display with a TTN_NEEDTEXT message
CTooltipManager::CreateToolTip(m_pToolTip, this, AFX_TOOLTIP_TYPE_DEFAULT);
m_pToolTip->AddTool(this, LPSTR_TEXTCALLBACK);
SetToolTips(m_pToolTip);
// Update: Added these two lines, which don't help either
m_pToolTip->Activate(TRUE);
EnableToolTips(TRUE);
return 0;
}
```
My message handler looks like this:
```
ON_NOTIFY_EX(TTN_NEEDTEXT, 0, &CMyTreeCtrl::OnTtnNeedText)
```
However I never receive a `TTN_NEEDTEXT` message. I had a look with Spy++ and it also looks like this message never gets sent.
What could be the problem here?
Update
------
I'm not sure whether this is relevant: The `CTreeCtrl`'s parent window is of type `CDockablePane`. Could there be some extra work needed for this to work?
|
Finally! I (partially) solved it:
It looks like the CDockablePane parent window indeed caused this problem...
First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window.
Then I edited the parent window's `OnCreate()` method:
```
int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
const DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |
TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;
// TREECTRL_ID is a custom member constant, set to 1
if(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )
{
TRACE0("Failed to create trace tree list control.\n");
return -1;
}
// m_pToolTip is a protected member of CDockablePane
m_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);
m_tree.SetToolTips(m_pToolTip);
return 0;
```
}
Unforunately we cannot simply call `AddTool()` with less parameters because the base class will complain in the form of an `ASSERT` about a `uFlag` member if there is no tool ID set.
And since we need to set the ID, we also need to set a rectangle. I created a `CRect` member and set it to `(0, 0, 10000, 10000)` in the CTor. I have not yet found a working way to change the tool's rect size so this is my very ugly workaround. This is also why I call this solution partial. **Update: [I asked a question regarding this.](https://stackoverflow.com/questions/867724/how-to-modify-the-tool-rect-of-a-ctooltipctrl)**
Finally there is the handler to get the tooltip info:
```
// Message map entry
ON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)
// Handler
void CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);
// This is a CString member
m_toolTipText.ReleaseBuffer();
m_toolTipText.Empty();
// Set your text here...
pGetInfoTip->pszText = m_toolTipText.GetBuffer();
*pResult = 0;
}
```
|
269,839 |
<p>So odd situation that I ran into today with OrderBy:</p>
<pre><code>Func<SomeClass, int> orderByNumber =
currentClass =>
currentClass.SomeNumber;
</code></pre>
<p>Then:</p>
<pre><code>someCollection.OrderBy(orderByNumber);
</code></pre>
<p>This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy.</p>
<pre><code>private int ReturnNumber(SomeClass currentClass)
{
return currentClass.SomeNumber;
}
</code></pre>
<p>Now when I try to plug that into the OrderBy:</p>
<pre><code>someCollection.OrderBy(ReturnNumber);
</code></pre>
<p>It can't infer the type like it can if I use a Func. Seems like to me they should be the same since the method itself is "strongly typed" like the Func.</p>
<p>Side Note: I realize I can do this:</p>
<pre><code>Func<SomeClass, int> orderByNumber = ReturnNumber;
</code></pre>
|
[
{
"answer_id": 269873,
"author": "ravenspoint",
"author_id": 16582,
"author_profile": "https://Stackoverflow.com/users/16582",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you still have to enable the tooltip, even though you are replacing the builtin.</p>\n\n<pre><code>EnableToolTips(TRUE);\n</code></pre>\n\n<p>Well, since that did not work for you and since no-one more expert has offered any help, here a few more suggestions from me. Although they are lame, they might get you moving again:</p>\n\n<ul>\n<li>Make sure your OnCreate() rotine is actually being executed.</li>\n<li>Enable the tool tip BEFORE you replace it.</li>\n<li><p>The code I use to do this looks like this. ( I confess I do not understand all the details, I copied it from some sample code, it worked and so I never looked at it any more. )</p>\n\n<p>// Enable the standard tooltip</p>\n\n<p>EnableToolTips(TRUE);</p>\n\n<p>// Disable the builtin tooltip </p>\n\n<p>CToolTipCtrl* pToolTipCtrl = (CToolTipCtrl*)CWnd::FromHandle((HWND)::SendMessage(m_hWnd, LVM_GETTOOLTIPS, 0, 0L));</p></li>\n</ul>\n"
},
{
"answer_id": 274406,
"author": "skst",
"author_id": 4858,
"author_profile": "https://Stackoverflow.com/users/4858",
"pm_score": 0,
"selected": false,
"text": "<p>Try to specifically handle all tooltip ids:</p>\n\n<pre><code>ON_NOTIFY_EX_RANGE(TTN_NEEDTEXT, 0, 0xFFFF, &CMyTreeCtrl::OnNeedTipText)\n</code></pre>\n\n<p>If that doesn't work, you may have to manually call RelayEvent() from PreTranslateMessage().</p>\n"
},
{
"answer_id": 275395,
"author": "Javier De Pedro",
"author_id": 14053,
"author_profile": "https://Stackoverflow.com/users/14053",
"pm_score": 1,
"selected": false,
"text": "<p>I haven't tried in a CTreeCtrl but I think you should call RelayEvent for the tooltip ctrl to know when the tooltip has to be displayed. Try this:</p>\n\n<p>MyTreeCtrl.h:</p>\n\n<pre><code>virtual BOOL PreTranslateMessage(MSG* pMsg);\n</code></pre>\n\n<p>MyTreeCtrl.cpp:</p>\n\n<pre><code>BOOL CMyTreeCtrl::PreTranslateMessage(MSG* pMsg) \n{\n m_pToolTip.Activate(TRUE);\n m_pToolTip.RelayEvent(pMsg);\n\n return CTreeCtrl::PreTranslateMessage(pMsg);\n}\n</code></pre>\n\n<p>I hope this help.</p>\n"
},
{
"answer_id": 799366,
"author": "JeffH",
"author_id": 73826,
"author_profile": "https://Stackoverflow.com/users/73826",
"pm_score": 1,
"selected": false,
"text": "<p>Don't you have to override OnToolHitTest()?</p>\n\n<p><a href=\"http://www.codeguru.com/forum/showthread.php?p=557485\" rel=\"nofollow noreferrer\">(old) Resource 1</a>\n<br/><br/>\n<a href=\"http://www.microsoft.com/msj/0397/c/c0397.aspx\" rel=\"nofollow noreferrer\">(old) Resource 2:</a></p>\n\n<blockquote>\n <p>In addition to returning the hit code (nHit), you also have to fill out the TOOLINFO struct. Here's how VIRGIL does it in CMainFrame::OnToolHitTest:</p>\n</blockquote>\n\n<pre><code> int nHit = MAKELONG(pt.x, pt.y);\n pTI->hwnd = m _ hWnd;\n pTI->uId = nHit;\n pTI->rect = CRect(CPoint(pt.x-1,pt.y-1),CSize(2,2));\n pTI->uFlags |= TTF _ NOTBUTTON;\n pTI->lpszText = LPSTR _ TEXTCALLBACK;\n</code></pre>\n\n<p>Most of this is obvious—like setting hwnd and uId—but some of it is less so. I set the rect member to a 2-pixel-wide, 2-pixel-high rectangle centered around the mouse location. The tooltip control uses this rectangle as the bounding rectangle of the \"tool,\" which I want to be tiny, so moving the mouse anywhere will constitute moving outside the tool. I set TTF _ NOTBUTTON in uFlags because the tooltip is not associated with a button. This is a special MFC flag defined in afxwin.h; MFC uses it to do help for tooltips. There's another MFC-extended flag for tooltips, TTF _ ALWAYSTIP. You can use it if you want MFC to display the tip even when your window is not active.\nYou may have noticed that so far I haven't told MFC or the tooltip or the TOOLINFO what the actual text of the tip is. That's what LPSTR _ TEXTCALLBACK is for. This special value tells the tooltip control (the internal, thread-global one that MFC uses) to call my window back to get the text. It does this by sending my window a WM _ NOTIFY message with notification code TTN _ NEEDTEXT. </p>\n"
},
{
"answer_id": 867675,
"author": "foraidt",
"author_id": 27596,
"author_profile": "https://Stackoverflow.com/users/27596",
"pm_score": 4,
"selected": true,
"text": "<p>Finally! I (partially) solved it:</p>\n\n<p>It looks like the CDockablePane parent window indeed caused this problem...</p>\n\n<p>First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window.</p>\n\n<p>Then I edited the parent window's <code>OnCreate()</code> method:</p>\n\n<pre><code>int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)\n{\n if (CDockablePane::OnCreate(lpCreateStruct) == -1)\n return -1;\n\nconst DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |\n TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |\n TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;\n\n// TREECTRL_ID is a custom member constant, set to 1\nif(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )\n{\n TRACE0(\"Failed to create trace tree list control.\\n\");\n return -1;\n}\n\n// m_pToolTip is a protected member of CDockablePane\nm_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);\nm_tree.SetToolTips(m_pToolTip);\n\n\nreturn 0;\n</code></pre>\n\n<p>}</p>\n\n<p>Unforunately we cannot simply call <code>AddTool()</code> with less parameters because the base class will complain in the form of an <code>ASSERT</code> about a <code>uFlag</code> member if there is no tool ID set.\nAnd since we need to set the ID, we also need to set a rectangle. I created a <code>CRect</code> member and set it to <code>(0, 0, 10000, 10000)</code> in the CTor. I have not yet found a working way to change the tool's rect size so this is my very ugly workaround. This is also why I call this solution partial. <strong>Update: <a href=\"https://stackoverflow.com/questions/867724/how-to-modify-the-tool-rect-of-a-ctooltipctrl\">I asked a question regarding this.</a></strong></p>\n\n<p>Finally there is the handler to get the tooltip info:</p>\n\n<pre><code>// Message map entry\nON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)\n\n\n// Handler\nvoid CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)\n{\n LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);\n\n // This is a CString member\n m_toolTipText.ReleaseBuffer();\n m_toolTipText.Empty();\n\n // Set your text here...\n\n pGetInfoTip->pszText = m_toolTipText.GetBuffer();\n\n *pResult = 0;\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269839",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21691/"
] |
So odd situation that I ran into today with OrderBy:
```
Func<SomeClass, int> orderByNumber =
currentClass =>
currentClass.SomeNumber;
```
Then:
```
someCollection.OrderBy(orderByNumber);
```
This is fine, but I was going to create a method instead because it might be usable somewhere else other than an orderBy.
```
private int ReturnNumber(SomeClass currentClass)
{
return currentClass.SomeNumber;
}
```
Now when I try to plug that into the OrderBy:
```
someCollection.OrderBy(ReturnNumber);
```
It can't infer the type like it can if I use a Func. Seems like to me they should be the same since the method itself is "strongly typed" like the Func.
Side Note: I realize I can do this:
```
Func<SomeClass, int> orderByNumber = ReturnNumber;
```
|
Finally! I (partially) solved it:
It looks like the CDockablePane parent window indeed caused this problem...
First I removed all the tooltip-specific code from the CTreeCtrl-derived class. Everything is done in the parent pane window.
Then I edited the parent window's `OnCreate()` method:
```
int CMyPane::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CDockablePane::OnCreate(lpCreateStruct) == -1)
return -1;
const DWORD dwStyle = WS_CHILD | WS_VISIBLE | WS_CLIPSIBLINGS | WS_CLIPCHILDREN |
TVS_CHECKBOXES | TVS_DISABLEDRAGDROP | TVS_HASBUTTONS | TVS_HASLINES | TVS_LINESATROOT |
TVS_INFOTIP | TVS_NOHSCROLL | TVS_SHOWSELALWAYS;
// TREECTRL_ID is a custom member constant, set to 1
if(!m_tree.Create(dwStyle, m_treeRect, this, TREECTRL_ID ) )
{
TRACE0("Failed to create trace tree list control.\n");
return -1;
}
// m_pToolTip is a protected member of CDockablePane
m_pToolTip->AddTool(&m_tree, LPSTR_TEXTCALLBACK, &m_treeRect, TREECTRL_ID);
m_tree.SetToolTips(m_pToolTip);
return 0;
```
}
Unforunately we cannot simply call `AddTool()` with less parameters because the base class will complain in the form of an `ASSERT` about a `uFlag` member if there is no tool ID set.
And since we need to set the ID, we also need to set a rectangle. I created a `CRect` member and set it to `(0, 0, 10000, 10000)` in the CTor. I have not yet found a working way to change the tool's rect size so this is my very ugly workaround. This is also why I call this solution partial. **Update: [I asked a question regarding this.](https://stackoverflow.com/questions/867724/how-to-modify-the-tool-rect-of-a-ctooltipctrl)**
Finally there is the handler to get the tooltip info:
```
// Message map entry
ON_NOTIFY(TVN_GETINFOTIP, TREECTRL_ID, &CMobileCatalogPane::OnTvnGetInfoTip)
// Handler
void CMyPane::OnTvnGetInfoTip(NMHDR *pNMHDR, LRESULT *pResult)
{
LPNMTVGETINFOTIP pGetInfoTip = reinterpret_cast<LPNMTVGETINFOTIP>(pNMHDR);
// This is a CString member
m_toolTipText.ReleaseBuffer();
m_toolTipText.Empty();
// Set your text here...
pGetInfoTip->pszText = m_toolTipText.GetBuffer();
*pResult = 0;
}
```
|
269,840 |
<p>I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them. </p>
<p>Can the header be updated without downloading the entire image? If so, how?</p>
|
[
{
"answer_id": 270066,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 6,
"selected": true,
"text": "<p>It's beta functionality, but you can specify new meta data when you <a href=\"http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTObjectCOPY.html\" rel=\"noreferrer\">copy an object</a>. Specify the same source and destination for the copy, and this has the effect of just updating the meta data on your object.</p>\n\n<pre><code>PUT /myObject HTTP/1.1\nHost: mybucket.s3.amazonaws.com \nx-amz-copy-source: /mybucket/myObject \nx-amz-metadata-directive: REPLACE \nx-amz-meta-myKey: newValue\n</code></pre>\n"
},
{
"answer_id": 8917419,
"author": "bkaid",
"author_id": 265570,
"author_profile": "https://Stackoverflow.com/users/265570",
"pm_score": 3,
"selected": false,
"text": "<p>This is out of beta and is available by doing a put command and copying the object as <a href=\"http://docs.amazonwebservices.com/AmazonS3/latest/API/RESTObjectCOPY.html\">documented here</a>. It is also available in their SDK's. For example with C#:</p>\n\n<pre><code>var s3Client = new AmazonS3Client(\"publicKey\", \"privateKey\");\nvar copyRequest = new CopyObjectRequest()\n .WithDirective(S3MetadataDirective.REPLACE)\n .WithSourceBucket(\"bucketName\")\n .WithSourceKey(\"fileName\")\n .WithDestinationBucket(\"bucketName\")\n .WithDestinationKey(\"fileName)\n .WithMetaData(new NameValueCollection { { \"x-amz-meta-yourKey\", \"your-value }, { \"x-amz-your-otherKey\", \"your-value\" } });\nvar copyResponse = s3Client.CopyObject(copyRequest);\n</code></pre>\n"
},
{
"answer_id": 9758282,
"author": "rjha94",
"author_id": 262376,
"author_profile": "https://Stackoverflow.com/users/262376",
"pm_score": 2,
"selected": false,
"text": "<p>with the amazon aws-sdk, Doing a copy_object with extra headers seems to do the trick for setting caching control headers for an existing S3 Object.</p>\n\n<p>=====================x===============================================</p>\n\n<pre><code><?php\n error_reporting(-1);\n require_once 'sdk.class.php';\n\n // UPLOAD FILES TO S3\n // Instantiate the AmazonS3 class\n $options = array(\"key\" => \"aws-key\" , \"secret\" => \"aws-secret\") ;\n\n\n $s3 = new AmazonS3($options);\n $bucket = \"bucket.3mik.com\" ;\n\n\n $exists = $s3->if_bucket_exists($bucket);\n if(!$exists) {\n trigger_error(\"S3 bucket does not exists \\n\" , E_USER_ERROR);\n }\n\n $name = \"cows-and-aliens.jpg\" ;\n echo \" change headers for $name \\n\" ;\n $source = array(\"bucket\" => $bucket, \"filename\" => $name);\n $dest = array(\"bucket\" => $bucket, \"filename\" => $name);\n\n //caching headers\n $offset = 3600*24*365;\n $expiresOn = gmdate('D, d M Y H:i:s \\G\\M\\T', time() + $offset);\n $headers = array('Expires' => $expiresOn, 'Cache-Control' => 'public, max-age=31536000');\n\n $meta = array('acl' => AmazonS3::ACL_PUBLIC, 'headers' => $headers);\n\n $response = $s3->copy_object($source,$dest,$meta);\n if($response->isOk()){\n printf(\"copy object done \\n\" );\n\n }else {\n printf(\"Error in copy object \\n\" );\n }\n\n?>\n</code></pre>\n\n<p>=======================x================================================</p>\n"
},
{
"answer_id": 14463356,
"author": "luissquall",
"author_id": 102353,
"author_profile": "https://Stackoverflow.com/users/102353",
"pm_score": 3,
"selected": false,
"text": "<p>This is how you do it with AWS SDK for PHP 2:</p>\n\n<pre><code><?php\nrequire 'vendor/autoload.php';\n\nuse Aws\\Common\\Aws;\nuse Aws\\S3\\Enum\\CannedAcl;\nuse Aws\\S3\\Exception\\S3Exception;\n\nconst MONTH = 2592000;\n\n// Instantiate an S3 client\n$s3 = Aws::factory('config.php')->get('s3');\n// Settings\n$bucketName = 'example.com';\n$objectKey = 'image.jpg';\n$maxAge = MONTH;\n$contentType = 'image/jpeg';\n\ntry {\n $o = $s3->copyObject(array(\n 'Bucket' => $bucketName,\n 'Key' => $objectKey,\n 'CopySource' => $bucketName . '/'. $objectKey,\n 'MetadataDirective' => 'REPLACE',\n 'ACL' => CannedAcl::PUBLIC_READ,\n 'command.headers' => array(\n 'Cache-Control' => 'public,max-age=' . $maxAge,\n 'Content-Type' => $contentType\n )\n ));\n\n // print_r($o->ETag);\n} catch (Exception $e) {\n echo $objectKey . ': ' . $e->getMessage() . PHP_EOL;\n}\n?>\n</code></pre>\n"
},
{
"answer_id": 29798456,
"author": "Jefin Stephan",
"author_id": 2198345,
"author_profile": "https://Stackoverflow.com/users/2198345",
"pm_score": 1,
"selected": false,
"text": "<p>In Java, try this</p>\n\n<pre><code>S3Object s3Object = amazonS3Client.getObject(bucketName, fileKey);\nObjectMetadata metadata = s3Object.getObjectMetadata();\nMap customMetaData = new HashMap();\ncustomMetaData.put(\"yourKey\", \"updateValue\");\ncustomMetaData.put(\"otherKey\", \"newValue\");\nmetadata.setUserMetadata(customMetaData);\n\namazonS3Client.putObject(new PutObjectRequest(bucketName, fileId, s3Object.getObjectContent(), metadata));\n</code></pre>\n\n<p>You can also try copy object. Here metadata will not copy while copying an Object. \nYou have to get metadata of original and set to copy request. \nThis method is more recommended to insert or update metadata of an Amazon S3 object</p>\n\n<pre><code>ObjectMetadata metadata = amazonS3Client.getObjectMetadata(bucketName, fileKey);\nObjectMetadata metadataCopy = new ObjectMetadata();\nmetadataCopy.addUserMetadata(\"yourKey\", \"updateValue\");\nmetadataCopy.addUserMetadata(\"otherKey\", \"newValue\");\nmetadataCopy.addUserMetadata(\"existingKey\", metadata.getUserMetaDataOf(\"existingValue\"));\n\nCopyObjectRequest request = new CopyObjectRequest(bucketName, fileKey, bucketName, fileKey)\n .withSourceBucketName(bucketName)\n .withSourceKey(fileKey)\n .withNewObjectMetadata(metadataCopy);\n\namazonS3Client.copyObject(request);\n</code></pre>\n"
},
{
"answer_id": 34396020,
"author": "Vivek",
"author_id": 3726185,
"author_profile": "https://Stackoverflow.com/users/3726185",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a helping code in Python. \n<div class=\"snippet\" data-lang=\"js\" data-hide=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code>import boto\r\n\r\none_year = 3600*24*365\r\ncckey = 'cache-control'\r\ns3_connection = S3Connection()\r\nbucket_name = 'my_bucket'\r\nbucket = s3_connection.get_bucket(bucket_name validate=False)\r\n\r\n\r\nfor key in bucket:\r\n key_name = key.key\r\n if key.size == 0: # continue on directories\r\n continue\r\n # Get key object\r\n key = bucket.get_key(key_name)\r\n\r\n if key.cache_control is not None:\r\n print(\"Exists\")\r\n continue\r\n\r\n cache_time = one_year\r\n #set metdata\r\n key.set_metadata(name=cckey, value = ('max-age=%d, public' % (cache_time)))\r\n key.set_metadata(name='content-type', value = key.content_type)\r\n # Copy the same key\r\n key2 = key.copy(key.bucket.name, key.name, key.metadata, preserve_acl=True)\r\n continue\r\n\r\n </code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>Explanation: Code adds new metadata to the existing key and then copies the same file.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7399/"
] |
I've uploaded a bunch of images to Amazon S3, and now want to add a Cache-Control header to them.
Can the header be updated without downloading the entire image? If so, how?
|
It's beta functionality, but you can specify new meta data when you [copy an object](http://docs.amazonwebservices.com/AmazonS3/2006-03-01/index.html?RESTObjectCOPY.html). Specify the same source and destination for the copy, and this has the effect of just updating the meta data on your object.
```
PUT /myObject HTTP/1.1
Host: mybucket.s3.amazonaws.com
x-amz-copy-source: /mybucket/myObject
x-amz-metadata-directive: REPLACE
x-amz-meta-myKey: newValue
```
|
269,845 |
<p>According to the help file that comes with the Spring.NET framework, you can inject a dependancy defined in the local file by using an 'idref' tag along with a 'local' attribute. </p>
<p>I have been trying to do this with no success and was hoping someone had the experience to help me out. </p>
<p>Below I have a snippet from the config where I am passing it as a constructor argument, but I have tried setting it as a property as well. Both methods seem to yield the same error.</p>
<pre><code><object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/>
<object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary">
<constructor-arg name="myClass">
<idref local="theTargetObject"/>
</constructor-arg>
</object>
</code></pre>
<p>Error creating context 'spring.root': Error creating object with name 'theClientObject' defined in 'file [C:\Test\TestApp\bin\Debug\my.config.xml]' : Unsatisfied dependency expressed through constructor argument with index 0 of type [TestClassLibrary.TargetObject] : Could not convert constructor argument value [theTargetObject] to required type [TestClassLibrary.TargetObject] : Cannot convert property value of type [System.String] to required type [TestClassLibrary.TargetObject] for property ''.</p>
|
[
{
"answer_id": 411132,
"author": "Erich Eichinger",
"author_id": 51264,
"author_profile": "https://Stackoverflow.com/users/51264",
"pm_score": 2,
"selected": false,
"text": "<p>I guess gef was on the right way but accidentially mixed it up when pasting the snippet.You are looking for the <a href=\"http://www.springframework.net/docs/1.2.0/reference/html/objects.html#objects-ref-element\" rel=\"nofollow noreferrer\"><ref> element</a>:</p>\n\n<pre><code><object id=\"theTargetObject\" type=\"TestClassLibrary.TargetObject, TestClassLibrary\"/>\n<object id=\"theClientObject\" type=\"TestClassLibrary.ClientObject, TestClassLibrary\">\n <property name=\"myClass\">\n <ref local=\"theTargetObject\"/>\n </property>\n</code></pre>\n\n<p></p>\n\n<p>the shorthand notation for this is:</p>\n\n<pre><code><object id=\"theClientObject\" type=\"TestClassLibrary.ClientObject, TestClassLibrary\">\n <property name=\"myClass ref=\"theTargetObject\"/>\n</code></pre>\n\n<p>hth,\nErich</p>\n"
},
{
"answer_id": 1276490,
"author": "intangible02",
"author_id": 154839,
"author_profile": "https://Stackoverflow.com/users/154839",
"pm_score": 1,
"selected": false,
"text": "<p>Please view the post <a href=\"http://forum.springsource.org/showthread.php?t=14211\" rel=\"nofollow noreferrer\">http://forum.springsource.org/showthread.php?t=14211</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269845",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
According to the help file that comes with the Spring.NET framework, you can inject a dependancy defined in the local file by using an 'idref' tag along with a 'local' attribute.
I have been trying to do this with no success and was hoping someone had the experience to help me out.
Below I have a snippet from the config where I am passing it as a constructor argument, but I have tried setting it as a property as well. Both methods seem to yield the same error.
```
<object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/>
<object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary">
<constructor-arg name="myClass">
<idref local="theTargetObject"/>
</constructor-arg>
</object>
```
Error creating context 'spring.root': Error creating object with name 'theClientObject' defined in 'file [C:\Test\TestApp\bin\Debug\my.config.xml]' : Unsatisfied dependency expressed through constructor argument with index 0 of type [TestClassLibrary.TargetObject] : Could not convert constructor argument value [theTargetObject] to required type [TestClassLibrary.TargetObject] : Cannot convert property value of type [System.String] to required type [TestClassLibrary.TargetObject] for property ''.
|
I guess gef was on the right way but accidentially mixed it up when pasting the snippet.You are looking for the [<ref> element](http://www.springframework.net/docs/1.2.0/reference/html/objects.html#objects-ref-element):
```
<object id="theTargetObject" type="TestClassLibrary.TargetObject, TestClassLibrary"/>
<object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary">
<property name="myClass">
<ref local="theTargetObject"/>
</property>
```
the shorthand notation for this is:
```
<object id="theClientObject" type="TestClassLibrary.ClientObject, TestClassLibrary">
<property name="myClass ref="theTargetObject"/>
```
hth,
Erich
|
269,864 |
<p>So I'm looking for a pattern like this:</p>
<blockquote>
<p>size='0x0'</p>
</blockquote>
<p>In a log file, but I'm only interested in large sizes (4 digits or more). The following regex works great in EditPadPro (nice tool BTW)</p>
<pre><code>size='0x[0-9a-fA-F]{4,}
</code></pre>
<p>But the same RegEx does not work in awk - seems like the repetition <code>{4,}</code> is messing it up. Same with WinGrep - any idea from the RegEx gurus? Thanks!</p>
|
[
{
"answer_id": 269874,
"author": "Adam Alexander",
"author_id": 33164,
"author_profile": "https://Stackoverflow.com/users/33164",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know of any elegant alternatives to the {4,} syntax, but if it is not working in your desired environment you could resort to this ugly hack:</p>\n\n<pre><code>size='0x[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]+\n</code></pre>\n\n<p>Hope this helps!</p>\n\n<p>Adam</p>\n"
},
{
"answer_id": 270023,
"author": "Keng",
"author_id": 730,
"author_profile": "https://Stackoverflow.com/users/730",
"pm_score": 0,
"selected": false,
"text": "<p>Don't forget the last apostrophe.</p>\n\n<pre><code>'\n</code></pre>\n"
},
{
"answer_id": 270101,
"author": "Dan Fego",
"author_id": 34426,
"author_profile": "https://Stackoverflow.com/users/34426",
"pm_score": 4,
"selected": true,
"text": "<p>You can in fact use awk, with a caveat.</p>\n\n<p>As mentioned on the following page, you need a special command-line option (--re-interval) to make it work out, since the interval expression (the {4,}) is not in the standard:</p>\n\n<p><a href=\"http://kansai.anesth.or.jp/gijutu/awk/gawk/gawk_28.html\" rel=\"noreferrer\">http://kansai.anesth.or.jp/gijutu/awk/gawk/gawk_28.html</a></p>\n\n<p>So in the end, you'll want something that looks like:</p>\n\n<pre><code>awk --re-interval \"/size='0x[0-9a-fA-F]{4,}'/\" thefile\n</code></pre>\n\n<p>This will print out the lines that match.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15797/"
] |
So I'm looking for a pattern like this:
>
> size='0x0'
>
>
>
In a log file, but I'm only interested in large sizes (4 digits or more). The following regex works great in EditPadPro (nice tool BTW)
```
size='0x[0-9a-fA-F]{4,}
```
But the same RegEx does not work in awk - seems like the repetition `{4,}` is messing it up. Same with WinGrep - any idea from the RegEx gurus? Thanks!
|
You can in fact use awk, with a caveat.
As mentioned on the following page, you need a special command-line option (--re-interval) to make it work out, since the interval expression (the {4,}) is not in the standard:
<http://kansai.anesth.or.jp/gijutu/awk/gawk/gawk_28.html>
So in the end, you'll want something that looks like:
```
awk --re-interval "/size='0x[0-9a-fA-F]{4,}'/" thefile
```
This will print out the lines that match.
|
269,872 |
<p>I have a collection of unmanaged dlls with a C# wrapper around them that I'm calling from a C# project. I've added a build event line that looks like:</p>
<pre><code>mkdir ..\Release
mkdir ..\Debug
copy ..\..\Includes\*.dll ..\Release\*.dll
copy ..\..\Includes\*.dll ..\Debug\*.dll
</code></pre>
<p>Problem is, when I go to publish the application, those dlls aren't included, and the publication is worse than useless, since it creates an application that runs until you call one of those dlls.</p>
<p>So, how do I include unmanaged dlls when I publish the project?</p>
|
[
{
"answer_id": 270414,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 3,
"selected": true,
"text": "<p>And the answer is: don't publish this, use the windows installer instead, <a href=\"http://msdn.microsoft.com/en-us/library/e2444w33(VS.80).aspx\" rel=\"nofollow noreferrer\">as described here.</a></p>\n"
},
{
"answer_id": 335981,
"author": "NoizWaves",
"author_id": 38438,
"author_profile": "https://Stackoverflow.com/users/38438",
"pm_score": 1,
"selected": false,
"text": "<p>I'm currently investigating the same issue. The literature on the topic is very sparse indeed!</p>\n\n<p>The only solution I can see is to embed the unmanaged DLL as an embedded resource inside the assembly, and programatically extract it out to the executing path before calling any functions.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21981/"
] |
I have a collection of unmanaged dlls with a C# wrapper around them that I'm calling from a C# project. I've added a build event line that looks like:
```
mkdir ..\Release
mkdir ..\Debug
copy ..\..\Includes\*.dll ..\Release\*.dll
copy ..\..\Includes\*.dll ..\Debug\*.dll
```
Problem is, when I go to publish the application, those dlls aren't included, and the publication is worse than useless, since it creates an application that runs until you call one of those dlls.
So, how do I include unmanaged dlls when I publish the project?
|
And the answer is: don't publish this, use the windows installer instead, [as described here.](http://msdn.microsoft.com/en-us/library/e2444w33(VS.80).aspx)
|
269,876 |
<p>I've always done web apps and now I need to do a console app. I need to use both an odbc connection and a regular connection. </p>
<p>In the past I would have used:</p>
<pre><code><add name="LinkConnectionString" connectionString="Data Source=SERENITY\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True" providerName="System.Data.SqlClient"/>
</code></pre>
<p>In the web.config, however I am not sure how to do the same thing with inline code.
So like string connectionString = @".....";</p>
<p>I have tried multiple combinations, looked online (including connectionstrings.com), but none of them worked. </p>
<p>Can anyone help me out? I want both the odbc and the regular... as they seem different should be different according to the sample ones online (that don't work). </p>
|
[
{
"answer_id": 269880,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 3,
"selected": false,
"text": "<p>You should be able to find whatever you need here:</p>\n\n<p><a href=\"http://www.connectionstrings.com/\" rel=\"noreferrer\">http://www.connectionstrings.com/</a></p>\n\n<p>For one of our apps we use this connection string:</p>\n\n<p>\"DRIVER={driver};SERVER=server.database;UID=username;PWD=password\"</p>\n"
},
{
"answer_id": 269885,
"author": "Gustavo Rubio",
"author_id": 14533,
"author_profile": "https://Stackoverflow.com/users/14533",
"pm_score": 1,
"selected": false,
"text": "<p>I think it deppends as to what database you want to connect, because of the Driver that its used to connect to the database engine.</p>\n\n<p>You might want to take a look at:</p>\n\n<p><a href=\"http://www.connectionstrings.com/\" rel=\"nofollow noreferrer\">http://www.connectionstrings.com/</a></p>\n\n<p>They have plenty of examples there.</p>\n"
},
{
"answer_id": 269940,
"author": "Nathan Koop",
"author_id": 18821,
"author_profile": "https://Stackoverflow.com/users/18821",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried something like this for SQLServer?</p>\n\n<pre><code> SqlConnection conn = new SqlConnection(@\"Data Source=SERENITY\\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True\");\n SqlCommand cmd = new SqlCommand(\"SELECT * FROM tableName\", conn);\n conn.Open();\n //<snip> Run Command\n conn.Close();\n</code></pre>\n\n<p>and this for ODBC</p>\n\n<pre><code>OdbcConnection conn = new OdbcConnection(@\"ODBC connection string\");\nOdbcCommand cmd = new OdbcCommand(\"SELECT * FROM tableName\", conn);\nconn.Open();\n//Run Command\nconn.Close();\n</code></pre>\n"
},
{
"answer_id": 269959,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 5,
"selected": false,
"text": "<p>A cool trick to building connection strings is to right click on your desktop, choose \"new text document\" - this will make a temporary notepad .txt file. Rename it to .udl and then double click it - you can now create any connection string. Click ok when done and open the file in notepad to see the connectionstring.</p>\n\n<p>UPDATED April 28, 2009 (powershell script):</p>\n\n<pre><code>function get-oledbconnection ([switch]$Open) {\n $null | set-content ($udl = \"$([io.path]::GetTempPath())\\temp.udl\");\n $psi = new-object Diagnostics.ProcessStartInfo\n $psi.CreateNoWindow = $true\n $psi.UseShellExecute = $true\n $psi.FileName = $udl\n $pi = [System.Diagnostics.Process]::Start($psi)\n $pi.WaitForExit()\n write-host (gc $udl) # verbose \n if (gc $udl) {\n $conn = new-object data.oledb.oledbconnection (gc $udl)[2]\n if ($Open) { $conn.Open() }\n }\n $conn\n}\n</code></pre>\n"
},
{
"answer_id": 711208,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p><code><add name=\"myName\" connectionString=\"dsn=myDSN;UID=myUID;\"\nproviderName=\"System.Data.Odbc\" /></code></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] |
I've always done web apps and now I need to do a console app. I need to use both an odbc connection and a regular connection.
In the past I would have used:
```
<add name="LinkConnectionString" connectionString="Data Source=SERENITY\SQLEXPRESS;Initial Catalog=Link;Integrated Security=True" providerName="System.Data.SqlClient"/>
```
In the web.config, however I am not sure how to do the same thing with inline code.
So like string connectionString = @".....";
I have tried multiple combinations, looked online (including connectionstrings.com), but none of them worked.
Can anyone help me out? I want both the odbc and the regular... as they seem different should be different according to the sample ones online (that don't work).
|
A cool trick to building connection strings is to right click on your desktop, choose "new text document" - this will make a temporary notepad .txt file. Rename it to .udl and then double click it - you can now create any connection string. Click ok when done and open the file in notepad to see the connectionstring.
UPDATED April 28, 2009 (powershell script):
```
function get-oledbconnection ([switch]$Open) {
$null | set-content ($udl = "$([io.path]::GetTempPath())\temp.udl");
$psi = new-object Diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.UseShellExecute = $true
$psi.FileName = $udl
$pi = [System.Diagnostics.Process]::Start($psi)
$pi.WaitForExit()
write-host (gc $udl) # verbose
if (gc $udl) {
$conn = new-object data.oledb.oledbconnection (gc $udl)[2]
if ($Open) { $conn.Open() }
}
$conn
}
```
|
269,882 |
<p>If I do this:</p>
<pre><code>// In header
class Foo {
void foo(bar*);
};
// In cpp
void Foo::foo(bar* const pBar) {
//Stuff
}
</code></pre>
<p>The compiler does not complain that the signatures for Foo::foo do not match. However if I had:</p>
<pre><code>void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp
</code></pre>
<p>The code will fail to compile.</p>
<p>What is going on?
I'm using gcc 4.1.x</p>
|
[
{
"answer_id": 269889,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 4,
"selected": false,
"text": "<p>In the first, you've promised the compiler, but not other users of the class that you will not edit the variable.</p>\n\n<p>In your second example, you've promised other users of the class that you will not edit their variable, but failed to uphold that promise.</p>\n\n<p>I should also note that there is a distinct difference between</p>\n\n<pre><code>bar* const variable\n</code></pre>\n\n<p>and</p>\n\n<pre><code>const bar* variable\n</code></pre>\n\n<p>and</p>\n\n<pre><code>const bar* const variable\n</code></pre>\n\n<p>In the first form, the pointer will never change, but you can edit the object that is pointed to. In the second form, you can edit the pointer(point it to another object), but never the variable that it points to. In the final form, you will neither edit the pointer, nor the object it points to. <a href=\"http://www.parashift.com/c++-faq-lite/const-correctness.html#faq-18.5\" rel=\"nofollow noreferrer\">Reference</a></p>\n\n<p>To add a bit more of a clarification to the question stated, you can always promise MORE const than less. Given a class:</p>\n\n<pre><code>class Foo {\n void func1 (int x);\n void func2 (int *x);\n}\n</code></pre>\n\n<p>You can compile the following implementation:</p>\n\n<pre><code>Foo::func1(const int x) {}\nFoo::func2(const int *x) {}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>Foo::func1(const int x) {}\nFoo::func2(const int* const x) {}\n</code></pre>\n\n<p>without any problems. You've told your users that you may possibly edit their variables. In your implementation, you've told the compiler that this particular implementation will not edit those variables, even though the told the users you might. You haven't broken a promise to the user, and so the code compiles.</p>\n"
},
{
"answer_id": 269890,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>In the former, the <code>const</code> doesn't affect the interface, only the implementation. You are saying to the compiler, \"I am not going to change the value of the <code>bar*</code> within this function\". You can still change what is pointed to by the pointer. In the latter, you are telling the compiler (and all callers) that you will not change the <code>bar</code> structure that the <code>bar*</code> <em>points to</em>.</p>\n"
},
{
"answer_id": 269896,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 3,
"selected": false,
"text": "<p>See <a href=\"https://stackoverflow.com/questions/117293/use-of-const-for-function-parameters\">this question</a>, <a href=\"https://stackoverflow.com/questions/219914/what-use-are-const-pointers-as-opposed-to-pointers-to-const-objects\">this question</a>, and <a href=\"https://stackoverflow.com/questions/232472/what-is-the-difference-between-these-declarations-in-c\">this question</a>.</p>\n\n<p>Basically, the const only means that the function will not modify the pointer's value. The pointers contents are not const, the same as the header's signature.</p>\n"
},
{
"answer_id": 269912,
"author": "anio",
"author_id": 35227,
"author_profile": "https://Stackoverflow.com/users/35227",
"pm_score": 0,
"selected": false,
"text": "<p>So the second const in:</p>\n\n<pre><code>void Foo::foo(const bar* const);\n</code></pre>\n\n<p>Is <strong><em>not</em></strong> part of the method signature?</p>\n"
},
{
"answer_id": 269941,
"author": "Dusty Campbell",
"author_id": 2174,
"author_profile": "https://Stackoverflow.com/users/2174",
"pm_score": 3,
"selected": true,
"text": "<p>The <em>const</em> keyword in the first example is meaningless. You are saying that you don't plan on changing the pointer. However, the pointer was passed by value and so it dos not matter if you change it or not; it will not effect the caller. Similarly, you could also do this:</p>\n\n<pre><code>// In header \nclass Foo {\nvoid foo( int b );\n};\n\n// In cpp\nvoid Foo::foo( const int b ) {\n//Stuff\n}\n</code></pre>\n\n<p>You can even do this:</p>\n\n<pre><code>// In header \nclass Foo {\nvoid foo( const int b );\n};\n\n// In cpp\nvoid Foo::foo( int b ) {\n//Stuff\n}\n</code></pre>\n\n<p>Since the <em>int</em> is passed by value, the constness does not matter.</p>\n\n<p>In the second example you are saying that your function takes a pointer to one type, but then implement it as taking a pointer to another type, therefore it fails.</p>\n"
},
{
"answer_id": 269968,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 0,
"selected": false,
"text": "<p>This is simpler to understand with a variable type other than a pointer. For example, you can have the following function declaration:</p>\n\n<pre><code>void foo( int i );\n</code></pre>\n\n<p>The definition can look like this:</p>\n\n<pre><code>void foo( const int i ) { ... }\n</code></pre>\n\n<p>Whether the variable 'i' is const or not on the definition side is an implementation detail. It has no impact for the clients of that function.</p>\n"
},
{
"answer_id": 269980,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 0,
"selected": false,
"text": "<p>It probably doesn't care much about <code>void Foo::foo(bar* const pBar)</code> because how you treat the pointer itself (const or not) doesn't matter one bit outside of the routine. The C rules say that no change to pBar will travel outside of foo either way.</p>\n\n<p>However, if it is <code>(const bar* pBar)</code>, that makes a difference, because it means the compiler is not to allow callers to pass in pointers to non-const objects.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35227/"
] |
If I do this:
```
// In header
class Foo {
void foo(bar*);
};
// In cpp
void Foo::foo(bar* const pBar) {
//Stuff
}
```
The compiler does not complain that the signatures for Foo::foo do not match. However if I had:
```
void foo(const bar*); //In header
void Foo::foo(bar*) {} //In cpp
```
The code will fail to compile.
What is going on?
I'm using gcc 4.1.x
|
The *const* keyword in the first example is meaningless. You are saying that you don't plan on changing the pointer. However, the pointer was passed by value and so it dos not matter if you change it or not; it will not effect the caller. Similarly, you could also do this:
```
// In header
class Foo {
void foo( int b );
};
// In cpp
void Foo::foo( const int b ) {
//Stuff
}
```
You can even do this:
```
// In header
class Foo {
void foo( const int b );
};
// In cpp
void Foo::foo( int b ) {
//Stuff
}
```
Since the *int* is passed by value, the constness does not matter.
In the second example you are saying that your function takes a pointer to one type, but then implement it as taking a pointer to another type, therefore it fails.
|
269,906 |
<p>Hopefully this won't be taken as asking the same question twice...</p>
<p>So I'm working on a Flash website (in AS2) which has an outer index swf which loads sub swf files using <code>loadMovie("subfoo1.swf", placeToShowSwf)</code>. These in turn load an xml file which tells it what content to load. Everything works peachy, but we'd like to add a button to the index swf that opens a sub swf file with one or two different values for one or two variables.</p>
<p>Unfortunately, just adding a button that says</p>
<pre><code>loadMovie("foo1.swf", placeToShowSwf);
placeToShowSwf.openProject(x);
</code></pre>
<p>doesn't work, I assume because <code>openProject(x)</code> is called on a file that isn't fully loaded. I know that there's not a problem with the code, because I made a button elsewhere that only calls <code>placeToShowSwf.openProject(x)</code> and there aren't any problems. </p>
<p>I see two solutions, both of which I'm unsure how to do.</p>
<ol>
<li>Change the desired value when the swf file is made, like a constructor for a class. But is there some sort of constructor function for swf files? It'd be really nice just to say <code>loadMovie(new foo1.swf(x), placeToShowSwf)</code> or something equivalent.</li>
<li>Wait until after swf (and probably xml) is loaded, and then call <code>placeToShowSwf.openProject(x)</code>. </li>
</ol>
<p>Anyone got any guidance towards either of these solutions, or perhaps some other way that my pea-like brain has been unable to fathom?</p>
|
[
{
"answer_id": 269910,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 0,
"selected": false,
"text": "<p>I use the <strong>Isolation Storage</strong> for configuration. You can also use the <strong>Temp</strong> folder to store temporary information like log.</p>\n"
},
{
"answer_id": 269917,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 1,
"selected": false,
"text": "<p>The best answer depends on the nature of the logs and configurations. If they are program-wide, and don't need to survive uninstallation of the application, then I think they're fine where they are. If the logs and configurations are user specific, or need to survive uninstallation, then they belong somewhere under %USERPROFILE% - %APPDATA% being the 'proper' base directory for this type of thing.</p>\n"
},
{
"answer_id": 269929,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 2,
"selected": false,
"text": "<p>Do not store config files in the application folder, Microsoft has stated this is NOT the ideal location. Windows has been moving towards blocking writing to C:\\Program Files\\ and you'll find in Vista any application that tries to write here, will fire up a UAC warning.</p>\n\n<p>Windows 7 will allow users to customize what UAC popups they use (expect some power users to block most of them) and your app will fail/freeze if the user never approves this write attempt.</p>\n\n<p>If you use the proper userprofile and appdata variables, then Win 2000, XP, Vista, and Win7 will map the data to the proper write friendly folder, with no UAC popups.</p>\n"
},
{
"answer_id": 269964,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 3,
"selected": false,
"text": "<p>For application settings - use <code>System.Environment.SpecialFolder.ApplicationData</code> - this is where a roaming profile data is stored, so it allows your user to log and work from different machines in the domain.</p>\n\n<p>For log files - <code>System.Environment.SpecialFolder.LocalApplicationData</code></p>\n"
},
{
"answer_id": 269990,
"author": "RWendi",
"author_id": 15152,
"author_profile": "https://Stackoverflow.com/users/15152",
"pm_score": 3,
"selected": false,
"text": "<p>To be honest %appdata% is still the best place to place your config files and log files, as it serves the purpose of a placeholder to store your application data. It should not be that hard to access, just write %appdata% in explorer and you will be directed straight to your %appdata% directory.</p>\n"
},
{
"answer_id": 270013,
"author": "Klathzazt",
"author_id": 35223,
"author_profile": "https://Stackoverflow.com/users/35223",
"pm_score": 2,
"selected": false,
"text": "<p>You can use SHGetSpecialFolderPath:</p>\n\n<pre><code>int MAX_PATH = 255;\n\nCString m_strMyPath;\n\nSHGetSpecialFolderPath(NULL, m_strMyPath.GetBuffer(MAX_PATH), CSIDL_COMMON_APPDATA, TRUE);\n</code></pre>\n\n<p>This will specify the 'special folder path' which you can safely write logs to for windows:</p>\n\n<p>For XP: <code>C:\\Documents and Settings\\All Users\\Application Data</code></p>\n\n<p>For Vista: <code>C:\\ProgramData</code></p>\n\n<p>Check the MSDN page here: <a href=\"http://msdn.microsoft.com/en-us/library/bb762204(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/bb762204(VS.85).aspx</a></p>\n"
},
{
"answer_id": 270060,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 6,
"selected": true,
"text": "<p>If you're not using <code>ConfigurationManager</code> to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too. </p>\n\n<p>The default behavior of <code>ConfigurationManager</code> puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in <code>System.Environment.SpecialFolder.LocalApplicationData</code>. It works properly under all versions of Windows that support .NET.</p>\n\n<p>As for log files, <code>System.Environment.SpecialFolder.LocalApplicationData</code> is generally the place that you want to put them, because it's guaranteed to be user-writeable. </p>\n\n<p>There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.</p>\n\n<p>I have a couple of complaints about <code>ConfigurationManager</code> and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated <code>Settings</code> class. The mechanism by which the <code>app.config</code> file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: \"what happened to my connection string?\"). And if there's a way of creating settings that don't have default values, I haven't found it.</p>\n"
},
{
"answer_id": 2862148,
"author": "WWC",
"author_id": 311749,
"author_profile": "https://Stackoverflow.com/users/311749",
"pm_score": 4,
"selected": false,
"text": "<p>Note: You can get the path to the LocalApplicationData folder in .NET by using the following function:</p>\n\n<pre><code>string strPath=System.Environment.GetFolderPath(System.Environment.SpecialFolder.LocalApplicationData);\n</code></pre>\n"
},
{
"answer_id": 12956746,
"author": "Dylan Hayes",
"author_id": 892460,
"author_profile": "https://Stackoverflow.com/users/892460",
"pm_score": 3,
"selected": false,
"text": "<p>The accepted answer notes that for log files the following is a good spot. \n<code>System.Environment.SpecialFolder.LocalApplicationData</code> This equates to a path of <code>C:\\Users\\[User]\\AppData\\Roaming</code> which you can see is user specific. Like the accepted answer mentions this is a guaranteed user-writeable location and can be useful for certain situations</p>\n\n<p>However in a web application environment you may be running your application under a network account and you or a coworker may need to try and track down where exactly those logs are going per application. I personally like to use the non user specific location enumeration of \n<code>System.Environment.SpecialFolder.CommonApplicationData</code> which equates to <code>C:\\ProgramData</code>. Yes, you will need to specify access rights for any folders you create, but it's usually a one time deal and then all of your application logs can live in one happy location.</p>\n\n<p>Additionally, while looking around the Internet, there is a project out there to programatically set write access to folders you create within <code>CommonApplicationData</code>, <em><a href=\"http://www.codeproject.com/Tips/61987/Allow-write-modify-access-to-CommonApplicationData\" rel=\"noreferrer\">Allow write/modify access to CommonApplicationData</a></em>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269906",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32139/"
] |
Hopefully this won't be taken as asking the same question twice...
So I'm working on a Flash website (in AS2) which has an outer index swf which loads sub swf files using `loadMovie("subfoo1.swf", placeToShowSwf)`. These in turn load an xml file which tells it what content to load. Everything works peachy, but we'd like to add a button to the index swf that opens a sub swf file with one or two different values for one or two variables.
Unfortunately, just adding a button that says
```
loadMovie("foo1.swf", placeToShowSwf);
placeToShowSwf.openProject(x);
```
doesn't work, I assume because `openProject(x)` is called on a file that isn't fully loaded. I know that there's not a problem with the code, because I made a button elsewhere that only calls `placeToShowSwf.openProject(x)` and there aren't any problems.
I see two solutions, both of which I'm unsure how to do.
1. Change the desired value when the swf file is made, like a constructor for a class. But is there some sort of constructor function for swf files? It'd be really nice just to say `loadMovie(new foo1.swf(x), placeToShowSwf)` or something equivalent.
2. Wait until after swf (and probably xml) is loaded, and then call `placeToShowSwf.openProject(x)`.
Anyone got any guidance towards either of these solutions, or perhaps some other way that my pea-like brain has been unable to fathom?
|
If you're not using `ConfigurationManager` to manage your application and user settings, you should be. The configuration toolkit in the .NET Framework is remarkably well thought out, and the Visual Studio tools that interoperate with it are too.
The default behavior of `ConfigurationManager` puts both invariant (application) and modifiable (user) settings in the right places: the application settings go in the application folder, and the user settings go in `System.Environment.SpecialFolder.LocalApplicationData`. It works properly under all versions of Windows that support .NET.
As for log files, `System.Environment.SpecialFolder.LocalApplicationData` is generally the place that you want to put them, because it's guaranteed to be user-writeable.
There are certainly cases where you wouldn't - for instance, if you want to write files to a network share so that you easily can access them remotely. There's a pretty wide range of ways to implement that, but most of them start with creating an application setting that contains the path to the shared folder. All of them involve administration.
I have a couple of complaints about `ConfigurationManager` and the VS tools: there needs to be better high-level documentation than there is, and better documentation of the VS-generated `Settings` class. The mechanism by which the `app.config` file turns into the application configuration file in the target build directory is opaque (and the source of one of the most frequently asked questions of all: "what happened to my connection string?"). And if there's a way of creating settings that don't have default values, I haven't found it.
|
269,918 |
<p>I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,</p>
<pre><code>varies_in_single_number_field('foo7bar', 'foo123bar')
# Returns True, because 7 != 123, and there's only one varying
# number region between the two strings.
</code></pre>
<p>In Python I can use the <code>difflib</code> to accomplish this:</p>
<pre><code>import difflib, doctest
def varies_in_single_number_field(str1, str2):
"""
A typical use case is as follows:
>>> varies_in_single_number_field('foo7bar00', 'foo123bar00')
True
Numerical variation in two dimensions is no good:
>>> varies_in_single_number_field('foo7bar00', 'foo123bar01')
False
Varying in a nonexistent field is okay:
>>> varies_in_single_number_field('foobar00', 'foo123bar00')
True
Identical strings don't *vary* in any number field:
>>> varies_in_single_number_field('foobar00', 'foobar00')
False
"""
in_differing_substring = False
passed_differing_substring = False # There should be only one.
differ = difflib.Differ()
for letter_diff in differ.compare(str1, str2):
letter = letter_diff[2:]
if letter_diff.startswith(('-', '+')):
if passed_differing_substring: # Already saw a varying field.
return False
in_differing_substring = True
if not letter.isdigit(): return False # Non-digit diff character.
elif in_differing_substring: # Diff character not found - end of diff.
in_differing_substring = False
passed_differing_substring = True
return passed_differing_substring # No variation if no diff was passed.
if __name__ == '__main__': doctest.testmod()
</code></pre>
<p>But I have no idea how to find something like <code>difflib</code> for C++. Alternative approaches welcome. :)</p>
|
[
{
"answer_id": 270006,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 1,
"selected": false,
"text": "<p>It's probably a bit of overkill, but you could use boost to interface to python. At the worst, difflib is implemented in pure python, and it's not too long. It should be possible to port from python to C...</p>\n"
},
{
"answer_id": 270143,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 3,
"selected": true,
"text": "<p>This might work, it at least passes your demonstration test:\nEDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now.</p>\n\n<pre><code>#include <iostream>\n#include <string>\n#include <vector>\n#include <algorithm>\n#include <cctype>\n\nbool starts_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(0, s1.length()) == s1);\n}\n\nbool ends_with(const std::string &s1, const std::string &s2) {\n return (s1.length() <= s2.length()) && (s2.substr(s2.length() - s1.length()) == s1);\n}\n\nbool is_numeric(const std::string &s) {\n for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {\n if(!std::isdigit(*it)) {\n return false;\n }\n }\n return true;\n}\n\nbool varies_in_single_number_field(std::string s1, std::string s2) {\n\n size_t index1 = 0;\n size_t index2 = s1.length() - 1;\n\n if(s1 == s2) {\n return false;\n }\n\n if((s1.empty() && is_numeric(s2)) || (s2.empty() && is_numeric(s1))) {\n return true;\n }\n\n if(s1.length() < s2.length()) {\n s1.swap(s2);\n }\n\n while(index1 < s1.length() && starts_with(s1.substr(0, index1), s2)) { index1++; }\n while(ends_with(s1.substr(index2), s2)) { index2--; }\n\n return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1)));\n\n}\n\nint main() {\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foo123bar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"foobar00\", \"foobar00\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"7aaa\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa7\", \"aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"7aaa\") << std::endl;\n std::cout << std::boolalpha << varies_in_single_number_field(\"aaa\", \"aaa7\") << std::endl;\n}\n</code></pre>\n\n<p>Basically, it looks for a string which has 3 parts, string2 begins with part1, string2 ends with part3 and part2 is only digits.</p>\n"
},
{
"answer_id": 270155,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 1,
"selected": false,
"text": "<p>You could do an ad hoc approach: You're looking to match strings s and s', where s=abc and s'=ab'c, and the b and b' should be two distinct numbers (possible empty). So:</p>\n\n<ol>\n<li>Compare the strings from the left, char by char, until you hit different characters, and then stop. You </li>\n<li>Similarly, compare the strings from the right until you hit different characters, OR hit that left marker.</li>\n<li>Then check the remainders in the middle to see if they're both numbers.</li>\n</ol>\n"
},
{
"answer_id": 270241,
"author": "cdleary",
"author_id": 3594,
"author_profile": "https://Stackoverflow.com/users/3594",
"pm_score": 0,
"selected": false,
"text": "<p>@Evan Teran: looks like we did this in parallel -- I have a markedly less readable O(n) implementation:</p>\n\n<pre><code>#include <cassert>\n#include <cctype>\n#include <string>\n#include <sstream>\n#include <iostream>\n\nusing namespace std;\n\nostringstream debug;\nconst bool DEBUG = true;\n\nbool varies_in_single_number_field(const string &str1, const string &str2) {\n bool in_difference = false;\n bool passed_difference = false;\n string str1_digits, str2_digits;\n size_t str1_iter = 0, str2_iter = 0;\n while (str1_iter < str1.size() && str2_iter < str2.size()) {\n const char &str1_char = str1.at(str1_iter);\n const char &str2_char = str2.at(str2_iter);\n debug << \"str1: \" << str1_char << \"; str2: \" << str2_char << endl;\n if (str1_char == str2_char) {\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n ++str1_iter, ++str2_iter;\n continue;\n }\n in_difference = true;\n if (passed_difference) { /* Already passed a difference. */\n debug << \"Already passed a difference.\" << endl;\n return false;\n }\n bool str1_char_is_digit = isdigit(str1_char);\n bool str2_char_is_digit = isdigit(str2_char);\n if (str1_char_is_digit && !str2_char_is_digit) {\n ++str1_iter;\n str1_digits.push_back(str1_char);\n } else if (!str1_char_is_digit && str2_char_is_digit) {\n ++str2_iter;\n str2_digits.push_back(str2_char);\n } else if (str1_char_is_digit && str2_char_is_digit) {\n ++str1_iter, ++str2_iter;\n str1_digits.push_back(str1_char);\n str2_digits.push_back(str2_char);\n } else { /* Both are non-digits and they're different. */\n return false;\n }\n }\n if (in_difference) {\n in_difference = false;\n passed_difference = true;\n }\n string str1_remainder = str1.substr(str1_iter);\n string str2_remainder = str2.substr(str2_iter);\n debug << \"Got to exit point; passed difference: \" << passed_difference\n << \"; str1 digits: \" << str1_digits\n << \"; str2 digits: \" << str2_digits\n << \"; str1 remainder: \" << str1_remainder\n << \"; str2 remainder: \" << str2_remainder\n << endl;\n return passed_difference\n && (str1_digits != str2_digits)\n && (str1_remainder == str2_remainder);\n}\n\nint main() {\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foo7bar00\", \"foo123bar01\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foo123bar00\") == true);\n assert(varies_in_single_number_field(\"foobar00\", \"foobar00\") == false);\n assert(varies_in_single_number_field(\"foobar00\", \"foobaz00\") == false);\n assert(varies_in_single_number_field(\"foo00bar\", \"foo01barz\") == false);\n assert(varies_in_single_number_field(\"foo01barz\", \"foo00bar\") == false);\n if (DEBUG) {\n cout << debug.str();\n }\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 270251,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 0,
"selected": false,
"text": "<p>How about using something like boost::regex?</p>\n\n<pre>\n// pseudo code, may or may not compile\nbool match_except_numbers(const std::string& s1, const std::string& s2)\n{\n static const boost::regex fooNumberBar(\"foo\\\\d+bar\");\n return boost::match(s1, fooNumberBar) && boost::match(s2, fooNumberBar);\n}\n</pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269918",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3594/"
] |
I'm trying to diff two strings to determine whether or not they solely vary in one numerical subset of the string structure; for example,
```
varies_in_single_number_field('foo7bar', 'foo123bar')
# Returns True, because 7 != 123, and there's only one varying
# number region between the two strings.
```
In Python I can use the `difflib` to accomplish this:
```
import difflib, doctest
def varies_in_single_number_field(str1, str2):
"""
A typical use case is as follows:
>>> varies_in_single_number_field('foo7bar00', 'foo123bar00')
True
Numerical variation in two dimensions is no good:
>>> varies_in_single_number_field('foo7bar00', 'foo123bar01')
False
Varying in a nonexistent field is okay:
>>> varies_in_single_number_field('foobar00', 'foo123bar00')
True
Identical strings don't *vary* in any number field:
>>> varies_in_single_number_field('foobar00', 'foobar00')
False
"""
in_differing_substring = False
passed_differing_substring = False # There should be only one.
differ = difflib.Differ()
for letter_diff in differ.compare(str1, str2):
letter = letter_diff[2:]
if letter_diff.startswith(('-', '+')):
if passed_differing_substring: # Already saw a varying field.
return False
in_differing_substring = True
if not letter.isdigit(): return False # Non-digit diff character.
elif in_differing_substring: # Diff character not found - end of diff.
in_differing_substring = False
passed_differing_substring = True
return passed_differing_substring # No variation if no diff was passed.
if __name__ == '__main__': doctest.testmod()
```
But I have no idea how to find something like `difflib` for C++. Alternative approaches welcome. :)
|
This might work, it at least passes your demonstration test:
EDIT: I've made some modifications to deal with some string indexing issues. I believe it should be good now.
```
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cctype>
bool starts_with(const std::string &s1, const std::string &s2) {
return (s1.length() <= s2.length()) && (s2.substr(0, s1.length()) == s1);
}
bool ends_with(const std::string &s1, const std::string &s2) {
return (s1.length() <= s2.length()) && (s2.substr(s2.length() - s1.length()) == s1);
}
bool is_numeric(const std::string &s) {
for(std::string::const_iterator it = s.begin(); it != s.end(); ++it) {
if(!std::isdigit(*it)) {
return false;
}
}
return true;
}
bool varies_in_single_number_field(std::string s1, std::string s2) {
size_t index1 = 0;
size_t index2 = s1.length() - 1;
if(s1 == s2) {
return false;
}
if((s1.empty() && is_numeric(s2)) || (s2.empty() && is_numeric(s1))) {
return true;
}
if(s1.length() < s2.length()) {
s1.swap(s2);
}
while(index1 < s1.length() && starts_with(s1.substr(0, index1), s2)) { index1++; }
while(ends_with(s1.substr(index2), s2)) { index2--; }
return is_numeric(s1.substr(index1 - 1, (index2 + 1) - (index1 - 1)));
}
int main() {
std::cout << std::boolalpha << varies_in_single_number_field("foo7bar00", "foo123bar00") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("foo7bar00", "foo123bar01") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("foobar00", "foo123bar00") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("foobar00", "foobar00") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("7aaa", "aaa") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("aaa7", "aaa") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("aaa", "7aaa") << std::endl;
std::cout << std::boolalpha << varies_in_single_number_field("aaa", "aaa7") << std::endl;
}
```
Basically, it looks for a string which has 3 parts, string2 begins with part1, string2 ends with part3 and part2 is only digits.
|
269,931 |
<p>I have a script that generates data in csv format which is sent to the user along with a set of headers that tell the browser it is a .csv file. Everything works great when users (left)click on the link to the script, they are presented with a download dialog with the filename ending in .csv and it suggests using excel, or calc, to open it. However, when users right-click and choose Save As it is being saved with the php script name.</p>
<p>Here is the header code:</p>
<pre><code>header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
$val = date("m_d_Y_g_i");
Header('Content-Disposition: attachment; filename="personal_information_'.$val.'.csv"');
</code></pre>
<p>So again, when users left-click it saves the file as personal_information_date.csv; when they right click it saves as download.php. I'm using FF3. Oddly enough, IE7 does not have this problem.</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 269955,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 2,
"selected": false,
"text": "<p>Use mod_rewrite to alias the file from file.csv to file.php, this is a browser issue rather than PHP because by saving the file it isn't running it before it is saving it.</p>\n\n<p>So to summarise:</p>\n\n<ol>\n<li>Link to <code>personal_information_date.csv</code></li>\n<li>Create a <code>mod_rewrite</code> rule that forwards <code>personal_information_date.csv</code> to <code>download.php</code> (e.g.: <code>RewriteRule ^personal_information_date.csv$ download.php</code>).</li>\n</ol>\n"
},
{
"answer_id": 269993,
"author": "Olaf Kock",
"author_id": 13447,
"author_profile": "https://Stackoverflow.com/users/13447",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>I believe that setting three different mimetypes doesn't help</li>\n<li>what's $val ? Is this known content or user provided - e.g. could it contain nasty characters (like \") or even linebreaks, e.g. introduce new HTTP header lines?</li>\n<li>have a look at the HTTP-Headers that arrive at the client. Either the Firefox built-in information or use LiveHttpHeaders (plugin to be found at the Mozilla site - logs all HTTP-Headers) - I'm sure there are more/other plugins for FF available.</li>\n</ul>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 270276,
"author": "Arne Burmeister",
"author_id": 12890,
"author_profile": "https://Stackoverflow.com/users/12890",
"pm_score": 1,
"selected": false,
"text": "<p>The HTTP client may ignore more than one content type header, the two other will be ignored - which of them? Depends on the browser implementation, therefor the different behaviour. The correct mime type is text/csv, not application/octet-stream! The content-disposition header is correct for the download.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a script that generates data in csv format which is sent to the user along with a set of headers that tell the browser it is a .csv file. Everything works great when users (left)click on the link to the script, they are presented with a download dialog with the filename ending in .csv and it suggests using excel, or calc, to open it. However, when users right-click and choose Save As it is being saved with the php script name.
Here is the header code:
```
header("Pragma: public");
header("Expires: 0"); // set expiration time
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
$val = date("m_d_Y_g_i");
Header('Content-Disposition: attachment; filename="personal_information_'.$val.'.csv"');
```
So again, when users left-click it saves the file as personal\_information\_date.csv; when they right click it saves as download.php. I'm using FF3. Oddly enough, IE7 does not have this problem.
Any ideas?
|
Use mod\_rewrite to alias the file from file.csv to file.php, this is a browser issue rather than PHP because by saving the file it isn't running it before it is saving it.
So to summarise:
1. Link to `personal_information_date.csv`
2. Create a `mod_rewrite` rule that forwards `personal_information_date.csv` to `download.php` (e.g.: `RewriteRule ^personal_information_date.csv$ download.php`).
|
269,932 |
<p>I wrote a managed C++ class that has the following function:</p>
<pre><code>void EndPointsMappingWrapper::GetLastError(char* strErrorMessage)
{
strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer();
}
</code></pre>
<p>As you can see, this is a simple method to copy the managed string of the last error to the unmanaged world (<code>char*</code>).</p>
<p>From my unmanaged class I call the method like this:</p>
<pre><code>char err[1000];
ofer->GetLastError(err);
</code></pre>
<p>Putting a breakpoint at the managed C++ method shows that the string is successfully translated into the <code>char*</code>. However, once I return to the unmanaged class, the content of <code>err[1000]</code> is lost and it's empty again.</p>
|
[
{
"answer_id": 269953,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 0,
"selected": false,
"text": "<p>We use the following C++ Class to do the conversions for us and it works fine. You should be able to modify your method to use it.</p>\n\n<p><strong>H File</strong></p>\n\n<pre><code>public ref class ManagedStringConverter\n{\npublic:\n ManagedStringConverter( System::String^ pString );\n ~ManagedStringConverter();\n\n property char* PrimitiveString\n {\n char* get() { return m_pString; }\n }\n\n /// <summary>\n /// Converts a System::String to a char * string. You must release this with FreeString.\n /// </summary>\n static const char* StringToChar( System::String^ str );\n\n /// <summary>\n /// Converts a System::String to a __wchar_t * string. You must release this with FreeString.\n /// </summary>\n static const __wchar_t * StringToWChar( System::String^ str );\n\n /// <summary>\n /// Frees memory allocated in StringToChar()\n /// </summary>\n static void FreeString( const char * pszStr );\n\nprivate:\n char* m_pString;\n};\n</code></pre>\n\n<p><strong>CPP File</strong></p>\n\n<pre><code>ManagedStringConverter::ManagedStringConverter( System::String^ pString )\n{\n m_pString = const_cast<char*>( ManagedStringConverter::StringToChar( pString ) );\n}\n\nManagedStringConverter::~ManagedStringConverter()\n{\n ManagedStringConverter::FreeString( m_pString );\n}\n\n// static\nconst char * ManagedStringConverter::StringToChar( System::String^ str )\n{\n IntPtr^ ip = Marshal::StringToHGlobalAnsi( str );\n if ( ip != IntPtr::Zero )\n {\n return reinterpret_cast<const char *>( ip->ToPointer() );\n }\n else\n {\n return nullptr;\n }\n}\n\n// static\nconst __wchar_t * ManagedStringConverter::StringToWChar( System::String^ str )\n{\n IntPtr^ ip = Marshal::StringToHGlobalUni( str );\n if ( ip != IntPtr::Zero )\n {\n return reinterpret_cast<const __wchar_t *>( ip->ToPointer() );\n }\n else\n {\n return nullptr;\n }\n}\n\n// static\nvoid ManagedStringConverter::FreeString( const char * pszStr )\n{\n IntPtr ip = IntPtr( (void *)pszStr );\n Marshal::FreeHGlobal( ip );\n}\n</code></pre>\n"
},
{
"answer_id": 269961,
"author": "Alex Shnayder",
"author_id": 26042,
"author_profile": "https://Stackoverflow.com/users/26042",
"pm_score": 0,
"selected": false,
"text": "<p>The problem is that StringToHGlobalAnsi creates a new unmanged memory and does not copy into the memory you intended to use which you assigned into strErrorMessage.<br>\nTo resolve this you should do some thing like:</p>\n\n<pre><code>void EndPointsMappingWrapper::GetLastError(char** strErrorMessage) \n{ \n *strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer(); \n}\n</code></pre>\n\n<p>And the usage should look like:</p>\n\n<pre><code>char* err;\nGetLastError(&err);\n\n//and here you need to free the error string memory\n</code></pre>\n\n<p>for more information check out this <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.stringtohglobalansi.aspx\" rel=\"nofollow noreferrer\">msdn article</a></p>\n"
},
{
"answer_id": 269973,
"author": "Nicola Bonelli",
"author_id": 19630,
"author_profile": "https://Stackoverflow.com/users/19630",
"pm_score": 3,
"selected": true,
"text": "<p>You are assigning the value of the passed parameter (strErrorMessage) instead of copying to that address the content of the buffer returned by Marshal::StringToHGlobalAnsi.</p>\n\n<p>A correct implementation should be:</p>\n\n<pre><code>void EndPointsMappingWrapper::GetLastError(char* strErrorMessage, int len) \n{ char *str = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer(); \n strncpy(strErrorMessage,str,len);\n strErrorMessage[len-1] = '\\0';\n Marshal::FreeHGlobal(IntPtr(str));\n}\n</code></pre>\n\n<p>The length is the size of the buffer passed.</p>\n\n<p><code>strncpy()</code> will copy at the most <strong>len</strong> bytes. If there is no null byte among the first n bytes of the <strong>str</strong>, the destination string won't be null terminated. For that reason we force the '\\0' in the last byte of the buffer.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269932",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33030/"
] |
I wrote a managed C++ class that has the following function:
```
void EndPointsMappingWrapper::GetLastError(char* strErrorMessage)
{
strErrorMessage = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer();
}
```
As you can see, this is a simple method to copy the managed string of the last error to the unmanaged world (`char*`).
From my unmanaged class I call the method like this:
```
char err[1000];
ofer->GetLastError(err);
```
Putting a breakpoint at the managed C++ method shows that the string is successfully translated into the `char*`. However, once I return to the unmanaged class, the content of `err[1000]` is lost and it's empty again.
|
You are assigning the value of the passed parameter (strErrorMessage) instead of copying to that address the content of the buffer returned by Marshal::StringToHGlobalAnsi.
A correct implementation should be:
```
void EndPointsMappingWrapper::GetLastError(char* strErrorMessage, int len)
{ char *str = (char*) Marshal::StringToHGlobalAnsi(_managedObject->GetLastError()).ToPointer();
strncpy(strErrorMessage,str,len);
strErrorMessage[len-1] = '\0';
Marshal::FreeHGlobal(IntPtr(str));
}
```
The length is the size of the buffer passed.
`strncpy()` will copy at the most **len** bytes. If there is no null byte among the first n bytes of the **str**, the destination string won't be null terminated. For that reason we force the '\0' in the last byte of the buffer.
|
269,944 |
<p>Is there a way to run a one-liner in sas, or do I have to create a file? I'm looking for something like the -e flag in perl.</p>
|
[
{
"answer_id": 270262,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 0,
"selected": false,
"text": "<p>Never having used sas, what I might try is something like:</p>\n\n<pre><code>echo <insert sas code here> | sas --execute-file -\n</code></pre>\n\n<p>Oftentimes applications will let you specify '-' as a file to have it read from STDIN. And 'echo' just prints its arguments out, and the | connects them together.</p>\n"
},
{
"answer_id": 270302,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The Unix version of SAS was ported from MVS years ago and to make a long story short, the SAS executable does not import from STDIN. To make this work in Unix, merely alter slightly the previous suggestion into something like:</p>\n\n<pre><code>echo \"your SAS code\" > temp;sas -sysin temp\n</code></pre>\n\n<p>Hope this is helpful.</p>\n"
},
{
"answer_id": 536142,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>sas -initstmt '%put hello world ; endsas ;' \n\nsas -initstmt 'proc print data=sashelp.class; run ;' \n</code></pre>\n\n<p>Off course this could also be: </p>\n\n<pre><code>sas -initstmt '%inc large_program.sas; endsas;'\n</code></pre>\n"
},
{
"answer_id": 539368,
"author": "Rog",
"author_id": 65338,
"author_profile": "https://Stackoverflow.com/users/65338",
"pm_score": 4,
"selected": true,
"text": "<p>My favourite is using the -stdio option</p>\n\n<p>Either:</p>\n\n<pre><code>sas -stdio\n</code></pre>\n\n<p>Then start typing. Or ...</p>\n\n<pre><code>echo \"proc options; run;\" | sas -stdio\n</code></pre>\n"
},
{
"answer_id": 37667019,
"author": "Chris Blake",
"author_id": 6432265,
"author_profile": "https://Stackoverflow.com/users/6432265",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use the <code>-nodms</code> option. This will give you a command line version of Base.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14167/"
] |
Is there a way to run a one-liner in sas, or do I have to create a file? I'm looking for something like the -e flag in perl.
|
My favourite is using the -stdio option
Either:
```
sas -stdio
```
Then start typing. Or ...
```
echo "proc options; run;" | sas -stdio
```
|
269,946 |
<p>I'm constructing a simple form in ERB but the HTML produced by the text_field tag makes the <em>for</em> attribute in the label tag invalid.</p>
<pre><code><div>
<p><%= label_tag "email[name]", "Name" %></p>
<%= text_field :email, :name, :class => "text_field" %>
</div>
</code></pre>
<p>Produces the HTML</p>
<pre><code><div>
<p><label for="email[name]">Name</label></p>
<input class="text_field" id="email_name" name="email[name]" size="30" type="text" />
</div>
</code></pre>
<p>Which results in the error </p>
<blockquote>
<p>character "[" is not allowed in the
value of attribute "for".</p>
</blockquote>
<p>How do I generate the text with without the nested parameter name email[name] to change the label tag <em>for</em> attribute? Is there an alternative approach that produces valid HTML?</p>
|
[
{
"answer_id": 270262,
"author": "davr",
"author_id": 14569,
"author_profile": "https://Stackoverflow.com/users/14569",
"pm_score": 0,
"selected": false,
"text": "<p>Never having used sas, what I might try is something like:</p>\n\n<pre><code>echo <insert sas code here> | sas --execute-file -\n</code></pre>\n\n<p>Oftentimes applications will let you specify '-' as a file to have it read from STDIN. And 'echo' just prints its arguments out, and the | connects them together.</p>\n"
},
{
"answer_id": 270302,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>The Unix version of SAS was ported from MVS years ago and to make a long story short, the SAS executable does not import from STDIN. To make this work in Unix, merely alter slightly the previous suggestion into something like:</p>\n\n<pre><code>echo \"your SAS code\" > temp;sas -sysin temp\n</code></pre>\n\n<p>Hope this is helpful.</p>\n"
},
{
"answer_id": 536142,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<pre><code>sas -initstmt '%put hello world ; endsas ;' \n\nsas -initstmt 'proc print data=sashelp.class; run ;' \n</code></pre>\n\n<p>Off course this could also be: </p>\n\n<pre><code>sas -initstmt '%inc large_program.sas; endsas;'\n</code></pre>\n"
},
{
"answer_id": 539368,
"author": "Rog",
"author_id": 65338,
"author_profile": "https://Stackoverflow.com/users/65338",
"pm_score": 4,
"selected": true,
"text": "<p>My favourite is using the -stdio option</p>\n\n<p>Either:</p>\n\n<pre><code>sas -stdio\n</code></pre>\n\n<p>Then start typing. Or ...</p>\n\n<pre><code>echo \"proc options; run;\" | sas -stdio\n</code></pre>\n"
},
{
"answer_id": 37667019,
"author": "Chris Blake",
"author_id": 6432265,
"author_profile": "https://Stackoverflow.com/users/6432265",
"pm_score": 0,
"selected": false,
"text": "<p>You could also use the <code>-nodms</code> option. This will give you a command line version of Base.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269946",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9424/"
] |
I'm constructing a simple form in ERB but the HTML produced by the text\_field tag makes the *for* attribute in the label tag invalid.
```
<div>
<p><%= label_tag "email[name]", "Name" %></p>
<%= text_field :email, :name, :class => "text_field" %>
</div>
```
Produces the HTML
```
<div>
<p><label for="email[name]">Name</label></p>
<input class="text_field" id="email_name" name="email[name]" size="30" type="text" />
</div>
```
Which results in the error
>
> character "[" is not allowed in the
> value of attribute "for".
>
>
>
How do I generate the text with without the nested parameter name email[name] to change the label tag *for* attribute? Is there an alternative approach that produces valid HTML?
|
My favourite is using the -stdio option
Either:
```
sas -stdio
```
Then start typing. Or ...
```
echo "proc options; run;" | sas -stdio
```
|
269,974 |
<p>Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element:</p>
<pre><code><div id='contentdiv'>bla content bla</div>
</code></pre>
<p>and I want to wrap it in the following way: </p>
<pre><code><div id='wrapperDiv'>
<div id='beforeDiv'></div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div>
</div>
</code></pre>
<p>I use the following jQuery/Javascript </p>
<pre><code>$('#contentDiv').each( function() {
var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>";
var afterHTML = "<div id='afterDiv'></div></div>";
$(this).before(beforeHTML);
$(this).after(afterHTML);
}
</code></pre>
<p>This however will not result in the correct wrapping, it will create:</p>
<pre><code><div id='wrapperDiv'>
<div id='beforeDiv'></div>
</div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div>
</code></pre>
<p>Using wrap() won't work either since that gets jQuery even more mixed up when using:</p>
<pre><code>$(this).wrap("<div id='wrapperDiv'><div id='beforeDiv'></div><div id='afterDiv'></div></div>");
</code></pre>
<p>How should I solve this?<br>
Thanks in advance!</p>
|
[
{
"answer_id": 269981,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p>your markup isn't complete...before and after are to take complete nodes only...</p>\n\n<p>what you are trying to do is <strong>wrap</strong> your content, which is different.</p>\n\n<p>you want this:</p>\n\n<p>.wrap(html);</p>\n\n<p><a href=\"http://docs.jquery.com/Manipulation/wrap#html\" rel=\"nofollow noreferrer\">http://docs.jquery.com/Manipulation/wrap#html</a></p>\n"
},
{
"answer_id": 270022,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 0,
"selected": false,
"text": "<p>I'm sorry, but this one should be obvious. In your case, you can't use wrap because it sticks the original node into the deepest node it finds in the wrapping HTML. You don't want that. Instead, read out the HTML from your object and combine it with what you have:</p>\n\n<pre><code>$('#contentDiv').each( function() {\n var beforeHTML = \"<div id='wrapperDiv'><div id='beforeDiv'></div>\";\n var afterHTML = \"<div id='afterDiv'></div></div>\";\n\n // This line below will do it...\n $(this).html(beforeHTML + $(this).html() + afterHTML);\n}\n</code></pre>\n"
},
{
"answer_id": 270045,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 2,
"selected": false,
"text": "<p>I think you're approaching it wrong. Think about what you actually want to achieve...</p>\n\n<p>You want to WRAP everything with one div. Then insert 1 div before, and 1 div after.</p>\n\n<p>so do .wrap() first, then append before and after-divs relative to the content-div.</p>\n\n<p>if you happen to have the actual HTML as a string (from an XHR or something) then you need to read out the html and concatenate it yourself as Douglas Mayle suggested.</p>\n"
},
{
"answer_id": 270059,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 4,
"selected": true,
"text": "<pre><code>$('#contentDiv').each(function() {\n $(this).wrap('<div id=\"wrapperDiv\">');\n $(this).before('<div id=\"beforeDiv\">');\n $(this).after('<div id=\"afterDiv\">');\n});\n</code></pre>\n\n<p>produces:</p>\n\n<pre><code><div id='wrapperDiv'>\n <div id='beforeDiv'></div>\n <div id='contentDiv'>bla content bla</div>\n <div id='afterDiv'></div>\n</div>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35197/"
] |
Does anyone know how to stop jQuery fromparsing html you insert through before() and after()? Say I have an element:
```
<div id='contentdiv'>bla content bla</div>
```
and I want to wrap it in the following way:
```
<div id='wrapperDiv'>
<div id='beforeDiv'></div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div>
</div>
```
I use the following jQuery/Javascript
```
$('#contentDiv').each( function() {
var beforeHTML = "<div id='wrapperDiv'><div id='beforeDiv'></div>";
var afterHTML = "<div id='afterDiv'></div></div>";
$(this).before(beforeHTML);
$(this).after(afterHTML);
}
```
This however will not result in the correct wrapping, it will create:
```
<div id='wrapperDiv'>
<div id='beforeDiv'></div>
</div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div>
```
Using wrap() won't work either since that gets jQuery even more mixed up when using:
```
$(this).wrap("<div id='wrapperDiv'><div id='beforeDiv'></div><div id='afterDiv'></div></div>");
```
How should I solve this?
Thanks in advance!
|
```
$('#contentDiv').each(function() {
$(this).wrap('<div id="wrapperDiv">');
$(this).before('<div id="beforeDiv">');
$(this).after('<div id="afterDiv">');
});
```
produces:
```
<div id='wrapperDiv'>
<div id='beforeDiv'></div>
<div id='contentDiv'>bla content bla</div>
<div id='afterDiv'></div>
</div>
```
|
269,979 |
<p>I'm developing a web app using Java servlet to access Mysql db, how can I get the number of connections to my DB that is currently open ?</p>
<p>Edit :</p>
<p>I tried "show processlist", it showed me : 2695159, but that's not right, I'm just developing this new project, I'm the only user, couldn't have that many processes running, what I want is the number of users accessing <strong>my project's DB</strong>, not the number of all db users, but just the ones logged in to my database which has only one table.</p>
|
[
{
"answer_id": 270008,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 2,
"selected": false,
"text": "<p>show processlist</p>\n"
},
{
"answer_id": 270014,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 3,
"selected": false,
"text": "<p>You could use the MySQL command <code>show processlist</code> to get the number of connections.</p>\n\n<p>However that'll also show you any connections made with the same userID to the database which may not be coming from your servlet.</p>\n\n<p>In general I would suggest that you're probably better off using a Connection Pool object (see <a href=\"http://java-source.net/open-source/connection-pools\" rel=\"noreferrer\">http://java-source.net/open-source/connection-pools</a>) to manage your connections to the MySQL server. This can increase performance by making DB connections persistent, so you don't always have the overhead of a new DB connection for each page load.</p>\n\n<p>If your servlet needs to know the number of connections then your Connection Pool should come with a method that tells you how many connections are currently active.</p>\n"
},
{
"answer_id": 270149,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 2,
"selected": false,
"text": "<p>show status like 'Threads_connected'\nor\nshow global status like 'Threads_connected'</p>\n\n<p>Not sure about the difference between those two in a user-context, and you might still suffer from the problem that you would see all connections, not only those from your app. </p>\n\n<p>you can even check Threads_running to only see running threads (e.g not sleeping).</p>\n"
},
{
"answer_id": 7592487,
"author": "Gerryjun",
"author_id": 970360,
"author_profile": "https://Stackoverflow.com/users/970360",
"pm_score": 4,
"selected": false,
"text": "<p>Depending on your MySQL version, you can perform a select on </p>\n\n<p><code>SELECT COUNT(*) FROM information_schema.PROCESSLIST;</code></p>\n\n<p>and you can do a <code>where</code> between the user, database, and host IP.</p>\n\n<p>For example:</p>\n\n<pre><code>USE information_schema;\nSELECT COUNT(*) FROM PROCESSLIST WHERE db =\"mycase\" AND HOST LIKE \"192.168.11.174%\"\n</code></pre>\n"
},
{
"answer_id": 11605155,
"author": "DmitrySemenov",
"author_id": 1233751,
"author_profile": "https://Stackoverflow.com/users/1233751",
"pm_score": 2,
"selected": false,
"text": "<p>You can only select from <code>Information_Schema.Processlist</code> the data that belongs to you. It means you can use it for monitoring ONLY if you're logged in as root, otherwise you will be seeing the connections coming from your user you got logged in with.</p>\n\n<p>If you want proper monitoring SQL, it will be:</p>\n\n<pre><code>SELECT variable_value\nFROM INFORMATION_SCHEMA.GLOBAL_STATUS\nWHERE variable_name='threads_connected'\n</code></pre>\n"
},
{
"answer_id": 11847466,
"author": "Vallabha Vamaravelli",
"author_id": 420343,
"author_profile": "https://Stackoverflow.com/users/420343",
"pm_score": 2,
"selected": false,
"text": "<p>Run the following query, it lists out host name and no. of connections from each host:</p>\n\n<p>SELECT host,count(host) FROM information_schema.processlist GROUP BY host;</p>\n"
},
{
"answer_id": 18627580,
"author": "subhash lamba",
"author_id": 1330652,
"author_profile": "https://Stackoverflow.com/users/1330652",
"pm_score": 0,
"selected": false,
"text": "<p>You may use this</p>\n\n<p>SHOW GLOBAL STATUS;\nor \nshow global status like \"Threads_connected\";</p>\n\n<p>from Connections status you can findout total number of connections.</p>\n"
},
{
"answer_id": 46375280,
"author": "Idham Perdameian",
"author_id": 973530,
"author_profile": "https://Stackoverflow.com/users/973530",
"pm_score": 1,
"selected": false,
"text": "<p>You also can count open connection by show the status from <code>Threads_connected</code> variable name like this:</p>\n\n<pre><code>SHOW STATUS WHERE variable_name = 'Threads_connected';\n</code></pre>\n\n<p>Or you can also count the process list directly from <code>information_schema.PROCESSLIST</code> like below:</p>\n\n<pre><code>SELECT COUNT(*) FROM information_schema.PROCESSLIST;\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32834/"
] |
I'm developing a web app using Java servlet to access Mysql db, how can I get the number of connections to my DB that is currently open ?
Edit :
I tried "show processlist", it showed me : 2695159, but that's not right, I'm just developing this new project, I'm the only user, couldn't have that many processes running, what I want is the number of users accessing **my project's DB**, not the number of all db users, but just the ones logged in to my database which has only one table.
|
Depending on your MySQL version, you can perform a select on
`SELECT COUNT(*) FROM information_schema.PROCESSLIST;`
and you can do a `where` between the user, database, and host IP.
For example:
```
USE information_schema;
SELECT COUNT(*) FROM PROCESSLIST WHERE db ="mycase" AND HOST LIKE "192.168.11.174%"
```
|
269,988 |
<p>I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?</p>
|
[
{
"answer_id": 270001,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>If a thread has to be able to execute some bit of code (usually in the form of a delegate) posted to it by another thread, it will have to basically be waiting for those instructions. What else is your main thread doing? It's not that hard to build an equivalent of the event loop (basically you'd have a producer/consumer queue of delegates) but you need to be aware that you can't just interrupt the main thread and say \"do this now\".</p>\n\n<p>Why does this have to execute on the main thread?</p>\n"
},
{
"answer_id": 270009,
"author": "Bjarke Ebert",
"author_id": 31890,
"author_profile": "https://Stackoverflow.com/users/31890",
"pm_score": 2,
"selected": false,
"text": "<p>A thread cannot just execute stuff on another thread. The closest you can get is to put a delegate on a queue for the other thread to execute, but that assumes that the other thread is cooperating about this.</p>\n\n<p>In a WinForms application, the main loop looks for such queued messages on each loop iteration.</p>\n\n<p>If you just need to communicate the finishing of the worker thread, you can use e.g. a flag variabe. If the main thread should be able to wait for job termination, use a semaphore or condition variable (monitor).</p>\n"
},
{
"answer_id": 270030,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 2,
"selected": false,
"text": "<p>Here's my exact scenario: I have a .NET class library exposed as a COM object (using regasm.exe). The COM object contains a method that runs an external application (using Process.Start). The COM object is used in Internet Explorer. So my web page runs the external application and I need to find a way to pass the ExitCode to the web page. </p>\n\n<p>At first I didn't start the external application on a new thread and just waited for the user to close the application and then my function returned the ExitCode to the caller. But while the application was running IE was not responsive. So I decided to start the application in a new thread but now I can no longer return the ExitCode.</p>\n\n<p>The COM object is created with: <code>new ActiveXObject</code> instruction and unfortunately javascript doesn't support event sinking so I can't write an event in C# that's triggered when the application exits.</p>\n"
},
{
"answer_id": 270770,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 2,
"selected": false,
"text": "<p>There's no way to explicitly make code run on a specific thread, (except for the thread that was used to create UI Controls - this is an exception) but if you simply want to call code other than the code when a thread completes, You use delegates.<br>\nFirst declare a delegate with the signature of the method you want to run on the new thread...</p>\n\n<pre><code>public delegate bool CheckPrimeDelegate(long n);\n</code></pre>\n\n<p>Then in your code, create an instance of the delegate, call it using BeginInvoke (passing any parameters it needs) and PASS a callback function delegate (OnChkPrimeDone)</p>\n\n<pre><code>class MyClassApp\n{\n static void Main() \n {\n CheckPrimeDelegate ckPrimDel = new CheckPrimeDelegate(Prime.Check);\n\n // Initiate the operation\n ckPrimDel.BeginInvoke(4501232117, new AsyncCallback(OnChkPrimeDone), null);\n\n // go do something else . . . . \n }\n\n static void OnChkPrimeDone( IAsyncResult iAr)\n {\n AsyncResult ar = iAr as AsynchResult;\n CheckPrimeDelegate ckPrimDel = ar.AsyncDelegate as CheckPrimeDelegate;\n bool isPrime = ckPrimDel.EndInvoke(ar);\n Console.WriteLine(\" Number is \" + (isPrime? \"prime \": \"not prime\");\n }\n}\n</code></pre>\n\n<p>When it is done, it will call the callback function (OnChkPrimeDone)</p>\n\n<p>If you explicitly need to run this callback function on the thread that was used to create the COM Active-X object, then check the .Net Managed Code wrapper variable that holds a reference to this object... If it has a method called InvokeRequired(), then, in your callback function, test the boolean return value of this method.<br>\nIf it has InvokeRequired() method and it returns true, then the active-X object will also expose a \"BeginInvoke()\" Method. Then, Create ANOTHER Delegate, populated with the same function, and call BeginInvoke\non the Active-X Object, passing it this new delegate... It will then run on the same thread as was used to create teh Active-X Object</p>\n\n<pre><code>If (MyActiveXObject.InvokeRequired())\n MyActiveXObject.BeginInvoke(...);\n</code></pre>\n"
},
{
"answer_id": 272252,
"author": "Darin Dimitrov",
"author_id": 29407,
"author_profile": "https://Stackoverflow.com/users/29407",
"pm_score": 5,
"selected": true,
"text": "<p>I found a simple solution to the problem :</p>\n\n<p>My COM object is declared like this:</p>\n\n<pre><code>public class Runner\n{\n public void Run(string executable, object processExitHandler)\n {\n ThreadPool.QueueUserWorkItem(state =>\n {\n var p = new Process()\n {\n StartInfo = new ProcessStartInfo()\n {\n FileName = executable\n }\n };\n p.Start();\n while (!p.HasExited)\n {\n Thread.Sleep(100);\n }\n\n state\n .GetType()\n .InvokeMember(\n \"call\", \n BindingFlags.InvokeMethod, \n null, \n state, \n new object[] { null, p.ExitCode }\n );\n }, processExitHandler);\n }\n}\n</code></pre>\n\n<p>And in my HTML page I use it like this:</p>\n\n<pre><code><!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<html>\n<head><title>ActiveXRunner</title> \n <script type=\"text/javascript\">\n function runNotepad() {\n var ax = new ActiveXObject('ActiveXRunner.Runner');\n ax.Run('c:\\\\windows\\\\notepad.exe', h);\n }\n\n function h(exitCode) {\n alert('exitCode = ' + exitCode);\n }\n </script>\n</head>\n<body>\n <a href=\"#\" onclick=\"runNotepad();\">Run notepad and show exit code when finished</a>\n</body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 3363089,
"author": "cdiggins",
"author_id": 184528,
"author_profile": "https://Stackoverflow.com/users/184528",
"pm_score": 5,
"selected": false,
"text": "<p>You can invoke a function on a specific thread by using a <code>System.Windows.Threading.Dispatcher</code> object (from the WindowsBase assembly).</p>\n\n<p>For example:</p>\n\n<pre><code>public class ClassCreatedBySomeThread\n{\n Dispatcher dispatcher = Dispatcher.CurrentDispatcher; \n\n public void SafelyCallMeFromAnyThread(Action a)\n {\n dispatcher.Invoke(a);\n }\n} \n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269988",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29407/"
] |
I have a .NET class library containing a class with a method that performs some lengthy operation. When a client calls this method it should perform the lengthy operation on a new thread in order to avoid blocking the caller. But once the method finishes it should execute some code on the main thread. In a WinForms application I could have used the System.Windows.Forms.Control.Invoke method but this is not my case. So how can I achieve this in C#?
|
I found a simple solution to the problem :
My COM object is declared like this:
```
public class Runner
{
public void Run(string executable, object processExitHandler)
{
ThreadPool.QueueUserWorkItem(state =>
{
var p = new Process()
{
StartInfo = new ProcessStartInfo()
{
FileName = executable
}
};
p.Start();
while (!p.HasExited)
{
Thread.Sleep(100);
}
state
.GetType()
.InvokeMember(
"call",
BindingFlags.InvokeMethod,
null,
state,
new object[] { null, p.ExitCode }
);
}, processExitHandler);
}
}
```
And in my HTML page I use it like this:
```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head><title>ActiveXRunner</title>
<script type="text/javascript">
function runNotepad() {
var ax = new ActiveXObject('ActiveXRunner.Runner');
ax.Run('c:\\windows\\notepad.exe', h);
}
function h(exitCode) {
alert('exitCode = ' + exitCode);
}
</script>
</head>
<body>
<a href="#" onclick="runNotepad();">Run notepad and show exit code when finished</a>
</body>
</html>
```
|
269,989 |
<p><strong>EDIT:</strong> I also have access to <a href="http://www.exslt.org/" rel="nofollow noreferrer">ESXLT</a> functions.</p>
<p>I have two node sets of string tokens. One set contains values like these:</p>
<pre><code>/Geography/North America/California/San Francisco
/Geography/Asia/Japan/Tokyo/Shinjuku
</code></pre>
<p>The other set contains values like these:</p>
<pre><code>/Geography/North America/
/Geography/Asia/Japan/
</code></pre>
<p>My goal is to find a "match" between the two. A match is made when any string in set 1 begins with a string in set 2. For example, a match would be made between <strong>/Geography/North America/California/San Francisco</strong> and <strong>/Geography/North America/</strong> because a string from set 1 begins with a string from set 2.</p>
<p>I can compare strings using wildcards by using a third-party extension. I can also use a regular expression all within an Xpath.</p>
<p>My problem is how do I structure the Xpath to select using a function between all nodes of both sets? XSL is also a viable option.</p>
<p>This XPATH:</p>
<pre><code>count($set1[.=$set2])
</code></pre>
<p>Would yield the count of intersection between set1 and set2, but it's a 1-to-1 comparison. Is it possible to use some other means of comparing the nodes?</p>
<p>EDIT: I did get this working, but I am cheating by using some of the other third-party extensions to get the same result. I am still interested in other methods to get this done.</p>
|
[
{
"answer_id": 273285,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": true,
"text": "<p>This:</p>\n\n<pre><code><xsl:variable name=\"matches\" select=\"$set1[starts-with(., $set2)]\"/>\n</code></pre>\n\n<p>will set <code>$matches</code> to a node-set containing every node in <code>$set1</code> whose text value starts with the text value of a node in $set2. That's what you're looking for, right?</p>\n\n<p><strong>Edit:</strong></p>\n\n<p>Well, I'm just wrong about this. Here's why.</p>\n\n<p><code>starts-with</code> expects its two arguments to both be strings. If they're not, it will convert them to strings before evaluating the function.</p>\n\n<p>If you give it a node-set as one of its arguments, it uses the string value of the node-set, which is the text value of the first node in the set. So in the above, <code>$set2</code> never gets searched; only the first node in the list ever gets examined, and so the predicate will only find nodes in <code>$set1</code> that start with the value of the first node in <code>$set2</code>.</p>\n\n<p>I was misled because this pattern (which I've been using a lot in the last few days) <em>does</em> work:</p>\n\n<pre><code><xsl:variable name=\"hits\" select=\"$set1[. = $set2]\"/>\n</code></pre>\n\n<p>But that predicate is using an comparison between node-sets, not between text values.</p>\n\n<p>The ideal way to do this would be by nesting predicates. That is, \"I want to find every node in <code>$set1</code> for which there's a node in <code>$set2</code> whose value starts with...\" and here's where XPath breaks down. Starts with what? What you'd like to write is something like:</p>\n\n<pre><code><xsl:variable name=\"matches\" select=\"$set1[$set2[starts-with(?, .)]]\"/>\n</code></pre>\n\n<p>only there's no expression you can write for the <code>?</code> that will return the node currently being tested by the outer predicate. (Unless I'm missing something blindingly obvious.)</p>\n\n<p>To get what you want, you have to test each node individually:</p>\n\n<pre><code><xsl:variable name=\"matches\">\n <xsl:for-each select=\"$set1\">\n <xsl:if test=\"$set2[starts-with(current(), .)]\">\n <xsl:copy-of select=\".\"/>\n </xsl:if>\n </xsl:for-each>\n</xsl:variable>\n</code></pre>\n\n<p>That's not a very satisfying solution because it evaluates to a result tree fragment, not a node-set. You'll have to use an extension function (like <code>msxsl:node-set</code>) to convert the RTF to a node-set if you want to use the variable in an XPath expression.</p>\n"
},
{
"answer_id": 273951,
"author": "ChuckB",
"author_id": 28605,
"author_profile": "https://Stackoverflow.com/users/28605",
"pm_score": -1,
"selected": false,
"text": "<p>I guess I couldn't make the XPath above work. I started with the following XML doc to initialize the two nodesets:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<sets>\n <set>\n <text>/Geography/North America/California/San Francisco</text>\n <text>/Geography/Asia/Japan/Tokyo/Shinjuku</text>\n </set>\n <set>\n <text>/Geography/North America/</text>\n <text>/Geography/Asia/Japan/</text>\n </set>\n</sets>\n</code></pre>\n\n<p>I think this stylesheet ought to implement Robert's solution, but I only get a count of '1':</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:variable name=\"set1\" select=\"sets/set[1]/text/text()\"/>\n <xsl:variable name=\"set2\" select=\"sets/set[2]/text/text()\"/>\n <xsl:value-of select=\"count($set1[starts-with(., $set2)])\"/>\n <xsl:text>\n</xsl:text>\n </xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>I did write a stylesheet that uses a recursive template and does produce the correct count of '2' with the given input doc, but it's far less elegant than Robert's answer. If only I could get the XPath to work--always wanting to learn.</p>\n"
},
{
"answer_id": 275298,
"author": "ChuckB",
"author_id": 28605,
"author_profile": "https://Stackoverflow.com/users/28605",
"pm_score": 0,
"selected": false,
"text": "<p>Robert's last <code>xsl:variable</code> is good for getting a result tree fragment containing the matching text values, but unless (as he suggests) you use EXSLT or MS extensions to XSLT 1.0 to convert the RTF to a node set, you can't get a count of the matching text nodes.</p>\n\n<p>Here is the XSLT stylesheet I mentioned in my prior response that recurs over the sample input document I gave to give a count of text nodes in set 1 for which a node in set 2 matches part or all of it:</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n\n <xsl:output indent=\"yes\" method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\" select=\"sets/set[1]/text[1]\"/>\n <xsl:with-param name=\"set2-node\" select=\"sets/set[2]/text[1]\"/>\n <xsl:with-param name=\"total-count\" select=\"0\"/>\n </xsl:call-template>\n <xsl:text>\n</xsl:text>\n </xsl:template>\n\n <xsl:template name=\"count-matches\">\n <xsl:param name=\"set1-node\"/>\n <xsl:param name=\"set2-node\"/>\n <xsl:param name=\"total-count\" select=\"0\"/>\n <xsl:variable name=\"this-count\">\n <xsl:choose>\n <xsl:when test=\"contains($set1-node, $set2-node)\">\n <xsl:value-of select=\"1\"/>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"0\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:variable>\n <xsl:choose>\n <xsl:when test=\"$set2-node/following-sibling::text\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\"\n select=\"$set1-node\"/>\n <xsl:with-param name=\"set2-node\"\n select=\"$set2-node/following-sibling::text[1]\"/>\n <xsl:with-param name=\"total-count\"\n select=\"$total-count + $this-count\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:when test=\"$set1-node/following-sibling::text\">\n <xsl:call-template name=\"count-matches\">\n <xsl:with-param name=\"set1-node\"\n select=\"$set1-node/following-sibling::text[1]\"/>\n <xsl:with-param name=\"set2-node\"\n select=\"$set2-node/preceding-sibling::text[last()]\"/>\n <xsl:with-param name=\"total-count\"\n select=\"$total-count + $this-count\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$total-count + $this-count\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>Not particularly concise, but because XSLT does not let programmers assign new values to already-defined variables, recursion is often necessary. I don't see a way in XSLT 1.0 to get a count of the sort requested by Zack using <code>xsl:for-each</code>.</p>\n"
},
{
"answer_id": 345481,
"author": "Dimitre Novatchev",
"author_id": 36305,
"author_profile": "https://Stackoverflow.com/users/36305",
"pm_score": 1,
"selected": false,
"text": "<p><strong>There is a simple and pure XSLT 1.0 solution (no extensions needed) for finding the count of matches</strong>:</p>\n\n<pre><code><xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\"/>\n\n <xsl:template match=\"/\">\n <xsl:variable name=\"vStars\">\n <xsl:for-each select=\"*/regions/*\">\n <xsl:for-each select=\"/*/cities/*[starts-with(.,current())]\">\n <xsl:value-of select=\"'*'\"/>\n </xsl:for-each>\n </xsl:for-each>\n </xsl:variable>\n\n <xsl:value-of select=\"string-length($vStars)\"/>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n\n<p><strong>When this transformation is applied on the following XML document</strong>:</p>\n\n<pre><code><t>\n <cities>\n <city>/Geography/North America/California/San Francisco</city>\n <city>/Geography/Asia/Japan/Tokyo/Shinjuku</city>\n </cities>\n <regions>\n <region>/Geography/North America/</region>\n <region>/Geography/Asia/Japan/</region>\n </regions>\n</t>\n</code></pre>\n\n<p><strong>the correct result is produced</strong>:</p>\n\n<p><strong><em>2</em></strong></p>\n\n<p><strong>Do note</strong> that one character (an asterisk) is produced for every match found and all these asterisks form the content of the <code>$vStars</code> variable. We then simply output its <code>string-length()</code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269989",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18265/"
] |
**EDIT:** I also have access to [ESXLT](http://www.exslt.org/) functions.
I have two node sets of string tokens. One set contains values like these:
```
/Geography/North America/California/San Francisco
/Geography/Asia/Japan/Tokyo/Shinjuku
```
The other set contains values like these:
```
/Geography/North America/
/Geography/Asia/Japan/
```
My goal is to find a "match" between the two. A match is made when any string in set 1 begins with a string in set 2. For example, a match would be made between **/Geography/North America/California/San Francisco** and **/Geography/North America/** because a string from set 1 begins with a string from set 2.
I can compare strings using wildcards by using a third-party extension. I can also use a regular expression all within an Xpath.
My problem is how do I structure the Xpath to select using a function between all nodes of both sets? XSL is also a viable option.
This XPATH:
```
count($set1[.=$set2])
```
Would yield the count of intersection between set1 and set2, but it's a 1-to-1 comparison. Is it possible to use some other means of comparing the nodes?
EDIT: I did get this working, but I am cheating by using some of the other third-party extensions to get the same result. I am still interested in other methods to get this done.
|
This:
```
<xsl:variable name="matches" select="$set1[starts-with(., $set2)]"/>
```
will set `$matches` to a node-set containing every node in `$set1` whose text value starts with the text value of a node in $set2. That's what you're looking for, right?
**Edit:**
Well, I'm just wrong about this. Here's why.
`starts-with` expects its two arguments to both be strings. If they're not, it will convert them to strings before evaluating the function.
If you give it a node-set as one of its arguments, it uses the string value of the node-set, which is the text value of the first node in the set. So in the above, `$set2` never gets searched; only the first node in the list ever gets examined, and so the predicate will only find nodes in `$set1` that start with the value of the first node in `$set2`.
I was misled because this pattern (which I've been using a lot in the last few days) *does* work:
```
<xsl:variable name="hits" select="$set1[. = $set2]"/>
```
But that predicate is using an comparison between node-sets, not between text values.
The ideal way to do this would be by nesting predicates. That is, "I want to find every node in `$set1` for which there's a node in `$set2` whose value starts with..." and here's where XPath breaks down. Starts with what? What you'd like to write is something like:
```
<xsl:variable name="matches" select="$set1[$set2[starts-with(?, .)]]"/>
```
only there's no expression you can write for the `?` that will return the node currently being tested by the outer predicate. (Unless I'm missing something blindingly obvious.)
To get what you want, you have to test each node individually:
```
<xsl:variable name="matches">
<xsl:for-each select="$set1">
<xsl:if test="$set2[starts-with(current(), .)]">
<xsl:copy-of select="."/>
</xsl:if>
</xsl:for-each>
</xsl:variable>
```
That's not a very satisfying solution because it evaluates to a result tree fragment, not a node-set. You'll have to use an extension function (like `msxsl:node-set`) to convert the RTF to a node-set if you want to use the variable in an XPath expression.
|
269,991 |
<p>In IIS Manager under Web Service Extensions, ASP.NET v2.0.50727 is set to "Prohibited" by default. I would like to set this to Allow during the install.</p>
<p>I am currently using WiX Version 2.</p>
<p>I have tried using:</p>
<pre><code><Component Id="Allow_WebServiceExtension_ASP.NET_2.0" DiskId="1" Guid="02247363-E423-41E1-AC15-BEF589B65A4D">
<WebServiceExtension Id="WebServiceExtension_ASP.NET_2.0" Allow="yes" File="%SystemRoot%\Microsoft.NET\Framework\[DOTNETFRAMEWORKVER]\aspnet_isapi.dll" Description="ASP.NET v2.0.50727" UIDeletable="no" />
</Component>
</code></pre>
<p>This adds a second ASP.NET 2.0.50727 entry and does not enable the first.</p>
|
[
{
"answer_id": 270277,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <a href=\"http://www.wixwiki.com/index.php?title=WebApplicationExtension_Element\" rel=\"nofollow noreferrer\">WebApplicationExtension</a> Element in WIX, it's in the IISExtension, need to add the reference to the WIX project.</p>\n"
},
{
"answer_id": 516893,
"author": "Friend Of George",
"author_id": 424,
"author_profile": "https://Stackoverflow.com/users/424",
"pm_score": 1,
"selected": true,
"text": "<p>I ended up putting the following code into a custom action:</p>\n\n<pre><code>Dim WebSvcObj As Object\nDim LocatorObj As Object = CreateObject(\"WbemScripting.SWbemLocator\")\nDim ProviderObj As Object = LocatorObj.ConnectServer(\".\", \"root/MicrosoftIISv2\", \"\", \"\")\nWebSvcObj = ProviderObj.get(\"IIsWebService='w3svc'\")\nWebSvcObj.EnableWebServiceExtension(\"ASP.NET v2.0.50727\")\n</code></pre>\n\n<p>It may not be pretty, but it does work.</p>\n"
},
{
"answer_id": 1372809,
"author": "uli78",
"author_id": 61434,
"author_profile": "https://Stackoverflow.com/users/61434",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem using wix3. Since I haven’t found any other solution (??) I decided also to do it with a custom action. With the little difference that I use c# and the WMI support of the framework (System.Management). \n<a href=\"http://msdn.microsoft.com/en-us/library/ms525309.aspx\" rel=\"nofollow noreferrer\">using WMI to configure IIS</a></p>\n\n<p>OK I found out that I just had two misstakes in my Wix \n 1. the @Group was missing -> I set it to \"ASP.NET v2.0.50727\"\n 2. The path to the file was wrong. I had one backslash to much.\nAfter fixing these issues wix-iis:WebServiceExtension worked perfect for me.</p>\n"
},
{
"answer_id": 2674215,
"author": "Bon",
"author_id": 321180,
"author_profile": "https://Stackoverflow.com/users/321180",
"pm_score": 0,
"selected": false,
"text": "<p>I modified the code to enable my .NET 4.0 Web Service Extension, using vbScript:</p>\n\n<pre><code> Dim LocatorObj\n Dim WebSvcObj\n Dim ProviderObj\n\n Set LocatorObj = CreateObject(\"WbemScripting.SWbemLocator\")\n Set ProviderObj = LocatorObj.ConnectServer(\".\", \"root/MicrosoftIISv2\", \"\", \"\")\n Set WebSvcObj = ProviderObj.get(\"IIsWebService='w3svc'\")\n WebSvcObj.EnableWebServiceExtension(\"ASP.NET v4.0.30319\")\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/424/"
] |
In IIS Manager under Web Service Extensions, ASP.NET v2.0.50727 is set to "Prohibited" by default. I would like to set this to Allow during the install.
I am currently using WiX Version 2.
I have tried using:
```
<Component Id="Allow_WebServiceExtension_ASP.NET_2.0" DiskId="1" Guid="02247363-E423-41E1-AC15-BEF589B65A4D">
<WebServiceExtension Id="WebServiceExtension_ASP.NET_2.0" Allow="yes" File="%SystemRoot%\Microsoft.NET\Framework\[DOTNETFRAMEWORKVER]\aspnet_isapi.dll" Description="ASP.NET v2.0.50727" UIDeletable="no" />
</Component>
```
This adds a second ASP.NET 2.0.50727 entry and does not enable the first.
|
I ended up putting the following code into a custom action:
```
Dim WebSvcObj As Object
Dim LocatorObj As Object = CreateObject("WbemScripting.SWbemLocator")
Dim ProviderObj As Object = LocatorObj.ConnectServer(".", "root/MicrosoftIISv2", "", "")
WebSvcObj = ProviderObj.get("IIsWebService='w3svc'")
WebSvcObj.EnableWebServiceExtension("ASP.NET v2.0.50727")
```
It may not be pretty, but it does work.
|
269,999 |
<p>I want the log to roll over as long as the application is running, but I want the log to start fresh when the application is restarted.</p>
<p><em>Updated:</em>
Based on <a href="https://stackoverflow.com/questions/269999/how-do-i-make-log4j-clear-a-log-at-startup#270026">erickson's</a> feedback, my appender looks like this:</p>
<pre><code> <appender name="myRFA" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="my-server.log"/>
<param name="Append" value="false" />
<param name="MaxFileSize" value="10MB"/>
<param name="MaxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ISO8601} %p - %t - %c - %m%n"/>
</layout>
</appender>
</code></pre>
<p>I simply added the following line:</p>
<pre><code><param name="Append" value="false" />
</code></pre>
<p>It now truncates the base log file at startup, but it leaves the rolled files alone.</p>
|
[
{
"answer_id": 270026,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 7,
"selected": true,
"text": "<p>If you set the <code>append</code> parameter to <code>false</code>, the base log file will be \"started fresh\" when the application restarts. Do you mean that you want any \"rolled\" log files to be deleted too?</p>\n"
},
{
"answer_id": 496741,
"author": "Eddie",
"author_id": 57752,
"author_profile": "https://Stackoverflow.com/users/57752",
"pm_score": 3,
"selected": false,
"text": "<p>I've written some custom code to find my <code>RollingFileAppender</code> (which is unnecessarily difficult to get access to in log4j!) which I then cause to roll over. I've adapted my code below for a single use. I use code similar to this at application startup to force my logs to roll (if non-empty) so I always start in a fresh log but never delete any log but the oldest.</p>\n\n<p>This code takes a given Logger and loops up the logger hierarchy until it finds a Logger that has Appenders attached. If it never does, then it gives up. If it does, it loops over all Appenders attached to that Logger and for each one that is a RollingFileAppender, it forces the log to roll. </p>\n\n<p>Something like this <strong>should</strong> be a lot easier to do in log4j, but I haven't found a simpler way of doing it.</p>\n\n<pre><code>public void rollLogFile(Logger logger) {\n while (logger != null && !logger.getAllAppenders().hasMoreElements()) {\n logger = (Logger)logger.getParent();\n }\n\n if (logger == null) {\n return;\n }\n\n for (Enumeration e2 = logger.getAllAppenders(); e2.hasMoreElements();) {\n final Appender appender = (Appender)e2.nextElement();\n if (appender instanceof RollingFileAppender) {\n final RollingFileAppender rfa = (RollingFileAppender)appender;\n final File logFile = new File(rfa.getFile());\n if (logFile.length() > 0) {\n rfa.rollOver();\n }\n }\n }\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/269999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28991/"
] |
I want the log to roll over as long as the application is running, but I want the log to start fresh when the application is restarted.
*Updated:*
Based on [erickson's](https://stackoverflow.com/questions/269999/how-do-i-make-log4j-clear-a-log-at-startup#270026) feedback, my appender looks like this:
```
<appender name="myRFA" class="org.apache.log4j.RollingFileAppender">
<param name="File" value="my-server.log"/>
<param name="Append" value="false" />
<param name="MaxFileSize" value="10MB"/>
<param name="MaxBackupIndex" value="10"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ISO8601} %p - %t - %c - %m%n"/>
</layout>
</appender>
```
I simply added the following line:
```
<param name="Append" value="false" />
```
It now truncates the base log file at startup, but it leaves the rolled files alone.
|
If you set the `append` parameter to `false`, the base log file will be "started fresh" when the application restarts. Do you mean that you want any "rolled" log files to be deleted too?
|
270,011 |
<p>The code is rather long yet simple:</p>
<ul>
<li>100 leaky JavaScript objects are created.</li>
<li>10 leaky elements are created from the JS objects.</li>
<li>1 element is removed and 1 is added 10000 times.</li>
</ul>
<p>I assume that the <code>detachEvent</code> call is not functioning properly.
Also, if you change <code>this.eventParams</code> from an array to a simple variable, the leak goes away. Why?</p>
<pre><code> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Memory Leak With Fix</title>
<style type="text/css">
.leakyEle
{
border: solid 1px red;
background-color: Gray;
}
</style>
<script type="text/javascript">
/******************************* MAIN ********************************/
var leakObjArray = new Array();
AddEvent(window, 'load', Startup, false);
function Startup() {
for(var i=0; i<100; i++) {
leakObjArray.push(new LeakyObj(i));
}
for(var j=0; j<10; j++) {
leakObjArray[j].CreateLeakyEle();
}
var container = document.getElementById('Container');
AddEvent(container, 'click', Run, false);
alert('Close this dialog and click the document to continue.');
}
function Run() {
var k = 0;
var l = 10;
for(var m = 0; m<10000; m++) {
leakObjArray[k].DestroyLeakyEle();
leakObjArray[l].CreateLeakyEle();
if(k<leakObjArray.length - 1) {
k++;
} else {
k = 0;
}
if(l<leakObjArray.length - 1) {
l++;
} else {
l = 0;
}
}
for(var i=0; i<leakObjArray.length; i++) {
leakObjArray[i].DestroyLeakyEle();
}
alert('Test Complete.');
}
/******************************* END MAIN ********************************/
/******************************* LEAKY OBJECT ********************************/
function LeakyObj(id) {
this.id = id;
this.leakyEle = null;
this.containerEle = document.getElementById('Container');
this.clicked = false;
this.eventParams = new Array();
}
LeakyObj.prototype.CreateLeakyEle = function() {
var leakyEle = document.createElement('div');
leakyEle.id = 'leakyEle' + this.id;
leakyEle.className = 'leakyEle';
leakyEle.innerHTML = this.id + ' --- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
this.leakyEle = leakyEle;
var _self = this;
this.eventParams.push(AddEventWithReturnParams(this.leakyEle, 'click', function() { _self.EventHandler(); }, false));
this.containerEle.appendChild(leakyEle);
}
LeakyObj.prototype.DestroyLeakyEle = function() {
if(this.leakyEle != null) {
this.containerEle.removeChild(this.leakyEle);
for(var i=0; i<this.eventParams.length; i++) {
RemoveEventOverload(this.eventParams[i]);
}
this.leakyEle = null;
}
}
LeakyObj.prototype.EventHandler = function() {
this.leakyEle.style.display = 'none';
this.clicked = true;
}
/******************************* END LEAKY OBJECT ********************************/
/******************************* GENERAL FUNCS ********************************/
function AddEvent(elm, evType, fn, useCapture){
var success = false;
if(elm.addEventListener) {
if(evType == 'mousewheel') evType = 'DOMMouseScroll';
elm.addEventListener(evType, fn, useCapture);
success = true;
} else if(elm.attachEvent) {
if(evType == 'mousewheel') {
window.onmousewheel = document.onmousewheel = fn;
success = true;
} else {
var r = elm.attachEvent('on' + evType, fn);
success = r;
}
} else {
success = false;
}
elm = null;
return success;
}
function AddEventWithReturnParams(elm, evType, fn, useCapture) {
var eventParams = new EventParams(elm, evType, fn, useCapture);
AddEvent(elm, evType, fn, useCapture);
return eventParams;
}
function RemoveEvent(elm, evType, fn, useCapture) {
if(elm) {
if(elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
return true;
} else if(elm.detachEvent) {
var r = elm.detachEvent('on' + evType, fn);
return r;
} else {
debugger;
}
}
}
function RemoveEventOverload(eventParams) {
if(eventParams) {
return RemoveEvent(eventParams.element, eventParams.eventType, eventParams.handler, eventParams.capture);
}
}
function EventParams(elm, evType, fn, useCapture) {
return {
element: elm,
eventType: evType,
handler: fn,
capture: useCapture
}
}
/******************************* END GENERAL FUNCS ********************************/
</script>
</head>
<body>
<div id="Container"></div>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 270082,
"author": "Lee Kowalkowski",
"author_id": 30945,
"author_profile": "https://Stackoverflow.com/users/30945",
"pm_score": 3,
"selected": true,
"text": "<p>looks like you're pushing stuff onto the eventParams array inside CreateLeakyEle, but never removing it? Is that right?</p>\n"
},
{
"answer_id": 270084,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": false,
"text": "<p>If you take a look at your code, you should notice that in each eventParams object stored in your eventParams array, you have references to the objects, but you never empty out your array. Try clearing out your array...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7423/"
] |
The code is rather long yet simple:
* 100 leaky JavaScript objects are created.
* 10 leaky elements are created from the JS objects.
* 1 element is removed and 1 is added 10000 times.
I assume that the `detachEvent` call is not functioning properly.
Also, if you change `this.eventParams` from an array to a simple variable, the leak goes away. Why?
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Memory Leak With Fix</title>
<style type="text/css">
.leakyEle
{
border: solid 1px red;
background-color: Gray;
}
</style>
<script type="text/javascript">
/******************************* MAIN ********************************/
var leakObjArray = new Array();
AddEvent(window, 'load', Startup, false);
function Startup() {
for(var i=0; i<100; i++) {
leakObjArray.push(new LeakyObj(i));
}
for(var j=0; j<10; j++) {
leakObjArray[j].CreateLeakyEle();
}
var container = document.getElementById('Container');
AddEvent(container, 'click', Run, false);
alert('Close this dialog and click the document to continue.');
}
function Run() {
var k = 0;
var l = 10;
for(var m = 0; m<10000; m++) {
leakObjArray[k].DestroyLeakyEle();
leakObjArray[l].CreateLeakyEle();
if(k<leakObjArray.length - 1) {
k++;
} else {
k = 0;
}
if(l<leakObjArray.length - 1) {
l++;
} else {
l = 0;
}
}
for(var i=0; i<leakObjArray.length; i++) {
leakObjArray[i].DestroyLeakyEle();
}
alert('Test Complete.');
}
/******************************* END MAIN ********************************/
/******************************* LEAKY OBJECT ********************************/
function LeakyObj(id) {
this.id = id;
this.leakyEle = null;
this.containerEle = document.getElementById('Container');
this.clicked = false;
this.eventParams = new Array();
}
LeakyObj.prototype.CreateLeakyEle = function() {
var leakyEle = document.createElement('div');
leakyEle.id = 'leakyEle' + this.id;
leakyEle.className = 'leakyEle';
leakyEle.innerHTML = this.id + ' --- XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX' +
'<br/>XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX';
this.leakyEle = leakyEle;
var _self = this;
this.eventParams.push(AddEventWithReturnParams(this.leakyEle, 'click', function() { _self.EventHandler(); }, false));
this.containerEle.appendChild(leakyEle);
}
LeakyObj.prototype.DestroyLeakyEle = function() {
if(this.leakyEle != null) {
this.containerEle.removeChild(this.leakyEle);
for(var i=0; i<this.eventParams.length; i++) {
RemoveEventOverload(this.eventParams[i]);
}
this.leakyEle = null;
}
}
LeakyObj.prototype.EventHandler = function() {
this.leakyEle.style.display = 'none';
this.clicked = true;
}
/******************************* END LEAKY OBJECT ********************************/
/******************************* GENERAL FUNCS ********************************/
function AddEvent(elm, evType, fn, useCapture){
var success = false;
if(elm.addEventListener) {
if(evType == 'mousewheel') evType = 'DOMMouseScroll';
elm.addEventListener(evType, fn, useCapture);
success = true;
} else if(elm.attachEvent) {
if(evType == 'mousewheel') {
window.onmousewheel = document.onmousewheel = fn;
success = true;
} else {
var r = elm.attachEvent('on' + evType, fn);
success = r;
}
} else {
success = false;
}
elm = null;
return success;
}
function AddEventWithReturnParams(elm, evType, fn, useCapture) {
var eventParams = new EventParams(elm, evType, fn, useCapture);
AddEvent(elm, evType, fn, useCapture);
return eventParams;
}
function RemoveEvent(elm, evType, fn, useCapture) {
if(elm) {
if(elm.removeEventListener) {
elm.removeEventListener(evType, fn, useCapture);
return true;
} else if(elm.detachEvent) {
var r = elm.detachEvent('on' + evType, fn);
return r;
} else {
debugger;
}
}
}
function RemoveEventOverload(eventParams) {
if(eventParams) {
return RemoveEvent(eventParams.element, eventParams.eventType, eventParams.handler, eventParams.capture);
}
}
function EventParams(elm, evType, fn, useCapture) {
return {
element: elm,
eventType: evType,
handler: fn,
capture: useCapture
}
}
/******************************* END GENERAL FUNCS ********************************/
</script>
</head>
<body>
<div id="Container"></div>
</body>
</html>
```
|
looks like you're pushing stuff onto the eventParams array inside CreateLeakyEle, but never removing it? Is that right?
|
270,029 |
<p>I am implementing a class to compare directory trees (in C#). At first I implemented the actual comparison in the class's constructor. Like this:</p>
<pre><code>DirectoryComparer c = new DirectoryComparer("C:\\Dir1", "C:\\Dir2");
</code></pre>
<p>But it doesn't feel "right" to do a possible lengthy operation in the constructor. An alternative way is to make the constructor private and add a static method like this:</p>
<pre><code>DirectoryComparer c = DirectoryComparer.Compare("C:\\Dir1", "C:\\Dir2");
</code></pre>
<p>What do you think? Do you expect a constructor to be "quick"? Is the second example better or is it just complicating the usage of the class?</p>
<p><strong>BTW:</strong> </p>
<p>I wont mark any answer as accepted because I don't think there is a correct answer, just preference and taste.</p>
<p><strong>Edit:</strong></p>
<p>Just to clarify my example a little. I'm not only insterested if the directories differs, I'm also interested in how they differ (which files). So a simple int return value wont be enough. The answer by cdragon76.myopenid.com actually is pretty close to what I want (+1 to you).</p>
|
[
{
"answer_id": 270032,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 3,
"selected": false,
"text": "<p>I prefer the second one.</p>\n\n<p>I expect the constructor to instanciate the class.\nThe method compare does what it is designed to do.</p>\n"
},
{
"answer_id": 270033,
"author": "Douglas Mayle",
"author_id": 8458,
"author_profile": "https://Stackoverflow.com/users/8458",
"pm_score": 2,
"selected": false,
"text": "<p>You should never do anything that might fail in a constructor. You don't want to ever create invalid objects. While you could implement a \"zombie\" state where the object doesn't do much, it's much better to perform any complex logic in seperate methods.</p>\n"
},
{
"answer_id": 270034,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, typically a constructor is something quick, it is designed to prepare the object for use, not to actually do operations. I like your second option as it keeps it a one line operation.</p>\n\n<p>You could also make it a bit easier by allowing the constructor to pass the two paths, then have a Compare() method that actually does the processing.</p>\n"
},
{
"answer_id": 270040,
"author": "Dana the Sane",
"author_id": 2567,
"author_profile": "https://Stackoverflow.com/users/2567",
"pm_score": 3,
"selected": false,
"text": "<p>I think an interface might be what you're after. I would create a class to represent a directory, and have that implement the DirectoryComparer interface. That interface would include the compare method. If C# already has a Comparable interface, you could also just implement that.</p>\n\n<p>In code, your call would be:</p>\n\n<pre><code>D1 = new Directory(\"C:\\\");\n..\nD1.compare(D2);\n</code></pre>\n"
},
{
"answer_id": 270049,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 1,
"selected": false,
"text": "<p>I like the second example because it explains what is exactly happening when you instantiate the object. Plus, I always use the constructor to initialize all of the global settings fro the class.</p>\n"
},
{
"answer_id": 270050,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 4,
"selected": false,
"text": "<p>I would think a combination of the two is the \"right\" choice, as I would expect the Compare method to return the comparison result, not the comparer itself.</p>\n\n<pre><code>DirectoryComparer c = new DirectoryComparer();\n\nint equality = c.Compare(\"C:\\\\Dir1\", \"C:\\\\Dir2\");\n</code></pre>\n\n<p>...and as Dana mentions, there is an <a href=\"http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx\" rel=\"nofollow noreferrer\">IComparer</a> interface in .Net that reflects this pattern.</p>\n\n<p>The <a href=\"http://msdn.microsoft.com/en-us/library/xh5ks3b3.aspx\" rel=\"nofollow noreferrer\">IComparer.Compare</a> method returns an int since the use of IComparer classes is primarily with sorting. The general pattern though fits the problem of the question in that:</p>\n\n<ol>\n<li>Constructor initializes an instance with (optionally) \"configuring\" parameters</li>\n<li>Compare method takes two \"data\" parameters, compares them and returns a \"result\"</li>\n</ol>\n\n<p>Now, the result can be an int, a bool, a collection of diffs. Whatever fits the need.</p>\n"
},
{
"answer_id": 270063,
"author": "Klathzazt",
"author_id": 35223,
"author_profile": "https://Stackoverflow.com/users/35223",
"pm_score": 1,
"selected": false,
"text": "<p>I think for a general purpose comparer you may on construction only want to specify the files you are comparing and then compare later- this way you can also implement extended logic:</p>\n\n<ul>\n<li>Compare again- what if the directories changed?</li>\n<li>Change the files you are comparing by updating the members.</li>\n</ul>\n\n<p>Also, you may want to consider in your implementation receiving messages from your OS when files have been changed in the target directories- and optionally recomparing again.</p>\n\n<p>The point is- you are imposing limits by assuming that this class will only be used to compare once for a single instance of those files.</p>\n\n<p>Therefore, I prefer:</p>\n\n<p><code>\nDirectoryComparer = new DirectoryComparer(&Dir1,&Dir2);</p>\n\n<p>DirectoryComparer->Compare();</p>\n\n<p></code></p>\n\n<p>Or</p>\n\n<p><code>\nDirectoryComparer = new DirectoryComparer();</p>\n\n<p>DirectoryComparer->Compare(&Dir1,&Dir2);</p>\n\n<p></code></p>\n"
},
{
"answer_id": 270123,
"author": "Alex Shnayder",
"author_id": 26042,
"author_profile": "https://Stackoverflow.com/users/26042",
"pm_score": 0,
"selected": false,
"text": "<p>If you are working with C#, you could use extension methods to create a method for comparing 2 directories that you would attach to the build in DirectoryClass, so it would look some thing like:</p>\n\n<pre><code>Directory dir1 = new Directory(\"C:\\.....\");\nDirectory dir2 = new Directory(\"D:\\.....\");\n\nDirectoryCompare c = dir1.CompareTo(dir2);\n</code></pre>\n\n<p>This would be much clearer implementation.\nMore on extension methods <a href=\"http://www.developer.com/net/csharp/article.php/3592216\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 270146,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<p>If an operation may take an unknown amount of time, it is an operation you might want to export into a different thread (so your main thread won't block and can do other things, like showing a spinning progress indicator for example). Other apps may not want to do this, they may want everything within a single thread (e.g. those that have no UI). Moving object creation to a separate thread is a bit awkward IMHO. I'd prefer to create the object (quickly) in my current thread and then just let a method of it run within another thread and once the method finished running, the other thread can die and I can grab the result of this method in my current thread by using another method of the object before dumping the object, since I'm happy as soon as I know the result (or keeping a copy if the result involves more details I may have to consume one at a time).</p>\n"
},
{
"answer_id": 270244,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 2,
"selected": false,
"text": "<p>I agree with the general sentiment of not doing lengthy operations inside constructors.</p>\n\n<p>Additionally, while on the subject of design, I'd consider changing your 2nd example so that the <code>DirectoryComparer.Compare</code> method returns something other than a <code>DirectoryComparer</code> object. (Perhaps a new class called <code>DirectoryDifferences</code> or <code>DirectoryComparisonResult</code>.) An object of type <code>DirectoryComparer</code> sounds like an object you would use to compare directories as opposed to an object that represents the differences between a pair of directories.</p>\n\n<p>Then if you want to define different ways of comparing directories (such as ignoring timestamps, readonly attributes, empty directories, etc.) you could make those parameters you pass to the <code>DirectoryComparer</code> class constructor. Or, if you always want <code>DirectoryComparer</code> to have the exact same rules for comparing directories, you could simply make <code>DirectoryComparer</code> a static class.</p>\n\n<p>For example:</p>\n\n<pre><code>DirectoryComparer comparer = new DirectoryComparer(\n DirectoryComparerOptions.IgnoreDirectoryAttributes\n);\nDirectoryComparerResult result = comparer.Compare(\"C:\\\\Dir1\", \"C:\\\\Dir2\");\n</code></pre>\n"
},
{
"answer_id": 270266,
"author": "John Nilsson",
"author_id": 24243,
"author_profile": "https://Stackoverflow.com/users/24243",
"pm_score": 0,
"selected": false,
"text": "<p>If the arguments are just going to be processed once then I don't think they belong as either constructor arguments or instance state.</p>\n\n<p>If however the comparison service is going to support some kind of suspendable algorithm or you want to notify listeners when the equality state of two directories changes based on filesystem events or something like that. Then ther directories is part of the instance state.</p>\n\n<p>In neither case is the constructor doing any work other than initializing an instance. In case two above the algorithm is either driven by a client, just like an Iterator for example, or it's driven by the event listening thread.</p>\n\n<p>I generally try to do things like this:\nDon't hold state in the instance if it can be passed as arguments to service methods.\nTry to design the object with immutable state.\nDefining attributes, like those used in equals and hashcode should allways be immutable.</p>\n\n<p>Conceptualy a constructor is a function mapping an object representation to the object it represents. </p>\n\n<p>By the definition above Integer.valueOf(1) is actually more of a constructor than new Integer(1) because Integer.valueOf(1) == Integer.valueOf(1).\n, \nIn either case this concept also means that all the cosntructor arguments, and only the constructor argument, should define the equals behavior of an object.</p>\n"
},
{
"answer_id": 272149,
"author": "user22367",
"author_id": 22367,
"author_profile": "https://Stackoverflow.com/users/22367",
"pm_score": 0,
"selected": false,
"text": "<p>I would definitely do the second.</p>\n\n<p>Long actions in a constructor are fine if they are actually building the object so it is usable.</p>\n\n<p>Now one thing that I see people do in constructors is call virtual methods. This is BAD since once someone uses you as a base class and overrides one of those functions you will call the base class's version not the derived class once you get into your constructor.</p>\n"
},
{
"answer_id": 272187,
"author": "BlaM",
"author_id": 999,
"author_profile": "https://Stackoverflow.com/users/999",
"pm_score": 0,
"selected": false,
"text": "<p>I don't think that talking about abstract terms like \"lengthy\" have anything to do with the decision if you put something in an constructor or not.</p>\n\n<p>A constructor is something that should be used to initialize an object, a method should be used to \"do something\", i.e. have a function.</p>\n"
},
{
"answer_id": 272230,
"author": "Andre",
"author_id": 17650,
"author_profile": "https://Stackoverflow.com/users/17650",
"pm_score": 1,
"selected": false,
"text": "<p>I think it's not only okay for a constructor to take as much time as needed to construct a valid object, but the constructor is required to do so. Deferring object creation is very bad as you end up with potentially invalid objects. So, you will have to check an object everytime before you touch it (this is how it is done in the MFC, you have <code>bool IsValid()</code> methods everywhere).</p>\n\n<p><strong>I only see a slight difference in the two ways of creating the object. One can see the new operator as a static function of the class anyway. So, this all boils down to syntactic sugar.</strong></p>\n\n<p>What does the <code>DirectoryComparer</code> class do? What is it's responsibility? From my point of view (which is a C++ programmer's view) it looks like you'd be better off with just using a free function, but I don't think that you can have free functions in C#, can you? I guess you will collect the files which are different in the <code>DirectoryComparer</code> object. If so, you could better create something like an array of files or an equivalent class that's named accordingly.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4422/"
] |
I am implementing a class to compare directory trees (in C#). At first I implemented the actual comparison in the class's constructor. Like this:
```
DirectoryComparer c = new DirectoryComparer("C:\\Dir1", "C:\\Dir2");
```
But it doesn't feel "right" to do a possible lengthy operation in the constructor. An alternative way is to make the constructor private and add a static method like this:
```
DirectoryComparer c = DirectoryComparer.Compare("C:\\Dir1", "C:\\Dir2");
```
What do you think? Do you expect a constructor to be "quick"? Is the second example better or is it just complicating the usage of the class?
**BTW:**
I wont mark any answer as accepted because I don't think there is a correct answer, just preference and taste.
**Edit:**
Just to clarify my example a little. I'm not only insterested if the directories differs, I'm also interested in how they differ (which files). So a simple int return value wont be enough. The answer by cdragon76.myopenid.com actually is pretty close to what I want (+1 to you).
|
I would think a combination of the two is the "right" choice, as I would expect the Compare method to return the comparison result, not the comparer itself.
```
DirectoryComparer c = new DirectoryComparer();
int equality = c.Compare("C:\\Dir1", "C:\\Dir2");
```
...and as Dana mentions, there is an [IComparer](http://msdn.microsoft.com/en-us/library/8ehhxeaf.aspx) interface in .Net that reflects this pattern.
The [IComparer.Compare](http://msdn.microsoft.com/en-us/library/xh5ks3b3.aspx) method returns an int since the use of IComparer classes is primarily with sorting. The general pattern though fits the problem of the question in that:
1. Constructor initializes an instance with (optionally) "configuring" parameters
2. Compare method takes two "data" parameters, compares them and returns a "result"
Now, the result can be an int, a bool, a collection of diffs. Whatever fits the need.
|
270,042 |
<p>I'm optimizing some frequently run Perl code (once per day per file). </p>
<p>Do comments slow Perl scripts down? My experiments lean towards no:</p>
<pre><code>use Benchmark;
timethese(20000000, {
'comments' => '$b=1;
# comment ... (100 times)
', 'nocomments' => '$b=1;'});
</code></pre>
<p>Gives pretty much identical values (apart from noise).</p>
<pre><code>Benchmark: timing 10000000 iterations of comments, nocomments...
comments: 1 wallclock secs ( 0.53 usr + 0.00 sys = 0.53 CPU) @ 18832391.71/s (n=10000000)
nocomments: 0 wallclock secs ( 0.44 usr + 0.00 sys = 0.44 CPU) @ 22935779.82/s (n=10000000)
Benchmark: timing 20000000 iterations of comments, nocomments...
comments: 0 wallclock secs ( 0.86 usr + -0.01 sys = 0.84 CPU) @ 23696682.46/s (n=20000000)
nocomments: 1 wallclock secs ( 0.90 usr + 0.00 sys = 0.90 CPU) @ 22099447.51/s (n=20000000)
</code></pre>
<p>I get similar results if I run the comments and no-comments versions as separate Perl scripts.</p>
<p>It seems counter-intuitive though, if nothing else the interpreter needs to read the comments into memory every time.</p>
|
[
{
"answer_id": 270056,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>Perl compiles a script and then executes it. Comments marginally slow the compile phase, but have zero effect on the run phase.</p>\n"
},
{
"answer_id": 270058,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 4,
"selected": false,
"text": "<p>Runtime performance? No.</p>\n\n<p>Parsing and lexing performance? Yes, of course.</p>\n\n<p>Since Perl tends to parse and lex on the fly, then comments will affect \"start up\" performance.</p>\n\n<p>Will they affect it noticably? Unlikely.</p>\n"
},
{
"answer_id": 270064,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 0,
"selected": false,
"text": "<p>I would expect that the one comment would only get parsed once, not multiple times in the loop, so I doubt it is a valid test.</p>\n\n<p>I would expect that comments would slightly slow compilation, but I expect it would be too minor to bother removing them.</p>\n"
},
{
"answer_id": 270067,
"author": "stephenbayer",
"author_id": 18893,
"author_profile": "https://Stackoverflow.com/users/18893",
"pm_score": 1,
"selected": false,
"text": "<p>From Paul Tomblins comment:</p>\n\n<blockquote>\n <blockquote>\n <p>Doesn't perl do some sort of on-the-fly compilation? Maybe the comments get discarded early? –</p>\n </blockquote>\n</blockquote>\n\n<p>Yes Perl does. </p>\n\n<p>It is a programming language in between compiled and interpreted. The code gets compiled on the fly and then run. the comments usually don't make any difference. The most it would probably effect is when it is initially parsing the file line by line and pre compiling it, you might see a nano second difference. </p>\n"
},
{
"answer_id": 270175,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 0,
"selected": false,
"text": "<p>Do Perl comments slow a script down? Well, parsing it, yes. Executing it after parsing it? No. How often is a script parsed? Only once, so if you have a comment within a for loop, the comment is discarded by the parses once, before the script even runs, once it started running, the comment is already gone (and the script is not stored as script internally by Perl), thus no matter how many times the for loop repeats, the comment won't have an influence. How fast can the parser skip over comments? The way Perl comments are done, very fast, thus I doubt you will notice. You will notice a higher start-up time if you have 5 lines of code and between each line 1 Mio lines of comments... but how likely is that and of what use would a comment that large be?</p>\n"
},
{
"answer_id": 270225,
"author": "Michael Carman",
"author_id": 8233,
"author_profile": "https://Stackoverflow.com/users/8233",
"pm_score": 3,
"selected": false,
"text": "<p>Perl is not a scripting language in the same sense that shell scripts are. The interpreter does not read the file line by line. The execution of a Perl program is done in two basic stages: compilation and runtime [1]. During the compilation stage the source code is parsed and converted into bytecode. During the runtime stage the bytecode is executed on a virtual machine.</p>\n\n<p>Comments will slow down the parsing stage but the difference is negligible compared to the time required to parse the script itself (which is already very small for most programs). About the only time you're really concerned with parsing time is in a webserver environment where the program could be called many times per second. mod_perl exists to solve this problem.</p>\n\n<p>You're using <code>Benchmark</code>. That's good! You should be looking for ways to improve the algorithm -- not micro-optimizing. Devel::DProf might be helpful to find any hot spots. You absolutely <em>should not</em> strip comments in a misguided attempt to make your program faster. You'll just make it unmaintainable.</p>\n\n<hr>\n\n<p>[1] This is commonly called \"just in time\" compilation. Perl actually has several more stages like <code>INIT</code> and <code>END</code> that don't matter here.</p>\n"
},
{
"answer_id": 270236,
"author": "Svante",
"author_id": 31615,
"author_profile": "https://Stackoverflow.com/users/31615",
"pm_score": 2,
"selected": false,
"text": "<p>The point is: optimize bottlenecks. Reading in a file consists of: </p>\n\n<ul>\n<li>opening the file, </li>\n<li>reading in its contents, </li>\n<li>closing the file, </li>\n<li>parsing the contents. </li>\n</ul>\n\n<p>Of these steps, reading is the fastest part by far (I am not sure about closing, it is a syscall, but you don't have to wait for it to finish). Even if it is 10% of the whole thing (which is is not, I think), then reducing it by half only gives 5% improved performance, at the cost of missing comments (which is a very bad thing). For the parser, throwing away a line that begins with # is not a tangible slowdown. And after that, the comments are gone, so there can be no slowdown.</p>\n\n<p>Now, imagine that you could actually improve the \"reading in the script\" part by 5% through stripping all comments (which is a really optimistic estimate, see above). How big is the share of \"reading in the script\" in overall time consumption of the script? Depends on how much it does, of course, but since perl scripts usually read at least one more file, it is 50% at most, but since perl scripts usually do something more, an honest estimate will bring this down to something in the range of 1%. So, the expected efficiency improvement by stripping all comments is <em>at</em> <em>most</em> (very optimistic) 2.5%, but really closer to 0.05%. And then, those where it actually gives more than 1% are already fast since they do almost nothing, so you are again optimizing at the wrong point.</p>\n\n<p>Concluding, optimize bottlenecks.</p>\n"
},
{
"answer_id": 270554,
"author": "Schwern",
"author_id": 14660,
"author_profile": "https://Stackoverflow.com/users/14660",
"pm_score": 5,
"selected": true,
"text": "<p>Perl is a just-in-time compiled language, so comments and POD have no effect on run-time performance.</p>\n\n<p>Comments and POD have a minuscule effect on compile-time, but they're so easy and fast for Perl to parse it's almost impossible to measure the performance hit. You can see this for yourself by using the <code>-c</code> flag to just compile.</p>\n\n<p>On my Macbook, a Perl program with 2 statements and 1000 lines of 70 character comments takes the same time to compile as one with 1000 lines of empty comments as one with just 2 print statements. Be sure to run each benchmark <em>twice</em> to allow your OS to cache the file, otherwise what you're benchmarking is the time to read the file from the disk.</p>\n\n<p>If startup time is a problem for you, it's not because of comments and POD.</p>\n"
},
{
"answer_id": 270741,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 2,
"selected": false,
"text": "<p>The Benchmark module is useless in this case. It's only measuring the times to run the code over and over again. Since your code doesn't actually do anything, most of it is optimized it away. That's why you're seeing it run 22 million times a second.</p>\n\n<p>I have almost on entire chapter about this in <a href=\"http://oreilly.com/catalog/9780596527242/\" rel=\"nofollow noreferrer\">Mastering Perl</a>. The error of measurement in the Benchmark technique is about 7%. Your benchmark numbers are well within that, so there's virtually no difference.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9056/"
] |
I'm optimizing some frequently run Perl code (once per day per file).
Do comments slow Perl scripts down? My experiments lean towards no:
```
use Benchmark;
timethese(20000000, {
'comments' => '$b=1;
# comment ... (100 times)
', 'nocomments' => '$b=1;'});
```
Gives pretty much identical values (apart from noise).
```
Benchmark: timing 10000000 iterations of comments, nocomments...
comments: 1 wallclock secs ( 0.53 usr + 0.00 sys = 0.53 CPU) @ 18832391.71/s (n=10000000)
nocomments: 0 wallclock secs ( 0.44 usr + 0.00 sys = 0.44 CPU) @ 22935779.82/s (n=10000000)
Benchmark: timing 20000000 iterations of comments, nocomments...
comments: 0 wallclock secs ( 0.86 usr + -0.01 sys = 0.84 CPU) @ 23696682.46/s (n=20000000)
nocomments: 1 wallclock secs ( 0.90 usr + 0.00 sys = 0.90 CPU) @ 22099447.51/s (n=20000000)
```
I get similar results if I run the comments and no-comments versions as separate Perl scripts.
It seems counter-intuitive though, if nothing else the interpreter needs to read the comments into memory every time.
|
Perl is a just-in-time compiled language, so comments and POD have no effect on run-time performance.
Comments and POD have a minuscule effect on compile-time, but they're so easy and fast for Perl to parse it's almost impossible to measure the performance hit. You can see this for yourself by using the `-c` flag to just compile.
On my Macbook, a Perl program with 2 statements and 1000 lines of 70 character comments takes the same time to compile as one with 1000 lines of empty comments as one with just 2 print statements. Be sure to run each benchmark *twice* to allow your OS to cache the file, otherwise what you're benchmarking is the time to read the file from the disk.
If startup time is a problem for you, it's not because of comments and POD.
|
270,074 |
<p>An application that has been working well for months has stopped picking up the JPA <code>@Entity</code> annotations that have been a part of it for months. As my integration tests run I see dozens of "<code>org.hibernate.MappingException: Unknown entity: com.whatever.OrderSystem</code>" type errors.</p>
<p>It isn't clear to me what's gone wrong here.</p>
<p>I have no <code>hibernate.cfg.xml</code> file because I'm using the Hibernate Entity Manager. Since I'm exclusively using annotations, there are no .hbm.xml files for my entities. My <code>persistence.xml</code> file is minimal, and lives in <code>META-INF</code> as it is supposed to.</p>
<p>I'm obviously missing something but can't put my finger on it.</p>
<p>I'm using hibernate-annotations 3.2.1, hibernate-entitymanager 3.2.1, persistence-api 1.0 and hibernate 3.2.1. hibernate-commons-annotations is also a part of the project's POM but I don't know if that's relevant.</p>
<p>Is there a web.xml entry that has vanished, or a Spring configuration entry that has accidentally been deleted?</p>
|
[
{
"answer_id": 270137,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 3,
"selected": true,
"text": "<p>I seem to recall I had a similar issue at one time. </p>\n\n<p>Its a long shot, but if you're not already doing this, have you explicitly specified the provider you are using?</p>\n\n<pre><code><persistence ...>\n <persistence-unit ...>\n <provider>org.hibernate.ejb.HibernatePersistence</provider> <---- explicit setting\n ....\n </persistence-unit>\n</persistence>\n</code></pre>\n\n<p>Otherwise, I'm not sure?</p>\n"
},
{
"answer_id": 288342,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>verify in your entity classe that you import javax.persistent.Entity and not org.hibernate.annotations.Entity</p>\n"
},
{
"answer_id": 400875,
"author": "kamal.gs",
"author_id": 43605,
"author_profile": "https://Stackoverflow.com/users/43605",
"pm_score": 0,
"selected": false,
"text": "<p>Is this happening for one specific class (few classes) or all the entity classes. The persistence.xml file has a list of class and or jar files that need to be scanned for @Entity mappings. If it was working earlier you can do a quick diff with the version of persistence.xml that was working correctly. Another issue could be that it is picking up a different persistence.xml file - you can verify this by introducing an error (for e.g., make the xml invalid) in the persistence.xml.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7178/"
] |
An application that has been working well for months has stopped picking up the JPA `@Entity` annotations that have been a part of it for months. As my integration tests run I see dozens of "`org.hibernate.MappingException: Unknown entity: com.whatever.OrderSystem`" type errors.
It isn't clear to me what's gone wrong here.
I have no `hibernate.cfg.xml` file because I'm using the Hibernate Entity Manager. Since I'm exclusively using annotations, there are no .hbm.xml files for my entities. My `persistence.xml` file is minimal, and lives in `META-INF` as it is supposed to.
I'm obviously missing something but can't put my finger on it.
I'm using hibernate-annotations 3.2.1, hibernate-entitymanager 3.2.1, persistence-api 1.0 and hibernate 3.2.1. hibernate-commons-annotations is also a part of the project's POM but I don't know if that's relevant.
Is there a web.xml entry that has vanished, or a Spring configuration entry that has accidentally been deleted?
|
I seem to recall I had a similar issue at one time.
Its a long shot, but if you're not already doing this, have you explicitly specified the provider you are using?
```
<persistence ...>
<persistence-unit ...>
<provider>org.hibernate.ejb.HibernatePersistence</provider> <---- explicit setting
....
</persistence-unit>
</persistence>
```
Otherwise, I'm not sure?
|
270,080 |
<p>What are the main differences between a Linked List and a BinarySearchTree? Is BST just a way of maintaining a LinkedList? My instructor talked about LinkedList and then BST but did't compare them or didn't say when to prefer one over another. This is probably a dumb question but I'm really confused. I would appreciate if someone can clarify this in a simple manner.</p>
|
[
{
"answer_id": 270088,
"author": "Aaron Silverman",
"author_id": 26197,
"author_profile": "https://Stackoverflow.com/users/26197",
"pm_score": 3,
"selected": false,
"text": "<p>I would say the MAIN difference is that a binary search tree is sorted. When you insert into a binary search tree, where those elements end up being stored in memory is a function of their value. With a linked list, elements are blindly added to the list regardless of their value.</p>\n\n<p>Right away you can some trade offs:\nLinked lists preserve insertion order and inserting is less expensive\nBinary search trees are generally quicker to search</p>\n"
},
{
"answer_id": 270090,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 4,
"selected": false,
"text": "<p>In computer science, a <a href=\"http://en.wikipedia.org/wiki/Binary_search_tree\" rel=\"noreferrer\">binary search tree (BST)</a> is a binary tree data structure which has the following properties:</p>\n\n<ul>\n<li>each node (item in the tree) has a distinct value;</li>\n<li>both the left and right subtrees must also be binary search trees;</li>\n<li>the left subtree of a node contains only values less than the node's value;</li>\n<li>the right subtree of a node contains only values greater than or equal to the node's value.</li>\n</ul>\n\n<p>In computer science, a <a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"noreferrer\">linked list</a> is one of the fundamental data structures, and can be used to implement other data structures.</p>\n\n<p>So a Binary Search tree is an abstract concept that may be implemented with a linked list or an array. While the linked list is a fundamental data structure. </p>\n"
},
{
"answer_id": 270092,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 3,
"selected": false,
"text": "<p>Linked lists and BSTs don't really have much in common, except that they're both data structures that act as containers. <a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"noreferrer\"><strong>Linked lists</strong></a> basically allow you to insert and remove elements efficiently at any location in the list, while maintaining the ordering of the list. This list is implemented using pointers from one element to the next (and often the previous).</p>\n\n<p>A <a href=\"http://en.wikipedia.org/wiki/Binary_search_tree\" rel=\"noreferrer\"><strong>binary search tree</strong></a> on the other hand is a data structure of a higher abstraction (i.e. it's not specified <em>how</em> this is implemented internally) that allows for efficient searches (i.e. in order to find a specific element you don't have to look at all the elements.</p>\n\n<p>Notice that a linked list can be thought of as a degenerated binary tree, i.e. a tree where all nodes only have one child.</p>\n"
},
{
"answer_id": 270094,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 7,
"selected": true,
"text": "<p>Linked List:</p>\n\n<pre><code>Item(1) -> Item(2) -> Item(3) -> Item(4) -> Item(5) -> Item(6) -> Item(7)\n</code></pre>\n\n<p>Binary tree:</p>\n\n<pre><code> Node(1)\n /\n Node(2)\n / \\\n / Node(3)\n RootNode(4)\n \\ Node(5)\n \\ /\n Node(6)\n \\\n Node(7)\n</code></pre>\n\n<p>In a linked list, the items are linked together through a single next pointer.\nIn a binary tree, each node can have 0, 1 or 2 subnodes, where (in case of a binary search tree) the key of the left node is lesser than the key of the node and the key of the right node is more than the node. As long as the tree is balanced, the searchpath to each item is a lot shorter than that in a linked list.</p>\n\n<p>Searchpaths:</p>\n\n<pre><code>------ ------ ------\nkey List Tree\n------ ------ ------\n1 1 3\n2 2 2\n3 3 3\n4 4 1\n5 5 3\n6 6 2\n7 7 3\n------ ------ ------\navg 4 2.43\n------ ------ ------\n</code></pre>\n\n<p>By larger structures the average search path becomes significant smaller:</p>\n\n<pre><code>------ ------ ------\nitems List Tree\n------ ------ ------\n 1 1 1\n 3 2 1.67\n 7 4 2.43\n 15 8 3.29\n 31 16 4.16\n 63 32 5.09\n------ ------ ------\n</code></pre>\n"
},
{
"answer_id": 270095,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 1,
"selected": false,
"text": "<p>A binary search tree can be implemented in any fashion, it doesn't need to use a linked list.</p>\n\n<p>A linked list is simply a structure which contains nodes and pointers/references to other nodes inside a node. Given the head node of a list, you may browse to any other node in a linked list. Doubly-linked lists have two pointers/references: the normal reference to the next node, but also a reference to the previous node. If the last node in a doubly-linked list references the first node in the list as the next node, and the first node references the last node as its previous node, it is said to be a circular list.</p>\n\n<p>A binary search tree is a tree that splits up its input into two roughly-equal halves based on a binary search comparison algorithm. Thus, it only needs a very few searches to find an element. For instance, if you had a tree with 1-10 and you needed to search for three, first the element at the top would be checked, probably a 5 or 6. Three would be less than that, so only the first half of the tree would then be checked. If the next value is 3, you have it, otherwise, a comparison is done, etc, until either it is not found or its data is returned. Thus the tree is fast for lookup, but not nessecarily fast for insertion or deletion. These are very rough descriptions.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Linked_list\" rel=\"nofollow noreferrer\">Linked List</a> from wikipedia, and <a href=\"http://en.wikipedia.org/wiki/Binary_Search_Tree\" rel=\"nofollow noreferrer\">Binary Search Tree</a>, also from wikipedia.</p>\n"
},
{
"answer_id": 270096,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>A linked list is just that... a list. It's linear; each node has a reference to the next node (and the previous, if you're talking of a doubly-linked list). A tree branches---each node has a reference to various child nodes. A binary tree is a special case in which each node has only two children. Thus, in a linked list, each node has a previous node and a next node, and in a binary tree, a node has a left child, right child, and parent.</p>\n\n<p>These relationships may be bi-directional or uni-directional, depending on how you need to be able to traverse the structure.</p>\n"
},
{
"answer_id": 270098,
"author": "Mike G.",
"author_id": 18901,
"author_profile": "https://Stackoverflow.com/users/18901",
"pm_score": 2,
"selected": false,
"text": "<p>It's actually pretty simple. A linked list is just a bunch of items chained together, in no particular order. You can think of it as a really skinny tree that never branches:</p>\n\n<p><code>1 -> 2 -> 5 -> 3 -> 9 -> 12 -> |i.</code> (that last is an ascii-art attempt at a terminating null)</p>\n\n<p>A Binary Search Tree is different in 2 ways: the binary part means that each node has <em>2</em> children, not one, and the search part means that those children are arranged to speed up searches - only smaller items to the left, and only larger ones to the right:</p>\n\n<pre><code> 5\n / \\\n 3 9\n / \\ \\\n1 2 12\n</code></pre>\n\n<p>9 has no left child, and 1, 2, and 12 are \"leaves\" - they have no branches.</p>\n\n<p>Make sense?</p>\n\n<p>For most \"lookup\" kinds of uses, a BST is better. But for just \"keeping a list of things to deal with later First-In-First-Out or Last-In-First-Out\" kinds of things, a linked list might work well.</p>\n"
},
{
"answer_id": 270099,
"author": "Salman Kasbati",
"author_id": 33931,
"author_profile": "https://Stackoverflow.com/users/33931",
"pm_score": 2,
"selected": false,
"text": "<p>Linked List is straight Linear data with adjacent nodes connected with each other e.g. A->B->C. You can consider it as a straight fence.</p>\n\n<p>BST is a hierarchical structure just like a tree with the main trunk connected to branches and those branches in-turn connected to other branches and so on. The \"Binary\" word here means each branch is connected to a maximum of two branches.</p>\n\n<p>You use linked list to represent straight data only with each item connected to a maximum of one item; whereas you can use BST to connect an item to two items. You can use BST to represent a data such as family tree, but that'll become n-ary search tree as there can be more than two children to each person.</p>\n"
},
{
"answer_id": 270103,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "<p>They are totally different data structures.</p>\n\n<p>A linked list is a sequence of element where each element is linked to the next one, and in the case of a doubly linked list, the previous one.</p>\n\n<p>A binary search tree is something totally different. It has a root node, the root node has up to two child nodes, and each child node can have up to two child notes etc etc. It is a pretty clever data structure, but it would be somewhat tedious to explain it here. Check out the <a href=\"http://en.wikipedia.org/wiki/Binary_tree\" rel=\"nofollow noreferrer\">Wikipedia artcle</a> on it.</p>\n"
},
{
"answer_id": 270104,
"author": "Steve Morgan",
"author_id": 5806,
"author_profile": "https://Stackoverflow.com/users/5806",
"pm_score": 2,
"selected": false,
"text": "<p>The issue with a linked list is searching within it (whether for retrieval or insert).</p>\n\n<p>For a single-linked list, you have to start at the head and search sequentially to find the desired element. To avoid the need to scan the whole list, you need additional references to nodes within the list, in which case, it's no longer a simple linked list. </p>\n\n<p>A binary tree allows for more rapid searching and insertion by being inherently sorted and navigable.</p>\n\n<p>An alternative that I've used successfully in the past is a SkipList. This provides something akin to a linked list but with extra references to allow search performance comparable to a binary tree.</p>\n"
},
{
"answer_id": 270107,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>A linked list is a sequential number of \"nodes\" linked to each other, ie:</p>\n\n<pre><code>public class LinkedListNode\n{\n Object Data;\n LinkedListNode NextNode;\n}\n</code></pre>\n\n<p>A Binary Search Tree uses a similar node structure, but instead of linking to the next node, it links to two child nodes:</p>\n\n<pre><code>public class BSTNode\n{\n Object Data\n BSTNode LeftNode;\n BSTNode RightNode;\n} \n</code></pre>\n\n<p>By following specific rules when adding new nodes to a BST, you can create a data structure that is very fast to traverse. Other answers here have detailed these rules, I just wanted to show at the code level the difference between node classes.</p>\n\n<p>It is important to note that if you insert sorted data into a BST, you'll end up with a linked list, and you lose the advantage of using a tree.</p>\n\n<p>Because of this, a linkedList is an O(N) traversal data structure, while a BST is a O(N) traversal data structure in the worst case, and a O(log N) in the best case.</p>\n"
},
{
"answer_id": 270116,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 4,
"selected": false,
"text": "<p>A <strong>Binary Search Tree</strong> is a binary tree in which each internal node <em>x</em> stores an element such that the element stored in the left subtree of <em>x</em> are less than or equal to <em>x</em> and elements stored in the right subtree of <em>x</em> are greater than or equal to <em>x</em>.</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/d/da/Binary_search_tree.svg/300px-Binary_search_tree.svg.png\" alt=\"alt text\"></p>\n\n<p>Now a <strong>Linked List</strong> consists of a sequence of nodes, each containing arbitrary values and one or two references pointing to the next and/or previous nodes.</p>\n\n<p><img src=\"https://upload.wikimedia.org/wikipedia/commons/thumb/6/6d/Singly-linked-list.svg/300px-Singly-linked-list.svg.png\" alt=\"Linked List\"></p>\n"
},
{
"answer_id": 270424,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 3,
"selected": false,
"text": "<p>They do have similarities, but the main difference is that a Binary Search Tree is designed to support efficient searching for an element, or \"key\".</p>\n\n<p>A binary search tree, like a doubly-linked list, points to two other elements in the structure. However, when adding elements to the structure, rather than just appending them to the end of the list, the binary tree is reorganized so that elements linked to the \"left\" node are less than the current node and elements linked to the \"right\" node are greater than the current node.</p>\n\n<p>In a simple implementation, the new element is compared to the first element of the structure (the root of the tree). If it's less, the \"left\" branch is taken, otherwise the \"right\" branch is examined. This continues with each node, until a branch is found to be empty; the new element fills that position.</p>\n\n<p>With this simple approach, if elements are added in order, you end up with a linked list (with the same performance). Different algorithms exist for maintaining some measure of balance in the tree, by rearranging nodes. For example, AVL trees do the most work to keep the tree as balanced as possible, giving the best search times. Red-black trees don't keep the tree as balanced, resulting in slightly slower searches, but do less work on average as keys are inserted or removed.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270080",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
What are the main differences between a Linked List and a BinarySearchTree? Is BST just a way of maintaining a LinkedList? My instructor talked about LinkedList and then BST but did't compare them or didn't say when to prefer one over another. This is probably a dumb question but I'm really confused. I would appreciate if someone can clarify this in a simple manner.
|
Linked List:
```
Item(1) -> Item(2) -> Item(3) -> Item(4) -> Item(5) -> Item(6) -> Item(7)
```
Binary tree:
```
Node(1)
/
Node(2)
/ \
/ Node(3)
RootNode(4)
\ Node(5)
\ /
Node(6)
\
Node(7)
```
In a linked list, the items are linked together through a single next pointer.
In a binary tree, each node can have 0, 1 or 2 subnodes, where (in case of a binary search tree) the key of the left node is lesser than the key of the node and the key of the right node is more than the node. As long as the tree is balanced, the searchpath to each item is a lot shorter than that in a linked list.
Searchpaths:
```
------ ------ ------
key List Tree
------ ------ ------
1 1 3
2 2 2
3 3 3
4 4 1
5 5 3
6 6 2
7 7 3
------ ------ ------
avg 4 2.43
------ ------ ------
```
By larger structures the average search path becomes significant smaller:
```
------ ------ ------
items List Tree
------ ------ ------
1 1 1
3 2 1.67
7 4 2.43
15 8 3.29
31 16 4.16
63 32 5.09
------ ------ ------
```
|
270,091 |
<p>I cannot understand how this is possible. Please help!!</p>
<p>I have an app with a trayicon. I want a form to be show when the user double clicks the trayicon. I have a problem where it is possible to get 2 or more forms showing by quickly triple or quadruple clicking the trayicon. The reason I don't want a singleton is that I want the form to be released each time it is closed to save memory, maybe this is not a good idea?</p>
<p>I have a field called m_form1.
I have a method called ShowForm1;
I call the method ShowForm1 on the double-click of the TrayIcon.</p>
<pre><code> private Form1 m_form1;
private void ShowForm1()
{
if (m_form1 == null)
{
Trace.WriteLine("*CREATE*" + Thread.CurrentThread.ManagedThreadId.ToString());
m_form1 = new Form1();
m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
m_form1.BringToFront();
m_form1.Activate();
}
</code></pre>
<p>So when Form1 takes a while to construct, then it is possible to create 2 because m_form1 is still null when the second call arrives. Locking does not seem to work as it is the same thread both calls (I'm guessing the UI thread) ie the trace writes out *CREATE*1 twice (below).</p>
<pre><code>[3560] *CREATE*1
[3560] *CREATE*1
</code></pre>
<p>Changing the code to include a lock statement does not help me.</p>
<pre><code> private Form1 m_form1;
private object m_Locker = new object();
private void ShowForm1()
{
lock (m_Locker)
{
if (m_form1 == null)
{
Trace.WriteLine("****CREATE****" + Thread.CurrentThread.ManagedThreadId.ToString());
m_form1 = new Form1();
m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
}
m_form1.BringToFront();
m_form1.Activate();
}
</code></pre>
<p>How should I handle this situation? </p>
<p>Thanks guys</p>
<p>Tim.</p>
|
[
{
"answer_id": 270106,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Have an additional boolean variable, \"m_formUnderConstruction\" which you test for before constructing the form, and which you set as soon as you've decided to construct it.</p>\n\n<p>The re-entrancy makes all of this a little icky, unfortunately. I've removed the lock, as if this ever gets called from a different thread then you've got the nasty situation of trying to show a form from a different thread to the one it was constructed on.</p>\n\n<pre><code>private Form1 m_form1;\nprivate bool m_underConstruction = false;\n\nprivate void ShowForm1()\n{\n if (m_underConstruction)\n {\n // We're about to show it anyway\n return;\n }\n m_underConstruction = true;\n try\n {\n if (m_form1 == null)\n {\n m_form1 = new Form1();\n m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);\n m_form1.Show();\n }\n }\n finally\n {\n m_underConstruction = false;\n }\n m_form1.BringToFront();\n m_form1.Activate();\n}\n</code></pre>\n"
},
{
"answer_id": 270136,
"author": "Sunny Milenov",
"author_id": 8220,
"author_profile": "https://Stackoverflow.com/users/8220",
"pm_score": 0,
"selected": false,
"text": "<p>Use Interlocked.Increment to change the nr of the tries. If it is 1, open the form, otherwise, don't. And use Interlocked.Decrement after the test or on form's close.</p>\n\n<pre><code>private int openedForms = 0;\nprivate Form1 m_form1;\nprivate void ShowForm1()\n{\n\n if (Interlocked.Increment(ref openedForms) = 1)\n {\n m_form1 = new Form1();\n m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);\n m_form1.Show();\n }\n else\n {\n Interlocked.Decrement(ref openedForms);\n }\n if (m_form1 != null)\n {\n m_form1.BringToFront();\n m_form1.Activate();\n }\n}\n\nprivate void m_form1_FormClosed(object Sender, EventArgs args)\n{\n Interlocked.Decrement(ref openedForms);\n}\n</code></pre>\n"
},
{
"answer_id": 398052,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Please see this, it handles all mouse event combinations for NotifyIcon as well as Form1.</p>\n\n<p>More here: <a href=\"http://code.msdn.microsoft.com/TheNotifyIconExample\" rel=\"nofollow noreferrer\">http://code.msdn.microsoft.com/TheNotifyIconExample</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1077232/"
] |
I cannot understand how this is possible. Please help!!
I have an app with a trayicon. I want a form to be show when the user double clicks the trayicon. I have a problem where it is possible to get 2 or more forms showing by quickly triple or quadruple clicking the trayicon. The reason I don't want a singleton is that I want the form to be released each time it is closed to save memory, maybe this is not a good idea?
I have a field called m\_form1.
I have a method called ShowForm1;
I call the method ShowForm1 on the double-click of the TrayIcon.
```
private Form1 m_form1;
private void ShowForm1()
{
if (m_form1 == null)
{
Trace.WriteLine("*CREATE*" + Thread.CurrentThread.ManagedThreadId.ToString());
m_form1 = new Form1();
m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
m_form1.BringToFront();
m_form1.Activate();
}
```
So when Form1 takes a while to construct, then it is possible to create 2 because m\_form1 is still null when the second call arrives. Locking does not seem to work as it is the same thread both calls (I'm guessing the UI thread) ie the trace writes out \*CREATE\*1 twice (below).
```
[3560] *CREATE*1
[3560] *CREATE*1
```
Changing the code to include a lock statement does not help me.
```
private Form1 m_form1;
private object m_Locker = new object();
private void ShowForm1()
{
lock (m_Locker)
{
if (m_form1 == null)
{
Trace.WriteLine("****CREATE****" + Thread.CurrentThread.ManagedThreadId.ToString());
m_form1 = new Form1();
m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
}
m_form1.BringToFront();
m_form1.Activate();
}
```
How should I handle this situation?
Thanks guys
Tim.
|
Have an additional boolean variable, "m\_formUnderConstruction" which you test for before constructing the form, and which you set as soon as you've decided to construct it.
The re-entrancy makes all of this a little icky, unfortunately. I've removed the lock, as if this ever gets called from a different thread then you've got the nasty situation of trying to show a form from a different thread to the one it was constructed on.
```
private Form1 m_form1;
private bool m_underConstruction = false;
private void ShowForm1()
{
if (m_underConstruction)
{
// We're about to show it anyway
return;
}
m_underConstruction = true;
try
{
if (m_form1 == null)
{
m_form1 = new Form1();
m_form1.FormClosed += new FormClosedEventHandler(m_form1_FormClosed);
m_form1.Show();
}
}
finally
{
m_underConstruction = false;
}
m_form1.BringToFront();
m_form1.Activate();
}
```
|
270,093 |
<p>I came across this code and wanted others to provide their point of view... is it good or bad ? ;)</p>
<pre><code>Class ReportClass
{
public string ReportName {get; set;}
}
</code></pre>
<p>Then it was used as follows in code:</p>
<pre><code>displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())
</code></pre>
<p>That is about the simplest form example I can give you.
Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?</p>
<p><strong>EDIT:</strong> I'm referring to the inplace assignment. Which I wasn't aware of until today</p>
|
[
{
"answer_id": 270108,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": -1,
"selected": false,
"text": "<p>Seems fine to me. It is probably compiled with C# 3.0 and that allows <a href=\"http://msdn.microsoft.com/en-us/library/bb384054.aspx\" rel=\"nofollow noreferrer\">C# automatic properties</a>.</p>\n"
},
{
"answer_id": 270118,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 2,
"selected": false,
"text": "<p>Did you mean the automatic properties or the in-place assignment?</p>\n\n<p>Depends on your team IMO. If your team were comprised of C-style devs. Then I think it is ok.</p>\n\n<p>But if this code is gonna be maintained further by, say, VB developers, then you'd need \nto make this more readable.</p>\n\n<p>Examples? The assignment operator (=) in C langauges also return the values it's assigned.</p>\n\n<pre><code>var a = 0;\nvar b = 0;\n\n// This makes a *and* b equals to 1\na = b = 1; \n\n// This line prints 3 and a is now equals to 3\nConsole.WriteLine(a = 3);\n\n// This line prints 7 and a and b is now equals to 7\nConsole.WriteLine(a = b = 7);\n</code></pre>\n\n<p>I think it is rather natural for this kind of assignment to happen. Because the C-languages seem to encourage shorthand notations IMO.</p>\n\n<p>If you need more readability and less trouble, then I'd say a newline is a nice add. </p>\n\n<pre><code>displayReport(\n ReportClass.ReportName = cmbReportName.SelectedValue.ToString());\n</code></pre>\n\n<p>Make your intentions clearer when each <em>compounded</em> statements are on different lines. (but still a compound statement)</p>\n\n<p>Or, extract the right part out into its own variable first, e.g.</p>\n\n<pre><code>var reportName = cmbReportName.SelectedValue.ToString();\n\ndisplayReport(ReportClass.ReportName = reportName);\n</code></pre>\n\n<p>I use it all the time, and I havn't seen anyone confused upon reading it yet.</p>\n"
},
{
"answer_id": 270129,
"author": "EvilSyn",
"author_id": 6350,
"author_profile": "https://Stackoverflow.com/users/6350",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is harder to maintain/harder to debug/harder to understand code. I would do the assignment on a line prior to calling that method.</p>\n\n<pre><code>ReportClass.ReportName = cmbReportName.SelectedValue.ToString();\ndisplayReport(ReportClass.ReportName);\n</code></pre>\n\n<p>I've never really been a fan of compound statements.</p>\n"
},
{
"answer_id": 270151,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "<p><strong>It is totally fine.</strong> Both of them.</p>\n<ul>\n<li><p>Automatic properties (the <code>{get; set;}</code> thing): Introduced in C#. Very useful feature.</p>\n</li>\n<li><p>Assignment in the parameters: Rarely used in C# but totally legal. Basically it assigns the value of the expression to the right of the assignment operator (=) to the property to the porperty on the left, and then passes this value on to the method.</p>\n<p>This is more common in C, but I see no reason why shouldn't it be allowed in C# as well. Sometimes it might help readability, sometimes it makes it much worse. Use common sense to decide which applies when.</p>\n</li>\n</ul>\n"
},
{
"answer_id": 270167,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": -1,
"selected": false,
"text": "<p>Is that really valid code? Seems like a static class to me.</p>\n\n<p>I would have guessed you used it like this:</p>\n\n<pre>\ndisplayReport(new ReportClass { ReportName = cmbReportName.SelectedValue.ToString() } )\n</pre>\n"
},
{
"answer_id": 270206,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>I tend to avoid in-place assignment - or indeed any side effects like this - except for one common idiom:</p>\n\n<pre><code>string line;\nwhile ((line = reader.ReadLine()) != null)\n{\n // Do something with line \n}\n</code></pre>\n\n<p>(And variants for reading streams etc.)</p>\n\n<p>I'm also okay with using object initializers in parameter calls, e.g.</p>\n\n<pre><code>Foo(new Bar { X=1, Y=2 });\n</code></pre>\n\n<p>but assigning to a property in an existing object... well, it's all subjective but it's not my cup of tea.</p>\n"
},
{
"answer_id": 270213,
"author": "Peter Wone",
"author_id": 1715673,
"author_profile": "https://Stackoverflow.com/users/1715673",
"pm_score": 2,
"selected": false,
"text": "<p>The Microsoft Framework Design Guidelines discourage the placement of multiple statements on one line, except where there is direct language support, such as in the <code>for</code> statement. Since there is explicit language support for multiple assignment,</p>\n\n<pre><code>int a, b, c;\na = b = c = 0;\n</code></pre>\n\n<p>is permitted. On the other hand, code of the form used in your example is discouraged.</p>\n\n<p>How about this one, people?</p>\n\n<pre><code>while ((packetPos = Packet.FindStart(buffer, nextUnconsideredPos)) > -1)\n</code></pre>\n\n<p>To avoid the inline assignment, you would have to factor redundantly, like this:</p>\n\n<pre><code>packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);\nwhile (packetPosition > -1)\n{\n ...\n packetPosition = Packet.FindStart(buffer, nextUnconsideredPosition);\n}\n</code></pre>\n"
},
{
"answer_id": 270215,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I find the assignment as parameter not very readable. The overall flow of execution is just skewed by having an operation actually happening inside the parameter list.</p>\n\n<p>I like to think that my code should express intent, not save whitespace. And my intent in this example would be exactly what EvilSyn suggests, first assign value, then pass it to the method.</p>\n"
},
{
"answer_id": 271949,
"author": "anonym0use",
"author_id": 35441,
"author_profile": "https://Stackoverflow.com/users/35441",
"pm_score": -1,
"selected": false,
"text": "<p>As far as naming the property goes you have a ReportClass, I would change that to Report and the property on it changed from ReportName to just Name. Saves you on typing (although yes intellisense is available). Looks better when coding up as Report.Name.</p>\n\n<p>I know its a little off topic but hey ho</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I came across this code and wanted others to provide their point of view... is it good or bad ? ;)
```
Class ReportClass
{
public string ReportName {get; set;}
}
```
Then it was used as follows in code:
```
displayReport(ReportClass.ReportName = cmbReportName.SelectedValue.ToString())
```
That is about the simplest form example I can give you.
Quetion is... why can't I find examples ? What would this be called? Is this just asking for trouble?
**EDIT:** I'm referring to the inplace assignment. Which I wasn't aware of until today
|
I tend to avoid in-place assignment - or indeed any side effects like this - except for one common idiom:
```
string line;
while ((line = reader.ReadLine()) != null)
{
// Do something with line
}
```
(And variants for reading streams etc.)
I'm also okay with using object initializers in parameter calls, e.g.
```
Foo(new Bar { X=1, Y=2 });
```
but assigning to a property in an existing object... well, it's all subjective but it's not my cup of tea.
|
270,112 |
<p>I have an application where the user selects the dates of a first statement and a last statement. Example, first statement = 1/1/08, last statement = 12/1/08, should equal 12 statements.</p>
<p>However, when using the following code, the result is 11:</p>
<pre><code>numPayments = DateDiff(DateInterval.Month, CDate(.FeeStartDate), CDate(.FeeEndDate))
</code></pre>
<p>Is there another way to calculate this, or do I have to be stuck with adding 1 to the result?</p>
|
[
{
"answer_id": 270119,
"author": "Jason",
"author_id": 16794,
"author_profile": "https://Stackoverflow.com/users/16794",
"pm_score": 3,
"selected": false,
"text": "<p>Add 1, as you write. ;) </p>\n\n<p>The difference between 1/1/2008 and 12/1/2008 is 11 months. No changing that. ;)</p>\n"
},
{
"answer_id": 270120,
"author": "dub",
"author_id": 30022,
"author_profile": "https://Stackoverflow.com/users/30022",
"pm_score": 2,
"selected": false,
"text": "<p>Well, the number of months between Jan 1st and Dec 1st is 11... what you're looking for is the difference of months +1. So just add one :)</p>\n"
},
{
"answer_id": 270128,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>Also, the DateDiff function you're using is a VB6 hold-over. Better to express it like this:</p>\n\n<pre><code>numPayments = (Date.Parse(.FeeEndDate) - Date.Parse(.FeeStartDate)).TotalMonths + 1\n</code></pre>\n"
},
{
"answer_id": 270133,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, you'd always have to add one though you may be able to add one to the end date or subtract one from the start date to also get this effect. Consider the case where the start and end dates are the same. Their difference is 0 but you'd still want 1 statement to show just to note one odd case.</p>\n"
},
{
"answer_id": 13736603,
"author": "Joa.know",
"author_id": 1721727,
"author_profile": "https://Stackoverflow.com/users/1721727",
"pm_score": 0,
"selected": false,
"text": "<p>You could try this one. Hope this is very helpful.</p>\n\n<pre><code>Dim myDate As Date\nDim dateNow As Date\nDim nextMonth As Date\n\nmyDate = Now\ndateNow = Format(myDate, \"MM/dd/yyyy\")\nnextMonth = DateAdd(DateInterval.Month, 5, dateNow) 'compute the next 5 months from date now. Let say, #12/6/2012# the result will be #5/6/2013#\n\n\nMessageBox.Show(DateDiff(DateInterval.Month, dateNow, nextMonth) & \"months==> \" & nextMonth)\n'This will count the number of months interval. The result will be 5 months=>> #5/6/2013 because we count december to may.\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270112",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4770/"
] |
I have an application where the user selects the dates of a first statement and a last statement. Example, first statement = 1/1/08, last statement = 12/1/08, should equal 12 statements.
However, when using the following code, the result is 11:
```
numPayments = DateDiff(DateInterval.Month, CDate(.FeeStartDate), CDate(.FeeEndDate))
```
Is there another way to calculate this, or do I have to be stuck with adding 1 to the result?
|
Yes, you'd always have to add one though you may be able to add one to the end date or subtract one from the start date to also get this effect. Consider the case where the start and end dates are the same. Their difference is 0 but you'd still want 1 statement to show just to note one odd case.
|
270,113 |
<p>I have two Slackware Linux systems on which the POSIX semaphore <code>sem_open()</code> call fails with errno set to 38. Sample code to reproduce below (the code works fine on CentOS / RedHat).</p>
<p>Are there any kernel or system configuration options that could cause this? Other suggestions?</p>
<p>Systems with issue are Slackware 10.1.0 kernel 2.6.11 /lib/librt-2.3.4.so /lib/libpthread-0.10.so, but the same code works on the much older RedHat 9 kernel 2.4.20 /lib/librt-2.3.2.so /lib/tls/libpthread-0.29.so. (and also works on CentOS 5 kernel 2.6.18 /lib/librt-2.5.so /lib/i686/nosegneg/libpthread-2.5.so).</p>
<p><code>man sem_open</code> suggests this errno means <code>sem_open()</code> is not supported by system.</p>
<pre><code>#define ENOSYS 38 /* Function not implemented */
</code></pre>
<p>The <code>sem_open()</code> userspace is in <code>librt</code> which we link against dynamically and <code>librt</code> is present on the affected systems.</p>
<p>The affected system claims to support POSIX semaphores: <code>_POSIX_SEMAPHORES</code> is true and <code>sysconf(_SC_SEMAPHORES)</code> confirms this.</p>
<p>Thanks,
Kieran</p>
<p>Edit 1: I've added more detail on the software versions in use and removed some irrelevant comments.</p>
<p>Edit 2: /dev/shm is mounted on the good systems and not mounted on the bad systems. Mounting it did not change the behaviour on the affected systems. I think /dev/shm is necessary too but sem_open() is failing before that, and strace supports this.</p>
<pre><code># /* Quick'n'dirty test program to illustrate sem_open failure
#Run this file to auto-build test and run as a.out
# Build
gcc $0 -lrt
if [ $? -ne 0 ] ; then exit ; fi
# Run
$( dirname $0)/a.out
exit
*/
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <semaphore.h>
int main(int argc, char *argv[]) {
const char *SEM_NAME = "SHRMEM_SCXL"; /* name of mutex */
sem_t *mutex = SEM_FAILED; /* ptr to mutex */
#ifdef _POSIX_SEMAPHORES
printf("_POSIX_SEMAPHORES %ld\n", _POSIX_SEMAPHORES);
#else
puts("Undefined");
#endif
printf("sysconf %s\n", sysconf(_SC_SEMAPHORES) ? "Yes" : "No" );
mutex = sem_open(SEM_NAME, O_CREAT, 0666, 1);
if (mutex == SEM_FAILED) printf("Failed %d\n", errno);
else {
puts("Success - pause while you check /dev/shm ");
sleep(5);
sem_close(mutex);
sem_unlink(SEM_NAME);
}
}
</code></pre>
|
[
{
"answer_id": 270377,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 4,
"selected": true,
"text": "<p>Is /dev/shm mounted? Older versions of slackware may not have mounted this filesystem at boot. From /etc/fstab:</p>\n\n<pre><code>tmpfs /dev/shm tmpfs defaults 0 0\n</code></pre>\n\n<p>Edit: That is probably not the problem after all. I think you may just need to upgrade your kernel or maybe even librt.</p>\n\n<p>Edit2: I think that for slackware 11, which I think you are using, you'll need a kernel newer than 2.6.13 to use the NPTL threading libraries (libs in /lib/tls) which appear to be required for the sem_open to work.</p>\n\n<p>Edit3: I managed to get it to work with a slackware 11 box I have by a) mounting /dev/shm and b) setting the environment variable <code>LD_ASSUME_KERNEL</code> to 2.6.13 (any kernel version > 2.6.12 will work). That seems to work even though the kernel is 2.6.11.11, but other things like threads might not.</p>\n"
},
{
"answer_id": 271901,
"author": "Kieran Tully",
"author_id": 18023,
"author_profile": "https://Stackoverflow.com/users/18023",
"pm_score": 2,
"selected": false,
"text": "<p>Older versions of the threading libraries don't support sharing POSIX semaphores between processes. From <code>man sem_init</code> </p>\n\n<blockquote>\n <p>The pshared argument indicates whether the semaphore is local to the \n current process ( pshared is zero) or is to be shared between several \n processes ( pshared is not zero). LinuxThreads currently does not \n support process-shared semaphores, thus sem_init always returns with \n error ENOSYS if pshared is not zero.</p>\n</blockquote>\n\n<p>As sem_open() creates named semaphores, it always tries to share them between processes.</p>\n\n<p>To support sharing anonymous semaphores between processes with sem_init() on Slackware 10</p>\n\n<ul>\n<li>upgrade libpthread and (possibly) librt</li>\n<li>upgrade the kernel</li>\n</ul>\n\n<p>Additionally, to support sharing named semaphores with sem_open()</p>\n\n<ul>\n<li><p>add a line to <code>/etc/fstab</code> to mount <code>/dev/shm</code> as a tmpfs</p>\n\n<p>tmpfs /dev/shm tmpfs defaults 0 0</p></li>\n<li><p>run <code>mount /dev/shm</code> or reboot </p></li>\n</ul>\n"
},
{
"answer_id": 272587,
"author": "bog",
"author_id": 20909,
"author_profile": "https://Stackoverflow.com/users/20909",
"pm_score": 1,
"selected": false,
"text": "<p>The \"process shared sema4s don't work\" hypothesis makes some sense to me. Not that it helps you, but if you have time and inclination you might want to try the following, to see whether the \"process-shared\" aspect is what is failing:</p>\n\n<ol>\n<li><p>create a semaphore using sem_init in unshared memory (for threads). If it works then sema4s work within the process.</p></li>\n<li><p>repeat experiment in shared memory. This should tell you if they work between processes. Note that you may need to actually try to USE the sema4 to see whether it works between processes.</p></li>\n</ol>\n"
},
{
"answer_id": 272650,
"author": "Kieran Tully",
"author_id": 18023,
"author_profile": "https://Stackoverflow.com/users/18023",
"pm_score": 0,
"selected": false,
"text": "<p>Another way to share a semaphore across processes is to use SystemV semaphores. </p>\n\n<p>These do work even where shared POSIX semaphores don't (at least on the systems described above.). </p>\n\n<p>See <a href=\"http://www.linuxdevcenter.com/pub/a/linux/2007/05/24/semaphores-in-linux.html\" rel=\"nofollow noreferrer\">http://www.linuxdevcenter.com/pub/a/linux/2007/05/24/semaphores-in-linux.html</a> for examples of the two types of semaphore use.</p>\n"
},
{
"answer_id": 2863471,
"author": "Giridhara",
"author_id": 344795,
"author_profile": "https://Stackoverflow.com/users/344795",
"pm_score": 0,
"selected": false,
"text": "<p>I was working with <a href=\"https://en.wikipedia.org/wiki/POSIX\" rel=\"nofollow noreferrer\">POSIX</a> message queues, and I have got the same error, mq_open was failed with errono 38 (ENOSYS).</p>\n<p>The workaround is to rebuild the kernel with POSIX MESSAGE QUEUE enabled in the kernel configuration.</p>\n<p>This will build the kernel with POSIX message queue support and it worked for me.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18023/"
] |
I have two Slackware Linux systems on which the POSIX semaphore `sem_open()` call fails with errno set to 38. Sample code to reproduce below (the code works fine on CentOS / RedHat).
Are there any kernel or system configuration options that could cause this? Other suggestions?
Systems with issue are Slackware 10.1.0 kernel 2.6.11 /lib/librt-2.3.4.so /lib/libpthread-0.10.so, but the same code works on the much older RedHat 9 kernel 2.4.20 /lib/librt-2.3.2.so /lib/tls/libpthread-0.29.so. (and also works on CentOS 5 kernel 2.6.18 /lib/librt-2.5.so /lib/i686/nosegneg/libpthread-2.5.so).
`man sem_open` suggests this errno means `sem_open()` is not supported by system.
```
#define ENOSYS 38 /* Function not implemented */
```
The `sem_open()` userspace is in `librt` which we link against dynamically and `librt` is present on the affected systems.
The affected system claims to support POSIX semaphores: `_POSIX_SEMAPHORES` is true and `sysconf(_SC_SEMAPHORES)` confirms this.
Thanks,
Kieran
Edit 1: I've added more detail on the software versions in use and removed some irrelevant comments.
Edit 2: /dev/shm is mounted on the good systems and not mounted on the bad systems. Mounting it did not change the behaviour on the affected systems. I think /dev/shm is necessary too but sem\_open() is failing before that, and strace supports this.
```
# /* Quick'n'dirty test program to illustrate sem_open failure
#Run this file to auto-build test and run as a.out
# Build
gcc $0 -lrt
if [ $? -ne 0 ] ; then exit ; fi
# Run
$( dirname $0)/a.out
exit
*/
#include <stdio.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
#include <semaphore.h>
int main(int argc, char *argv[]) {
const char *SEM_NAME = "SHRMEM_SCXL"; /* name of mutex */
sem_t *mutex = SEM_FAILED; /* ptr to mutex */
#ifdef _POSIX_SEMAPHORES
printf("_POSIX_SEMAPHORES %ld\n", _POSIX_SEMAPHORES);
#else
puts("Undefined");
#endif
printf("sysconf %s\n", sysconf(_SC_SEMAPHORES) ? "Yes" : "No" );
mutex = sem_open(SEM_NAME, O_CREAT, 0666, 1);
if (mutex == SEM_FAILED) printf("Failed %d\n", errno);
else {
puts("Success - pause while you check /dev/shm ");
sleep(5);
sem_close(mutex);
sem_unlink(SEM_NAME);
}
}
```
|
Is /dev/shm mounted? Older versions of slackware may not have mounted this filesystem at boot. From /etc/fstab:
```
tmpfs /dev/shm tmpfs defaults 0 0
```
Edit: That is probably not the problem after all. I think you may just need to upgrade your kernel or maybe even librt.
Edit2: I think that for slackware 11, which I think you are using, you'll need a kernel newer than 2.6.13 to use the NPTL threading libraries (libs in /lib/tls) which appear to be required for the sem\_open to work.
Edit3: I managed to get it to work with a slackware 11 box I have by a) mounting /dev/shm and b) setting the environment variable `LD_ASSUME_KERNEL` to 2.6.13 (any kernel version > 2.6.12 will work). That seems to work even though the kernel is 2.6.11.11, but other things like threads might not.
|
270,125 |
<p>I have to pass parameters between two rails apps. In one side (sender) I have an array of hashes. I have a code like the following to send the data:</p>
<pre><code> http = Net::HTTP.new('localhost', '3030')
result = http.post('/processar_lotes', my_array_of_hashes)
</code></pre>
<p>Some questions</p>
<ul>
<li>Is there any (kind of) serialize or something like this that I can pass to the other app?</li>
<li>At the other side, how can I de-serialize the information?</li>
<li>Is there a limit to the size of what I pass as a parameter?</li>
</ul>
|
[
{
"answer_id": 270154,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 2,
"selected": true,
"text": "<p>Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark. Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).</p>\n\n<p>Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit. Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.</p>\n\n<p>But since it's a small amount of data, I would say it won't matter.</p>\n"
},
{
"answer_id": 270299,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 2,
"selected": false,
"text": "<p>With 1kb of data, you are better off using standard file IO. Most likely, you could serialize the entire object tree to disk and dismply deserialize when you startup again. If you wanted to get fancy, you could use JAXB to serialize to XML instead of binary files.</p>\n\n<p>As much as I love to fit every problem to the database solution, I don't think that's very practical here. Unless you have some special need of database specific capabilities, you are introducting a lot of overhead, complexity, maintenance problems by using a database.</p>\n\n<p>The only areas where you might really want to use the database is if you have a lot of small objects/rows and you frequently perform sorts and filters on the data. But even then, you could probably keep a dozen in-memory ordered lists and get better performance with less resources and without the headache of a database.</p>\n\n<p>If you really think you need a database in this scenario, consider HSQL. I don't consider it a real database, but it's a in-memory database that can persist to a file. Low overhead, low complexity, and relatively few points of failure. Plus, if you need to edit the persisted data, you can do so with a text editor. Can't say that about Derby.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
I have to pass parameters between two rails apps. In one side (sender) I have an array of hashes. I have a code like the following to send the data:
```
http = Net::HTTP.new('localhost', '3030')
result = http.post('/processar_lotes', my_array_of_hashes)
```
Some questions
* Is there any (kind of) serialize or something like this that I can pass to the other app?
* At the other side, how can I de-serialize the information?
* Is there a limit to the size of what I pass as a parameter?
|
Considering that these objects can vary per file size, and your computer's specs (bus speed, HD speed) affect this, the only way to be sure is to write your own benchmark. Just create a simple for loop, count from 1 to 1000, and read the file inside the loop over and over (but do not create and destroy the objects inside the loop, just focus on the reading part).
Of course this whole exercise reeks of pre-optimization, which can lead to bad coding habit. Just write your code in the most readable, simple fashion, and if there is a speed problem, refactor as needed.
But since it's a small amount of data, I would say it won't matter.
|
270,148 |
<p>I have these 3 tables + data:</p>
<p><strong>items</strong>: itemId, itemName
<br />data: 1, my item one</p>
<p><strong>categories</strong>: catId, catName
<br />data: 1, my cat one. 2, my cat two</p>
<p><strong>map</strong>: mapId, itemId, catId</p>
<p>When you include item "my item one" in category "my cat one", you insert [1, 1, 1] into the map. When you add "my item one" to "my cat two", you insert [2, 1, 2] into the map. Now let's say we change our mind and only want the item in "my cat two". This means we need to know what categories the item is no longer in and delete the associations from the map. What's the most efficient sequence of steps to take to do so? (I'm looking for a solution that will scale beyond this trivial example.)</p>
|
[
{
"answer_id": 270173,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>Assuming you've already got the category ID for \"my cat two\" and the item ID for \"my item 1\":</p>\n\n<pre><code>DELETE FROM MAP WHERE ItemID = @MyItem1Id\n AND CatID <> @MyCat2Id\n</code></pre>\n\n<p>If you have a set of categories you want to keep the item in, you could either:</p>\n\n<ol>\n<li>Delete everything from the map for that item and then re-add the set</li>\n<li>Use a query like the above but with \"AND CatID NOT IN [ ... ]\"</li>\n</ol>\n"
},
{
"answer_id": 270180,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>If you decide that an item should only be in the new category, the following should work:</p>\n\n<pre><code>DELETE\n M\nFROM\n Map M\nWHERE\n M.itemid = @item_id AND\n M.catid <> @new_cat_id\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] |
I have these 3 tables + data:
**items**: itemId, itemName
data: 1, my item one
**categories**: catId, catName
data: 1, my cat one. 2, my cat two
**map**: mapId, itemId, catId
When you include item "my item one" in category "my cat one", you insert [1, 1, 1] into the map. When you add "my item one" to "my cat two", you insert [2, 1, 2] into the map. Now let's say we change our mind and only want the item in "my cat two". This means we need to know what categories the item is no longer in and delete the associations from the map. What's the most efficient sequence of steps to take to do so? (I'm looking for a solution that will scale beyond this trivial example.)
|
Assuming you've already got the category ID for "my cat two" and the item ID for "my item 1":
```
DELETE FROM MAP WHERE ItemID = @MyItem1Id
AND CatID <> @MyCat2Id
```
If you have a set of categories you want to keep the item in, you could either:
1. Delete everything from the map for that item and then re-add the set
2. Use a query like the above but with "AND CatID NOT IN [ ... ]"
|
270,177 |
<p>I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.</p>
<p>I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?</p>
<p>Here's a snippet of code:</p>
<p>HTML</p>
<pre><code><a href="javascript:;">
<img id="img1" src="image1.gif" />
<img id="img2" src="image2.gif" style="display:none;" />
<img id="img3" src="image3.gif" style="display:none;" />
</a>
</code></pre>
<p>JS</p>
<pre><code>var numImages = 3;
var currentImage = 1;
imageInterval = window.setInterval("changeImage();", 2000);
function changeImage()
{
$("#img" + currentImage).fadeOut("slow", function() {
if (currentImage >= numImages)
{
currentImage = 0;
}
$("#img" + (currentImage + 1) ).fadeIn("slow", function() {
currentImage++;
});
});
}
</code></pre>
|
[
{
"answer_id": 270249,
"author": "RichH",
"author_id": 16779,
"author_profile": "https://Stackoverflow.com/users/16779",
"pm_score": 1,
"selected": false,
"text": "<p>You have id=\"img2\" twice.</p>\n\n<p>Can you not simpify - calculate the current and next id first. Then do your $().fadeOut() and on the next line $().fadeIn() and avoid all of the function complexity.</p>\n"
},
{
"answer_id": 270259,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 2,
"selected": false,
"text": "<p>Just off the top of my head ... why are you doing the currentImage bookkeeping in the callback functions? It seems to me this is easier, and might even have something to do with your problem:</p>\n\n<pre><code>function changeImage()\n{\n $(\"#img\" + currentImage).fadeOut(\"slow\");\n currentImage = (currentImage >= numImages) ? 1 : currentImage + 1;\n $(\"#img\" + currentImage).fadeIn(\"slow\");\n}\n</code></pre>\n"
},
{
"answer_id": 270289,
"author": "Steve Perks",
"author_id": 16124,
"author_profile": "https://Stackoverflow.com/users/16124",
"pm_score": 1,
"selected": false,
"text": "<p>Your problem is that if you click on img2 before it's finished fading in, currentImage is still thinking you're looking after the transition between img1 and img2, but in reality img2 is now live and you're waiting on img3.</p>\n\n<p>I think that Jim's solution should see you OK.</p>\n\n<p>As a freebee, consider adding this too to allow you to add more images without having to edit the script:</p>\n\n<pre><code>numImages = $(\"a > img\").size();\n</code></pre>\n"
},
{
"answer_id": 271342,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 3,
"selected": false,
"text": "<p>Have you thought about using the <a href=\"http://malsup.com/jquery/cycle/\" rel=\"nofollow noreferrer\">Cycle Plugin</a>? It sounds like this does exactly what you're trying to do, and it offers a lot of flexibility. I've used this plugin myself with great results. Highly recommended.</p>\n"
},
{
"answer_id": 2990974,
"author": "tom",
"author_id": 360577,
"author_profile": "https://Stackoverflow.com/users/360577",
"pm_score": 1,
"selected": false,
"text": "<p>also</p>\n\n<pre><code>setInterval (function () {\n $(\"img:eq(0)\").fadeOut (\"slow\").next (\"img\").fadeIn (\"slow\");\n}, 2000);\n</code></pre>\n"
},
{
"answer_id": 6354699,
"author": "Chris",
"author_id": 632174,
"author_profile": "https://Stackoverflow.com/users/632174",
"pm_score": 0,
"selected": false,
"text": "<p>I'm having a similar problem using a function I based off of <a href=\"http://snook.ca/archives/javascript/simplest-jquery-slideshow\" rel=\"nofollow\">snook.ca's simplest jquery slideshow</a>. (see my comment @tom) Although mine happens whether I'm clicking or scrolling or not!</p>\n\n<p>It seems as though after the first run through the cycle the timings get all messed up and start half fading in or out and just jumping in with no fade! I was watching the html panel in firebug and found that the css display attribute wasn't getting set from 'block' back to 'none' properly, eventually resulting in all of the images having <code>display:block</code> set on them reglardless of their supposed fade state.</p>\n\n<p>I did wonder if this was a timing issue with the fade speed getting messed up with the setInterval delay causing a mixed order of triggering. If this is the case then I don't know how to fix it.</p>\n\n<p>But having seen the css behaviour I now wonder if it's an underlying problem in the way that jQuery implements it's 'fadeIn' and 'fadeOut' functions??!!</p>\n"
},
{
"answer_id": 59708994,
"author": "Yamil Duba",
"author_id": 8658119,
"author_profile": "https://Stackoverflow.com/users/8658119",
"pm_score": 0,
"selected": false,
"text": "<p>I gave your code a little workaround and came up with this working piece of code:</p>\n\n<pre><code>$(document).ready(() => {\n\nlet numImages = 4;\nlet currentImage = 1;\n\nfunction changeImage() {\n $('#img-' + currentImage).fadeOut(1000, function() {\n if (currentImage === numImages) {\n currentImage = 0;\n }\n currentImage++;\n $('#img-' + currentImage).fadeIn(1000, function() {\n changeImage();\n });\n })\n}\n\nchangeImage();\n\n})\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1396/"
] |
I have a bunch of images that need to rotate in and out one at a time every 2 seconds with fancy JQuery fadeIn and fadeOut. I have all the images in the HTML to pre-load them and a setInterval timer that fades the current image out, then fades the next image in. Problem is that sometimes when you are clicking or scrolling during the fade in/out process, the JS gets interrupted and the current image never disappears and the next one fades in giving you two images.
I get the feeling it has something to do with setInterval not running properly every 2 seconds, but are there any better ways to accomplish what I need?
Here's a snippet of code:
HTML
```
<a href="javascript:;">
<img id="img1" src="image1.gif" />
<img id="img2" src="image2.gif" style="display:none;" />
<img id="img3" src="image3.gif" style="display:none;" />
</a>
```
JS
```
var numImages = 3;
var currentImage = 1;
imageInterval = window.setInterval("changeImage();", 2000);
function changeImage()
{
$("#img" + currentImage).fadeOut("slow", function() {
if (currentImage >= numImages)
{
currentImage = 0;
}
$("#img" + (currentImage + 1) ).fadeIn("slow", function() {
currentImage++;
});
});
}
```
|
Have you thought about using the [Cycle Plugin](http://malsup.com/jquery/cycle/)? It sounds like this does exactly what you're trying to do, and it offers a lot of flexibility. I've used this plugin myself with great results. Highly recommended.
|
270,187 |
<p>Is it possible to create an attribute that can be initialized with a variable number of arguments?</p>
<p>For example:</p>
<pre><code>[MyCustomAttribute(new int[3,4,5])] // this doesn't work
public MyClass ...
</code></pre>
|
[
{
"answer_id": 270223,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, but you need to initialize the array that you are passing in. Here is an example from a row test in our unit tests that tests a variable number of command line options;</p>\n\n<pre><code>[Row( new[] { \"-l\", \"/port:13102\", \"-lfsw\" } )]\npublic void MyTest( string[] args ) { //... }\n</code></pre>\n"
},
{
"answer_id": 270224,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>That should be okay. From the spec, section 17.2:</p>\n\n<p>An expression E is an <em>attribute-argument-expression</em> if all of the following statements are true:</p>\n\n<ul>\n<li>The type of E is an attribute parameter type (§17.1.3).</li>\n<li>At compile-time, the value of E can be resolved to one of the following:\n\n<ul>\n<li>A constant value.</li>\n<li>A System.Type object.</li>\n<li>A one-dimensional array of <em>attribute-argument-expressions</em>.</li>\n</ul></li>\n</ul>\n\n<p>Here's an example:</p>\n\n<pre><code>using System;\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]\npublic class SampleAttribute : Attribute\n{\n public SampleAttribute(int[] foo)\n {\n }\n}\n\n[Sample(new int[]{1, 3, 5})]\nclass Test\n{\n}\n</code></pre>\n"
},
{
"answer_id": 270227,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "<p>Try declaring the constructor like this:</p>\n\n<pre><code>public class MyCustomAttribute : Attribute\n{\n public MyCustomAttribute(params int[] t)\n {\n }\n}\n</code></pre>\n\n<p>Then you can use it like:</p>\n\n<p><code>[MyCustomAttribute(3, 4, 5)]</code></p>\n"
},
{
"answer_id": 270228,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 2,
"selected": false,
"text": "<p>You can do that. Another example could be:</p>\n\n<pre><code>class MyAttribute: Attribute\n{\n public MyAttribute(params object[] args)\n {\n }\n}\n\n[MyAttribute(\"hello\", 2, 3.14f)]\nclass Program\n{\n static void Main(string[] args)\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 270231,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 9,
"selected": true,
"text": "<p>Attributes will take an array. Though if you control the attribute, you can also use <code>params</code> instead (which is nicer to consumers, IMO):</p>\n\n<pre><code>class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(params int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(3, 4, 5)]\nclass MyClass { }\n</code></pre>\n\n<p>Your syntax for array creation just happens to be off:</p>\n\n<pre><code>class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(new int[] { 3, 4, 5 })]\nclass MyClass { }\n</code></pre>\n"
},
{
"answer_id": 270447,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>You can do it, but it isn't CLS compliant:</p>\n\n<pre><code>[assembly: CLSCompliant(true)]\n\nclass Foo : Attribute\n{\n public Foo(string[] vals) { }\n}\n[Foo(new string[] {\"abc\",\"def\"})]\nstatic void Bar() {}\n</code></pre>\n\n<p>Shows:</p>\n\n<pre><code>Warning 1 Arrays as attribute arguments is not CLS-compliant\n</code></pre>\n\n<p>For regular reflection usage, it may be preferable to have multiple attributes, i.e.</p>\n\n<pre><code>[Foo(\"abc\"), Foo(\"def\")]\n</code></pre>\n\n<p>However, this won't work with <code>TypeDescriptor</code>/<code>PropertyDescriptor</code>, where only a single instance of any attribute is supported (either the first or last wins, I can't recall which).</p>\n"
},
{
"answer_id": 36087202,
"author": "TBrink",
"author_id": 5335295,
"author_profile": "https://Stackoverflow.com/users/5335295",
"pm_score": 2,
"selected": false,
"text": "<p>To piggy back on Marc Gravell's answer, yes you can define an attribute with array parameters but applying an attribute with an array parameter is not CLS-compliant. However just defining an attribute with an array property is perfectly CLS-compliant.</p>\n\n<p>What made me realize this was that Json.NET, a CLS-compliant library, has an attribute class JsonPropertyAttribute with a property named ItemConverterParameters that's an array of objects.</p>\n"
},
{
"answer_id": 72259423,
"author": "Michal Pokluda",
"author_id": 1102229,
"author_profile": "https://Stackoverflow.com/users/1102229",
"pm_score": 0,
"selected": false,
"text": "<p>I use maybe a bit stupid workaround using this trick:</p>\n<pre><code>public class CLParam : Attribute\n{\n /// <summary>\n /// Command line parameter\n /// </summary>\n public string Names { get; set; }\n}\n</code></pre>\n<p>and then splitting the Names into string[]:</p>\n<pre><code>var names = loadAtt.Names.Split(',');\n</code></pre>\n<p>I allows me to use attribute like this:</p>\n<pre><code>class CLContext\n{\n [CLParam(Names = "selectscene,ss")]\n public List<string> SelectScene { get; set; }\n</code></pre>\n<p>But of course for ints you would need to parse texts, so maybe a bit slow...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Is it possible to create an attribute that can be initialized with a variable number of arguments?
For example:
```
[MyCustomAttribute(new int[3,4,5])] // this doesn't work
public MyClass ...
```
|
Attributes will take an array. Though if you control the attribute, you can also use `params` instead (which is nicer to consumers, IMO):
```
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(params int[] values) {
this.Values = values;
}
}
[MyCustomAttribute(3, 4, 5)]
class MyClass { }
```
Your syntax for array creation just happens to be off:
```
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(int[] values) {
this.Values = values;
}
}
[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }
```
|
270,190 |
<p>I have 4 databases with similar schema's, and I'm trying to create a query to return just the table, column pairs that exist ONLY in database 1 and do not exist in database 2, 3, or 4.</p>
<p>Currently I can return the symmetric difference between database 1 and 2 via the following query...</p>
<pre><code>select table_name, column_name from (
select table_name, column_name from [Database1].information_schema.columns
union all
select table_name, column_name from [Database2].information_schema.columns) as tmp
group by table_name, column_name having count(*) = 1
</code></pre>
<p>However, in trying to isolate just those columns in database 1, and doing the same across all 4 databases, things are getting complicated. What is the cleanest solution for this query?</p>
|
[
{
"answer_id": 270223,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, but you need to initialize the array that you are passing in. Here is an example from a row test in our unit tests that tests a variable number of command line options;</p>\n\n<pre><code>[Row( new[] { \"-l\", \"/port:13102\", \"-lfsw\" } )]\npublic void MyTest( string[] args ) { //... }\n</code></pre>\n"
},
{
"answer_id": 270224,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>That should be okay. From the spec, section 17.2:</p>\n\n<p>An expression E is an <em>attribute-argument-expression</em> if all of the following statements are true:</p>\n\n<ul>\n<li>The type of E is an attribute parameter type (§17.1.3).</li>\n<li>At compile-time, the value of E can be resolved to one of the following:\n\n<ul>\n<li>A constant value.</li>\n<li>A System.Type object.</li>\n<li>A one-dimensional array of <em>attribute-argument-expressions</em>.</li>\n</ul></li>\n</ul>\n\n<p>Here's an example:</p>\n\n<pre><code>using System;\n\n[AttributeUsage(AttributeTargets.All, AllowMultiple = false, Inherited = true)]\npublic class SampleAttribute : Attribute\n{\n public SampleAttribute(int[] foo)\n {\n }\n}\n\n[Sample(new int[]{1, 3, 5})]\nclass Test\n{\n}\n</code></pre>\n"
},
{
"answer_id": 270227,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 5,
"selected": false,
"text": "<p>Try declaring the constructor like this:</p>\n\n<pre><code>public class MyCustomAttribute : Attribute\n{\n public MyCustomAttribute(params int[] t)\n {\n }\n}\n</code></pre>\n\n<p>Then you can use it like:</p>\n\n<p><code>[MyCustomAttribute(3, 4, 5)]</code></p>\n"
},
{
"answer_id": 270228,
"author": "Alan",
"author_id": 31223,
"author_profile": "https://Stackoverflow.com/users/31223",
"pm_score": 2,
"selected": false,
"text": "<p>You can do that. Another example could be:</p>\n\n<pre><code>class MyAttribute: Attribute\n{\n public MyAttribute(params object[] args)\n {\n }\n}\n\n[MyAttribute(\"hello\", 2, 3.14f)]\nclass Program\n{\n static void Main(string[] args)\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 270231,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 9,
"selected": true,
"text": "<p>Attributes will take an array. Though if you control the attribute, you can also use <code>params</code> instead (which is nicer to consumers, IMO):</p>\n\n<pre><code>class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(params int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(3, 4, 5)]\nclass MyClass { }\n</code></pre>\n\n<p>Your syntax for array creation just happens to be off:</p>\n\n<pre><code>class MyCustomAttribute : Attribute {\n public int[] Values { get; set; }\n\n public MyCustomAttribute(int[] values) {\n this.Values = values;\n }\n}\n\n[MyCustomAttribute(new int[] { 3, 4, 5 })]\nclass MyClass { }\n</code></pre>\n"
},
{
"answer_id": 270447,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>You can do it, but it isn't CLS compliant:</p>\n\n<pre><code>[assembly: CLSCompliant(true)]\n\nclass Foo : Attribute\n{\n public Foo(string[] vals) { }\n}\n[Foo(new string[] {\"abc\",\"def\"})]\nstatic void Bar() {}\n</code></pre>\n\n<p>Shows:</p>\n\n<pre><code>Warning 1 Arrays as attribute arguments is not CLS-compliant\n</code></pre>\n\n<p>For regular reflection usage, it may be preferable to have multiple attributes, i.e.</p>\n\n<pre><code>[Foo(\"abc\"), Foo(\"def\")]\n</code></pre>\n\n<p>However, this won't work with <code>TypeDescriptor</code>/<code>PropertyDescriptor</code>, where only a single instance of any attribute is supported (either the first or last wins, I can't recall which).</p>\n"
},
{
"answer_id": 36087202,
"author": "TBrink",
"author_id": 5335295,
"author_profile": "https://Stackoverflow.com/users/5335295",
"pm_score": 2,
"selected": false,
"text": "<p>To piggy back on Marc Gravell's answer, yes you can define an attribute with array parameters but applying an attribute with an array parameter is not CLS-compliant. However just defining an attribute with an array property is perfectly CLS-compliant.</p>\n\n<p>What made me realize this was that Json.NET, a CLS-compliant library, has an attribute class JsonPropertyAttribute with a property named ItemConverterParameters that's an array of objects.</p>\n"
},
{
"answer_id": 72259423,
"author": "Michal Pokluda",
"author_id": 1102229,
"author_profile": "https://Stackoverflow.com/users/1102229",
"pm_score": 0,
"selected": false,
"text": "<p>I use maybe a bit stupid workaround using this trick:</p>\n<pre><code>public class CLParam : Attribute\n{\n /// <summary>\n /// Command line parameter\n /// </summary>\n public string Names { get; set; }\n}\n</code></pre>\n<p>and then splitting the Names into string[]:</p>\n<pre><code>var names = loadAtt.Names.Split(',');\n</code></pre>\n<p>I allows me to use attribute like this:</p>\n<pre><code>class CLContext\n{\n [CLParam(Names = "selectscene,ss")]\n public List<string> SelectScene { get; set; }\n</code></pre>\n<p>But of course for ints you would need to parse texts, so maybe a bit slow...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270190",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7287/"
] |
I have 4 databases with similar schema's, and I'm trying to create a query to return just the table, column pairs that exist ONLY in database 1 and do not exist in database 2, 3, or 4.
Currently I can return the symmetric difference between database 1 and 2 via the following query...
```
select table_name, column_name from (
select table_name, column_name from [Database1].information_schema.columns
union all
select table_name, column_name from [Database2].information_schema.columns) as tmp
group by table_name, column_name having count(*) = 1
```
However, in trying to isolate just those columns in database 1, and doing the same across all 4 databases, things are getting complicated. What is the cleanest solution for this query?
|
Attributes will take an array. Though if you control the attribute, you can also use `params` instead (which is nicer to consumers, IMO):
```
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(params int[] values) {
this.Values = values;
}
}
[MyCustomAttribute(3, 4, 5)]
class MyClass { }
```
Your syntax for array creation just happens to be off:
```
class MyCustomAttribute : Attribute {
public int[] Values { get; set; }
public MyCustomAttribute(int[] values) {
this.Values = values;
}
}
[MyCustomAttribute(new int[] { 3, 4, 5 })]
class MyClass { }
```
|
270,230 |
<p>What is the difference between having</p>
<pre class="lang-java prettyprint-override"><code><%# Eval("State") %>
</code></pre>
<p>in your <code>aspx</code> page, versus having</p>
<pre class="lang-java prettyprint-override"><code><%# DataBinder.Eval(Container.DataItem, "State") %>
</code></pre>
<p>in your <code>aspx</code> page?</p>
|
[
{
"answer_id": 270242,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": false,
"text": "<p>There is no difference. The \"Eval\" method is just a shortcut for the DataBinder.Eval(Container.DataItem, \"blah\") method.</p>\n"
},
{
"answer_id": 270245,
"author": "Josh Mein",
"author_id": 2486,
"author_profile": "https://Stackoverflow.com/users/2486",
"pm_score": 2,
"selected": false,
"text": "<p>the Eval method is just a shortcut of the latter</p>\n"
},
{
"answer_id": 270252,
"author": "Jeromy Irvine",
"author_id": 8223,
"author_profile": "https://Stackoverflow.com/users/8223",
"pm_score": 6,
"selected": true,
"text": "<p><code>Eval("State")</code> is a simplified form of the <code>DataBinder.Eval(Container.DataItem, "State")</code> syntax. It only works inside of data-bound template controls.</p>\n<p>For more info, see <a href=\"http://msdn.microsoft.com/en-us/library/ms178366.aspx\" rel=\"nofollow noreferrer\">the MSDN documentation</a>.</p>\n"
},
{
"answer_id": 13805517,
"author": "GLP",
"author_id": 968273,
"author_profile": "https://Stackoverflow.com/users/968273",
"pm_score": -1,
"selected": false,
"text": "<p>I have seen following code </p>\n\n<pre><code><%# (DataBinder.Eval(Container.DataItem, \"ApplicationId\").ToString() == \"-1\" ? \"N/A\" : Eval(\"ApplicationId\").ToString()) %>\n</code></pre>\n\n<p>So I guess they slightly different.</p>\n"
},
{
"answer_id": 14624021,
"author": "Raman Sharma",
"author_id": 2028752,
"author_profile": "https://Stackoverflow.com/users/2028752",
"pm_score": 3,
"selected": false,
"text": "<p>There are a lot of differences between <code><%# Eval %></code> and <code><%# DataBinder.Eval %></code> under the covers, even though <a href=\"https://msdn.microsoft.com/en-us/library/ms178366.aspx#Anchor_1\" rel=\"nofollow\">the documentation</a> states that using <code>Eval</code> (<code>TemplateControl.Eval</code> to be exact) actually calls <code>DataBinder.Eval</code> and that their task is to do exactly the same job.</p>\n\n<p>That is correct, but using just <code>Eval</code> means that ASP.NET itself resolves the object that is databound. It does this internally with a stack where items are added when <code>Control.DataBind()</code> is called. The trick is that this happens only if the <code>Page</code> property of the control is non-<code>null</code> at that point.</p>\n\n<p>If the <code>Page</code>-managed stack isn't up to date when you get to the point that <code>DataItem</code> needs to be resolved, the <code>Page.GetDataItem()</code> method will give an exception with a message like</p>\n\n<blockquote>\n <p>Databinding methods such as <code>Eval()</code>, <code>XPath()</code>, and <code>Bind()</code> can only be used in the context of a databound control.</p>\n</blockquote>\n\n<p><code>DataBinder.Eval</code> still works in those circumstances because you provide it the target object manually, so ASP.NET doesn't need to do any resolving on its own.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33690/"
] |
What is the difference between having
```java
<%# Eval("State") %>
```
in your `aspx` page, versus having
```java
<%# DataBinder.Eval(Container.DataItem, "State") %>
```
in your `aspx` page?
|
`Eval("State")` is a simplified form of the `DataBinder.Eval(Container.DataItem, "State")` syntax. It only works inside of data-bound template controls.
For more info, see [the MSDN documentation](http://msdn.microsoft.com/en-us/library/ms178366.aspx).
|
270,260 |
<p>Let's imagine I got this:</p>
<p>index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php</p>
<pre><code><form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
</code></pre>
<p>Script.php:</p>
<p>Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.</p>
<p>Is there a way to do this?</p>
|
[
{
"answer_id": 270279,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 3,
"selected": true,
"text": "<p>i may be missing something in your question, but the <code>$_POST</code> variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:</p>\n\n<pre><code>print_r($_POST);\n\n// contains:\n\narray\n(\n [1] => 1\n [24] => 2233\n [55] => 231321\n)\n\n// example access:\n\nforeach($_POST as $name => $value) {\n print \"Name: {$name} Value: {$value} <br />\";\n}\n</code></pre>\n"
},
{
"answer_id": 270281,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 0,
"selected": false,
"text": "<p>It sounds like you're using a class or framework to generate your forms, you need to read the documentation for the framework to see if/where it's collecting this data.</p>\n"
},
{
"answer_id": 270285,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 1,
"selected": false,
"text": "<p>Use an array_keys on the $_POST variable in script.php to pull out the names you created and use those to get the values.</p>\n\n<pre><code>$keys = array_keys( $_POST );\nforeach( $keys as $key ) {\n echo \"Name=\" . $key . \" Value=\" . $_POST[$key];\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270260",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21209/"
] |
Let's imagine I got this:
index.php generates form with unpredictable number of inputs with certain IDs/Names and different values that can be edited by user and saved by script.php
```
<form action="script.php" method="post">
<input id="1" name="1" type="text" value="1"/>
<input id="24" name="24" type="text" value="2233"/>
<input id="55" name="55" type="text" value="231321"/>
</form>
```
Script.php:
Here I need to get something like array of all inputs that were generated by index.php and save every value that corresponds to its id/name.
Is there a way to do this?
|
i may be missing something in your question, but the `$_POST` variable will contain all the name => value pairs you're asking for. for example, in your above HTML snippet:
```
print_r($_POST);
// contains:
array
(
[1] => 1
[24] => 2233
[55] => 231321
)
// example access:
foreach($_POST as $name => $value) {
print "Name: {$name} Value: {$value} <br />";
}
```
|
270,268 |
<p>I have a class which has a method that is receiving an object as a parameter.
This method is invoked via RMI.</p>
<pre><code>public RMIClass extends Serializable {
public RMIMethod(MyFile file){
// do stuff
}
}
</code></pre>
<p>MyFile has a property called "body", which is a byte array. </p>
<pre><code>public final class MyFile implements Serializable {
private byte[] body = new byte[0];
//....
public byte[] getBody() {
return body;
}
//....
}
</code></pre>
<p>This property holds the gzipped data of a file that was parsed by another application.</p>
<p>I need to decompress this byte array before performing further actions with it. </p>
<p>All the examples I see of decompressing gzipped data assume that I want to write it to the disk and create a physical file, which I do not.</p>
<p>How do I do this?</p>
<p>Thanks in advance.</p>
|
[
{
"answer_id": 270278,
"author": "Geo",
"author_id": 31610,
"author_profile": "https://Stackoverflow.com/users/31610",
"pm_score": 0,
"selected": false,
"text": "<p>Why don't you create your own class that extends <strong>OutputStream</strong> or , whatever is the archive writing to ?</p>\n"
},
{
"answer_id": 270286,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>Look at those samples, and wherever they're using FileOutputStream, use ByteArrayOutputStream instead. Wherever they're using FileInputStream, use ByteArrayInputStream instead. The rest should be simple.</p>\n"
},
{
"answer_id": 270290,
"author": "basszero",
"author_id": 287,
"author_profile": "https://Stackoverflow.com/users/287",
"pm_score": 3,
"selected": false,
"text": "<p>Wrap your byte array with a <a href=\"http://java.sun.com/javase/6/docs/api/java/io/ByteArrayInputStream.html\" rel=\"noreferrer\">ByteArrayInputStream</a> and feed it into a <a href=\"http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html\" rel=\"noreferrer\">GZipInputStream</a></p>\n"
},
{
"answer_id": 56170655,
"author": "Judd",
"author_id": 843116,
"author_profile": "https://Stackoverflow.com/users/843116",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to write to a ByteBuffer you can do this.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>private static void uncompress(final byte[] input, final ByteBuffer output) throws IOException\n {\n final GZIPInputStream inputGzipStream = new GZIPInputStream(new ByteArrayInputStream(input));\n Channels.newChannel(inputGzipStream).read(output);\n }\n</code></pre>\n"
},
{
"answer_id": 70748230,
"author": "Tony BenBrahim",
"author_id": 80075,
"author_profile": "https://Stackoverflow.com/users/80075",
"pm_score": 1,
"selected": false,
"text": "<p>JDK 9+</p>\n<pre><code> private byte[] gzipUncompress(byte[] compressedBytes) throws IOException {\n try (InputStream inputStream = new GZIPInputStream(new ByteArrayInputStream(compressedBytes))) {\n try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {\n inputStream.transferTo(outputStream);\n return outputStream.toByteArray();\n }\n }\n</code></pre>\n<p>}</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34380/"
] |
I have a class which has a method that is receiving an object as a parameter.
This method is invoked via RMI.
```
public RMIClass extends Serializable {
public RMIMethod(MyFile file){
// do stuff
}
}
```
MyFile has a property called "body", which is a byte array.
```
public final class MyFile implements Serializable {
private byte[] body = new byte[0];
//....
public byte[] getBody() {
return body;
}
//....
}
```
This property holds the gzipped data of a file that was parsed by another application.
I need to decompress this byte array before performing further actions with it.
All the examples I see of decompressing gzipped data assume that I want to write it to the disk and create a physical file, which I do not.
How do I do this?
Thanks in advance.
|
Wrap your byte array with a [ByteArrayInputStream](http://java.sun.com/javase/6/docs/api/java/io/ByteArrayInputStream.html) and feed it into a [GZipInputStream](http://java.sun.com/javase/6/docs/api/java/util/zip/GZIPInputStream.html)
|
270,287 |
<p>What is a good way to edit a Web.config file programmatically?</p>
<p>I looked into System.Xml but couldn't find any obvious answers.</p>
|
[
{
"answer_id": 270301,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.</p>\n"
},
{
"answer_id": 270316,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.</p>\n\n<p>I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.</p>\n\n<p>Saving the updated configuration file may cause the app to recycle depending on how it is built.</p>\n"
},
{
"answer_id": 270317,
"author": "Mike Marshall",
"author_id": 29798,
"author_profile": "https://Stackoverflow.com/users/29798",
"pm_score": 1,
"selected": false,
"text": "<p>Yes I agree with Josh. I have tried this before and I've had two negative effects:</p>\n\n<ol>\n<li>Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources</li>\n<li>If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways</li>\n</ol>\n"
},
{
"answer_id": 270318,
"author": "Frank Rosario",
"author_id": 10922,
"author_profile": "https://Stackoverflow.com/users/10922",
"pm_score": 2,
"selected": false,
"text": "<p>In theory; you could just generate a web config file programmatically and with some templating to make it easy.</p>\n\n<p>However, if you're trying to edit your web.config from within the site; it's <strong>highly</strong> recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.</p>\n\n<p>As Anders asked, what is it you're trying to do?</p>\n"
},
{
"answer_id": 270335,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.dotnetspider.com/resources/17562-Edit-Delete-Create-Encrypt-sections.aspx\" rel=\"noreferrer\">This fellow</a> shows sample code if you still want to do it after all the caveats:</p>\n\n<pre><code>protected void EditConfigButton(object sender, EventArgs e)\n{\n Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\");\n AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection(\"appSettings\");\n //Edit\n if (objAppsettings != null)\n {\n objAppsettings.Settings[\"test\"].Value = \"newvalueFromCode\";\n objConfig.Save();\n }\n}\n</code></pre>\n\n<p>One valid reason for editing a web.config is to encrypt it, which is what that article is about.</p>\n"
},
{
"answer_id": 307158,
"author": "spacemonkeys",
"author_id": 32336,
"author_profile": "https://Stackoverflow.com/users/32336",
"pm_score": 1,
"selected": false,
"text": "<p>Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved</p>\n\n<p>If its a value that is application specific, then it should be in an application specific config file</p>\n"
},
{
"answer_id": 3173565,
"author": "netbuild",
"author_id": 161464,
"author_profile": "https://Stackoverflow.com/users/161464",
"pm_score": 1,
"selected": false,
"text": "<p>Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.</p>\n\n<p>Try XML Webpad - <a href=\"http://xmlwebpad.codeplex.com/\" rel=\"nofollow noreferrer\">http://xmlwebpad.codeplex.com/</a></p>\n\n<p>Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4886/"
] |
What is a good way to edit a Web.config file programmatically?
I looked into System.Xml but couldn't find any obvious answers.
|
[This fellow](http://www.dotnetspider.com/resources/17562-Edit-Delete-Create-Encrypt-sections.aspx) shows sample code if you still want to do it after all the caveats:
```
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
```
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
|
270,288 |
<p>I'm currently optimizing the performance on my company's site; when it was taking 6-10 seconds to download 2MB+ of our homepage and assets (the site is mostly Flash with a lot of media, so it's not 2MB of HTML and viewstate). There are a lot of things that will need to be done to get this download size down; but one thing I definitely want to do is enable HTTP compression to compress our static content, specifically XML, CSS, and JS; I don't imagine compression will do much for the SWFs and JPGs.</p>
<p>I want to enable this on just our staging site so I can do some server testing and benchmarking. This means I'm going to have to do some Metabase editing, since IIS 6 doesn't allow you to set compression on an individual site via IIS manager. The problem with that is the Metabase is locked by IIS so I can't save; and even if I save the edits, I'm required to restart IIS for the changes to take affect; which will take down other live sites hosted on the same server. Is there anyway to enable compression for one site without restarting IIS? I don't mind restarting our staging site; I just don't want this work to take down other sites on the server.</p>
<p>Any assistance is greatly appreciated.</p>
|
[
{
"answer_id": 270301,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on what you are doing, the method is really a bit different in each situation. However the most robust method is to load it as an XmlDocument and modify it as needed via that method, but you MUST be careful to only modify it in the needed manner.</p>\n"
},
{
"answer_id": 270316,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the WebConfigurationManager to read specific configuration sections. This will return a ConfigurationSection object. You can use this to read/modify the ConfigurationElements in the section. Once you have updated them, you can Save the ConfigurationSection and it will update the file with your changes.</p>\n\n<p>I use this to automatically encrypt the appSettings and connectionStrings on Application_Start if they aren't already encrypted. I haven't actually changed any settings this way, but it seems like you ought to be able to do so.</p>\n\n<p>Saving the updated configuration file may cause the app to recycle depending on how it is built.</p>\n"
},
{
"answer_id": 270317,
"author": "Mike Marshall",
"author_id": 29798,
"author_profile": "https://Stackoverflow.com/users/29798",
"pm_score": 1,
"selected": false,
"text": "<p>Yes I agree with Josh. I have tried this before and I've had two negative effects:</p>\n\n<ol>\n<li>Slow loading if the current page after postback because ASP.NET is loading the web.config and all related resources</li>\n<li>If you change the web.config early enough in the load cycle (e.g. global.asax events) the site may never load or fail in unpredictable ways</li>\n</ol>\n"
},
{
"answer_id": 270318,
"author": "Frank Rosario",
"author_id": 10922,
"author_profile": "https://Stackoverflow.com/users/10922",
"pm_score": 2,
"selected": false,
"text": "<p>In theory; you could just generate a web config file programmatically and with some templating to make it easy.</p>\n\n<p>However, if you're trying to edit your web.config from within the site; it's <strong>highly</strong> recommended you don't. At the very least; you'd trigger an app reset every time you updated it; which would be especially bad if you're using in-process sessions.</p>\n\n<p>As Anders asked, what is it you're trying to do?</p>\n"
},
{
"answer_id": 270335,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 5,
"selected": true,
"text": "<p><a href=\"http://www.dotnetspider.com/resources/17562-Edit-Delete-Create-Encrypt-sections.aspx\" rel=\"noreferrer\">This fellow</a> shows sample code if you still want to do it after all the caveats:</p>\n\n<pre><code>protected void EditConfigButton(object sender, EventArgs e)\n{\n Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(\"~\");\n AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection(\"appSettings\");\n //Edit\n if (objAppsettings != null)\n {\n objAppsettings.Settings[\"test\"].Value = \"newvalueFromCode\";\n objConfig.Save();\n }\n}\n</code></pre>\n\n<p>One valid reason for editing a web.config is to encrypt it, which is what that article is about.</p>\n"
},
{
"answer_id": 307158,
"author": "spacemonkeys",
"author_id": 32336,
"author_profile": "https://Stackoverflow.com/users/32336",
"pm_score": 1,
"selected": false,
"text": "<p>Agree with others, editing the webconfig is achievable, but has knock on effects are just to dangerous / risk involved</p>\n\n<p>If its a value that is application specific, then it should be in an application specific config file</p>\n"
},
{
"answer_id": 3173565,
"author": "netbuild",
"author_id": 161464,
"author_profile": "https://Stackoverflow.com/users/161464",
"pm_score": 1,
"selected": false,
"text": "<p>Lot of time you want to modify application specific settings after deployment like say when something is wrong e.g. switching the database connection in case current DB goes down. Moreover sometimes you want to create your own XML based configuration file which you want o modify programatically.</p>\n\n<p>Try XML Webpad - <a href=\"http://xmlwebpad.codeplex.com/\" rel=\"nofollow noreferrer\">http://xmlwebpad.codeplex.com/</a></p>\n\n<p>Its a framework to view an edit XML files. Once you integrate it with your web app, editing web.config ill be as simple as viewing the web.config page, making the required changes and hitting the save button (all from within your application).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10922/"
] |
I'm currently optimizing the performance on my company's site; when it was taking 6-10 seconds to download 2MB+ of our homepage and assets (the site is mostly Flash with a lot of media, so it's not 2MB of HTML and viewstate). There are a lot of things that will need to be done to get this download size down; but one thing I definitely want to do is enable HTTP compression to compress our static content, specifically XML, CSS, and JS; I don't imagine compression will do much for the SWFs and JPGs.
I want to enable this on just our staging site so I can do some server testing and benchmarking. This means I'm going to have to do some Metabase editing, since IIS 6 doesn't allow you to set compression on an individual site via IIS manager. The problem with that is the Metabase is locked by IIS so I can't save; and even if I save the edits, I'm required to restart IIS for the changes to take affect; which will take down other live sites hosted on the same server. Is there anyway to enable compression for one site without restarting IIS? I don't mind restarting our staging site; I just don't want this work to take down other sites on the server.
Any assistance is greatly appreciated.
|
[This fellow](http://www.dotnetspider.com/resources/17562-Edit-Delete-Create-Encrypt-sections.aspx) shows sample code if you still want to do it after all the caveats:
```
protected void EditConfigButton(object sender, EventArgs e)
{
Configuration objConfig = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration("~");
AppSettingsSection objAppsettings = (AppSettingsSection)objConfig.GetSection("appSettings");
//Edit
if (objAppsettings != null)
{
objAppsettings.Settings["test"].Value = "newvalueFromCode";
objConfig.Save();
}
}
```
One valid reason for editing a web.config is to encrypt it, which is what that article is about.
|
270,292 |
<p>For a windows script I am writing, I need to detect if the machine has Apache 2.2 installed, and to find the application path. </p>
<p>One solution I came up with is to wget <a href="http://localhost:8080/server-info" rel="nofollow noreferrer">http://localhost:8080/server-info</a> and parse the root and the config file from it. This would fail if the server does not use port 8080</p>
<p>Another option would be to call “sc qc Apache2.2” and to parse the returning string. This would fail if the server is not installed as a service, or is using a different name. </p>
<p>Is there any better way to do that?</p>
|
[
{
"answer_id": 270324,
"author": "Powerlord",
"author_id": 15880,
"author_profile": "https://Stackoverflow.com/users/15880",
"pm_score": 0,
"selected": false,
"text": "<p>As I recall, Apache writes some registry keys. If you know how to read them from a script, that might help.</p>\n"
},
{
"answer_id": 270336,
"author": "James Schek",
"author_id": 17871,
"author_profile": "https://Stackoverflow.com/users/17871",
"pm_score": 3,
"selected": true,
"text": "<p>Not a lot of great options if they didn't install it using the installer. If they used the MSI/installer, you can check the registry:</p>\n\n<pre><code>HKEY_LOCAL_MACHINE\\SOFTWARE\\Apache Software Foundation\\Apache\\2.2.2\\ServerRoot \nHKEY_CURRENT_USER\\SOFTWARE\\Apache Software Foundation\\Apache\\2.2.2\\ServerRoot\n</code></pre>\n\n<p>You can also check the running process list:</p>\n\n<pre><code>WMIC PROCESS get Caption,Commandline,Processid\n</code></pre>\n\n<p>Look for the appropriate EXE. If for some reason you needed the port number, then use netstat and search for the appropriate port.</p>\n\n<p>Also, when you say \"a windows script\", I am assuming you are using something modern and capable like <a href=\"http://msdn.microsoft.com/en-us/library/9bbdkx3k(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows Scripting Host</a> (my favorite) or <a href=\"http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx\" rel=\"nofollow noreferrer\">PowerShell</a>. Don't even bother with batch files.</p>\n"
},
{
"answer_id": 65550658,
"author": "Hilal Alghallabi",
"author_id": 14931934,
"author_profile": "https://Stackoverflow.com/users/14931934",
"pm_score": 0,
"selected": false,
"text": "<p>uvdesk</p>\n<p>Unable to locate the path on the server.</p>\n<p>Try putting index.php after your helpdesk installation's site url or If you are using apache, make sure that mode_rewrite module is enabled and AllowOverride directive for document root is set to All/FileInfo in your server's configuration file.<code>[enter code here][1]</code></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5661/"
] |
For a windows script I am writing, I need to detect if the machine has Apache 2.2 installed, and to find the application path.
One solution I came up with is to wget <http://localhost:8080/server-info> and parse the root and the config file from it. This would fail if the server does not use port 8080
Another option would be to call “sc qc Apache2.2” and to parse the returning string. This would fail if the server is not installed as a service, or is using a different name.
Is there any better way to do that?
|
Not a lot of great options if they didn't install it using the installer. If they used the MSI/installer, you can check the registry:
```
HKEY_LOCAL_MACHINE\SOFTWARE\Apache Software Foundation\Apache\2.2.2\ServerRoot
HKEY_CURRENT_USER\SOFTWARE\Apache Software Foundation\Apache\2.2.2\ServerRoot
```
You can also check the running process list:
```
WMIC PROCESS get Caption,Commandline,Processid
```
Look for the appropriate EXE. If for some reason you needed the port number, then use netstat and search for the appropriate port.
Also, when you say "a windows script", I am assuming you are using something modern and capable like [Windows Scripting Host](http://msdn.microsoft.com/en-us/library/9bbdkx3k(VS.85).aspx) (my favorite) or [PowerShell](http://www.microsoft.com/windowsserver2003/technologies/management/powershell/default.mspx). Don't even bother with batch files.
|
270,309 |
<p>I want to do something like this:</p>
<pre>
<code>
create table app_users
(
app_user_id smallint(6) not null auto_increment primary key,
api_key char(36) not null default uuid()
);
</code>
</pre>
<p>However this results in a error, is there a way to call a function for a default value in mysql?</p>
<p>thanks.</p>
|
[
{
"answer_id": 270332,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 3,
"selected": false,
"text": "<p>Unfortunately no, MySQL 5 requires constants for the default. The issue was discussed in much more detail in the link below. But the only answer is to allow null and add a table trigger.</p>\n\n<p>MySQL only recently accepted UUID as part of their DB package, and it's not as feature rich as we'd like.</p>\n\n<p><a href=\"http://www.phpbuilder.com/board/showthread.php?t=10349169\" rel=\"noreferrer\">http://www.phpbuilder.com/board/showthread.php?t=10349169</a></p>\n"
},
{
"answer_id": 270338,
"author": "Harrison Fisk",
"author_id": 16111,
"author_profile": "https://Stackoverflow.com/users/16111",
"pm_score": 8,
"selected": true,
"text": "<p>No, you can't.</p>\n\n<p>However, you could easily create a trigger to do this, such as:</p>\n\n<pre>\nCREATE TRIGGER before_insert_app_users\n BEFORE INSERT ON app_users \n FOR EACH ROW\n SET new.api_key = uuid();\n</pre>\n"
},
{
"answer_id": 270339,
"author": "Thibaut Barrère",
"author_id": 20302,
"author_profile": "https://Stackoverflow.com/users/20302",
"pm_score": 3,
"selected": false,
"text": "<p>I believe <a href=\"http://dev.mysql.com/doc/refman/5.0/en/data-type-defaults.html\" rel=\"noreferrer\">you can't</a>: </p>\n\n<blockquote>\n <p>the default value must be a constant; it cannot be a function or an expression</p>\n</blockquote>\n"
},
{
"answer_id": 29752768,
"author": "Pamput",
"author_id": 1659888,
"author_profile": "https://Stackoverflow.com/users/1659888",
"pm_score": 5,
"selected": false,
"text": "<p>As already stated you can't.</p>\n\n<p>If you want to simulate this behavior you can use a trigger in this way:</p>\n\n<pre><code>CREATE TRIGGER before_insert_app_users\nBEFORE INSERT ON app_users\nFOR EACH ROW\n IF new.uuid IS NULL\n THEN\n SET new.uuid = uuid();\n END IF;\n</code></pre>\n\n<p>You still have to update previously existing rows, like this:</p>\n\n<pre><code>UPDATE app_users SET uuid = (SELECT uuid());\n</code></pre>\n"
},
{
"answer_id": 51445194,
"author": "ravindu1024",
"author_id": 2286245,
"author_profile": "https://Stackoverflow.com/users/2286245",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if the above answers are for an older version, but I saw somewhere that you can do this using the unhex() function. I tried it and it works. (maria db version 10.2)</p>\n\n<p>You can do </p>\n\n<pre><code>.... column_name binary(16) not null default unhex(replace(uuid(),'-','')) \n</code></pre>\n\n<p>and it works. To see the uuid just do hex(column_name). </p>\n"
},
{
"answer_id": 51623586,
"author": "StephenS",
"author_id": 1139715,
"author_profile": "https://Stackoverflow.com/users/1139715",
"pm_score": 2,
"selected": false,
"text": "<p>Note that MySQL's <code>UUID()</code> returns <code>CHAR(36)</code>, and storing UUIDs as text (as shown in the other answers) is obviously inefficient. Instead, the column should be <code>BINARY(16)</code>, and you can use <code>UUID_TO_BIN()</code> when inserting data and <code>BIN_TO_UUID()</code> when reading it back.</p>\n\n<pre><code>CREATE TABLE app_users\n(\n app_user_id SMALLINT(6) NOT NULL AUTO_INCREMENT PRIMARY KEY,\n api_key BINARY(16)\n);\n\nCREATE TRIGGER before_insert_app_users\nBEFORE INSERT ON app_users\nFOR EACH ROW\n IF new.api_key IS NULL\n THEN\n SET new.api_key = UUID_TO_BIN(UUID());\n END IF;\n</code></pre>\n\n<p>Note that since MySQL doesn't really know this is a UUID, it can be difficult to troubleshoot problems with it stored as binary. This article explains how to create a generated column that will convert the UUID to text as needed without taking up any space or worrying about keeping separate binary and text versions in sync: <a href=\"https://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/\" rel=\"nofollow noreferrer\">https://mysqlserverteam.com/storing-uuid-values-in-mysql-tables/</a></p>\n"
},
{
"answer_id": 52382915,
"author": "ibotty",
"author_id": 3714434,
"author_profile": "https://Stackoverflow.com/users/3714434",
"pm_score": 2,
"selected": false,
"text": "<p>In MariaDB starting from version 10.2.1 you can. See <a href=\"https://mariadb.com/kb/en/library/create-table/#default\" rel=\"nofollow noreferrer\">its documentation</a>.</p>\n\n<pre><code>CREATE TABLE test ( uuid BINARY(16) PRIMARY KEY DEFAULT unhex(replace(uuid(),'-','')) );\nINSERT INTO test () VALUES ();\nSELECT * FROM test;\n</code></pre>\n"
},
{
"answer_id": 52769071,
"author": "Shadow",
"author_id": 5389997,
"author_profile": "https://Stackoverflow.com/users/5389997",
"pm_score": 6,
"selected": false,
"text": "<p>As of <a href=\"https://dev.mysql.com/doc/refman/8.0/en/data-type-defaults.html\" rel=\"noreferrer\">mysql v8.0.13</a> it is possible to use an expression as a default value for a field:</p>\n\n<blockquote>\n <p>The default value specified in a DEFAULT clause can be a literal constant or an expression. With one exception, enclose expression default values within parentheses to distinguish them from literal constant default values.</p>\n</blockquote>\n\n<pre><code>CREATE TABLE t1 (\n uuid_field VARCHAR(32) DEFAULT (uuid()),\n binary_uuid BINARY(16) DEFAULT (UUID_TO_BIN(UUID()))\n);\n</code></pre>\n"
},
{
"answer_id": 69688616,
"author": "Federico Razzoli",
"author_id": 9445059,
"author_profile": "https://Stackoverflow.com/users/9445059",
"pm_score": 0,
"selected": false,
"text": "<p>Harrison Fisk's answer was great when it was written, but now it's outdated.</p>\n<p>Nowadays you can use an expression as a <code>DEFAULT</code> value. This is supported since MySQL 8.0 and MariaDB 10.2. Note that, if you're going to use non-deterministic functions like <code>NOW()</code> or <code>USER()</code>, you should not use <code>binlog_format=statement</code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270309",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1638/"
] |
I want to do something like this:
```
create table app_users
(
app_user_id smallint(6) not null auto_increment primary key,
api_key char(36) not null default uuid()
);
```
However this results in a error, is there a way to call a function for a default value in mysql?
thanks.
|
No, you can't.
However, you could easily create a trigger to do this, such as:
```
CREATE TRIGGER before_insert_app_users
BEFORE INSERT ON app_users
FOR EACH ROW
SET new.api_key = uuid();
```
|
270,325 |
<p>We frequently have users that create multiple accounts and then end up storing the same lesson activity data more than once. Once they realize the error, then they contact us to merge the accounts into a single one that they can use. </p>
<p>I've been beating myself to death trying to figure out how to write a query in MySQL that will merge their activity logs into a single profile so that I can then delete the other profiles, but I still can't find the query that will work.</p>
<p>The tables look like this:</p>
<pre><code>CREATE TABLE user_rtab (
user_id int PRIMARY KEY,
username varchar,
last_name varchar,
first_name varchar
);
CREATE TABLE lessonstatus_rtab (
lesson_id int,
user_id int,
accessdate timestamp,
score double,
);
</code></pre>
<p>What happens is that a user ends up taking the same lessons and also different lessons under two or more accounts and then they want to take all of their lesson statuses and have them assigned under one user account.</p>
<p>Can anyone provide a query that would accomplish this based on the lastname and firstname fields from the user table to determine all user accounts and then use only the user or username field to migrate all necessary statuses to the one single account?</p>
|
[
{
"answer_id": 270357,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 1,
"selected": false,
"text": "<p>How about this, assuming we are merging user_id 2 into 1.</p>\n\n<p>This updates the lessons done under 2 that have not been done under 1.</p>\n\n<pre><code>UPDATE lessonstatus_rtab\nSET user_id = 1\nWHERE user_id = 2\nAND NOT EXISTS\n(SELECT *\n FROM lessonstatus_rtab e\n WHERE e.lesson_id = lessonstatus_rtab.lesson_id\n AND user_id = 1)\n</code></pre>\n\n<p>Anything leftover is a duplicate and can now be removed: </p>\n\n<pre><code>DELETE FROM lessonstatus_rtab\nWHERE user_id = 2\n</code></pre>\n"
},
{
"answer_id": 270359,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 2,
"selected": false,
"text": "<p>Attempting to merge this data via last/first is a horrible idea, the more users you have, the more likely you are to mesh up incorrect entries. You have IDs on your tables for a reason, use them.</p>\n\n<p>I don't see any reason why you can't say \"I want to merge user 7 into 12\" and then do the following:</p>\n\n<pre><code>UPDATE lessonstatus_rtab SET user_id=12 WHERE user_id=7;\nDELETE FROM user_rtab WHERE user_id=7;\n</code></pre>\n"
},
{
"answer_id": 270378,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 2,
"selected": true,
"text": "<p>One of my current clients is facing a similar problem, except that they have dozens of tables that have to be merged. This is one reason to use a real life primary key (natural key). Your best bet is to try to avoid this problem before it even happens.</p>\n\n<p>Another thing to keep in mind, is that two people can share both the same first and last name. Maybe you don't consider this an issue because of your user base, but if they're already creating multiple accounts how long is it until they start making up fake names or creating names that are almost the same, but not quite. Names are generally not a great thing to match on to determine if two people are the same or not.</p>\n\n<p>As to the technical part of your question, it depends a lot on what the business rules are. If they have the same lesson in there twice with different scores do you use the highest score? How do you decide to which user account to link everything? No matter what, it's going to probably be a multi-step process.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270325",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20178/"
] |
We frequently have users that create multiple accounts and then end up storing the same lesson activity data more than once. Once they realize the error, then they contact us to merge the accounts into a single one that they can use.
I've been beating myself to death trying to figure out how to write a query in MySQL that will merge their activity logs into a single profile so that I can then delete the other profiles, but I still can't find the query that will work.
The tables look like this:
```
CREATE TABLE user_rtab (
user_id int PRIMARY KEY,
username varchar,
last_name varchar,
first_name varchar
);
CREATE TABLE lessonstatus_rtab (
lesson_id int,
user_id int,
accessdate timestamp,
score double,
);
```
What happens is that a user ends up taking the same lessons and also different lessons under two or more accounts and then they want to take all of their lesson statuses and have them assigned under one user account.
Can anyone provide a query that would accomplish this based on the lastname and firstname fields from the user table to determine all user accounts and then use only the user or username field to migrate all necessary statuses to the one single account?
|
One of my current clients is facing a similar problem, except that they have dozens of tables that have to be merged. This is one reason to use a real life primary key (natural key). Your best bet is to try to avoid this problem before it even happens.
Another thing to keep in mind, is that two people can share both the same first and last name. Maybe you don't consider this an issue because of your user base, but if they're already creating multiple accounts how long is it until they start making up fake names or creating names that are almost the same, but not quite. Names are generally not a great thing to match on to determine if two people are the same or not.
As to the technical part of your question, it depends a lot on what the business rules are. If they have the same lesson in there twice with different scores do you use the highest score? How do you decide to which user account to link everything? No matter what, it's going to probably be a multi-step process.
|
270,334 |
<p>I have a class that contains two methods like these:</p>
<pre><code>public String getFoo(Int32 a)
{
return getBar(a, "b", null);
}
public String getBar(Int32 a, String b, Int32 c)
{
//do something
return "";
}
</code></pre>
<p>However when I compile my class I get two errors:</p>
<ol>
<li>The best overloaded method match for getBar(int,string,int) has some invalid arguments</li>
<li>Argument '3': cannot convert from '<code><null></code>' to 'int'</li>
</ol>
<p>I think I understand why I'm getting this error: the compiler doesn't know
at the time of compilation what the real type of the object is.
Can someone confirm if I'm correct about the cause of the error or point out the real reason?</p>
<p>More importantly, can I design my code this way? If so, what do I need to do to fix the errors? My reason for designing my class this way is because I don't want to duplicate the code in getBar, in getFoo. The two methods do essentially the same thing except one takes a third parameter.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 270345,
"author": "Jacob Krall",
"author_id": 3140,
"author_profile": "https://Stackoverflow.com/users/3140",
"pm_score": 1,
"selected": false,
"text": "<p><code>Int32</code> is a value type, which means <code>null</code> is not a valid argument for parameters of type <code>Int32</code>.</p>\n\n<p>If you really need nullable ints, use the <code>int?</code> type.</p>\n\n<p>The two errors you are seeing are actually the same error.</p>\n"
},
{
"answer_id": 270346,
"author": "jerhinesmith",
"author_id": 1108,
"author_profile": "https://Stackoverflow.com/users/1108",
"pm_score": 2,
"selected": false,
"text": "<p>Try making the third argument to the <code>getBar</code> a nullable int.</p>\n\n<p>So, the signature would look like this:</p>\n\n<pre><code>public String getBar(Int32 a, String b, Int32? c)\n</code></pre>\n\n<p>You can find out more about nullable types in .NET <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s.aspx\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://msdn.microsoft.com/en-us/library/2cf62fcy.aspx\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 270354,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 4,
"selected": true,
"text": "<p>In .NET, there is a distinct concept between reference types and value types.</p>\n\n<p>A reference type is an object that is allocated on the heap (It will be a subclass of System.Object). All that is on the stack is a pointer to this object. Because of that, it is perfectly valid to store a null pointer.</p>\n\n<p>A value type is an object that is allocated on the stack, it will be a subclass of System.ValueType. Because a value type lives on the stack, when you pass its value to a function, you pass the entire contents of the object. </p>\n\n<p>Value types cannot be null.</p>\n\n<p>Most C# primitive types are value types. String is a special type of primitive that is actually a reference type.</p>\n\n<p>In .NET 2.0, MS added the ability to enclose a generic type inside of a struct so that it could simulate a nullable type. What really happens is that the logic inside of the Nullable<T> struct is emulating a null for you.</p>\n\n<p>They expressed it using a syntax shortcut by adding a question mark to the type, for example:</p>\n\n<pre><code>int? nullableInt = null;\nfloat? nullableFloat = null;\n</code></pre>\n\n<p>etc...</p>\n\n<p>If you don't like the int? syntax, you can always use Nullable<SomeType></p>\n\n<pre><code>public String getBar(Int32 a, String b, Nullable<Int32> c)\n</code></pre>\n\n<p>As a side note, I prefer to add an overload when doing what you are doing, just to make the syntax nicer.</p>\n\n<pre><code>public String getBar(Int32 a, String b)\n{\n this.getBar(a,b,null);\n}\n\npublic String getBar(Int32 a, String b, Nullable<Int32> c)\n{\n}\n</code></pre>\n"
},
{
"answer_id": 270355,
"author": "George Mauer",
"author_id": 5056,
"author_profile": "https://Stackoverflow.com/users/5056",
"pm_score": 1,
"selected": false,
"text": "<p>Int32 is an alias for int which is a value/non-nullable type. For a nullable version of it use System.Nullable or simply 'int?'.</p>\n\n<p>Also don't forget to convert back to a non-nullable int:</p>\n\n<pre><code>int? nullable = ...;\nint non_nullable = nullable??0; \n</code></pre>\n\n<p>where the number indicates what value it should assume if it is indeed null.</p>\n"
},
{
"answer_id": 270360,
"author": "svlists",
"author_id": 30560,
"author_profile": "https://Stackoverflow.com/users/30560",
"pm_score": 1,
"selected": false,
"text": "<p>Sunny is correct.<br>\nInt32 is a value type and can not hold the value 'null'. If you need to pass 'null' as a parameter value, use Nullable instead of Int32 as your argument type.</p>\n\n<p>You can find more information at <a href=\"http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx\" rel=\"nofollow noreferrer\">Nullable Types (C# Programming Guide)</a> on MSDN.</p>\n"
},
{
"answer_id": 270368,
"author": "Tim Scott",
"author_id": 29493,
"author_profile": "https://Stackoverflow.com/users/29493",
"pm_score": 0,
"selected": false,
"text": "<p>Int32 cannot be null. Make it a nullable type instead:</p>\n\n<pre><code>public String getBar(Int32 a, String b, Int32? c)\n{\n if (c.HasValue)\n {\n ...do something with c.Value...\n }\n return \"\";\n}\n</code></pre>\n"
},
{
"answer_id": 270372,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "<p>OK, so <del>five</del>seven people proposed <code>int?</code> as the solution. I propose two other solutions that <em>might</em> be more appropriate, depending on the situation;</p>\n\n<ul>\n<li><p><strong>Create an overload</strong> of the method that only has two arguments, and omit the <code>null</code> when calling:</p>\n\n<pre><code>public String getFoo(Int32 a)\n{\n return getBar(a, \"b\", null);\n}\n\npublic String getBar(Int32 a, String b)\n{\n //do something else, without the int\n}\n</code></pre>\n\n<p>Although you probably don't want to do this since you stated that you wanted to avoid code duplication.</p></li>\n<li><p><strong>Use <code>default</code> instead of <code>null</code></strong>:</p>\n\n<pre><code>return getBar(a, \"b\", default(int));\n</code></pre>\n\n<p>Incidentally, this is the same as passing the value <code>0</code>.</p></li>\n</ul>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9809/"
] |
I have a class that contains two methods like these:
```
public String getFoo(Int32 a)
{
return getBar(a, "b", null);
}
public String getBar(Int32 a, String b, Int32 c)
{
//do something
return "";
}
```
However when I compile my class I get two errors:
1. The best overloaded method match for getBar(int,string,int) has some invalid arguments
2. Argument '3': cannot convert from '`<null>`' to 'int'
I think I understand why I'm getting this error: the compiler doesn't know
at the time of compilation what the real type of the object is.
Can someone confirm if I'm correct about the cause of the error or point out the real reason?
More importantly, can I design my code this way? If so, what do I need to do to fix the errors? My reason for designing my class this way is because I don't want to duplicate the code in getBar, in getFoo. The two methods do essentially the same thing except one takes a third parameter.
Thanks.
|
In .NET, there is a distinct concept between reference types and value types.
A reference type is an object that is allocated on the heap (It will be a subclass of System.Object). All that is on the stack is a pointer to this object. Because of that, it is perfectly valid to store a null pointer.
A value type is an object that is allocated on the stack, it will be a subclass of System.ValueType. Because a value type lives on the stack, when you pass its value to a function, you pass the entire contents of the object.
Value types cannot be null.
Most C# primitive types are value types. String is a special type of primitive that is actually a reference type.
In .NET 2.0, MS added the ability to enclose a generic type inside of a struct so that it could simulate a nullable type. What really happens is that the logic inside of the Nullable<T> struct is emulating a null for you.
They expressed it using a syntax shortcut by adding a question mark to the type, for example:
```
int? nullableInt = null;
float? nullableFloat = null;
```
etc...
If you don't like the int? syntax, you can always use Nullable<SomeType>
```
public String getBar(Int32 a, String b, Nullable<Int32> c)
```
As a side note, I prefer to add an overload when doing what you are doing, just to make the syntax nicer.
```
public String getBar(Int32 a, String b)
{
this.getBar(a,b,null);
}
public String getBar(Int32 a, String b, Nullable<Int32> c)
{
}
```
|
270,337 |
<p>I have a page with a GridView on it that launches a popup, using Javascript. The user then selects an item, that updates the data connected to the GridView and closes the popup.</p>
<p>How do I refresh the first (ie the Calling page) so that I can refresh the data shown in my Gridview?</p>
|
[
{
"answer_id": 270351,
"author": "TonyB",
"author_id": 3543,
"author_profile": "https://Stackoverflow.com/users/3543",
"pm_score": 1,
"selected": false,
"text": "<p>Try this inside your popup:</p>\n\n<pre><code><script>\nwindow.opener.location.reload()\n</script>\n</code></pre>\n\n<p>That should refresh the page that opened the pop-up</p>\n"
},
{
"answer_id": 270465,
"author": "stevemegson",
"author_id": 25028,
"author_profile": "https://Stackoverflow.com/users/25028",
"pm_score": 0,
"selected": false,
"text": "<p>If you simply need to trigger a postback on the calling page, this should work:</p>\n\n<pre><code><script>\nwindow.parent.document.forms[0].submit();\n</script>\n</code></pre>\n\n<p>By explicitly submitting the form, you avoid the warning that appears if you just refresh the calling page.</p>\n\n<p>If you need to trigger an OnSelectedIndexChanged event on the GridView during the postback, then things are a bit fiddlier, but you should be able to do it by calling <code>window.parent.document.__doPostBack()</code> with suitable arguments.</p>\n"
},
{
"answer_id": 281792,
"author": "David Smit",
"author_id": 29441,
"author_profile": "https://Stackoverflow.com/users/29441",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the Solution:</p>\n\n<pre><code>Dim CloseScript As String = \"<script language='javascript'>function closeWindow(){ window.opener.document.forms[0].submit();window.close();}closeWindow();</script>\"\n</code></pre>\n\n<p>In .NET 2.0 you have to add this to the page to register above Javascript: </p>\n\n<pre><code> 'register with ClientScript \n 'The RegisterStartupScript method is also slightly different \n 'from ASP.NET 1.x \n Dim s As Type = Me.[GetType]()\n If Not ClientScript.IsClientScriptBlockRegistered(s, \"CloseScript\") Then\n ClientScript.RegisterClientScriptBlock(s, \"CloseScript\", CloseScript)\n End If\n</code></pre>\n"
},
{
"answer_id": 2869528,
"author": "Justin",
"author_id": 191347,
"author_profile": "https://Stackoverflow.com/users/191347",
"pm_score": 0,
"selected": false,
"text": "<p>Does this avoid the 'page cannot be refreshed' message</p>\n\n<pre><code>window.opener.location = window.opener.location;\n</code></pre>\n\n<p><em>(sorry I would have just left a comment on TonyB's post but I don't have enough SO points, so I'm not allowed... :(</em></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270337",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29441/"
] |
I have a page with a GridView on it that launches a popup, using Javascript. The user then selects an item, that updates the data connected to the GridView and closes the popup.
How do I refresh the first (ie the Calling page) so that I can refresh the data shown in my Gridview?
|
Try this inside your popup:
```
<script>
window.opener.location.reload()
</script>
```
That should refresh the page that opened the pop-up
|
270,347 |
<p><code>std::auto_ptr</code> is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows <code>auto_ptr<T> x = new T();</code>, which of course leads to horrible crashes, while being simple to do by mistake.</p>
<p>From an <a href="https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one#110706">answer</a> to another question here on stackoverflow:</p>
<blockquote>
<p>Note that the implementation of std::auto_ptr in Visual Studio 2005 is horribly broken.
<a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98871" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98871</a>
<a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842" rel="nofollow noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842</a></p>
</blockquote>
<p>I want to use </p>
<ul>
<li><code>boost::scoped_ptr</code>, for pointers that shouldn't pass ownership.</li>
<li><code>boost::shared_ptr</code>, for pointers in containers and elsewhere where they are required. </li>
<li><code>std::auto_ptr</code>, for pointers that should/can pass ownership.</li>
</ul>
<p>But since <code>std::auto_ptr</code> is broken for me, I wonder what would be the best approach:</p>
<ul>
<li>Replace <code>std::auto_ptr</code> with something from the net. Like this <a href="http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491" rel="nofollow noreferrer">this</a> one from Rani Sharoni (haven't tried it yet).</li>
<li>Use <code>boost::shared_ptr</code> instead. Will of course work, although there will be some minor overhead that I don't care about. But I want to use <code>auto_ptr</code> to signal the intent of the pointer. (See <a href="https://stackoverflow.com/questions/197048/idiomatic-use-of-stdautoptr-or-only-use-sharedptr#197083">this</a> answer for a vote on this approach.)</li>
<li>I will never need to pass ownership in practice, so I shouldn't worry about this.</li>
</ul>
<hr>
<p>Update:
Here is what I did:
I copied the aforementioned auto_ptr implementation by Rani Sharoni. <a href="http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491" rel="nofollow noreferrer">From here</a>.</p>
<p>Did some minor tests:</p>
<pre><code>class T
{
public:
T() {
OutputDebugStringA("T\n");
};
~T() {
OutputDebugStringA("~T\n");
};
};
{
fix::auto_ptr<T> x(new T); // This just works.
}
{
fix::auto_ptr<T> x = (new T); // Doesn't compile. Great!
}
{
fix::auto_ptr<T> x = fix::auto_ptr<T>(new T); // Transfer of ownership works also.
}
</code></pre>
<p>Of course these tests are by no means exhaustive and you shouldn't trust them. Implementing an exception safe templated class is hairy business. At least this works better than the built in one.</p>
<p><strike>Note: I don't know if I'm allowed to use this implementation yet, with respect to copyright. I have emailed Rani and I'm waiting for a reply. I'll update this post when I know more.</strike>
Permission is granted for everyone to use Rani Sharoni's auto_ptr implementation as you wish.</p>
<p>Thank you for all your replies.</p>
|
[
{
"answer_id": 270363,
"author": "MP24",
"author_id": 6206,
"author_profile": "https://Stackoverflow.com/users/6206",
"pm_score": 0,
"selected": false,
"text": "<p>Use boost::shared_ptr/boost::scoped_ptr. It will be the preferred smart pointer in upcoming C++ standards (is in TR1 already).</p>\n\n<p>Edit:\nPlease find a related discussion here: <a href=\"https://stackoverflow.com/questions/197048/idiomatic-use-of-stdautoptr-or-only-use-sharedptr\">Idiomatic use of std::auto_ptr or only use shared_ptr?</a></p>\n"
},
{
"answer_id": 270365,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 1,
"selected": false,
"text": "<p>Why do you think std::auto_ptr<> is broken.</p>\n\n<p>I would have though that somthing as bad as that would have been reported to the standards comitte!</p>\n\n<p>Do you mean that you need to:</p>\n\n<pre><code>std::auto_ptr<T> x(new T); // Use the explicit constructor.\n</code></pre>\n"
},
{
"answer_id": 270487,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using <a href=\"http://www.stlport.org/\" rel=\"nofollow noreferrer\">STLPort</a>?</p>\n"
},
{
"answer_id": 270500,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 2,
"selected": false,
"text": "<p>Use a unique_ptr. I think these were introduced to be a better auto_ptr.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_35_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.unique_ptr\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/1_35_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.unique_ptr</a></p>\n\n<p>In fact, I'm led to believe auto_ptr may be deprecated in favour of it:</p>\n\n<p><a href=\"http://objectmix.com/c/113487-std-auto_ptr-deprecated.html\" rel=\"nofollow noreferrer\">http://objectmix.com/c/113487-std-auto_ptr-deprecated.html</a></p>\n"
},
{
"answer_id": 271644,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 4,
"selected": true,
"text": "<p>Move to boost smart pointers.</p>\n\n<p>In the meantime, you may want to extract a working auto_ptr implementation from an old / another STL, so you have working code.</p>\n\n<p>I believe that auto_ptr semantics are fundamentally broken - it saves typing, but the interface actually is not simpler: you still have to track which instance is the current owner and make sure the owner leaves last. </p>\n\n<p>unique-ptr \"fixes\" that, by making release not only give up ownership, but also setting the RHS to null. It is the closest replacement for auto-ptr, but with its different semantics it is not a drop-in replacement.</p>\n\n<p>There's an introductory article to <a href=\"http://www.codeproject.com/KB/stl/boostsmartptr.aspx\" rel=\"nofollow noreferrer\">boost smart pointers</a>, by, ahem, me.</p>\n"
},
{
"answer_id": 1237411,
"author": "Maciek",
"author_id": 142168,
"author_profile": "https://Stackoverflow.com/users/142168",
"pm_score": 0,
"selected": false,
"text": "<p>As far as I recall, wasn't it : </p>\n\n<pre><code>auto_ptr<T> x = auto_ptr<T>(new T()); ??\n</code></pre>\n"
},
{
"answer_id": 1237459,
"author": "Pavel Minaev",
"author_id": 111335,
"author_profile": "https://Stackoverflow.com/users/111335",
"pm_score": 0,
"selected": false,
"text": "<p>Not an answer, but for general interest of anyone for whom these bugs are relevant. There's <a href=\"https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=319580\" rel=\"nofollow noreferrer\">one more related bug</a> with VC8's <code>auto_ptr</code>, which has to do with implicit upcasts. It's probably the most evil of the bunch, because other bugs just let you compile code that is otherwise illegal according to Standard without failing, but at least compliant code works fine. With this bug, the code that is actually compliant does not work properly.</p>\n\n<p>The problem is this. Standard specifies <code>auto_ptr</code> constructors and conversion operators in such a way that they support implicit upcasting of <code>auto_ptr</code>s, just as with normal pointers. However, VC8 implementation of that does a <code>reinterpret_cast</code> rather than a <code>static_cast</code> there. Naturally, not only this is U.B. by the letter of the standard, but it also breaks with multiple base classes and/or virtual inheritance. Here's an example of legal code broken by this:</p>\n\n<pre><code>struct Base1 { int x; };\nstruct Base2 { int y; };\nstruct Derived : Base1, Base2 {};\n\nstd::auto_ptr<Derived> createDerived()\n{\n return std::auto_ptr<Derived>(new Derived);\n}\n\nstd::auto_ptr<Base2> base2(createDerived());\n</code></pre>\n\n<p>At one of my past jobs, when we ran into this problem in production, we ended up simply patching the headers ourselves (it's a trivial 2-line fix).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35256/"
] |
`std::auto_ptr` is broken in VC++ 8 (which is what we use at work). My main gripe with it is that it allows `auto_ptr<T> x = new T();`, which of course leads to horrible crashes, while being simple to do by mistake.
From an [answer](https://stackoverflow.com/questions/106508/what-is-a-smart-pointer-and-when-should-i-use-one#110706) to another question here on stackoverflow:
>
> Note that the implementation of std::auto\_ptr in Visual Studio 2005 is horribly broken.
> <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=98871>
> <http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=101842>
>
>
>
I want to use
* `boost::scoped_ptr`, for pointers that shouldn't pass ownership.
* `boost::shared_ptr`, for pointers in containers and elsewhere where they are required.
* `std::auto_ptr`, for pointers that should/can pass ownership.
But since `std::auto_ptr` is broken for me, I wonder what would be the best approach:
* Replace `std::auto_ptr` with something from the net. Like this [this](http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491) one from Rani Sharoni (haven't tried it yet).
* Use `boost::shared_ptr` instead. Will of course work, although there will be some minor overhead that I don't care about. But I want to use `auto_ptr` to signal the intent of the pointer. (See [this](https://stackoverflow.com/questions/197048/idiomatic-use-of-stdautoptr-or-only-use-sharedptr#197083) answer for a vote on this approach.)
* I will never need to pass ownership in practice, so I shouldn't worry about this.
---
Update:
Here is what I did:
I copied the aforementioned auto\_ptr implementation by Rani Sharoni. [From here](http://groups.google.com/group/comp.std.c++/msg/97a2539a1bbbe491).
Did some minor tests:
```
class T
{
public:
T() {
OutputDebugStringA("T\n");
};
~T() {
OutputDebugStringA("~T\n");
};
};
{
fix::auto_ptr<T> x(new T); // This just works.
}
{
fix::auto_ptr<T> x = (new T); // Doesn't compile. Great!
}
{
fix::auto_ptr<T> x = fix::auto_ptr<T>(new T); // Transfer of ownership works also.
}
```
Of course these tests are by no means exhaustive and you shouldn't trust them. Implementing an exception safe templated class is hairy business. At least this works better than the built in one.
Note: I don't know if I'm allowed to use this implementation yet, with respect to copyright. I have emailed Rani and I'm waiting for a reply. I'll update this post when I know more.
Permission is granted for everyone to use Rani Sharoni's auto\_ptr implementation as you wish.
Thank you for all your replies.
|
Move to boost smart pointers.
In the meantime, you may want to extract a working auto\_ptr implementation from an old / another STL, so you have working code.
I believe that auto\_ptr semantics are fundamentally broken - it saves typing, but the interface actually is not simpler: you still have to track which instance is the current owner and make sure the owner leaves last.
unique-ptr "fixes" that, by making release not only give up ownership, but also setting the RHS to null. It is the closest replacement for auto-ptr, but with its different semantics it is not a drop-in replacement.
There's an introductory article to [boost smart pointers](http://www.codeproject.com/KB/stl/boostsmartptr.aspx), by, ahem, me.
|
270,350 |
<p>I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number :</p>
<pre><code>var fib : Func<int32, int32>;
fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);
fib(3);
</code></pre>
<p>When I run this code I get a nullreferenceexception. Any ideas as to what I'm doing wrong?</p>
|
[
{
"answer_id": 270559,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 4,
"selected": true,
"text": "<p>You aren't doing anything wrong. If anything, the compiler should warn you about using fib, an unassigned variable, inside the body of the lambda.</p>\n\n<p>However the compiler ought to be capturing fib as a location, so that when the assignment completes and the delegate is later invoked, fib is properly assigned and recursion should work as expected.</p>\n\n<p>The most obvious possible reason for the failure is that Prism isn't capturing locations, but values, which would be grossly unintuitive and at odds with every other closure implementation in non-pure languages.</p>\n\n<p>For example, try this code in JavaScript (contrary to Craig's assertion in the comments to this post, JavaScript also captures locations, not values):</p>\n\n<pre><code><html>\n<head>\n<script language='javascript'>\nfunction main()\n{\n var x = 1;\n var f = function() { return x; };\n alert(f());\n x = 2;\n alert(f());\n}\n</script>\n</head>\n<body>\n<input type=button onclick=\"javascript:main()\"></input>\n</body>\n</html>\n</code></pre>\n\n<p>The alert boxes after you click on the button show 1 and 2 respectively, while following Prism/Oxygene semantics they would show 1 both times.</p>\n"
},
{
"answer_id": 271859,
"author": "Robert Giesecke",
"author_id": 35443,
"author_profile": "https://Stackoverflow.com/users/35443",
"pm_score": 0,
"selected": false,
"text": "<p>Prism handles the capture of local variables differently then native Delphi or C#.\nIn those 2 all references in your code of those locals will be mapped to fields of the compiler generated class that will hold your anonymous method.\nIn prism, these locals stay ordinary locals, yet the fields of this hidden fields are set when you instantiate the anonymous method.</p>\n\n<p>One way to get a recursive lambda, would be to use a reference type to hold the lambda for you.</p>\n\n<p>All of this sounds much more complicated then it really is.<br>\n2 methods of accomplishing your goal:<br>\n1) </p>\n\n<pre><code>\n var fib := new class(Call : Func<Integer, Integer> := nil); \n fib.Call := n -> iif(n > 1, fib.Call(n - 1) + fib.Call(n - 2), n); \n var x := fib.Call(3); \n</code></pre>\n\n<p>2)When you do not want to have a reference to this wrapper, you can do it like so: </p>\n\n<pre><code>\n var fib : Func; \n with fibWrapper := new class(Call : Func<Integer, Integer> := nil) do \n begin \n fibWrapper.Call := n -> iif(n > 1, fibWrapper.Call(n - 1) + fibWrapper.Call(n - 2), n); \n fib := fibWrapper.Call; \n end;\n</code></pre>\n\n<p>btw, the reason behind Prism not following C# here, is that for threading and loop, this reusing of captured vars makes for hard weird runtime problems.\nIn Prism, captures are really captured the moment you assign the anonymous method or lambda. Which has a certain immuatble touch to it...</p>\n\n<p>Cheers,\nRobert</p>\n"
},
{
"answer_id": 271877,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": 0,
"selected": false,
"text": "<p>Does the same apply to Anonymous Methods? I'm guessing it does, but can't quite figure out the syntax to get this to run</p>\n\n<pre><code> var f : Tfib;\n f := method(n : Int32): Int32\n begin\n if n > 1 then \n Result := f(n-1) + f(n-2)\n else\n Result := n;\n end;\n</code></pre>\n\n<p><strong>Edit</strong></p>\n\n<p>It does.</p>\n\n<pre><code> var f := new class(call : TFib := nil);\n f.call := method(n : Int32): Int32\n begin\n if n > 1 then \n Result := f.call(n-1) + f.call(n-2)\n else\n Result := n;\n end;\n</code></pre>\n"
},
{
"answer_id": 272039,
"author": "Carlo Kok",
"author_id": 22180,
"author_profile": "https://Stackoverflow.com/users/22180",
"pm_score": 1,
"selected": false,
"text": "<p>as a temporary workaround you can use:</p>\n\n<pre><code>var f := new class(f: Tfib := nil);\nf.f := method(n : Int32): Int32\nbegin\n if n > 1 then \n Result := f.f(n-1) + f.f(n-2)\n else\n Result := n;\nend;\nf.f(3);\n</code></pre>\n"
},
{
"answer_id": 1491314,
"author": "Cary Jensen",
"author_id": 84904,
"author_profile": "https://Stackoverflow.com/users/84904",
"pm_score": 2,
"selected": false,
"text": "<p>Steve:</p>\n\n<p>The issue has apparently been addressed in Delphi Prism 2010. The following code sample works in the official release.</p>\n\n<pre><code> var fib : Func<int32, int32>;\n fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);\n var i := fib(9); //1,1,2,3,5,8,13,21,34\n MessageBox.Show(i.ToString);\n</code></pre>\n\n<p>The MessageBox shows the value 34.</p>\n\n<p>In response to Jeroen's question, this code was run in the original, official release build, 3.0.21.661.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22712/"
] |
I have been experimenting with Lambda expressions in Oxygene. Very simple recursive lambda expression to calculate a fibonacci number :
```
var fib : Func<int32, int32>;
fib := n -> iif(n > 1, fib(n - 1) + fib(n - 2), n);
fib(3);
```
When I run this code I get a nullreferenceexception. Any ideas as to what I'm doing wrong?
|
You aren't doing anything wrong. If anything, the compiler should warn you about using fib, an unassigned variable, inside the body of the lambda.
However the compiler ought to be capturing fib as a location, so that when the assignment completes and the delegate is later invoked, fib is properly assigned and recursion should work as expected.
The most obvious possible reason for the failure is that Prism isn't capturing locations, but values, which would be grossly unintuitive and at odds with every other closure implementation in non-pure languages.
For example, try this code in JavaScript (contrary to Craig's assertion in the comments to this post, JavaScript also captures locations, not values):
```
<html>
<head>
<script language='javascript'>
function main()
{
var x = 1;
var f = function() { return x; };
alert(f());
x = 2;
alert(f());
}
</script>
</head>
<body>
<input type=button onclick="javascript:main()"></input>
</body>
</html>
```
The alert boxes after you click on the button show 1 and 2 respectively, while following Prism/Oxygene semantics they would show 1 both times.
|
270,391 |
<p>I'm using MessageFormat to format some addresses with a template like this:</p>
<pre><code>"{0}\n{1}\n{2}\n{3}, {4} {5}"
</code></pre>
<p>where</p>
<ul>
<li>0 = street 1</li>
<li>1 = street 2</li>
<li>2 = street 3</li>
<li>3 = city</li>
<li>4 = state</li>
<li>5 = zip</li>
</ul>
<p>Most of these fields are optional when captured. How do I avoid having an empty line when for instance, there is not street 3? I could use a template like this "{0}{1}{2}{3}{4}{5}" and then substitute either "street 3\n" or "" accordingly, but then the template doesn't provide much benefit toward formatting.</p>
<p>Is there a way to include conditionals in the format string? Or is there another, preferably lightweight, templating tool available that supports conditional formatting?</p>
|
[
{
"answer_id": 270461,
"author": "sk.",
"author_id": 16399,
"author_profile": "https://Stackoverflow.com/users/16399",
"pm_score": 2,
"selected": false,
"text": "<p>Don't know how lightweight you'd consider it but <a href=\"http://velocity.apache.org/\" rel=\"nofollow noreferrer\">Apache Velocity</a> is one of the best-known templating engines for Java.</p>\n"
},
{
"answer_id": 270466,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>You could just do the formatting the way you're doing it and then remove blank lines by replacing a run of more than one <code>'\\n'</code>s with a single <code>'\\n'</code>, e.g.</p>\n\n<pre><code>result = result.replaceAll(\"\\n+\", \"\\n\");\n</code></pre>\n"
},
{
"answer_id": 270474,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Use Velocity or <a href=\"http://freemarker.org/\" rel=\"nofollow noreferrer\">Freemarker</a>.</p>\n"
},
{
"answer_id": 270516,
"author": "anjanb",
"author_id": 11142,
"author_profile": "https://Stackoverflow.com/users/11142",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.antlr.org/wiki/display/ST/Defining+Templates\" rel=\"nofollow noreferrer\">jguru StringTemplates</a></p>\n\n<p>This was used to build the site jGuru -- it's been around for a while now.</p>\n"
},
{
"answer_id": 304201,
"author": "Rob Williams",
"author_id": 26682,
"author_profile": "https://Stackoverflow.com/users/26682",
"pm_score": 3,
"selected": false,
"text": "<p><strong>EDIT: rewrite...</strong></p>\n\n<p>If you <em>don't care about design</em>, then you can readily pick a template engine at random, or because you like its name, or whatever. If you don't have criteria for selecting an engine, then who cares which one you pick?</p>\n\n<p>On the other hand, if you <em>do care about design</em>, such as in using the Model-View-Controller (MVC) design pattern, then your choices quickly diminish.</p>\n\n<p>Most of the answers here emphasize the power of the various template engines. But the whole point of MVC is that you don't want to do more, because doing more in your templates will eventually hurt you very bad. Business logic does not belong in the View, it belongs in the Model. Control logic belongs in the controller. There is only one template engine that actually enforces the MVC pattern. If you don't desire the MVC pattern (perhaps you are moving beyond it), that one engine still helps you to not hurt yourself and encourages you to partition your functionality properly.</p>\n\n<p>There is really only one good template engine: <strong>StringTemplate</strong>. See <a href=\"http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf\" rel=\"noreferrer\">http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf</a> for details of why.</p>\n\n<p>I have used it on multiple platforms (Python, Java, .Net) as well as many of the alternatives, and StringTemplate rules.</p>\n\n<p>Decision done. Enjoy. Best wishes.</p>\n"
},
{
"answer_id": 370496,
"author": "Michael Neale",
"author_id": 699,
"author_profile": "https://Stackoverflow.com/users/699",
"pm_score": 3,
"selected": false,
"text": "<p>Others have mentioned string template, but we recently switched to MVEL (which also does more, but really doesn't add much weight): <a href=\"http://mvel.codehaus.org/\" rel=\"noreferrer\">http://mvel.codehaus.org/</a> (and I find it easier to use). </p>\n"
},
{
"answer_id": 424921,
"author": "GaryF",
"author_id": 1035,
"author_profile": "https://Stackoverflow.com/users/1035",
"pm_score": 0,
"selected": false,
"text": "<p>Freemarker is pretty good. It's light, fast, has conditional formatting, and a tonne of other features.</p>\n"
},
{
"answer_id": 24086109,
"author": "dns",
"author_id": 2300614,
"author_profile": "https://Stackoverflow.com/users/2300614",
"pm_score": 2,
"selected": false,
"text": "<p>IMHO <a href=\"http://www.x5software.com/chunk/\" rel=\"nofollow\">Chunk Templating engine</a> is the best. The jar file only has <strong>180 KB</strong>! and support <strong>IF</strong> and <strong>iteration</strong>. How cool is that !</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270391",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21176/"
] |
I'm using MessageFormat to format some addresses with a template like this:
```
"{0}\n{1}\n{2}\n{3}, {4} {5}"
```
where
* 0 = street 1
* 1 = street 2
* 2 = street 3
* 3 = city
* 4 = state
* 5 = zip
Most of these fields are optional when captured. How do I avoid having an empty line when for instance, there is not street 3? I could use a template like this "{0}{1}{2}{3}{4}{5}" and then substitute either "street 3\n" or "" accordingly, but then the template doesn't provide much benefit toward formatting.
Is there a way to include conditionals in the format string? Or is there another, preferably lightweight, templating tool available that supports conditional formatting?
|
**EDIT: rewrite...**
If you *don't care about design*, then you can readily pick a template engine at random, or because you like its name, or whatever. If you don't have criteria for selecting an engine, then who cares which one you pick?
On the other hand, if you *do care about design*, such as in using the Model-View-Controller (MVC) design pattern, then your choices quickly diminish.
Most of the answers here emphasize the power of the various template engines. But the whole point of MVC is that you don't want to do more, because doing more in your templates will eventually hurt you very bad. Business logic does not belong in the View, it belongs in the Model. Control logic belongs in the controller. There is only one template engine that actually enforces the MVC pattern. If you don't desire the MVC pattern (perhaps you are moving beyond it), that one engine still helps you to not hurt yourself and encourages you to partition your functionality properly.
There is really only one good template engine: **StringTemplate**. See <http://www.cs.usfca.edu/~parrt/papers/mvc.templates.pdf> for details of why.
I have used it on multiple platforms (Python, Java, .Net) as well as many of the alternatives, and StringTemplate rules.
Decision done. Enjoy. Best wishes.
|
270,434 |
<p>In Reporting Services I would like to add a parameter that contains data from a custom code block. Ideally, I would be able to run the following code (this is a simple testing example):</p>
<pre><code>Function GetPeriods() As String()
Dim values As System.Collections.ArrayList =
New System.Collections.ArrayList()
For i as integer = 1 to 24
values.Add(i)
Next
Return values.ToArray()
End Function
</code></pre>
<p>and put the following in the "Text Field" of the parameter:</p>
<pre><code>=Code.GetPeriods()
</code></pre>
<p>However, when I run the report, the parameter I apply this to is disabled and empty. Is there a different technique that should be used? Or am I doing something wrong?</p>
|
[
{
"answer_id": 273746,
"author": "Gene",
"author_id": 35630,
"author_profile": "https://Stackoverflow.com/users/35630",
"pm_score": 0,
"selected": false,
"text": "<p>Everything I've seen requires parameters and their respective settings to be part of the RDL. </p>\n\n<p>That being said, if you're going to \"hardcode\" the values, you could create a dataset just for the report, perhaps in XML, or if it needs to be programmatically driven, do it in a web service.</p>\n"
},
{
"answer_id": 279890,
"author": "Timothy Walters",
"author_id": 14454,
"author_profile": "https://Stackoverflow.com/users/14454",
"pm_score": 2,
"selected": false,
"text": "<p>If you're using SQL 2008 Reporting Services then you can have a look at <a href=\"http://msdn.microsoft.com/en-au/library/ms153561.aspx\" rel=\"nofollow noreferrer\">this page</a> which introduces the concept of using custom assemblies.</p>\n\n<p>If you're using SQL 2005 Reporting Services then <a href=\"http://msdn.microsoft.com/en-au/library/ms153561(SQL.90).aspx\" rel=\"nofollow noreferrer\">this link</a> is the one you want.</p>\n\n<p>It's a mostly trivial thing, simply compile your code into a class library and follow the instructions provided to allow your report to reference it.</p>\n"
},
{
"answer_id": 294721,
"author": "user38123",
"author_id": 38123,
"author_profile": "https://Stackoverflow.com/users/38123",
"pm_score": 1,
"selected": false,
"text": "<p>You can create the same stored procedure on SQL Server and load parameter values from that procedure.</p>\n"
},
{
"answer_id": 294854,
"author": "msvcyc",
"author_id": 37450,
"author_profile": "https://Stackoverflow.com/users/37450",
"pm_score": 2,
"selected": false,
"text": "<p>You are returning an array item (an array of strings) into a text field. Instead, try returning a plain string. That should work. If you would still like to return an array list, you must basically bind it to a list control in your RDL. You can definitely do that with dataset extensions. However, I am not sure if there is any other easy way. Check the proprties of the list control and see if it allows you to directly bind to an array list.</p>\n"
},
{
"answer_id": 337378,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I checked your code. The only thing that's wrong is your function returns <code>String()</code>. When I changed your method signature to return <code>Array</code>, it worked fine, in my report.</p>\n\n<p>Change the signature to <code>Function GetPeriods() As Array</code></p>\n"
},
{
"answer_id": 598512,
"author": "Maksym Gontar",
"author_id": 67407,
"author_profile": "https://Stackoverflow.com/users/67407",
"pm_score": 1,
"selected": false,
"text": "<p>To access your members/functions implemented in custom code of SSRS report you should set the access modifier to \"Public\":</p>\n\n<pre><code>Public Function GetPeriods() As String\n...\n</code></pre>\n\n<p>see article <a href=\"http://blogs.sqlxml.org/bryantlikes/articles/824.aspx\" rel=\"nofollow noreferrer\">Writing Custom Code in SQL Server Reporting Services</a></p>\n"
},
{
"answer_id": 1213354,
"author": "Bratch",
"author_id": 14326,
"author_profile": "https://Stackoverflow.com/users/14326",
"pm_score": 1,
"selected": false,
"text": "<p>I've been trying to do this same thing, set a simple list of parameter values from report code. None of the links in any of these answers shows how to do this and after quite a bit of digging around I don't think it's even possible. Yes it is possible to get the values from a database query, from a web service, or from a custom assembly, but each of these creates a lot of overhead compared to getting the list from a simple function call like =Code.GetValues(), where the function uses a For loop to create the values.</p>\n\n<p>msvcyc is correct in pointing out that the parameter is expecting a string value, but the function is returning an array. I changed the return type to Array as suggested by prashant sable, but the select list is still grayed out, it does not work. And coldice is correct in saying that the access modifier should be Public.</p>\n\n<p>In my digging around I found <a href=\"http://www.jameskovacs.com/blog/CommentView.aspx?guid=31eeaafd-a118-4e76-917d-78d54441aee9\" rel=\"nofollow noreferrer\">an article by James Kovac</a> from 2005 that pointed out why this is not possible. The Parameters class has a get method, but no set method. In the VS 2008 object browser for SSRS 2008 the object name has changed, but it still does not contain a set method (see Microsoft.ReportingServices.Interfaces.IParameter.Name or .Value).</p>\n\n<p>My current workaround is to just hard code the list of values, but if your value list needs to be dynamic then your only choices are database queries, web services, or custom assemblies. I think the easiest workaround of these three is to get the values from the database engine, as suggested by oleksiy.t, as long as you can write a query to return the value list you want. Your list of integers, or my list of time intervals, would both be easy queries to write. Otherwise you will need to use one of the other two workarounds.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/105/"
] |
In Reporting Services I would like to add a parameter that contains data from a custom code block. Ideally, I would be able to run the following code (this is a simple testing example):
```
Function GetPeriods() As String()
Dim values As System.Collections.ArrayList =
New System.Collections.ArrayList()
For i as integer = 1 to 24
values.Add(i)
Next
Return values.ToArray()
End Function
```
and put the following in the "Text Field" of the parameter:
```
=Code.GetPeriods()
```
However, when I run the report, the parameter I apply this to is disabled and empty. Is there a different technique that should be used? Or am I doing something wrong?
|
If you're using SQL 2008 Reporting Services then you can have a look at [this page](http://msdn.microsoft.com/en-au/library/ms153561.aspx) which introduces the concept of using custom assemblies.
If you're using SQL 2005 Reporting Services then [this link](http://msdn.microsoft.com/en-au/library/ms153561(SQL.90).aspx) is the one you want.
It's a mostly trivial thing, simply compile your code into a class library and follow the instructions provided to allow your report to reference it.
|
270,444 |
<p>I'm getting this error:</p>
<pre><code>javax.servlet.ServletException: bean not found within scope
</code></pre>
<p>on a page with this at the top.</p>
<pre class="lang-html prettyprint-override"><code><jsp:useBean id="bean" type="com.example.Bean" scope="request" />
</code></pre>
<p>The class exists in the classpath, it worked this morning, and I don't get what not found within scope means.</p>
<p>How is this caused and how can I solve it?</p>
|
[
{
"answer_id": 904223,
"author": "victor hugo",
"author_id": 70616,
"author_profile": "https://Stackoverflow.com/users/70616",
"pm_score": 1,
"selected": false,
"text": "<p>You must add</p>\n\n<pre><code><jsp:useBean id=\"givingFormBean\" type=\"some.packg.GivingForm\" scope=\"request\" />\n</code></pre>\n\n<p>Because by default the bean is <a href=\"http://java.sun.com/products/jsp/tags/11/syntaxref11.fm14.html\" rel=\"nofollow noreferrer\">looked on the <em>page</em> scope</a></p>\n"
},
{
"answer_id": 3029379,
"author": "BalusC",
"author_id": 157882,
"author_profile": "https://Stackoverflow.com/users/157882",
"pm_score": 6,
"selected": true,
"text": "<p>You need the <code>class</code> attribute instead of the <code>type</code> attribute. </p>\n\n<p>The following:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><jsp:useBean id=\"bean\" type=\"com.example.Bean\" scope=\"request\" />\n</code></pre>\n\n<p>does <em>basically</em> the following behind the scenes:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Bean bean = (Bean) pageContext.getAttribute(\"bean\", PageContext.REQUEST_SCOPE);\n\nif (bean == null) {\n throw new ServletException(\"bean not found within scope\");\n}\n\n// Use bean ...\n</code></pre>\n\n<p>While the following:</p>\n\n<pre class=\"lang-html prettyprint-override\"><code><jsp:useBean id=\"bean\" class=\"com.example.Bean\" scope=\"request\" />\n</code></pre>\n\n<p>does basically the following behind the scenes:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>Bean bean = (Bean) pageContext.getAttribute(\"bean\", PageContext.REQUEST_SCOPE);\n\nif (bean == null) {\n bean = new Bean();\n pageContext.setAttribute(\"bean\", bean, PageContext.REQUEST_SCOPE);\n}\n\n// Use bean ...\n</code></pre>\n\n<p>If it has worked before and it didn't work \"in a sudden\", then it means that <em>something</em> which is responsible for putting the bean in the scope has stopped working. For example a servlet which does the following in the <code>doGet()</code>:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>request.setAttribute(\"bean\", new Bean());\nrequest.getRequestDispatcher(\"page.jsp\").forward(request, response);\n</code></pre>\n\n<p>Maybe you've invoked the JSP page directly by URL instead of invoking the Servlet by URL. If you'd like to disable direct access to JSP pages, then put them in <code>/WEB-INF</code> and forward to it instead.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12386/"
] |
I'm getting this error:
```
javax.servlet.ServletException: bean not found within scope
```
on a page with this at the top.
```html
<jsp:useBean id="bean" type="com.example.Bean" scope="request" />
```
The class exists in the classpath, it worked this morning, and I don't get what not found within scope means.
How is this caused and how can I solve it?
|
You need the `class` attribute instead of the `type` attribute.
The following:
```html
<jsp:useBean id="bean" type="com.example.Bean" scope="request" />
```
does *basically* the following behind the scenes:
```java
Bean bean = (Bean) pageContext.getAttribute("bean", PageContext.REQUEST_SCOPE);
if (bean == null) {
throw new ServletException("bean not found within scope");
}
// Use bean ...
```
While the following:
```html
<jsp:useBean id="bean" class="com.example.Bean" scope="request" />
```
does basically the following behind the scenes:
```java
Bean bean = (Bean) pageContext.getAttribute("bean", PageContext.REQUEST_SCOPE);
if (bean == null) {
bean = new Bean();
pageContext.setAttribute("bean", bean, PageContext.REQUEST_SCOPE);
}
// Use bean ...
```
If it has worked before and it didn't work "in a sudden", then it means that *something* which is responsible for putting the bean in the scope has stopped working. For example a servlet which does the following in the `doGet()`:
```java
request.setAttribute("bean", new Bean());
request.getRequestDispatcher("page.jsp").forward(request, response);
```
Maybe you've invoked the JSP page directly by URL instead of invoking the Servlet by URL. If you'd like to disable direct access to JSP pages, then put them in `/WEB-INF` and forward to it instead.
|
270,445 |
<p>Is there a way to compile multiple java source directories in a single maven project? </p>
|
[
{
"answer_id": 270451,
"author": "sal",
"author_id": 13753,
"author_profile": "https://Stackoverflow.com/users/13753",
"pm_score": 6,
"selected": false,
"text": "<p>This worked for me</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code><build>\n <sourceDirectory>.</sourceDirectory>\n <plugins>\n <plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <configuration>\n <includes>\n <include>src/main/java/**/*.java</include>\n <include>src/main2/java/**/*.java</include>\n </includes>\n </configuration>\n </plugin>\n </plugins>\n</build>\n</code></pre>\n"
},
{
"answer_id": 270490,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": true,
"text": "<p>You can add a new source directory with build-helper:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><build>\n <plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>build-helper-maven-plugin</artifactId>\n <version>3.2.0</version>\n <executions>\n <execution>\n <phase>generate-sources</phase>\n <goals>\n <goal>add-source</goal>\n </goals>\n <configuration>\n <sources>\n <source>src/main/generated</source>\n </sources>\n </configuration>\n </execution>\n </executions>\n </plugin>\n </plugins>\n</build>\n</code></pre>\n"
},
{
"answer_id": 8091425,
"author": "arntg",
"author_id": 1041319,
"author_profile": "https://Stackoverflow.com/users/1041319",
"pm_score": 2,
"selected": false,
"text": "<p>Used the build-helper-maven-plugin from the post - and update src/main/generated. And mvn clean compile works on my ../common/src/main/java, or on ../common, so kept the latter. Then yes, confirming that IntelliJ IDEA (ver 10.5.2) level of the compilation failed as David Phillips mentioned.\nThe issue was that IDEA did not add another source root to the project. Adding it manually solved the issue. It's not nice as editing anything in the project should come from maven and not from direct editing of IDEA's project options. Yet I will be able to live with it until they support build-helper-maven-plugin directly such that it will auto add the sources.</p>\n\n<p>Then needed another workaround to make this work though. Since each time IDEA re-imported maven settings after a pom change me newly added source was kept on module, yet it lost it's Source Folders selections and was useless. So for IDEA - need to set these once:</p>\n\n<ul>\n<li>Select - Project Settings / Maven / Importing / keep source and test\nfolders on reimport. </li>\n<li>Add - Project Structure / Project Settings / Modules / {Module} / Sources / Add Content Root.</li>\n</ul>\n\n<p>Now keeping those folders on import is not the best practice in the world either, ..., but giving it a try.</p>\n"
},
{
"answer_id": 9395142,
"author": "domi.vds",
"author_id": 1225863,
"author_profile": "https://Stackoverflow.com/users/1225863",
"pm_score": 5,
"selected": false,
"text": "<p>To make it work in intelliJ, you can also add generatedSourcesDirectory to the compiler plugin this way:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.8.1</version>\n <configuration>\n <generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory>\n </configuration>\n</plugin>\n</code></pre>\n"
},
{
"answer_id": 14913197,
"author": "ursa",
"author_id": 2078908,
"author_profile": "https://Stackoverflow.com/users/2078908",
"pm_score": 1,
"selected": false,
"text": "<p>This can be done in two steps:</p>\n\n<ul>\n<li>For each source directory you should create own module.</li>\n<li>In all modules you should specify the same build directory: <code>${build.directory}</code></li>\n</ul>\n\n<p>If you work with started Jetty (<code>jetty:run</code>), then recompilation of any class in any module (with Maven, IDEA or Eclipse) will lead to Jetty's restart. The same behavior you'll get for modified resources.</p>\n"
},
{
"answer_id": 18284281,
"author": "sendon1982",
"author_id": 2680640,
"author_profile": "https://Stackoverflow.com/users/2680640",
"pm_score": 3,
"selected": false,
"text": "<p>This also works with maven by defining the resources tag. You can name your src folder names whatever you like.</p>\n\n<pre class=\"lang-xml prettyprint-override\"><code> <resources>\n <resource>\n <directory>src/main/java</directory>\n <includes>\n <include>**/*.java</include>\n <include>**/*.properties</include>\n <include>**/*.xml</include>\n </includes>\n </resource>\n\n <resource>\n <directory>src/main/resources</directory>\n <includes>\n <include>**/*.java</include>\n <include>**/*.properties</include>\n <include>**/*.xml</include>\n </includes>\n </resource>\n\n <resource>\n <directory>src/main/generated</directory>\n <includes>\n <include>**/*.java</include>\n <include>**/*.properties</include>\n <include>**/*.xml</include>\n </includes>\n </resource>\n </resources>\n</code></pre>\n"
},
{
"answer_id": 23625612,
"author": "comeGetSome",
"author_id": 1005652,
"author_profile": "https://Stackoverflow.com/users/1005652",
"pm_score": 6,
"selected": false,
"text": "<p>I naively do it this way :</p>\n\n<pre><code><build>\n <finalName>osmwse</finalName>\n <sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>\n</build>\n</code></pre>\n"
},
{
"answer_id": 56923240,
"author": "Prabhu",
"author_id": 11750839,
"author_profile": "https://Stackoverflow.com/users/11750839",
"pm_score": 1,
"selected": false,
"text": "<p>In the configuration, you can use <code><compileSourceRoots></code>.</p>\n\n<pre><code>oal: org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-cli)\n[DEBUG] Style: Regular\n[DEBUG] Configuration: <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<configuration>\n <basedir default-value=\"${basedir}\"/>\n <buildDirectory default-value=\"${project.build.directory}\"/>\n <compilePath default-value=\"${project.compileClasspathElements}\"/>\n <compileSourceRoots default-value=\"${project.compileSourceRoots}\"/>\n <compilerId default-value=\"javac\">${maven.compiler.compilerId}</compilerId>\n <compilerReuseStrategy default-value=\"${reuseCreated}\">${maven.compiler.compilerReuseStrategy}</compilerReuseStrategy>\n <compilerVersion>${maven.compiler.compilerVersion}</compilerVersion>\n <debug default-value=\"true\">${maven.compiler.debug}</debug>\n <debuglevel>${maven.compiler.debuglevel}</debuglevel>\n <encoding default-value=\"${project.build.sourceEncoding}\">${encoding}</encoding>\n <executable>${maven.compiler.executable}</executable>\n <failOnError default-value=\"true\">${maven.compiler.failOnError}</failOnError>\n <failOnWarning default-value=\"false\">${maven.compiler.failOnWarning}</failOnWarning>\n <forceJavacCompilerUse default-value=\"false\">${maven.compiler.forceJavacCompilerUse}</forceJavacCompilerUse>\n <fork default-value=\"false\">${maven.compiler.fork}</fork>\n <generatedSourcesDirectory default-value=\"${project.build.directory}/generated-sources/annotations\"/>\n <maxmem>${maven.compiler.maxmem}</maxmem>\n <meminitial>${maven.compiler.meminitial}</meminitial>\n <mojoExecution default-value=\"${mojoExecution}\"/>\n <optimize default-value=\"false\">${maven.compiler.optimize}</optimize>\n <outputDirectory default-value=\"${project.build.outputDirectory}\"/>\n <parameters default-value=\"false\">${maven.compiler.parameters}</parameters>\n <project default-value=\"${project}\"/>\n <projectArtifact default-value=\"${project.artifact}\"/>\n <release>${maven.compiler.release}</release>\n <session default-value=\"${session}\"/>\n <showDeprecation default-value=\"false\">${maven.compiler.showDeprecation}</showDeprecation>\n <showWarnings default-value=\"false\">${maven.compiler.showWarnings}</showWarnings>\n <skipMain>${maven.main.skip}</skipMain>\n <skipMultiThreadWarning default-value=\"false\">${maven.compiler.skipMultiThreadWarning}</skipMultiThreadWarning>\n <source default-value=\"1.6\">${maven.compiler.source}</source>\n <staleMillis default-value=\"0\">${lastModGranularityMs}</staleMillis>\n <target default-value=\"1.6\">${maven.compiler.target}</target>\n <useIncrementalCompilation default-value=\"true\">${maven.compiler.useIncrementalCompilation}</useIncrementalCompilation>\n <verbose default-value=\"false\">${maven.compiler.verbose}</verbose>\n</configuration>\n</code></pre>\n\n<p>these are all the configurations available for 3.8.1 version of compiler plugin. Different versions have different configurations which you can find by running your code with <code>-X</code> after the general mvn command. Like</p>\n\n<pre><code>mvn clean install -X\nmvn compiler:compile -X\n</code></pre>\n\n<p>and search with id or goal or plugin name\nThis may help with other plugins too. Eclipse, intelliJ may not show all configurations as suggestions.</p>\n"
},
{
"answer_id": 58694915,
"author": "Maksym",
"author_id": 7179509,
"author_profile": "https://Stackoverflow.com/users/7179509",
"pm_score": 3,
"selected": false,
"text": "<p>This worked for with maven 3.5.4 and now Intellij Idea see this code as source:</p>\n<pre><code><plugin>\n <groupId>org.apache.maven.plugins</groupId>\n <artifactId>maven-compiler-plugin</artifactId>\n <version>3.3</version>\n <configuration>\n <generatedSourcesDirectory>src/main/generated</generatedSourcesDirectory> \n </configuration>\n</plugin>\n</code></pre>\n"
},
{
"answer_id": 59879607,
"author": "radzimir",
"author_id": 632331,
"author_profile": "https://Stackoverflow.com/users/632331",
"pm_score": 2,
"selected": false,
"text": "<p>While the answer from evokk is basically correct, it is missing <strong>test classes</strong>.\nYou must add test classes with goal <strong>add-test-source</strong>:</p>\n<pre><code><execution>\n <phase>generate-sources</phase>\n <goals>\n <goal>add-test-source</goal>\n </goals>\n <configuration>\n <sources>\n <source>target/generated/some-test-classes</source>\n </sources>\n </configuration>\n</execution>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270445",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13753/"
] |
Is there a way to compile multiple java source directories in a single maven project?
|
You can add a new source directory with build-helper:
```xml
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.2.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>src/main/generated</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
```
|
270,458 |
<p>I am building a really basic Cocoa application using WebKit, to display a Flash/Silverlight application within it. Very basic, no intentions for it to be a browser itself.</p>
<p>So far I have been able to get it to open basic html links (<code><a href="..." /></code>) in a new instance of Safari using </p>
<pre><code>[[NSWorkspace sharedWorkspace] openURL:[request URL]];
</code></pre>
<p>Now my difficulty is opening a link in a new instance of Safari when <code>window.open()</code> is used in JavaScript. I "think" (and by this, I have been hacking away at the code and am unsure if i actually did or not) I got this kind of working by setting the WebView's <code>policyDelegate</code> and implementing its</p>
<pre><code>-webView:decidePolicyForNavigationAction:request:frame:decisionListener:
</code></pre>
<p>delegate method. However this led to some erratic behavior.</p>
<p>So the simple question, what do I need to do so that when <code>window.open()</code> is called, the link is opened in a new instance of Safari.</p>
<p>Thanks</p>
<p>Big point, I am normally a .NET developer, and have only been working with Cocoa/WebKit for a few days.</p>
|
[
{
"answer_id": 271715,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 2,
"selected": false,
"text": "<p>You don't mention what kind of erratic behaviour you are seeing. A quick possibility, is that when implementing the delegate method you forgot to tell the webview you are ignoring the click by calling the ignore method of the <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/WebKit/Protocols/WebPolicyDecisionListener_Protocol/Reference/Reference.html#//apple_ref/occ/intf/WebPolicyDecisionListener\" rel=\"nofollow noreferrer\">WebPolicyDecisionListener</a> that was passed to your delegate, which may have put things into a weird state.</p>\n\n<p>If that is not the issue, then how much control do you have over the content you are displaying? The policy delegate gives you easy mechanisms to filter all resource loads (as you have discovered), and all new window opens via <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/WebKit/Protocols/WebPolicyDelegate_Protocol/Reference/Reference.html#//apple_ref/occ/instm/NSObject/webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:\" rel=\"nofollow noreferrer\">webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:</a>. All window.open calls should funnel through that, as will anything else that triggers a new window.</p>\n\n<p>If there are other window opens you want to keep inside your app, you will to do a little more work. One of the arguments passed into the delegate is a dictionary containing <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/WebKit/Protocols/WebPolicyDelegate_Protocol/Reference/Reference.html#//apple_ref/doc/uid/20001912-7527\" rel=\"nofollow noreferrer\">information</a> about the event. Insie that dictionary the WebActionElementKey will have a dictionary containing a number of <a href=\"http://developer.apple.com/documentation/Cocoa/Reference/WebKit/Classes/WebView_Class/Reference/Reference.html#//apple_ref/doc/uid/20001903-BBCHHFBA\" rel=\"nofollow noreferrer\">details</a>, including the original dom content of the link. If you want to poke around in there you can grab the actual DOM element, and check the text of the href to see if it starts with window.open. That is a bit heavy weight, but if you want fine grained control it will give it to you.</p>\n"
},
{
"answer_id": 272546,
"author": "FireWire",
"author_id": 35263,
"author_profile": "https://Stackoverflow.com/users/35263",
"pm_score": 3,
"selected": false,
"text": "<p>I made from progress last night and pinned down part of my problem.</p>\n\n<p>I am already using <code>webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:</code> and I have gotten it to work with anchor tags, however the method never seems to get called when JavaScript is invoked.</p>\n\n<p>However when <code>window.open()</code> is called <code>webView:createWebViewWithRequest:request</code> is called, I have tried to force the window to open in Safari here, however request is always null. So I can never read the URL out.</p>\n\n<p>I have done some searching around, and this seems to be a known \"<em>misfeature</em>\" however I have not been able to find a way to work around it. </p>\n\n<p>From what I understand <code>createWebViewWithRequest</code> gives you the ability to create the new webview, the the requested url is then sent to the new webView to be loaded. <a href=\"http://code.google.com/p/pandoraboy/source/browse/tags/pandoraboy_0_3/Controller.m#156\" rel=\"nofollow noreferrer\">This is the best explanation I have been able to find so far.</a></p>\n\n<p>So while many people have pointed out this problem, I have yet to see any solution which fits my needs. I will try to delve a little deeper into the <code>decidePolicyForNewWindowAction</code> again.</p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 510789,
"author": "Yoni Shalom",
"author_id": 29614,
"author_profile": "https://Stackoverflow.com/users/29614",
"pm_score": 3,
"selected": false,
"text": "<p>Well, I'm handling it by creating a dummy webView, setting it's frameLoad delegate to a custom class that handles </p>\n\n<pre><code>- (void)webView:decidePolicyForNavigationAction:actionInformation :request:frame:decisionListener:\n</code></pre>\n\n<p>and opens a new window there.</p>\n\n<p>code : </p>\n\n<pre><code>- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {\n //this is a hack because request URL is null here due to a bug in webkit \n return [newWindowHandler webView];\n}\n</code></pre>\n\n<p>and NewWindowHandler : </p>\n\n<pre><code>@implementation NewWindowHandler\n\n-(NewWindowHandler*)initWithWebView:(WebView*)newWebView {\n webView = newWebView;\n\n [webView setUIDelegate:self];\n [webView setPolicyDelegate:self]; \n [webView setResourceLoadDelegate:self];\n\n return self;\n}\n\n- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {\n [[NSWorkspace sharedWorkspace] openURL:[actionInformation objectForKey:WebActionOriginalURLKey]];\n}\n\n-(WebView*)webView {\n return webView;\n}\n</code></pre>\n"
},
{
"answer_id": 15382439,
"author": "lmirosevic",
"author_id": 399772,
"author_profile": "https://Stackoverflow.com/users/399772",
"pm_score": 2,
"selected": false,
"text": "<p>There seems to be a bug with <code>webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:</code> in that the request is always <code>nil</code>, but there is a robust solution that works with both normal <code>target=\"_blank\"</code> links as well as javascript ones.</p>\n\n<p>Basically I use another ephemeral WebView to handle the new page load in. Similar to Yoni Shalom but with a little more syntactic sugar.</p>\n\n<p>To use it first set a delegate object for your WebView, in this case I'm setting myself as the delegate:</p>\n\n<pre><code>webView.UIDelegate = self;\n</code></pre>\n\n<p>Then just implement the <code>webView:createWebViewWithRequest:</code> delegate method and use my block based API to do something when a new page is loaded, in this case I'm opening the page in an external browser:</p>\n\n<pre><code>-(WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {\n return [GBWebViewExternalLinkHandler riggedWebViewWithLoadHandler:^(NSURL *url) {\n [[NSWorkspace sharedWorkspace] openURL:url];\n }];\n}\n</code></pre>\n\n<p>That's pretty much it. Here's the code for my class. Header:</p>\n\n<pre><code>// GBWebViewExternalLinkHandler.h\n// TabApp2\n//\n// Created by Luka Mirosevic on 13/03/2013.\n// Copyright (c) 2013 Goonbee. All rights reserved.\n//\n\n#import <Foundation/Foundation.h>\n\n@class WebView;\n\ntypedef void(^NewWindowCallback)(NSURL *url);\n\n@interface GBWebViewExternalLinkHandler : NSObject\n\n+(WebView *)riggedWebViewWithLoadHandler:(NewWindowCallback)handler;\n\n@end\n</code></pre>\n\n<p>Implemetation:</p>\n\n<pre><code>// GBWebViewExternalLinkHandler.m\n// TabApp2\n//\n// Created by Luka Mirosevic on 13/03/2013.\n// Copyright (c) 2013 Goonbee. All rights reserved.\n//\n\n#import \"GBWebViewExternalLinkHandler.h\"\n\n#import <WebKit/WebKit.h>\n\n@interface GBWebViewExternalLinkHandler ()\n\n@property (strong, nonatomic) WebView *attachedWebView;\n@property (strong, nonatomic) GBWebViewExternalLinkHandler *retainedSelf;\n@property (copy, nonatomic) NewWindowCallback handler;\n\n@end\n\n@implementation GBWebViewExternalLinkHandler\n\n-(id)init {\n if (self = [super init]) {\n //create a new webview with self as the policyDelegate, and keep a ref to it\n self.attachedWebView = [WebView new];\n self.attachedWebView.policyDelegate = self;\n }\n\n return self;\n}\n\n-(void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener {\n //execute handler\n if (self.handler) {\n self.handler(actionInformation[WebActionOriginalURLKey]);\n }\n\n //our job is done so safe to unretain yourself\n self.retainedSelf = nil;\n}\n\n+(WebView *)riggedWebViewWithLoadHandler:(NewWindowCallback)handler {\n //create a new handler\n GBWebViewExternalLinkHandler *newWindowHandler = [GBWebViewExternalLinkHandler new];\n\n //store the block\n newWindowHandler.handler = handler;\n\n //retain yourself so that we persist until the webView:decidePolicyForNavigationAction:request:frame:decisionListener: method has been called\n newWindowHandler.retainedSelf = newWindowHandler;\n\n //return the attached webview\n return newWindowHandler.attachedWebView;\n}\n\n@end\n</code></pre>\n\n<p>Licensed as Apache 2.</p>\n"
},
{
"answer_id": 20481412,
"author": "kmarin",
"author_id": 2312866,
"author_profile": "https://Stackoverflow.com/users/2312866",
"pm_score": 2,
"selected": false,
"text": "<p>By reading all posts, i have come up with my simple solution, all funcs are in same class,here it is, opens a link with browser.</p>\n\n<pre><code>- (WebView *)webView:(WebView *)sender createWebViewWithRequest:(NSURLRequest *)request {\n\n return [self externalWebView:sender];\n}\n\n\n\n\n- (void)webView:(WebView *)sender decidePolicyForNavigationAction:(NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id<WebPolicyDecisionListener>)listener\n{\n [[NSWorkspace sharedWorkspace] openURL:[actionInformation objectForKey:WebActionOriginalURLKey]];\n}\n\n-(WebView*)externalWebView:(WebView*)newWebView\n{\n WebView *webView = newWebView;\n\n [webView setUIDelegate:self];\n [webView setPolicyDelegate:self];\n [webView setResourceLoadDelegate:self];\n return webView;\n}\n</code></pre>\n"
},
{
"answer_id": 26794346,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Explanation:</p>\n\n<p>Windows created from JavaScript via window.open go through createWebViewWithRequest.\nAll window.open calls result in a createWebViewWithRequest: with a null request, then later a location change on that WebView.</p>\n\n<p>For further information, <a href=\"https://lists.apple.com/archives/webkitsdk-dev/2004/Jun/msg00041.html\" rel=\"nofollow\">see this old post</a> on the WebKit mailing list.</p>\n"
},
{
"answer_id": 32174149,
"author": "adam.wulf",
"author_id": 173244,
"author_profile": "https://Stackoverflow.com/users/173244",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to returning a new WebView and waiting for its <code>loadRequest:</code> method to be called, I ended up overwriting the <code>window.open</code> function in the WebView's JSContext:</p>\n\n<p>First, I set my controller to be the WebFrameLoadDelegate of the WebView:</p>\n\n<pre><code>myWebView.frameLoadDelegate = self;\n</code></pre>\n\n<p>Then, in the delegate method, I overwrote the <code>window.open</code> function, and I can process the URL there instead.</p>\n\n<pre><code>- (void)webView:(WebView *)webView didCreateJavaScriptContext:(JSContext *)context forFrame:(WebFrame *)frame{\ncontext[@\"window\"][@\"open\"] = ^(id url){\n NSLog(@\"url to load: %@\", url);\n };\n}\n</code></pre>\n\n<p>This let me handle the request however I needed to without the awkward need to create additional WebViews.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35263/"
] |
I am building a really basic Cocoa application using WebKit, to display a Flash/Silverlight application within it. Very basic, no intentions for it to be a browser itself.
So far I have been able to get it to open basic html links (`<a href="..." />`) in a new instance of Safari using
```
[[NSWorkspace sharedWorkspace] openURL:[request URL]];
```
Now my difficulty is opening a link in a new instance of Safari when `window.open()` is used in JavaScript. I "think" (and by this, I have been hacking away at the code and am unsure if i actually did or not) I got this kind of working by setting the WebView's `policyDelegate` and implementing its
```
-webView:decidePolicyForNavigationAction:request:frame:decisionListener:
```
delegate method. However this led to some erratic behavior.
So the simple question, what do I need to do so that when `window.open()` is called, the link is opened in a new instance of Safari.
Thanks
Big point, I am normally a .NET developer, and have only been working with Cocoa/WebKit for a few days.
|
I made from progress last night and pinned down part of my problem.
I am already using `webView:decidePolicyForNewWindowAction:request:newFrameName:decisionListener:` and I have gotten it to work with anchor tags, however the method never seems to get called when JavaScript is invoked.
However when `window.open()` is called `webView:createWebViewWithRequest:request` is called, I have tried to force the window to open in Safari here, however request is always null. So I can never read the URL out.
I have done some searching around, and this seems to be a known "*misfeature*" however I have not been able to find a way to work around it.
From what I understand `createWebViewWithRequest` gives you the ability to create the new webview, the the requested url is then sent to the new webView to be loaded. [This is the best explanation I have been able to find so far.](http://code.google.com/p/pandoraboy/source/browse/tags/pandoraboy_0_3/Controller.m#156)
So while many people have pointed out this problem, I have yet to see any solution which fits my needs. I will try to delve a little deeper into the `decidePolicyForNewWindowAction` again.
Thanks!
|
270,468 |
<p>Can anyone please let me know the procedure to perform silent installation of SQL Server Express 2005 and the way to specify the installation parameters.</p>
|
[
{
"answer_id": 270521,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 3,
"selected": false,
"text": "<p>Get the MSI and do</p>\n\n<pre><code>string InstallFile = \"SSCERuntime-ENU-x86.msi\"\nstring LogFile = \"C:\\Install.log\"\n\nProcess proc;\nproc = Process.Start(\"msiexec\", \"/l \" + LogFile + \" /quiet /i \" + InstallFile);\n</code></pre>\n"
},
{
"answer_id": 270565,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>If you are doing this to support deployment of a desktop application, it's a bad idea.</p>\n\n<p>Use the Compact Edition of SQL Server rather than Express Edition. It's more suited to in-process situations, and it's much easier to deploy.</p>\n"
},
{
"answer_id": 273272,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Thanks for a prompt reply , I would try it ,\nbut i am loooking something like this for SQL EXPRESS\n<a href=\"http://msdn.microsoft.com/en-us/library/ms144259.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms144259.aspx</a></p>\n"
},
{
"answer_id": 2031807,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>You can find the variables here, <a href=\"http://msdn.microsoft.com/en-us/library/ms345154(SQL.90).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms345154(SQL.90).aspx</a></p>\n\n<p>You should be able to install silently using msiexec /qn REBOOT=ReallySuppress ADDLOCAL=ALL INSTANCENAME= SAPWD=</p>\n\n<p>You may want to set some other vars that you can find in the above link lik SQLAUTOSTART and DISABLENETWORKPROTOCOLS.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Can anyone please let me know the procedure to perform silent installation of SQL Server Express 2005 and the way to specify the installation parameters.
|
Get the MSI and do
```
string InstallFile = "SSCERuntime-ENU-x86.msi"
string LogFile = "C:\Install.log"
Process proc;
proc = Process.Start("msiexec", "/l " + LogFile + " /quiet /i " + InstallFile);
```
|
270,479 |
<p>My solution includes these two projects:</p>
<ul>
<li>MyNamespace.Web.UI</li>
<li>MyNamespace.Web.Core</li>
</ul>
<p>UI references Core, and Core references Foobar.dll, which exists nowhere except my library. When I build from Visual Studio 2008 Foobar.dll is in the UI project's Bin folder as expected. I have made certain it was not there before the build. </p>
<p>But when I build from NAnt, it is not there, which results in a runtime exception. Here's what the NAnt task looks like:</p>
<pre><code><target name="compile" depends="init">
<exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe"
commandline="${solution.file} /m /t:Clean /p:Configuration=${project.config} /v:q" workingdir="." />
<exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe"
commandline="${solution.file} /m /t:Rebuild /p:Configuration=${project.config} /v:q" workingdir="." />
</target>
</code></pre>
<p>In VS I have tried building, rebuilding, rebuilding all in release mode and debug mode, etc. It's always the same. Foobar.dll is in the Bin folder. Not so with NAnt. I have tried also to remove the /m switch from the NAnt script. Same result.</p>
<p>There are several other dlls referenced in Core and not in UI, and they appear in Bin as expected after the NAnt build.</p>
<p>My workaround is to reference Foobar.dll in the UI project, but that makes me a little nauseous. Any idea what can cause this?</p>
<p>(Incidentally Foobar.dll is actually NHibernate.ProxyGenerators.CastleDynamicProxy.dll)</p>
|
[
{
"answer_id": 270497,
"author": "Rich Reuter",
"author_id": 283,
"author_profile": "https://Stackoverflow.com/users/283",
"pm_score": 0,
"selected": false,
"text": "<p>In some things that I've worked on, I've resorted to using NAnt's <a href=\"http://nant.sourceforge.net/release/latest/help/tasks/copy.html\" rel=\"nofollow noreferrer\">copy task</a> to copy the DLL into the bin directory so that the project will build. I don't know if that's necessarily best practice, but it works.</p>\n"
},
{
"answer_id": 284878,
"author": "Jacob Adams",
"author_id": 32518,
"author_profile": "https://Stackoverflow.com/users/32518",
"pm_score": 1,
"selected": false,
"text": "<p>I've used the MSBuild task in NantContrib before and it seemed to copy the library dlls into the bin folder. Granted this doesn't really explain why your approach doesn't work, but I'm assuming your goal is to get it to build, not figure out why it won't build</p>\n"
},
{
"answer_id": 284902,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>You likely have the option in VS to \"Copy Local\" on, which is implicitly, well, copying it locally before the build. You'll need to emulate that in NAnt. </p>\n\n<p>Similar to why you can just do a \"Publish\" for a web project from Visual Studio, but for the command line you have to both build and then copy out the output to wherever you are going.</p>\n"
},
{
"answer_id": 543724,
"author": "Joshua Cauble",
"author_id": 61924,
"author_profile": "https://Stackoverflow.com/users/61924",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with Cory. Since you are shelling out to msbuild you need to make sure you copy any 3rd party (yours or otherwise) dlls into your bin or output folder. </p>\n\n<p>You can use the task to do this in nant before you run the tasks. then everything should be fine. </p>\n\n<p>The only gotcha would be that you would have to know where to put it before the msbuild tasks run so you may have to create the folder structure first and hope msbuild does not wipe it out.</p>\n\n<p>Hope that helps.</p>\n"
},
{
"answer_id": 34050070,
"author": "Hinesh Mandalia",
"author_id": 5631656,
"author_profile": "https://Stackoverflow.com/users/5631656",
"pm_score": 0,
"selected": false,
"text": "<p>I have had a similar issue. I solved this by explicitly adding </p>\n\n<blockquote>\n <p><Private>True</Private></p>\n</blockquote>\n\n<p>within the reference in the .csproj file which should force copy local.</p>\n\n<pre><code><Reference Include=\"Microsoft.Web.Infrastructure, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL\">\n <SpecificVersion>False</SpecificVersion>\n <HintPath>..\\lib\\Microsoft.Web.Infrastructure.1.0.0.0\\lib\\net40\\Microsoft.Web.Infrastructure.dll</HintPath>\n <Private>True</Private>\n</Reference>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29493/"
] |
My solution includes these two projects:
* MyNamespace.Web.UI
* MyNamespace.Web.Core
UI references Core, and Core references Foobar.dll, which exists nowhere except my library. When I build from Visual Studio 2008 Foobar.dll is in the UI project's Bin folder as expected. I have made certain it was not there before the build.
But when I build from NAnt, it is not there, which results in a runtime exception. Here's what the NAnt task looks like:
```
<target name="compile" depends="init">
<exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe"
commandline="${solution.file} /m /t:Clean /p:Configuration=${project.config} /v:q" workingdir="." />
<exec program="${framework::get-framework-directory(framework::get-target-framework())}\msbuild.exe"
commandline="${solution.file} /m /t:Rebuild /p:Configuration=${project.config} /v:q" workingdir="." />
</target>
```
In VS I have tried building, rebuilding, rebuilding all in release mode and debug mode, etc. It's always the same. Foobar.dll is in the Bin folder. Not so with NAnt. I have tried also to remove the /m switch from the NAnt script. Same result.
There are several other dlls referenced in Core and not in UI, and they appear in Bin as expected after the NAnt build.
My workaround is to reference Foobar.dll in the UI project, but that makes me a little nauseous. Any idea what can cause this?
(Incidentally Foobar.dll is actually NHibernate.ProxyGenerators.CastleDynamicProxy.dll)
|
You likely have the option in VS to "Copy Local" on, which is implicitly, well, copying it locally before the build. You'll need to emulate that in NAnt.
Similar to why you can just do a "Publish" for a web project from Visual Studio, but for the command line you have to both build and then copy out the output to wherever you are going.
|
270,493 |
<p>I need two divs to look a bit like this: </p>
<pre><code> | |
---| LOGO |------------------------
| |_______________| LINKS |
| CONTENT |
</code></pre>
<p>What's the neatest/most elegant way of making them overlap neatly? The logo will have a fixed height and width and will be touching the top edge of the page.</p>
|
[
{
"answer_id": 270501,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "<p>With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:</p>\n\n<pre><code>div#logo {\n position: absolute;\n left: 100px; // or whatever\n}\n</code></pre>\n\n<p>Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want. </p>\n"
},
{
"answer_id": 270503,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>Using CSS, you set the logo div to position absolute, and set the z-order to be above the second div.</p>\n\n<pre><code>#logo\n{\n position: absolute:\n z-index: 2000;\n left: 100px;\n width: 100px;\n height: 50px;\n}\n</code></pre>\n"
},
{
"answer_id": 270511,
"author": "Owen",
"author_id": 4853,
"author_profile": "https://Stackoverflow.com/users/4853",
"pm_score": 8,
"selected": true,
"text": "<p>I might approach it like so (CSS and HTML): </p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"false\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>html,\r\nbody {\r\n margin: 0px;\r\n}\r\n#logo {\r\n position: absolute; /* Reposition logo from the natural layout */\r\n left: 75px;\r\n top: 0px;\r\n width: 300px;\r\n height: 200px;\r\n z-index: 2;\r\n}\r\n#content {\r\n margin-top: 100px; /* Provide buffer for logo */\r\n}\r\n#links {\r\n height: 75px;\r\n margin-left: 400px; /* Flush links (with a 25px \"padding\") right of logo */\r\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"logo\">\r\n <img src=\"https://via.placeholder.com/200x100\" />\r\n</div>\r\n<div id=\"content\">\r\n \r\n <div id=\"links\">dssdfsdfsdfsdf</div>\r\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 270512,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 7,
"selected": false,
"text": "<p>Just use negative margins, in the second div say:</p>\n\n<pre><code><div style=\"margin-top: -25px;\">\n</code></pre>\n\n<p>And make sure to set the z-index property to get the layering you want.</p>\n"
},
{
"answer_id": 270665,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 1,
"selected": false,
"text": "<p>If you want the logo to take space, you are probably better of floating it left and then moving down the content using margin, sort of like this:</p>\n\n<pre>\n#logo {\n float: left;\n margin: 0 10px 10px 20px;\n}\n\n#content {\n margin: 10px 0 0 10px;\n}\n</pre>\n\n<p>or whatever margin you want.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need two divs to look a bit like this:
```
| |
---| LOGO |------------------------
| |_______________| LINKS |
| CONTENT |
```
What's the neatest/most elegant way of making them overlap neatly? The logo will have a fixed height and width and will be touching the top edge of the page.
|
I might approach it like so (CSS and HTML):
```css
html,
body {
margin: 0px;
}
#logo {
position: absolute; /* Reposition logo from the natural layout */
left: 75px;
top: 0px;
width: 300px;
height: 200px;
z-index: 2;
}
#content {
margin-top: 100px; /* Provide buffer for logo */
}
#links {
height: 75px;
margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */
}
```
```html
<div id="logo">
<img src="https://via.placeholder.com/200x100" />
</div>
<div id="content">
<div id="links">dssdfsdfsdfsdf</div>
</div>
```
|
270,494 |
<p>I have a form with a textbox and a button. IE is the only browser that will not submit the form when Enter is pressed (works in FF, Opera, Safari, Chrome, etc.). I found this javascript function to try to coax IE into behaving; but no avail:</p>
<pre><code>function checkEnter(e){
var characterCode
if (e && e.which) {
e = e
characterCode = e.which
} else {
e = event
characterCode = e.keyCode
}
if (characterCode == 13) {
document.forms[0].submit()
return false
} else {
return true
}
}
</code></pre>
<p>Implementation: </p>
<pre><code>searchbox.Attributes("OnKeyUp") = "checkEnter(event)"
</code></pre>
<p>Any advice?</p>
<p><strong>EDIT:</strong> <a href="http://www.codeproject.com/KB/aspnet/EnterKeyToButtonClick.aspx" rel="noreferrer">This page</a> on <a href="http://www.codeproject.com/" rel="noreferrer">CodeProject</a> outlines what Dillie was saying, and it works perfectly.</p>
|
[
{
"answer_id": 270505,
"author": "TravisO",
"author_id": 35116,
"author_profile": "https://Stackoverflow.com/users/35116",
"pm_score": 2,
"selected": false,
"text": "<pre><code>// Use the following Javascript in your HTML view\n// put it somewhere between <head> and </head>\n\n <script language=\"JavaScript\" type=\"text/javascript\"><!--\n function KeyDownHandler(btn)\n {\n if (event.keyCode == 13)\n {\n event.returnValue=false;\n event.cancel = true;\n btn.click();\n }\n }\n // -->\n </script>\n\n // Put this in your TextBox(es) aka inside <asp:textbox ... >\n onkeydown=\"KeyDownHandler(ButtonID)\"\n</code></pre>\n"
},
{
"answer_id": 270518,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": -1,
"selected": false,
"text": "<p>Does it use a GET instead of a POST? Is the URL too long? I've seen that...</p>\n"
},
{
"answer_id": 270532,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 5,
"selected": true,
"text": "<p>The other thing I have done in the past is wrap the form area in a Panel and set the DefaultButton attribute to the submit button you have. This effectively maps the enter key to the submission as long as you have a form element in focus in the panel area.</p>\n"
},
{
"answer_id": 270624,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": -1,
"selected": false,
"text": "<p>Basically, a form needs either a button, input type=\"submit\" or an input type=\"image\" to enable the builtin behaviour to submit a form on enter. You shouldn't need a javascript to submit it.</p>\n"
},
{
"answer_id": 487965,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p>Just create a text input in a hidden div on the page. This will circumvent the IE bug.</p>\n\n<p>Example div:</p>\n\n<pre><code> <!-- Fix for IE bug (One text input and submit, disables submit on pressing \"Enter\") -->\n <div style=\"display:none\">\n <input type=\"text\" name=\"hiddenText\"/>\n </div>\n</code></pre>\n"
},
{
"answer_id": 937241,
"author": "Alec",
"author_id": 115681,
"author_profile": "https://Stackoverflow.com/users/115681",
"pm_score": 1,
"selected": false,
"text": "<p>When using <code>display:none</code>, IE won't see the button and therefore won't be able to use it to submit the form. Instead, you could use <code>z-index</code> and absolute positioning to hide it under another element, e.g. with the style:</p>\n\n<p><code>position:absolute; bottom: -20px; left: -20px; z-index: -1;</code></p>\n\n<p>Now it'll still be there, usable by IE, but hidden beneath another element.</p>\n"
},
{
"answer_id": 4953783,
"author": "Paul",
"author_id": 591537,
"author_profile": "https://Stackoverflow.com/users/591537",
"pm_score": 2,
"selected": false,
"text": "<p>There is a good write up of this problem here, and a nice jquery based solution:</p>\n\n<blockquote>\n <p><a href=\"http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter\" rel=\"nofollow\">http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter</a></p>\n</blockquote>\n"
},
{
"answer_id": 9699405,
"author": "pro",
"author_id": 352728,
"author_profile": "https://Stackoverflow.com/users/352728",
"pm_score": 0,
"selected": false,
"text": "<p>This is due to a peculiarity in IE for single text field inputs.</p>\n\n<p>A simple solution is to stop the page having a single text field by adding another hidden one.</p>\n\n<pre><code><input type=\"text\" name=\"hidden\" style=\"visibility:hidden;display:none;\" />\n</code></pre>\n\n<p>see.. \n<a href=\"https://web.archive.org/web/20210125133120/https://www.4guysfromrolla.com/articles/060805-1.aspx\" rel=\"nofollow\">https://web.archive.org/web/20210125133120/https://www.4guysfromrolla.com/articles/060805-1.aspx</a></p>\n"
},
{
"answer_id": 11036546,
"author": "svandragt",
"author_id": 997,
"author_profile": "https://Stackoverflow.com/users/997",
"pm_score": 1,
"selected": false,
"text": "<p>Hide the button - not using display:none, but with the following styles:</p>\n\n<pre><code>position: absolute; /* no longer takes up layout space */\nvisibility: hidden; /* no longer clickable / visible */\n</code></pre>\n\n<p>If you do this, you won't need to add any other elements or hidden inputs.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270494",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
I have a form with a textbox and a button. IE is the only browser that will not submit the form when Enter is pressed (works in FF, Opera, Safari, Chrome, etc.). I found this javascript function to try to coax IE into behaving; but no avail:
```
function checkEnter(e){
var characterCode
if (e && e.which) {
e = e
characterCode = e.which
} else {
e = event
characterCode = e.keyCode
}
if (characterCode == 13) {
document.forms[0].submit()
return false
} else {
return true
}
}
```
Implementation:
```
searchbox.Attributes("OnKeyUp") = "checkEnter(event)"
```
Any advice?
**EDIT:** [This page](http://www.codeproject.com/KB/aspnet/EnterKeyToButtonClick.aspx) on [CodeProject](http://www.codeproject.com/) outlines what Dillie was saying, and it works perfectly.
|
The other thing I have done in the past is wrap the form area in a Panel and set the DefaultButton attribute to the submit button you have. This effectively maps the enter key to the submission as long as you have a form element in focus in the panel area.
|
270,510 |
<p>I am looking to encrypt some data using <a href="http://en.wikipedia.org/wiki/Advanced_Encryption_Standard" rel="noreferrer">Rijndael/AES</a> in <a href="http://en.wikipedia.org/wiki/VBScript" rel="noreferrer">VBScript</a> using a specific key and <a href="http://en.wikipedia.org/wiki/Initialization_vector" rel="noreferrer">IV</a> value. Are there any good function libraries or COM components that would be good to use?</p>
<p>I looked at <a href="http://en.wikipedia.org/wiki/CAPICOM" rel="noreferrer">CAPICOM</a>; it allows a passphrase only, and won't allow setting specific key and IV values.</p>
|
[
{
"answer_id": 293716,
"author": "Mike Henry",
"author_id": 14934,
"author_profile": "https://Stackoverflow.com/users/14934",
"pm_score": 0,
"selected": false,
"text": "<p>One option would be to create a simple wrapper class in .NET for the <a href=\"http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx\" rel=\"nofollow noreferrer\">RijndaelManaged class</a> from the .NET framework and expose it via <a href=\"http://msdn.microsoft.com/en-us/library/zsfww439.aspx\" rel=\"nofollow noreferrer\" title=\"Exposing .NET Framework Components to COM\">COM Interop</a> so you can call it from VBScript.</p>\n"
},
{
"answer_id": 858525,
"author": "Cheeso",
"author_id": 48082,
"author_profile": "https://Stackoverflow.com/users/48082",
"pm_score": 2,
"selected": false,
"text": "<p>One response suggested wrapping the <code>RijndaelManaged</code> class in COM. You could also wrap some other AES implementation in COM. I just tried <a href=\"http://code.google.com/p/slowaes\" rel=\"nofollow noreferrer\">SlowAES</a>, which is a JavaScript implementation of AES. Wrapping it in COM via a Windows Script Component makes it callable from VBScript. I would recommend this only if you cannot use the .NET approach; I would guess the AES for .NET will be faster than the AES implemented in JavaScript.</p>\n<p>In my tests of the COM-wrapped-SlowAEs, I used CBC mode, and the encryption was completely compatible with the RijndaelManaged class in .NET.</p>\n<p>Here's the WSC; I left out the 3 .js files provided by SlowAES. You need to insert them unchanged where I marked the file.</p>\n<pre><code><?xml version="1.0"?>\n\n<!--\n\n//\n// Ionic.COM.SlowAES.wsc\n//\n// This is a Windows Script Component that exposes the SlowAES\n// encryption engine via COM. This AES can be used from any \n// COM-capable environment, including Javascript or VBScript. \n//\n//\n// This code is licensed under the Microsoft Public License. See the\n// accompanying License.txt file for details.\n//\n// Copyright 2009 Dino Chiesa\n//\n\n-->\n\n<package>\n\n<component id="Ionic.Com.SlowAES">\n\n <comment>\nSlowAES is a Javascript implementation of AES. \n See http://code.google.com/p/slowaes. \nThis is a COM package for SlowAES.\n </comment>\n\n<?component error="true" debug="true"?>\n\n<registration\n description="WSC Component for SlowAES"\n progid="Ionic.Com.SlowAES"\n version="1.00"\n classid="{ba78383f-1bcc-4df6-9fb9-61cd639ebc94}"\n remotable="False">\n\n <!-- boilerplate registration/unregistration logic -->\n <script language="VBScript">\n <![CDATA[\n\nstrComponent = "Ionic SlowAES"\n\nFunction Register\n MsgBox strComponent & " - registered."\nEnd Function\n\nFunction Unregister\n MsgBox strComponent & " - unregistered."\nEnd Function\n\n ]]>\n </script>\n</registration>\n\n<public>\n <method name="EncryptString">\n<parameter name="plainText"/>\n </method>\n\n <method name="DecryptBytes">\n<parameter name="cipherText"/>\n </method>\n\n <method name="DecryptBytesToString">\n<parameter name="cipherText"/>\n </method>\n\n <method name="DecryptHexString">\n<parameter name="hexStringCipherText"/>\n </method>\n\n <method name="DecryptCommaDelimitedStringToString">\n<parameter name="cipherText"/>\n </method>\n\n <property name="Key">\n <put/>\n </property>\n\n <property name="Mode">\n <put/>\n <get/>\n </property>\n\n <property name="IV">\n <put/>\n <get/>\n </property>\n\n <property name="KeySize">\n <put/>\n <get/>\n </property>\n</public>\n\n<script language="JavaScript">\n<![CDATA[\n\n// ...insert slowAES code here... //\n\n// defaults\nvar _keysize = slowAES.aes.SIZE_128;\nvar _mode = slowAES.modeOfOperation.CBC;\nvar _iv = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];\nvar _key;\n\n/* \n* byteArrayToHexString\n* convert a byte array to hex string.\n*/\nfunction byteArrayToHexString(a)\n{\ntry { hexcase } catch(e) { hexcase=0; }\nvar hex_tab = hexcase ? "0123456789ABCDEF" : "0123456789abcdef";\nvar r= "";\nfor (var i = 0; i < a.length; i++)\n{\n var b = hex_tab.charAt((a[i] >> 4) & 0x0F) + \n hex_tab.charAt(a[i] & 0x0F);\n r+= b;\n}\nreturn r;\n}\n\n/* \n* hexStringToByteArray\n* convert a string of hex byts to a byte array\n*/\nfunction hexStringToByteArray(s)\n{\nvar r= Array(s.length/2);\nfor (var i = 0; i < s.length; i+=2)\n{\n r[i/2] = parseInt(s.substr(i,2),16);\n}\nreturn r;\n}\n\nfunction EncryptString(plainText)\n{\n var bytesToEncrypt = cryptoHelpers.convertStringToByteArray(plainText);\n var result = slowAES.encrypt(bytesToEncrypt, \n _mode,\n _key,\n _keysize,\n _iv);\nreturn result['cipher'];\n}\n\nfunction DecryptBytesToString(cipherText)\n{\nvar d = DecryptBytes(cipherText);\nvar s = cryptoHelpers.convertByteArrayToString(d);\ns[cipherText.length]= 0;\nreturn s;\n}\n\nfunction DecryptHexString(hexStringCipherText)\n{\nvar cipherText = hexStringToByteArray(hexStringCipherText);\nreturn DecryptBytesToString(cipherText);\n}\n\nfunction DecryptCommaDelimitedStringToString(cipherText)\n{\nvar c = [];\nvar atoms = cipherText.split(",");\nfor (i=0; i < atoms.length; i++)\n{\n c.push(parseInt(atoms[i], 10));\n}\nvar d = DecryptBytes(c);\nreturn cryptoHelpers.convertByteArrayToString(d);\n}\n\nfunction DecryptBytes(cipherText)\n{\nif (cipherText == undefined) return null;\n\nvar originalSize = cipherText.length;\n\nvar result = slowAES.decrypt(cipherText, \n originalSize,\n _mode,\n _key,\n _keysize,\n _iv);\n\nreturn result;\n}\n\nfunction put_Key(keyString)\n{\n _key = hexStringToByteArray(keyString);\n}\n\nfunction put_KeySize(size)\n{\nif (size == 128) _keysize = slowAES.aes.keySize.SIZE_128;\nelse if (size == 192) _keysize = slowAES.aes.keySize.SIZE_192;\nelse if (size == 256) _keysize = slowAES.aes.keySize.SIZE_256;\nelse\n throw "Unsupported key size. Must be one of { 128, 192, 256 }.";\n}\n\nfunction get_KeySize()\n{\nif (_keysize == slowAES.aes.keySize.SIZE_128) return 128;\nelse if (_keysize == slowAES.aes.keySize.SIZE_192) return 192;\nelse if (_keysize == slowAES.aes.keySize.SIZE_256) return 256;\nelse return -1;\n}\n\nfunction put_IV(ivString)\n{\n _iv = hexStringToByteArray(ivString);\n}\n\nfunction get_IV()\n{\nreturn byteArrayToHexString(_iv);\n}\n\nfunction put_Mode(mode)\n{\nif (mode == "CBC") _mode= slowAES.modeOfOperation.CBC;\nelse if (mode == "OFB") _mode= slowAES.modeOfOperation.OFB;\nelse if (mode == "CFB") _mode= slowAES.modeOfOperation.CFB;\nelse throw "Unsupported mode. Must be one of {CBC, OFB, CFB}";\n}\n\nfunction get_Mode()\n{\nif (_mode == slowAES.modeOfOperation.CBC) return "CBC";\nif (_mode == slowAES.modeOfOperation.OFB) return "OFB";\nif (_mode == slowAES.modeOfOperation.CFB) return "CFB";\nreturn "???";\n}\n\n]]>\n\n</script>\n\n</component>\n\n</package>\n</code></pre>\n<p>Save that to a file called SlowAES.wsc. Register it with "regsvr32 SlowAES.wsc."\nHere's some VBScript code that uses the component.</p>\n<pre><code>' '\n' byteArrayToHexString'\n' convert a byte array to hex string.'\n' '\nFunction byteArrayToHexString(a)\nDim r,b,i\nr = ""\nFor i = 0 To UBound(a)\n b = Hex( (a(i) And &HF0) / 16) & Hex(a(i) And &HF)\n r= r & b\nNext\nbyteArrayToHexString= r\nEnd Function\n\n' '\n' hexStringToByteArray'\n' convert a string of hex byts to a byte array'\n' '\nFunction hexStringToByteArray(s)\nDim r()\nReDim r(Len(s)/2-1)\nDim x\nFor i = 0 To Len(s)-2 Step 2\n x= "&H" & Mid(s,i+1,2)\n r(i/2) = CInt(x)\nNext\nhexStringToByteArray= r\nEnd Function\n\nFunction DemoEncryption()\nWScript.echo "Testing Ionic.Com.SlowAES..."\n\nWScript.echo "key: " & byteArrayToHexString(key)\nWScript.echo "iv: " & byteArrayToHexString(iv)\nWScript.echo "key length: " & keyLengthInBytes & " bytes"\nWScript.echo "key length: " & (keyLengthInBytes*8) & " bits"\nWScript.echo "plaintext: " & plaintext\nWScript.echo "plaintext.length: " & Len(plaintext)\n\nWScript.echo "instantiate Ionic.Com.SlowAES"\nDim aes\nset aes = CreateObject("Ionic.Com.SlowAES")\n\nWScript.echo "keysize"\naes.KeySize = keyLengthInBytes * 8\n\nWScript.echo "key"\naes.Key = byteArrayToHexString(key)\n\nWScript.echo "iv "\naes.IV= byteArrayToHexString(iv)\n\nWScript.echo "mode "\naes.Mode = "CBC"\n\nWScript.echo "encrypting... "\nDim result\nresult= aes.EncryptString(plaintext)\n\n' result is a comma-separated string '\n' if we Eval() on it we convert it to an array '\nDim expr\nexpr = "Array(" & result & ")" \n\nresult= Eval( expr )\n\nWScript.echo "Cryptotext/Eval: " & byteArrayToHexString(result)\nWScript.echo "Cryptotext.length: " & UBound(result)+1\n\nWScript.echo "decrypting... "\nDim decrypted\n'The javascript way to do this is to pass the byte array.'\n' Like so:'\n' var decrypted = aes.DecryptBytesToString(result);'\n' '\n'This does not work from VBScript. So, convert to a hexstring,'\n'pass the hex string, and then convert back, in the COM component.'\ndecrypted= aes.DecryptHexString(byteArrayToHexString(result))\n\nWScript.echo "decrypted: " & decrypted\nEnd Function\n\ndim plaintext, iv, key, keyLengthInBytes\n\nplaintext= "Hello. This is a test. of the emergency broadcasting system."\n' iv must be a hexstring representation of an array of bytes, length=16'\niv = hexStringToByteArray("feedbeeffeedbeefbaadf00dbaadf00d")\n' key must be a hexstring representation of an array of bytes, length=16 or 32'\nkey = hexStringToByteArray("cafebabe0099887766554433221100AA")\nkeyLengthInBytes= UBound(key)+1\n\nIf Err.Number <> 0 Then Err.Clear\n\nCall DemoEncryption\n\nIf (Err.Number <> 0) Then WScript.echo("Error: " & Err.Description)\n</code></pre>\n<p>If you also want a password-based key derivation capability, then you can grab <a href=\"http://anandam.name/pbkdf2/\" rel=\"nofollow noreferrer\">the very succint JavaScript code for PBKDF2 here</a>, and <a href=\"http://cheeso.members.winisp.net/srcview.aspx?dir=AES-example&file=Ionic.Com.PBKDF2.wsc\" rel=\"nofollow noreferrer\">create another WSC for that</a>, without too much trouble.</p>\n<hr />\n<p><strong>EDIT</strong>: I did what I described - grabbed the source for PBKDF2 and integrated it into the code for SlowAES. I also produced a second, independent implementation in C# that uses the built-in .NET class libraries to do the RFC 2898-key derivation and AES encryption.</p>\n<p>The result is 3 test applications, one in C#, one in JavaScript and another in VBScript. <a href=\"http://cheeso.members.winisp.net/srcview.aspx?dir=AES-example\" rel=\"nofollow noreferrer\">The source is available</a>. They all take the same set of arguments. They each use a <a href=\"https://www.rfc-editor.org/rfc/rfc2898\" rel=\"nofollow noreferrer\">RFC 2898</a>-compliant key derivation function. You can specify the password, <a href=\"http://en.wikipedia.org/wiki/Salt_%28cryptography%29\" rel=\"nofollow noreferrer\">salt</a>, <a href=\"http://en.wikipedia.org/wiki/Initialization_vector\" rel=\"nofollow noreferrer\">IV</a>, and plaintext, as well as the number of RFC 2898 iterations to use in the <a href=\"http://en.wikipedia.org/wiki/PBKDF2\" rel=\"nofollow noreferrer\">PBKDF2</a>. You can easily verify that the ciphertext is the same for each of these test programs. Maybe this example will be useful for someone.</p>\n"
},
{
"answer_id": 28129895,
"author": "Grnd Xhef",
"author_id": 4490604,
"author_profile": "https://Stackoverflow.com/users/4490604",
"pm_score": 3,
"selected": false,
"text": "<p>One way is to declare encryption classes within vbscript, without needing external added COM objects or wrapper. The following example takes a string, encrypts and decrypts using Rijndael managed class:</p>\n\n<pre><code>'-----------------------------------------------------\nDim obj,arr,i,r,str,enc,asc\ndim bytes,bytesd,s,sc,sd\nset obj=WScript.CreateObject(\"System.Security.Cryptography.RijndaelManaged\")\nSet asc = CreateObject(\"System.Text.UTF8Encoding\")\ns=\"This is a private message\"\nbytes=asc.GetBytes_4(s)\nobj.GenerateKey()\nobj.GenerateIV()\nset enc=obj.CreateEncryptor()\nset dec=obj.CreateDecryptor()\n\nbytec=enc.TransformFinalBlock((bytes),0,lenb(bytes))\nsc=asc.GetString((bytec))\nmsgbox sc\n\nbyted=dec.TransformFinalBlock((bytec),0,lenb(bytec))\nsd=asc.GetString((byted))\nmsgbox sd\n'-----------------------------------------------------\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270510",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am looking to encrypt some data using [Rijndael/AES](http://en.wikipedia.org/wiki/Advanced_Encryption_Standard) in [VBScript](http://en.wikipedia.org/wiki/VBScript) using a specific key and [IV](http://en.wikipedia.org/wiki/Initialization_vector) value. Are there any good function libraries or COM components that would be good to use?
I looked at [CAPICOM](http://en.wikipedia.org/wiki/CAPICOM); it allows a passphrase only, and won't allow setting specific key and IV values.
|
One way is to declare encryption classes within vbscript, without needing external added COM objects or wrapper. The following example takes a string, encrypts and decrypts using Rijndael managed class:
```
'-----------------------------------------------------
Dim obj,arr,i,r,str,enc,asc
dim bytes,bytesd,s,sc,sd
set obj=WScript.CreateObject("System.Security.Cryptography.RijndaelManaged")
Set asc = CreateObject("System.Text.UTF8Encoding")
s="This is a private message"
bytes=asc.GetBytes_4(s)
obj.GenerateKey()
obj.GenerateIV()
set enc=obj.CreateEncryptor()
set dec=obj.CreateDecryptor()
bytec=enc.TransformFinalBlock((bytes),0,lenb(bytes))
sc=asc.GetString((bytec))
msgbox sc
byted=dec.TransformFinalBlock((bytec),0,lenb(bytec))
sd=asc.GetString((byted))
msgbox sd
'-----------------------------------------------------
```
|
270,531 |
<p>I've got an arbitrary list of .NET assemblies.</p>
<p>I need to programmatically check if each DLL was built for x86 (as opposed to x64 or Any CPU). Is this possible?</p>
|
[
{
"answer_id": 270545,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 8,
"selected": false,
"text": "<p>You can use the <a href=\"http://msdn.microsoft.com/en-us/library/ms164699%28v=vs.80%29.aspx\" rel=\"nofollow noreferrer\">CorFlags</a> <a href=\"http://en.wikipedia.org/wiki/Command-line_interface\" rel=\"nofollow noreferrer\">CLI</a> tool (for instance, C:\\Program Files\\Microsoft SDKs\\Windows\\v7.0\\Bin\\CorFlags.exe) to determine the status of an assembly, based on its output and opening an assembly as a binary asset you should be able to determine where you need to seek to determine if the 32BIT flag is set to 1 (<em>x86</em>) or 0 (<em>Any CPU</em> or <em>x64</em>, depending on <code>PE</code>):</p>\n<pre class=\"lang-none prettyprint-override\"><code>Option | PE | 32BIT\n----------|-------|---------\nx86 | PE32 | 1\nAny CPU | PE32 | 0\nx64 | PE32+ | 0\n</code></pre>\n<p>The blog post <em><a href=\"https://web.archive.org/web/20130424225355/http://theruntime.com/blogs/brianpeek/archive/2007/11/13/x64-development-with-net.aspx\" rel=\"nofollow noreferrer\">x64 Development with .NET</a></em> has some information about <code>corflags</code>.</p>\n<p>Even better, you can <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.module.getpekind(VS.80).aspx\" rel=\"nofollow noreferrer\">use <code>Module.GetPEKind</code></a> to determine whether an assembly is <code>PortableExecutableKinds</code> value <code>PE32Plus</code> (64-bit), <code>Required32Bit</code> (32-bit and <a href=\"https://en.wikipedia.org/wiki/Windows_on_Windows\" rel=\"nofollow noreferrer\">WoW</a>), or <code>ILOnly</code> (any CPU) along with other attributes.</p>\n"
},
{
"answer_id": 270549,
"author": "x0n",
"author_id": 6920,
"author_profile": "https://Stackoverflow.com/users/6920",
"pm_score": 9,
"selected": true,
"text": "<p>Look at <code>System.Reflection.AssemblyName.GetAssemblyName(string assemblyFile)</code>.</p>\n<p>You can examine assembly metadata from the returned AssemblyName instance:</p>\n<p>Using <strong>PowerShell</strong>:</p>\n<pre>\n[36] C:\\> [reflection.assemblyname]::GetAssemblyName(\"${pwd}\\Microsoft.GLEE.dll\") | fl\n\nName : Microsoft.GLEE\nVersion : 1.0.0.0\nCultureInfo :\nCodeBase : file:///C:/projects/powershell/BuildAnalyzer/...\nEscapedCodeBase : file:///C:/projects/powershell/BuildAnalyzer/...\n<b>ProcessorArchitecture : MSIL</b>\nFlags : PublicKey\nHashAlgorithm : SHA1\nVersionCompatibility : SameMachine\nKeyPair :\nFullName : Microsoft.GLEE, Version=1.0.0.0, Culture=neut...\n</pre>\n<p>Here, <a href=\"http://msdn.microsoft.com/library/system.reflection.processorarchitecture\" rel=\"noreferrer\">ProcessorArchitecture</a> identifies the target platform.</p>\n<ul>\n<li><strong>Amd64</strong>: A 64-bit processor based on the x64 architecture.</li>\n<li><strong>Arm</strong>: An ARM processor.</li>\n<li><strong>IA64</strong>: A 64-bit Intel <a href=\"https://en.wikipedia.org/wiki/Itanium\" rel=\"noreferrer\">Itanium</a> processor only.</li>\n<li><strong>MSIL</strong>: Neutral with respect to processor and bits-per-word.</li>\n<li><strong>X86</strong>: A 32-bit Intel processor, either native or in the Windows on Windows environment on a 64-bit platform (<a href=\"https://en.wikipedia.org/wiki/WoW64\" rel=\"noreferrer\">WoW64</a>).</li>\n<li><strong>None</strong>: An unknown or unspecified combination of processor and bits-per-word.</li>\n</ul>\n<p>I'm using PowerShell in this example to call the method.</p>\n"
},
{
"answer_id": 1002800,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 7,
"selected": false,
"text": "<p>Just for clarification, CorFlags.exe is part of the <a href=\"http://en.wikipedia.org/wiki/Microsoft_Windows_SDK\" rel=\"nofollow noreferrer\">.NET Framework SDK</a>. I have the development tools on my machine, and the simplest way for me determine whether a DLL is 32-bit only is to:</p>\n<ol>\n<li><p>Open the Visual Studio Command Prompt (In Windows: menu Start/Programs/Microsoft Visual Studio/Visual Studio Tools/Visual Studio 2008 Command Prompt)</p>\n</li>\n<li><p>CD to the directory containing the DLL in question</p>\n</li>\n<li><p>Run corflags like this:\n<code>corflags MyAssembly.dll</code></p>\n</li>\n</ol>\n<p>You will get output something like this:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8\nCopyright (c) Microsoft Corporation. All rights reserved.\n\nVersion : v2.0.50727\nCLR Header: 2.5\nPE : PE32\nCorFlags : 3\nILONLY : 1\n32BIT : 1\nSigned : 0\n</code></pre>\n<p>As per comments the flags above are to be read as following:</p>\n<ul>\n<li>Any CPU: PE = PE32 and 32BIT = 0</li>\n<li>x86: PE = PE32 and 32BIT = 1</li>\n<li>64-bit: PE = PE32+ and 32BIT = 0</li>\n</ul>\n"
},
{
"answer_id": 6937975,
"author": "jdearana",
"author_id": 207949,
"author_profile": "https://Stackoverflow.com/users/207949",
"pm_score": 1,
"selected": false,
"text": "<p>Another way to check the target platform of a .NET assembly is inspecting the assembly with <a href=\"http://en.wikipedia.org/wiki/.NET_Reflector\" rel=\"nofollow\">.NET Reflector</a>...</p>\n\n<p>@#~#€~! I've just realized that the new version is not free! So, correction, if you have a free version of .NET reflector, you can use it to check the target platform. </p>\n"
},
{
"answer_id": 9767750,
"author": "Jason",
"author_id": 1278235,
"author_profile": "https://Stackoverflow.com/users/1278235",
"pm_score": 5,
"selected": false,
"text": "<p>Just write your own. The core of the PE architecture hasn't been seriously changed since its implementation in <a href=\"https://en.wikipedia.org/wiki/Windows_95\" rel=\"nofollow noreferrer\">Windows 95</a>.</p>\n<p>Here's a C# example:</p>\n<pre><code> public static ushort GetPEArchitecture(string pFilePath)\n {\n ushort architecture = 0;\n try\n {\n using (System.IO.FileStream fStream = new System.IO.FileStream(pFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read))\n {\n using (System.IO.BinaryReader bReader = new System.IO.BinaryReader(fStream))\n {\n // Check the MZ signature\n if (bReader.ReadUInt16() == 23117)\n {\n // Seek to e_lfanew.\n fStream.Seek(0x3A, System.IO.SeekOrigin.Current);\n\n // Seek to the start of the NT header.\n fStream.Seek(bReader.ReadUInt32(), System.IO.SeekOrigin.Begin);\n\n if (bReader.ReadUInt32() == 17744) // Check the PE\\0\\0 signature.\n {\n // Seek past the file header,\n fStream.Seek(20, System.IO.SeekOrigin.Current);\n\n // Read the magic number of the optional header.\n architecture = bReader.ReadUInt16();\n }\n }\n }\n }\n }\n catch (Exception) { /* TODO: Any exception handling you want\n to do, personally I just take 0\n as a sign of failure */\n }\n\n // If architecture returns 0, there has been an error.\n return architecture;\n }\n}\n</code></pre>\n<p>Now the current constants are:</p>\n<pre class=\"lang-none prettyprint-override\"><code>0x10B - PE32 format.\n0x20B - PE32+ format.\n</code></pre>\n<p>But with this method it allows for the possibilities of new constants. Just validate the return as you see fit.</p>\n"
},
{
"answer_id": 14936673,
"author": "Ludwo",
"author_id": 990170,
"author_profile": "https://Stackoverflow.com/users/990170",
"pm_score": 3,
"selected": false,
"text": "<p>Try to use CorFlagsReader <a href=\"http://apichange.codeplex.com/SourceControl/changeset/view/76c98b8c7311#ApiChange.Api/src/Introspection/CorFlagsReader.cs\" rel=\"noreferrer\">from this project at CodePlex</a>. It has no references to other assemblies and it can be used as is.</p>\n"
},
{
"answer_id": 16181822,
"author": "Chris",
"author_id": 64257,
"author_profile": "https://Stackoverflow.com/users/64257",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/270531/how-can-i-determine-if-a-net-assembly-was-built-for-x86-or-x64/270545#270545\">cfeduke notes</a> the possibility of calling GetPEKind. It's potentially interesting to do this from PowerShell.</p>\n<p>Here, for example, is code for a cmdlet that could be used: <a href=\"https://stackoverflow.com/a/16181743/64257\">https://stackoverflow.com/a/16181743/64257</a></p>\n<p>Alternatively, at <a href=\"https://stackoverflow.com/a/4719567/64257\">https://stackoverflow.com/a/4719567/64257</a> it is noted that "there's also the Get-PEHeader cmdlet in the <a href=\"http://pscx.codeplex.com/\" rel=\"nofollow noreferrer\">PowerShell Community Extensions</a> that can be used to test for executable images."</p>\n"
},
{
"answer_id": 19035620,
"author": "Morgan Mellor",
"author_id": 2820702,
"author_profile": "https://Stackoverflow.com/users/2820702",
"pm_score": 3,
"selected": false,
"text": "<pre><code>[TestMethod]\npublic void EnsureKWLLibrariesAreAll64Bit()\n{\n var assemblies = Assembly.GetExecutingAssembly().GetReferencedAssemblies().Where(x => x.FullName.StartsWith(\"YourCommonProjectName\")).ToArray();\n foreach (var assembly in assemblies)\n {\n var myAssemblyName = AssemblyName.GetAssemblyName(assembly.FullName.Split(',')[0] + \".dll\");\n Assert.AreEqual(ProcessorArchitecture.MSIL, myAssemblyName.ProcessorArchitecture);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36316170,
"author": "Eric Lease",
"author_id": 4342563,
"author_profile": "https://Stackoverflow.com/users/4342563",
"pm_score": 3,
"selected": false,
"text": "<p>Below is a batch file that will run <em>corflags.exe</em> against all DLL files and EXE files in the current working directory and all sub-directories, parse the results and display the target architecture of each.</p>\n<p>Depending on the version of <em>corflags.exe</em> that is used, the line items in the output will either include <em>32BIT</em>, <em><strong>or</strong></em> <em>32BITREQ</em> (and <em>32BITPREF</em>). Whichever of these two is included in the output is the critical line item that must be checked to differentiate between <em>Any CPU</em> and <em>x86</em>. If you are using an older version of <em>corflags.exe</em> (pre <a href=\"https://en.wikipedia.org/wiki/Microsoft_Windows_SDK\" rel=\"nofollow noreferrer\">Windows SDK</a> v8.0A), then only the <em>32BIT</em> line item will be present in the output, as others have indicated in past answers. Otherwise <em>32BITREQ</em> and <em>32BITPREF</em> replace it.</p>\n<p>This assumes <em>corflags.exe</em> is in the <em>%PATH%</em>. The simplest way to ensure this is to use a <em>Developer Command Prompt</em>. Alternatively you could copy it from its <a href=\"https://stackoverflow.com/a/4450356/4342563\">default location</a>.</p>\n<p>If the batch file below is run against an unmanaged DLL or EXE file, it will incorrectly display it as <em>x86</em>, since the actual output from <em>Corflags.exe</em> will be an error message similar to:</p>\n<blockquote>\n<p>corflags : error CF008 : The specified file does not have a valid managed header</p>\n</blockquote>\n<pre class=\"lang-none prettyprint-override\"><code>@echo off\n\necho.\necho Target architecture for all exes and dlls:\necho.\n\nREM For each exe and dll in this directory and all subdirectories...\nfor %%a in (.exe, .dll) do forfiles /s /m *%%a /c "cmd /c echo @relpath" > testfiles.txt\n\nfor /f %%b in (testfiles.txt) do (\n REM Dump corflags results to a text file\n corflags /nologo %%b > corflagsdeets.txt\n\n REM Parse the corflags results to look for key markers\n findstr /C:"PE32+">nul .\\corflagsdeets.txt && (\n REM `PE32+` indicates x64\n echo %%~b = x64\n ) || (\n REM pre-v8 Windows SDK listed only "32BIT" line item,\n REM newer versions list "32BITREQ" and "32BITPREF" line items\n findstr /C:"32BITREQ : 0">nul /C:"32BIT : 0" .\\corflagsdeets.txt && (\n REM `PE32` and NOT 32bit required indicates Any CPU\n echo %%~b = Any CPU\n ) || (\n REM `PE32` and 32bit required indicates x86\n echo %%~b = x86\n )\n )\n\n del corflagsdeets.txt\n)\n\ndel testfiles.txt\necho.\n</code></pre>\n"
},
{
"answer_id": 39852004,
"author": "Wernfried Domscheit",
"author_id": 3027266,
"author_profile": "https://Stackoverflow.com/users/3027266",
"pm_score": 1,
"selected": false,
"text": "<p>A tool is <a href=\"https://learn.microsoft.com/en-us/sysinternals/downloads/sigcheck\" rel=\"nofollow noreferrer\">sigcheck</a>:</p>\n<pre class=\"lang-none prettyprint-override\"><code>sigcheck c:\\Windows\\winhlp32.exe\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>Sigcheck v2.71 - File version and signature viewer\nCopyright (C) 2004-2018 Mark Russinovich\nSysinternals - www.sysinternals.com\n\nc:\\windows\\winhlp32.exe:\n Verified: Signed\n Signing date: 20:05 02.05.2022\n Publisher: Microsoft Windows\n Company: Microsoft Corporation\n Description: Windows Winhlp32 Stub\n Product: Microsoft® Windows® Operating System\n Prod version: 10.0.19041.1\n File version: 10.0.19041.1 (WinBuild.160101.0800)\n MachineType: 32-bit\n</code></pre>\n<hr/>\n<pre class=\"lang-none prettyprint-override\"><code>sigcheck -nobanner c:\\Windows\\HelpPane.exe\n</code></pre>\n<p>Output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>c:\\windows\\HelpPane.exe:\n Verified: Signed\n Signing date: 00:42 23.04.2022\n Publisher: Microsoft Windows\n Company: Microsoft Corporation\n Description: Microsoft Help and Support\n Product: Microsoft® Windows® Operating System\n Prod version: 10.0.19041.1151\n File version: 10.0.19041.1151 (WinBuild.160101.0800)\n MachineType: 64-bit\n</code></pre>\n"
},
{
"answer_id": 45365087,
"author": "Ayush joshi",
"author_id": 2594972,
"author_profile": "https://Stackoverflow.com/users/2594972",
"pm_score": 2,
"selected": false,
"text": "<p>One more way would be to use <em>dumpbin</em> from the Visual Studio tools on the DLL and look for the appropriate output:</p>\n<pre class=\"lang-none prettyprint-override\"><code>dumpbin.exe /HEADERS <your DLL file path>\n FILE HEADER VALUE\n 14C machine (x86)\n 4 number of sections\n 5885AC36 time date stamp Mon Jan 23 12:39:42 2017\n 0 file pointer to symbol table\n 0 number of symbols\n E0 size of optional header\n 2102 characteristics\n Executable\n 32 bit word machine\n DLL\n</code></pre>\n<p>Note: The above output is for a 32-bit DLL file</p>\n<p>One more useful option with <em>dumpbin.exe</em> is /EXPORTS. It will show you the function exposed by the DLL file</p>\n<pre class=\"lang-none prettyprint-override\"><code>dumpbin.exe /EXPORTS <PATH OF THE DLL FILE>\n</code></pre>\n"
},
{
"answer_id": 45811291,
"author": "Prabhakaran Rajagopal",
"author_id": 5092574,
"author_profile": "https://Stackoverflow.com/users/5092574",
"pm_score": 4,
"selected": false,
"text": "<p>DotPeek from <a href=\"https://en.wikipedia.org/wiki/JetBrains\" rel=\"noreferrer\">JetBrains</a> provides a quick and easy way to see <em>msil</em> (Any CPU), x86, and x64:</p>\n<p><a href=\"https://i.stack.imgur.com/KYHkA.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/KYHkA.png\" alt=\"DotPeek\" /></a></p>\n"
},
{
"answer_id": 49516509,
"author": "BlackGad",
"author_id": 2310482,
"author_profile": "https://Stackoverflow.com/users/2310482",
"pm_score": 2,
"selected": false,
"text": "<p>A more generic way - use the file structure to determine bitness and image type:</p>\n<pre><code>public static CompilationMode GetCompilationMode(this FileInfo info)\n{\n if (!info.Exists)\n throw new ArgumentException($"{info.FullName} does not exist");\n\n var intPtr = IntPtr.Zero;\n try\n {\n uint unmanagedBufferSize = 4096;\n intPtr = Marshal.AllocHGlobal((int)unmanagedBufferSize);\n\n using (var stream = File.Open(info.FullName, FileMode.Open, FileAccess.Read))\n {\n var bytes = new byte[unmanagedBufferSize];\n stream.Read(bytes, 0, bytes.Length);\n Marshal.Copy(bytes, 0, intPtr, bytes.Length);\n }\n\n // Check DOS header magic number\n if (Marshal.ReadInt16(intPtr) != 0x5a4d)\n return CompilationMode.Invalid;\n\n // This will get the address for the WinNT header\n var ntHeaderAddressOffset = Marshal.ReadInt32(intPtr + 60);\n\n // Check WinNT header signature\n var signature = Marshal.ReadInt32(intPtr + ntHeaderAddressOffset);\n if (signature != 0x4550)\n return CompilationMode.Invalid;\n\n // Determine file bitness by reading magic from IMAGE_OPTIONAL_HEADER\n var magic = Marshal.ReadInt16(intPtr + ntHeaderAddressOffset + 24);\n\n var result = CompilationMode.Invalid;\n uint clrHeaderSize;\n if (magic == 0x10b)\n {\n clrHeaderSize = (uint)Marshal.ReadInt32(intPtr + ntHeaderAddressOffset + 24 + 208 + 4);\n result |= CompilationMode.Bit32;\n }\n else if (magic == 0x20b)\n {\n clrHeaderSize = (uint)Marshal.ReadInt32(intPtr + ntHeaderAddressOffset + 24 + 224 + 4);\n result |= CompilationMode.Bit64;\n }\n else return CompilationMode.Invalid;\n\n result |= clrHeaderSize != 0\n ? CompilationMode.CLR\n : CompilationMode.Native;\n\n return result;\n }\n finally\n {\n if (intPtr != IntPtr.Zero)\n Marshal.FreeHGlobal(intPtr);\n }\n}\n</code></pre>\n<p>Compilation mode enumeration</p>\n<pre class=\"lang-none prettyprint-override\"><code>[Flags]\npublic enum CompilationMode\n{\n Invalid = 0,\n Native = 0x1,\n CLR = Native << 1,\n Bit32 = CLR << 1,\n Bit64 = Bit32 << 1\n}\n</code></pre>\n<p>Source code with explanation is <a href=\"https://github.com/BlackGad/PS.FileStructureAnalyzer\" rel=\"nofollow noreferrer\">at GitHub</a>.</p>\n"
},
{
"answer_id": 51911353,
"author": "thalm",
"author_id": 355485,
"author_profile": "https://Stackoverflow.com/users/355485",
"pm_score": 2,
"selected": false,
"text": "<p>I've cloned a super handy tool that adds a context menu entry for assemblies in <a href=\"https://en.wikipedia.org/wiki/File_Explorer\" rel=\"nofollow noreferrer\">Windows Explorer</a> to show all available information:</p>\n<p>Download from <em><a href=\"https://github.com/tebjan/AssemblyInformation/releases\" rel=\"nofollow noreferrer\">Releases · tebjan/AssemblyInformation</a></em>.</p>\n<p><a href=\"https://i.stack.imgur.com/EwVii.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/EwVii.png\" alt=\"Enter image description here\" /></a></p>\n"
},
{
"answer_id": 61889953,
"author": "Alexei - check Codidact",
"author_id": 2780791,
"author_profile": "https://Stackoverflow.com/users/2780791",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to already mentioned tools is <a href=\"https://www.telerik.com/products/decompiler.aspx\" rel=\"nofollow noreferrer\">Telerik JustDecompile</a> (free tool) which will display the information next to the assembly name:</p>\n\n<p><a href=\"https://i.stack.imgur.com/41Igu.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/41Igu.png\" alt=\"Any or x86 or x64 information in Telerik\"></a></p>\n"
},
{
"answer_id": 67100044,
"author": "Maxim",
"author_id": 3137536,
"author_profile": "https://Stackoverflow.com/users/3137536",
"pm_score": 0,
"selected": false,
"text": "<p>I like the <a href=\"https://github.com/icsharpcode/ILSpy\" rel=\"nofollow noreferrer\">ILSpy</a> tool. It shows not only architecture, but the target framework as well:</p>\n<pre><code>// linq2db, Version=3.0.0.0, Culture=neutral, PublicKeyToken=e41013125f9e410a\n// Global type: <Module>\n// Architecture: AnyCPU (64-bit preferred)\n// Runtime: v4.0.30319\n// This assembly is signed with a strong name key.\n// This assembly was compiled using the /deterministic option.\n// Hash algorithm: SHA1\n</code></pre>\n<p>So it is possible to determine if it is <a href=\"https://en.wikipedia.org/wiki/.NET_Core\" rel=\"nofollow noreferrer\">.NET Core</a> 2.1, .NET Framework 4.6 or any other one:</p>\n<p><a href=\"https://i.stack.imgur.com/43LFa.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/43LFa.png\" alt=\"Target framework\" /></a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/536/"
] |
I've got an arbitrary list of .NET assemblies.
I need to programmatically check if each DLL was built for x86 (as opposed to x64 or Any CPU). Is this possible?
|
Look at `System.Reflection.AssemblyName.GetAssemblyName(string assemblyFile)`.
You can examine assembly metadata from the returned AssemblyName instance:
Using **PowerShell**:
```
[36] C:\> [reflection.assemblyname]::GetAssemblyName("${pwd}\Microsoft.GLEE.dll") | fl
Name : Microsoft.GLEE
Version : 1.0.0.0
CultureInfo :
CodeBase : file:///C:/projects/powershell/BuildAnalyzer/...
EscapedCodeBase : file:///C:/projects/powershell/BuildAnalyzer/...
**ProcessorArchitecture : MSIL**
Flags : PublicKey
HashAlgorithm : SHA1
VersionCompatibility : SameMachine
KeyPair :
FullName : Microsoft.GLEE, Version=1.0.0.0, Culture=neut...
```
Here, [ProcessorArchitecture](http://msdn.microsoft.com/library/system.reflection.processorarchitecture) identifies the target platform.
* **Amd64**: A 64-bit processor based on the x64 architecture.
* **Arm**: An ARM processor.
* **IA64**: A 64-bit Intel [Itanium](https://en.wikipedia.org/wiki/Itanium) processor only.
* **MSIL**: Neutral with respect to processor and bits-per-word.
* **X86**: A 32-bit Intel processor, either native or in the Windows on Windows environment on a 64-bit platform ([WoW64](https://en.wikipedia.org/wiki/WoW64)).
* **None**: An unknown or unspecified combination of processor and bits-per-word.
I'm using PowerShell in this example to call the method.
|
270,541 |
<p>What algorithms could i use to determine common characters in a set of strings?</p>
<p>To make the example simple, I only care about 2+ characters in a row and if it shows up in 2 or more of the sample. For instance:</p>
<ol>
<li>0000abcde0000 </li>
<li>0000abcd00000 </li>
<li>000abc0000000</li>
<li>00abc000de000</li>
</ol>
<p>I'd like to know:</p>
<p>00 was used in 1,2,3,4<br>
000 was used in 1,2,3,4<br>
0000 was used in 1,2,3<br>
00000 was used in 2,3<br>
ab was used in 1,2,3,4<br>
abc was used in 1,2,3,4<br>
abcd was used in 1,2<br>
bc was used in 1,2,3,4<br>
bcd was used in 1,2<br>
cd was used in 1,2<br>
de was used in 1,4 </p>
|
[
{
"answer_id": 270563,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 0,
"selected": false,
"text": "<p>you can use an analysis of distance matrix. Any diagonal movement (no cost change) is an exact match.</p>\n"
},
{
"answer_id": 270568,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>This is most probably an NP-hard problem. It looks similar to <a href=\"http://en.wikipedia.org/wiki/Sequence_alignment\" rel=\"nofollow noreferrer\">multiple sequence alignment</a>, which is. Basically, you could adapt multidimensional <a href=\"http://en.wikipedia.org/wiki/Smith-Waterman\" rel=\"nofollow noreferrer\">Smith-Waterman</a> (= local sequence alignment) for your needs. There might be a more efficient algorithm, though.</p>\n"
},
{
"answer_id": 270571,
"author": "LarryF",
"author_id": 18518,
"author_profile": "https://Stackoverflow.com/users/18518",
"pm_score": 1,
"selected": false,
"text": "<p>Do you know the \"values\" you need to search for ahead of time? Or do you need code to parse the strings, and give you stats like you posted?</p>\n\n<p>Using the Boyer-Moore algorithm is a very quick way to tell if substrings exist (and even locate them), if you know what you are looking for ahead of time.</p>\n"
},
{
"answer_id": 270638,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": 2,
"selected": false,
"text": "<p>Build a tree where the path through the tree is the letter sequence. Have each node contain a \"set\" that the string references are added to in passing (or just keep a count). Then keep track of N locations in the word where N is the longest sequence you care about (e.g., start a new handle at each char walking all handles down at each step and abort each handle after N steps)</p>\n\n<p>This would work better with a small, finite and dense alphabet (DNA was the first place I thought to use it).</p>\n\n<p><em>Edit:</em> If you known in advance the pattern you care about, the above can be altered to work by building the tree ahead of time and then only checking to see if you are on the tree rather than extending it.</p>\n\n<p>an example</p>\n\n<p>input</p>\n\n<pre><code>abc\nabd\nabde\nacc\nbde\n</code></pre>\n\n<p>the tree</p>\n\n<pre><code>a : 4\n b : 3\n c : 1\n d : 2\n e : 1\n c : 1\n c : 1\nb : 4\n d : 3\n e : 2\n c : 1\nc : 3\n c : 1\nd : 3\n e : 2\n</code></pre>\n"
},
{
"answer_id": 270880,
"author": "joel.neely",
"author_id": 3525,
"author_profile": "https://Stackoverflow.com/users/3525",
"pm_score": 3,
"selected": true,
"text": "<p>I'm assuming that this is not homework. (If it is, you're one your own re plagiarism! ;-)</p>\n\n<p>Below is a quick-and-dirty solution. The time complexity is <code>O(m**2 * n)</code> where <code>m</code> is the average string length and <code>n</code> is the size of the array of strings.</p>\n\n<p>An instance of <code>Occurrence</code> keeps the set of indices which contain a given string. The <code>commonOccurrences</code> routine scans a string array, calling <code>captureOccurrences</code> for each non-null string. The <code>captureOccurrences</code> routine puts the current index into an <code>Occurrence</code> for each possible substring of the string it is given. Finally, <code>commonOccurrences</code> forms the result set by picking only those <code>Occurrences</code> that have at least two indices.</p>\n\n<p>Note that your example data has many more common substrings than you identified in the question. For example, <code>\"00ab\"</code> occurs in each of the input strings. An additional filter to select interesting strings based on content (e.g. all digits, all alphabetic, etc.) is -- as they say -- left as an exercise for the reader. ;-)</p>\n\n<p>QUICK AND DIRTY JAVA SOURCE:</p>\n\n<pre><code>package com.stackoverflow.answers;\n\nimport java.util.Collections;\nimport java.util.HashMap;\nimport java.util.Map;\nimport java.util.Set;\nimport java.util.TreeSet;\n\npublic class CommonSubstringFinder {\n\n public static final int MINIMUM_SUBSTRING_LENGTH = 2;\n\n public static class Occurrence implements Comparable<Occurrence> {\n private final String value;\n private final Set<Integer> indices;\n public Occurrence(String value) {\n this.value = value == null ? \"\" : value;\n indices = new TreeSet<Integer>();\n }\n public String getValue() {\n return value;\n }\n public Set<Integer> getIndices() {\n return Collections.unmodifiableSet(indices);\n }\n public void occur(int index) {\n indices.add(index);\n }\n public String toString() {\n StringBuilder result = new StringBuilder();\n result.append('\"').append(value).append('\"');\n String separator = \": \";\n for (Integer i : indices) {\n result.append(separator).append(i);\n separator = \",\";\n }\n return result.toString();\n }\n public int compareTo(Occurrence that) {\n return this.value.compareTo(that.value);\n }\n }\n\n public static Set<Occurrence> commonOccurrences(String[] strings) {\n Map<String,Occurrence> work = new HashMap<String,Occurrence>();\n if (strings != null) {\n int index = 0;\n for (String string : strings) {\n if (string != null) {\n captureOccurrences(index, work, string);\n }\n ++index;\n }\n }\n Set<Occurrence> result = new TreeSet<Occurrence>();\n for (Occurrence occurrence : work.values()) {\n if (occurrence.indices.size() > 1) {\n result.add(occurrence);\n }\n }\n return result;\n }\n\n private static void captureOccurrences(int index, Map<String,Occurrence> work, String string) {\n final int maxLength = string.length();\n for (int i = 0; i < maxLength; ++i) {\n for (int j = i + MINIMUM_SUBSTRING_LENGTH; j < maxLength; ++j) {\n String partial = string.substring(i, j);\n Occurrence current = work.get(partial);\n if (current == null) {\n current = new Occurrence(partial);\n work.put(partial, current);\n }\n current.occur(index);\n }\n }\n }\n\n private static final String[] TEST_DATA = {\n \"0000abcde0000\",\n \"0000abcd00000\",\n \"000abc0000000\",\n \"00abc000de000\",\n };\n public static void main(String[] args) {\n Set<Occurrence> found = commonOccurrences(TEST_DATA);\n for (Occurrence occurrence : found) {\n System.out.println(occurrence);\n }\n }\n\n}\n</code></pre>\n\n<p>SAMPLE OUTPUT: (note that there was actually only one Occurrence per line; I can't seem to prevent the blockquote markup from merging lines)</p>\n\n<blockquote>\n <p>\"00\": 0,1,2,3\n \"000\": 0,1,2,3<br>\n \"0000\": 0,1,2\n \"0000a\": 0,1<br>\n \"0000ab\": 0,1\n \"0000abc\": 0,1<br>\n \"0000abcd\": 0,1\n \"000a\": 0,1,2<br>\n \"000ab\": 0,1,2\n \"000abc\": 0,1,2<br>\n \"000abcd\": 0,1\n \"00a\": 0,1,2,3<br>\n \"00ab\": 0,1,2,3\n \"00abc\": 0,1,2,3<br>\n \"00abc0\": 2,3\n \"00abc00\": 2,3<br>\n \"00abc000\": 2,3\n \"00abcd\": 0,1<br>\n \"0a\": 0,1,2,3\n \"0ab\": 0,1,2,3<br>\n \"0abc\": 0,1,2,3\n \"0abc0\": 2,3<br>\n \"0abc00\": 2,3\n \"0abc000\": 2,3<br>\n \"0abcd\": 0,1\n \"ab\": 0,1,2,3\n \"abc\": 0,1,2,3\n \"abc0\": 2,3\n \"abc00\": 2,3<br>\n \"abc000\": 2,3\n \"abcd\": 0,1\n \"bc\": 0,1,2,3\n \"bc0\": 2,3\n \"bc00\": 2,3<br>\n \"bc000\": 2,3\n \"bcd\": 0,1\n \"c0\": 2,3 \n \"c00\": 2,3\n \"c000\": 2,3\n \"cd\": 0,1<br>\n \"de\": 0,3\n \"de0\": 0,3\n \"de00\": 0,3<br>\n \"e0\": 0,3\n \"e00\": 0,3</p>\n</blockquote>\n"
},
{
"answer_id": 270902,
"author": "florin",
"author_id": 18308,
"author_profile": "https://Stackoverflow.com/users/18308",
"pm_score": 1,
"selected": false,
"text": "<p>Look up \"Suffix Trees\" on the web. Or pick up \"Algorithms on Strings, Trees and Sequences\" by Dan Gusfield. I don't have the book with me to verify, but the <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\" rel=\"nofollow noreferrer\">wikipedia page on suffix trees</a> says that page 205 contains a solution for your problem: \"finding the longest substrings common to at least k strings in a set\".</p>\n"
},
{
"answer_id": 271291,
"author": "Darius Bacon",
"author_id": 27024,
"author_profile": "https://Stackoverflow.com/users/27024",
"pm_score": 0,
"selected": false,
"text": "<p>You may find a <a href=\"http://en.wikipedia.org/wiki/Suffix_array\" rel=\"nofollow noreferrer\">suffix array</a> simpler and more efficient than a suffix tree, depending on how frequent common substrings are in your data -- if they're common enough, you'll need the more sophisticated suffix-array construction algorithm. (The naive method is to just use your library sort function.)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270541",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16794/"
] |
What algorithms could i use to determine common characters in a set of strings?
To make the example simple, I only care about 2+ characters in a row and if it shows up in 2 or more of the sample. For instance:
1. 0000abcde0000
2. 0000abcd00000
3. 000abc0000000
4. 00abc000de000
I'd like to know:
00 was used in 1,2,3,4
000 was used in 1,2,3,4
0000 was used in 1,2,3
00000 was used in 2,3
ab was used in 1,2,3,4
abc was used in 1,2,3,4
abcd was used in 1,2
bc was used in 1,2,3,4
bcd was used in 1,2
cd was used in 1,2
de was used in 1,4
|
I'm assuming that this is not homework. (If it is, you're one your own re plagiarism! ;-)
Below is a quick-and-dirty solution. The time complexity is `O(m**2 * n)` where `m` is the average string length and `n` is the size of the array of strings.
An instance of `Occurrence` keeps the set of indices which contain a given string. The `commonOccurrences` routine scans a string array, calling `captureOccurrences` for each non-null string. The `captureOccurrences` routine puts the current index into an `Occurrence` for each possible substring of the string it is given. Finally, `commonOccurrences` forms the result set by picking only those `Occurrences` that have at least two indices.
Note that your example data has many more common substrings than you identified in the question. For example, `"00ab"` occurs in each of the input strings. An additional filter to select interesting strings based on content (e.g. all digits, all alphabetic, etc.) is -- as they say -- left as an exercise for the reader. ;-)
QUICK AND DIRTY JAVA SOURCE:
```
package com.stackoverflow.answers;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
public class CommonSubstringFinder {
public static final int MINIMUM_SUBSTRING_LENGTH = 2;
public static class Occurrence implements Comparable<Occurrence> {
private final String value;
private final Set<Integer> indices;
public Occurrence(String value) {
this.value = value == null ? "" : value;
indices = new TreeSet<Integer>();
}
public String getValue() {
return value;
}
public Set<Integer> getIndices() {
return Collections.unmodifiableSet(indices);
}
public void occur(int index) {
indices.add(index);
}
public String toString() {
StringBuilder result = new StringBuilder();
result.append('"').append(value).append('"');
String separator = ": ";
for (Integer i : indices) {
result.append(separator).append(i);
separator = ",";
}
return result.toString();
}
public int compareTo(Occurrence that) {
return this.value.compareTo(that.value);
}
}
public static Set<Occurrence> commonOccurrences(String[] strings) {
Map<String,Occurrence> work = new HashMap<String,Occurrence>();
if (strings != null) {
int index = 0;
for (String string : strings) {
if (string != null) {
captureOccurrences(index, work, string);
}
++index;
}
}
Set<Occurrence> result = new TreeSet<Occurrence>();
for (Occurrence occurrence : work.values()) {
if (occurrence.indices.size() > 1) {
result.add(occurrence);
}
}
return result;
}
private static void captureOccurrences(int index, Map<String,Occurrence> work, String string) {
final int maxLength = string.length();
for (int i = 0; i < maxLength; ++i) {
for (int j = i + MINIMUM_SUBSTRING_LENGTH; j < maxLength; ++j) {
String partial = string.substring(i, j);
Occurrence current = work.get(partial);
if (current == null) {
current = new Occurrence(partial);
work.put(partial, current);
}
current.occur(index);
}
}
}
private static final String[] TEST_DATA = {
"0000abcde0000",
"0000abcd00000",
"000abc0000000",
"00abc000de000",
};
public static void main(String[] args) {
Set<Occurrence> found = commonOccurrences(TEST_DATA);
for (Occurrence occurrence : found) {
System.out.println(occurrence);
}
}
}
```
SAMPLE OUTPUT: (note that there was actually only one Occurrence per line; I can't seem to prevent the blockquote markup from merging lines)
>
> "00": 0,1,2,3
> "000": 0,1,2,3
>
> "0000": 0,1,2
> "0000a": 0,1
>
> "0000ab": 0,1
> "0000abc": 0,1
>
> "0000abcd": 0,1
> "000a": 0,1,2
>
> "000ab": 0,1,2
> "000abc": 0,1,2
>
> "000abcd": 0,1
> "00a": 0,1,2,3
>
> "00ab": 0,1,2,3
> "00abc": 0,1,2,3
>
> "00abc0": 2,3
> "00abc00": 2,3
>
> "00abc000": 2,3
> "00abcd": 0,1
>
> "0a": 0,1,2,3
> "0ab": 0,1,2,3
>
> "0abc": 0,1,2,3
> "0abc0": 2,3
>
> "0abc00": 2,3
> "0abc000": 2,3
>
> "0abcd": 0,1
> "ab": 0,1,2,3
> "abc": 0,1,2,3
> "abc0": 2,3
> "abc00": 2,3
>
> "abc000": 2,3
> "abcd": 0,1
> "bc": 0,1,2,3
> "bc0": 2,3
> "bc00": 2,3
>
> "bc000": 2,3
> "bcd": 0,1
> "c0": 2,3
> "c00": 2,3
> "c000": 2,3
> "cd": 0,1
>
> "de": 0,3
> "de0": 0,3
> "de00": 0,3
>
> "e0": 0,3
> "e00": 0,3
>
>
>
|
270,542 |
<p>I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of my functions check the input parameters upon entry, asserting if they are invalid, and it would be useful to test for this. For example:</p>
<pre><code>void MyFunction(int param)
{
assert(param > 0); // param cannot be less than 1
...
}
</code></pre>
<p>I would like to be able to do something like this:</p>
<pre><code>BOOST_CHECK_ASSERT(MyFunction(0), true);
BOOST_CHECK_ASSERT(MyFunction(-1), true);
BOOST_CHECK_ASSERT(MyFunction(1), false);
...
</code></pre>
<p>You can check for exceptions being thrown using Boost Test so I wondered if there was some assert magic too...</p>
|
[
{
"answer_id": 270704,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 4,
"selected": true,
"text": "<p>I don't think so. You could always write your own assert which throws an exception and then use BOOST_CHECK_NOTHROW() for that exception.</p>\n"
},
{
"answer_id": 270758,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 0,
"selected": false,
"text": "<p>Sorry, but you're attacking your problem the wrong way.</p>\n\n<p>\"assert\" is the spawn of the devil (a.k.a. \"C\") and is useless with any language that has proper exceptions. It's waaaaaay better to reimplement an assert-like functionality with exceptions. This way you actually get a chance of handling errors the right way (incl proper cleanup procedures) or triggering them at will (for unit testing).</p>\n\n<p>Besides, if your code ever runs in Windows, when you fail an assertion you get a useless popup offering you to debug/abort/retry. Nice for automated unit tests.</p>\n\n<p>So do yourself a favor and re-code an assert function that throws exceptions. There's one here:\n<a href=\"https://stackoverflow.com/questions/37473/how-can-i-assert-without-using-abort\">How can I assert() without using abort()?</a></p>\n\n<p>Wrap it in a macro so you get _ _FILE _ _ and _ _ LINE _ _ (useful for debug) and you're done.</p>\n"
},
{
"answer_id": 1150324,
"author": "legalize",
"author_id": 139855,
"author_profile": "https://Stackoverflow.com/users/139855",
"pm_score": 3,
"selected": false,
"text": "<p>There are two kinds of errors I like to check for: invariants and run-time errors. </p>\n\n<p>Invariants are things that should always be true, no matter what. For those, I use asserts. Things like you shouldn't be passing me a zero pointer for the output buffer you're giving me. That's a bug in the code, plain and simple. In a debug build, it will assert and give me a chance to correct it. In a retail build, it will cause an access violation and generate a minidump (Windows, at least in my code) or a coredump (Mac/unix). There's no <code>catch</code> that I can do that makes sense to deal with dereferencing a zero pointer. On Windows <code>catch (...)</code> can suppress access violations and give the user a false sense of confidence that things are OK when they've already gone horribly, horribly wrong.</p>\n\n<p>This is one reason why I've come to believe that <code>catch (...)</code> is generally a code smell in C++ and the only reasonable place where I can think of that being present is in <code>main</code> (or <code>WinMain</code>) right before you generate a core dump and politely exit the app.</p>\n\n<p>Run-time errors are things like \"I can't write this file because of permissions\" or \"I can't write this file because the disk is full\". For these sorts of errors throwing an exception makes sense because the user can do something about it like change the permission on a directory, delete some files or choose an alternate location to save the file. These run-time errors are correctable by the user. A violation of an invariant can't be corrected by the user, only by a programmer. (Sometimes the two are the same, but typically they aren't.)</p>\n\n<p>Your unit tests should force code to throw the run-time error exceptions that your code could generate. You might also want to force exceptions from your collaborators to ensure that your system under test is exception safe.</p>\n\n<p>However, I don't believe there is value in trying to force your code to assert against invariants with unit tests.</p>\n"
},
{
"answer_id": 1150669,
"author": "Vladimir Prus",
"author_id": 126517,
"author_profile": "https://Stackoverflow.com/users/126517",
"pm_score": 2,
"selected": false,
"text": "<p>I think this question, and some of replies, confuse run-time errors detection with bug detection. They also confuse intent and mechanism.</p>\n\n<p>Run-time error is something that can happen in a 100% correct program. It need detection, and it needs proper reporting and handling, and it should be tested. Bugs also happen, and for programmer's convenience it's better to catch them early using precondition checks or invariant checks or random assert. But this is programmer's tool. The error message will make no sense for ordinary user, and it does not seem reasonable to test function behaviour on the data that properly written program will never pass to it.</p>\n\n<p>As for intent and mechanism, it should be noted that exception is nothing magic. Some time ago, Peter Dimov said on Boost mailing list (approximately) that \"exceptions are just non-local jump mechanism\". And this is very true. If you have application where it's possible to continue after some internal error, without the risk that something will be corrupted before repair, you can implement custom assert that throws C++ exception. But it would not change the intent, and won't make testing for asserts much more reasonable.</p>\n"
},
{
"answer_id": 1772832,
"author": "Grafoid",
"author_id": 215570,
"author_profile": "https://Stackoverflow.com/users/215570",
"pm_score": 4,
"selected": false,
"text": "<p>Having the same problem, I digged through the documentation (and code) and\nfound a \"solution\".</p>\n\n<p>The Boost UTF uses <code>boost::execution_monitor</code> (in\n<code><boost/test/execution_monitor.hpp></code>). This is designed with the aim to catch\neverything that could happen during test execution. When an assert is found\nexecution_monitor intercepts it and throws <code>boost::execution_exception</code>. Thus,\nby using <code>BOOST_REQUIRE_THROW</code> you may assert the failure of an assert.</p>\n\n<p>so:</p>\n\n<pre><code>#include <boost/test/unit_test.hpp>\n#include <boost/test/execution_monitor.hpp> // for execution_exception\n\nBOOST_AUTO_TEST_CASE(case_1)\n{\n BOOST_REQUIRE_THROW(function_w_failing_assert(),\n boost::execution_exception);\n}\n</code></pre>\n\n<p>Should do the trick. (It works for me.)</p>\n\n<p>However (or disclaimers): </p>\n\n<ul>\n<li><p>It works for me. That is, on Windows XP, MSVC 7.1, boost 1.41.0. It might\nbe unsuitable or broken on your setup.</p></li>\n<li><p>It might not be the intention of the author of Boost Test.\n(although it seem to be the purpose of execution_monitor).</p></li>\n<li><p>It will treat every form of fatal error the same way. I e it could be\nthat something other than your assert is failing. In this case you \ncould miss e g a memory corruption bug, and/or miss a failed failed assert.</p></li>\n<li><p>It might break on future boost versions.</p></li>\n<li><p>I expect it would fail if run in Release config, since the assert will be\ndisabled and the code that the assert was set to prevent will\nrun. Resulting in very undefined behavior.</p></li>\n<li><p>If, in Release config for msvc, some assert-like or other fatal error\nwould occur anyway it would not be caught. (see execution_monitor docs).</p></li>\n<li><p>If you use assert or not is up to you. I like them.</p></li>\n</ul>\n\n<p>See:</p>\n\n<ul>\n<li><p><a href=\"http://www.boost.org/doc/libs/1_41_0/libs/test/doc/html/execution-monitor/reference.html#boost.execution_exception\" rel=\"noreferrer\">http://www.boost.org/doc/libs/1_41_0/libs/test/doc/html/execution-monitor/reference.html#boost.execution_exception</a></p></li>\n<li><p>the execution-monitor user-guide.</p></li>\n</ul>\n\n<p>Also, thanks to Gennadiy Rozental (Author of Boost Test), if you happen to\nread this, Great Work!!</p>\n"
},
{
"answer_id": 6837339,
"author": "grokus",
"author_id": 203091,
"author_profile": "https://Stackoverflow.com/users/203091",
"pm_score": 2,
"selected": false,
"text": "<p>At work I ran into the same problem. My solution is to use a compile flag. When my flag GROKUS_TESTABLE is on my GROKUS_ASSERT is turned into an exception and with Boost you can test code paths that throw exceptions. When GROKUS_TESTABLE is off, GROKUS_ASSERT is translated to c++ assert().</p>\n\n<pre><code>#if GROKUS_TESTABLE\n#define GROKUS_ASSERT ... // exception\n#define GROKUS_CHECK_THROW BOOST_CHECK_THROW\n#else\n#define GROKUS_ASSERT ... // assert\n#define GROKUS_CHECK_THROW(statement, exception) {} // no-op\n#endif\n</code></pre>\n\n<p>My original motivation was to aid debugging, i.e. assert() can be debugged quickly and exceptions often are harder to debug in gdb. My compile flag seems to balance debuggability and testability pretty well.</p>\n\n<p>Hope this helps</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
I use the Boost Test framework to unit test my C++ code and wondered if it is possible to test if a function will assert? Yes, sounds a bit strange but bear with me! Many of my functions check the input parameters upon entry, asserting if they are invalid, and it would be useful to test for this. For example:
```
void MyFunction(int param)
{
assert(param > 0); // param cannot be less than 1
...
}
```
I would like to be able to do something like this:
```
BOOST_CHECK_ASSERT(MyFunction(0), true);
BOOST_CHECK_ASSERT(MyFunction(-1), true);
BOOST_CHECK_ASSERT(MyFunction(1), false);
...
```
You can check for exceptions being thrown using Boost Test so I wondered if there was some assert magic too...
|
I don't think so. You could always write your own assert which throws an exception and then use BOOST\_CHECK\_NOTHROW() for that exception.
|
270,561 |
<p>Developing a website and just trying to get back into the swing of (clever) SQL queries etc, my mind had totally gone tonight!</p>
<p>There is a website <a href="http://www.ufindus.com/" rel="nofollow noreferrer">http://www.ufindus.com/</a> which has a textbox allowing you to enter either a place name or a postcode/zipcode. I am trying to do something similiar but I am rubbish at SQL - so how do you construct an SQL statement that could potentially look at 2 columns (i.e. place and postcode) because you can't query both fields for the same value e.g </p>
<pre><code>place = 'YORK' AND postcode = 'YORK'
</code></pre>
<p>or</p>
<pre><code>place = 'YO21 5EA' AND postcode = 'YO21 5EA'
</code></pre>
<p>so do you have to put some logic in to be intelligent enough to detect whether it looks like a place name or a postcode - that just seems too complicated to me!! Any help would be much appreciated.</p>
|
[
{
"answer_id": 270575,
"author": "Ken Pespisa",
"author_id": 30812,
"author_profile": "https://Stackoverflow.com/users/30812",
"pm_score": 4,
"selected": true,
"text": "<p>You could use an \"OR\" to get the job done. For example,</p>\n\n<p>place = 'YORK' or postcode = 'YORK'</p>\n\n<p>You might also do better using the LIKE statement, as in </p>\n\n<p>WHERE place LIKE 'YORK%' or postcode LIKE 'YORK%'</p>\n\n<p>(this assumes both place and postcode are character-based columns)</p>\n"
},
{
"answer_id": 270577,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>why not use OR instead of AND?</p>\n\n<pre><code>place = @textboxvalue OR post = @textboxvalue\n</code></pre>\n"
},
{
"answer_id": 270578,
"author": "Kevin Fairchild",
"author_id": 3743,
"author_profile": "https://Stackoverflow.com/users/3743",
"pm_score": 0,
"selected": false,
"text": "<p>What's wrong with attempting to match on the place and postcode? If I put in 'York' and (somewhere) that happens to be a valid postcode, I should get that result. As for preventing the same thing being entered twice, well, you can handle that on the validation prior to doing the database call.</p>\n\n<p>Ah. Guess I was a bit slow on the up-take. Yes... what the others suggested is right, 'OR' is what you were looking for. I misinterpreted.</p>\n"
},
{
"answer_id": 271547,
"author": "Jørn Jensen",
"author_id": 34585,
"author_profile": "https://Stackoverflow.com/users/34585",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, first I'm assuming that you have a table with a mapping of postcodes to placenames. </p>\n\n<p>Let's call this table '<em>postcode</em>' with columns '<em>postcode</em>' and '<em>postplace</em>'. Both of these are of a char-type.</p>\n\n<p>Then.. whatever you do, make sure the input from the user is not part of dynamic sql. Make sure it is a <strong>parameter</strong>. Otherwise, you are inviting SQL injection attacks that can really ruin your day. This is <strong>important</strong>.</p>\n\n<p>Our user input is in <em>@textboxstring</em>. </p>\n\n<p>Given this, you can get the postcode and postplace like this:</p>\n\n<p><code>\nselect @textboxstring = RTRIM(@textboxstring) + '%';\nselect postcode, postplace \nfrom postcode \nwhere postcode like @textboxstring or postplace like @textboxstring;\n</code></p>\n\n<p>Note that I'm modifying @textboxstring to get wildcard match with <code>like</code> without having to use dynamic sql.</p>\n\n<p>If the postcode was integer, you would need to convert the input to int before executing the sql. So with a @textboxint as well, you could do this:</p>\n\n<p><code>\nselect @textboxstring = RTRIM(@textboxstring) + '%';\nselect postcode, postplace \nfrom postcode \nwhere postcode = @textboxint or postplace like @textboxstring;\n</code></p>\n\n<p>Oh, and you need to handle that your search can have multiple results. You probably only want the first row.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270561",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5175/"
] |
Developing a website and just trying to get back into the swing of (clever) SQL queries etc, my mind had totally gone tonight!
There is a website <http://www.ufindus.com/> which has a textbox allowing you to enter either a place name or a postcode/zipcode. I am trying to do something similiar but I am rubbish at SQL - so how do you construct an SQL statement that could potentially look at 2 columns (i.e. place and postcode) because you can't query both fields for the same value e.g
```
place = 'YORK' AND postcode = 'YORK'
```
or
```
place = 'YO21 5EA' AND postcode = 'YO21 5EA'
```
so do you have to put some logic in to be intelligent enough to detect whether it looks like a place name or a postcode - that just seems too complicated to me!! Any help would be much appreciated.
|
You could use an "OR" to get the job done. For example,
place = 'YORK' or postcode = 'YORK'
You might also do better using the LIKE statement, as in
WHERE place LIKE 'YORK%' or postcode LIKE 'YORK%'
(this assumes both place and postcode are character-based columns)
|
270,592 |
<pre><code>class AbstractQuery {
virtual bool isCanBeExecuted()=0;
public:
AbstractQuery() {}
virtual bool Execute()=0;
};
class DropTableQuery: public AbstractQuery {
vector< std::pair< string, string> > QueryContent;
QueryValidate qv;
public:
explicit DropTableQuery(const string& qr): AbstractQuery(), qv(qr) {}
bool Execute();
};
</code></pre>
<p>Is it necessary to call base contructor in derived class constructor?</p>
|
[
{
"answer_id": 270599,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 4,
"selected": true,
"text": "<p>No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor).</p>\n\n<p>So for a typical interface you could have something like this:</p>\n\n<pre><code>class MyInterface {\npublic:\n virtual ~MyInterface() {}\n virtual void execute() = 0;\n};\n</code></pre>\n\n<p>EDIT: Here's a reason why you should have a virtual destructor:</p>\n\n<pre><code>MyInterface* iface = GetMeSomeThingThatSupportsInterface();\ndelete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor\n</code></pre>\n"
},
{
"answer_id": 270606,
"author": "Johann Gerell",
"author_id": 6345,
"author_profile": "https://Stackoverflow.com/users/6345",
"pm_score": 2,
"selected": false,
"text": "<p>No, not in the example you provided. The base class' default constructors will be called automatically in the same order that the base classes are declared, before any member of the derived class is initialized.</p>\n"
},
{
"answer_id": 270660,
"author": "Qwertie",
"author_id": 22820,
"author_profile": "https://Stackoverflow.com/users/22820",
"pm_score": 2,
"selected": false,
"text": "<p>It is <strong>never</strong> obligatory to explicitly call the base class constructor, unless it has parameters. The compiler will call the constructor automatically. Theoretically the base class still has a constructor, but the compiler may optimize it away into non-existence if it doesn't do anything.</p>\n"
},
{
"answer_id": 14056114,
"author": "fatma.ekici",
"author_id": 1678760,
"author_profile": "https://Stackoverflow.com/users/1678760",
"pm_score": 0,
"selected": false,
"text": "<p>If the base class's constructor does not need any parameters, you do not need to call it in the derived class since it is called as a default constructor. However you need to provide a virtual destructor for your base class even if it is empty. Otherwise compiler will generate a default destructor which is non-virtual by default.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270592",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28298/"
] |
```
class AbstractQuery {
virtual bool isCanBeExecuted()=0;
public:
AbstractQuery() {}
virtual bool Execute()=0;
};
class DropTableQuery: public AbstractQuery {
vector< std::pair< string, string> > QueryContent;
QueryValidate qv;
public:
explicit DropTableQuery(const string& qr): AbstractQuery(), qv(qr) {}
bool Execute();
};
```
Is it necessary to call base contructor in derived class constructor?
|
No, in fact for it is unnecessary for the base class to have an explicitly defined constructor (though make sure you have a virtual destructor).
So for a typical interface you could have something like this:
```
class MyInterface {
public:
virtual ~MyInterface() {}
virtual void execute() = 0;
};
```
EDIT: Here's a reason why you should have a virtual destructor:
```
MyInterface* iface = GetMeSomeThingThatSupportsInterface();
delete iface; // this is undefined behaviour if MyInterface doesn't have a virtual destructor
```
|
270,611 |
<p>Is it a good idea to store my SQL queries in a global resource file instead of having it in my codebehind? I know stored procedures would be a better solution but I don't have that luxury on this project. </p>
<p>I don't want queries all over my pages and thought a central repository would be a better idea.</p>
|
[
{
"answer_id": 270621,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 0,
"selected": false,
"text": "<p>I would look up strongly typed datasets with tableadapters and let the tableadapters handle all queries. When you are used with it you'll never go back.</p>\n\n<p>Just add a dataset to your solution, add a connection, and a tableadapter for a table, then start build all querys (update, select, delete, search and so on) and handle it easy in code behind.</p>\n"
},
{
"answer_id": 270676,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 0,
"selected": false,
"text": "<p>Ok, I'll try to answer again, now when I have more information.</p>\n\n<p>I would make a query-class that hold all querystrings as shared properties or functions that could be named quite well to be easy to use.</p>\n"
},
{
"answer_id": 270710,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I am in the same situation with some developers preferring to write the queries in the resource file. We are using subsonic and I would prefer to use stored procedures rather then using direct queries.</p>\n\n<p>One option, even though it is bad is to place those queries in a config file and read when needed but this is a very bad option and we may use it if everyone cannot be agreement of using the stored procedures.</p>\n"
},
{
"answer_id": 270844,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 4,
"selected": true,
"text": "<p>Resource files are usually used for localization. But a string is just a string is just a string, and do you really want to be sending any old string in a resource file to your database?</p>\n\n<p>I completely agree with others that you should be using linq or typed datasets, etc. Personally I've only had to resort to text queries a handful of times over the years, and when I do it's usually something like the following:</p>\n\n<p>You set up a small framework and then all you need to do is maintain an Xml file. An single specific xml file is a lot easier to manage and deploy than a resource dll. You also have a well known place (repository) that stores Sql Queries and some metadata about them versus just some naming convention.</p>\n\n<p>Never underestimate the utility of a (simple) class over a string literal. Once you've started using the class you can then add things down the road that you can't (easily) do with just a simple string. </p>\n\n<hr>\n\n<p>Notepad compiler, so apologies if this isn't 100%. It's just a sketch of how everything interacts.</p>\n\n<pre><code>public static class SqlResource\n{\n private static Dictionary<string,SqlQuery> dictionary;\n\n public static void Initialize(string file)\n {\n List<SqlQuery> list;\n\n // deserialize the xml file\n using (StreamReader streamReader = new StreamReader(file))\n {\n XmlSerializer deserializer = new XmlSerializer(typeof(List<SqlQuery>));\n list = (List<SqlQuery>)deserializer.Deserialize(streamReader);\n }\n dictionary = new Dictionary<string,SqlQuery>();\n foreach(var item in list )\n {\n dictionary.Add(item.Name,item);\n }\n }\n public static SqlQuery GetQueryByName(string name)\n {\n SqlQuery query = dictionary[name];\n\n if( query == null )\n throw new ArgumentException(\"The query '\" + name + \"' is not valid.\");\n\n if( query.IsObsolete )\n {\n // TODO - log this.\n }\n return query;\n\n }\n}\n\npublic sealed class SqlQuery\n{\n [XmlAttributeAttribute(\"name\")]\n public bool Name { get; set; }\n\n [XmlElement(\"Sql\")]\n public bool Sql { get; set; }\n\n [XmlAttributeAttribute(\"obsolete\")]\n public bool IsObsolete { get; set; }\n\n [XmlIgnore]\n public TimeSpan Timeout { get; set;}\n\n /// <summary>\n /// Serialization only - XmlSerializer can't serialize normally\n /// </summary>\n [XmlAttribute(\"timeout\")]\n public string Timeout_String \n {\n get { return Timeout.ToString(); }\n set { Timeout = TimeSpan.Parse(value); } \n }\n}\n</code></pre>\n\n<p>your xml file might look like</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<ArrayOfSqlQuery xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <SqlQuery name=\"EmployeeByEmployeeID\" timeout=\"00:00:30\" >\n <Sql>\nSELECT * From Employee WHERE EmployeeID = @T0 \n </Sql>\n </SqlQuery>\n <SqlQuery name=\"EmployeesForManager\" timeout=\"00:05:00\" obsolete=\"true\" >\n <Sql>\nSELECT * From Employee WHERE ManagerID = @T0 \n </Sql>\n </SqlQuery>\n</ArrayOfSqlQuery>\n</code></pre>\n"
},
{
"answer_id": 2962615,
"author": "Robert Bratton",
"author_id": 357002,
"author_profile": "https://Stackoverflow.com/users/357002",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the XML config file to associate names with stored procedures too. I'm doing that for a current C# project. The \"query\" would define what procedure to call.</p>\n\n<p>Since some database engines don't support stored queries, that's not always an option.</p>\n\n<p>Sometimes for small projects, it's OK to use parameterized SQL queries (don't concatenate string). This is especially true for select statements.</p>\n\n<p>Views can also be used for selects instead of stored procedures.</p>\n\n<p>Rob</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270611",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18234/"
] |
Is it a good idea to store my SQL queries in a global resource file instead of having it in my codebehind? I know stored procedures would be a better solution but I don't have that luxury on this project.
I don't want queries all over my pages and thought a central repository would be a better idea.
|
Resource files are usually used for localization. But a string is just a string is just a string, and do you really want to be sending any old string in a resource file to your database?
I completely agree with others that you should be using linq or typed datasets, etc. Personally I've only had to resort to text queries a handful of times over the years, and when I do it's usually something like the following:
You set up a small framework and then all you need to do is maintain an Xml file. An single specific xml file is a lot easier to manage and deploy than a resource dll. You also have a well known place (repository) that stores Sql Queries and some metadata about them versus just some naming convention.
Never underestimate the utility of a (simple) class over a string literal. Once you've started using the class you can then add things down the road that you can't (easily) do with just a simple string.
---
Notepad compiler, so apologies if this isn't 100%. It's just a sketch of how everything interacts.
```
public static class SqlResource
{
private static Dictionary<string,SqlQuery> dictionary;
public static void Initialize(string file)
{
List<SqlQuery> list;
// deserialize the xml file
using (StreamReader streamReader = new StreamReader(file))
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<SqlQuery>));
list = (List<SqlQuery>)deserializer.Deserialize(streamReader);
}
dictionary = new Dictionary<string,SqlQuery>();
foreach(var item in list )
{
dictionary.Add(item.Name,item);
}
}
public static SqlQuery GetQueryByName(string name)
{
SqlQuery query = dictionary[name];
if( query == null )
throw new ArgumentException("The query '" + name + "' is not valid.");
if( query.IsObsolete )
{
// TODO - log this.
}
return query;
}
}
public sealed class SqlQuery
{
[XmlAttributeAttribute("name")]
public bool Name { get; set; }
[XmlElement("Sql")]
public bool Sql { get; set; }
[XmlAttributeAttribute("obsolete")]
public bool IsObsolete { get; set; }
[XmlIgnore]
public TimeSpan Timeout { get; set;}
/// <summary>
/// Serialization only - XmlSerializer can't serialize normally
/// </summary>
[XmlAttribute("timeout")]
public string Timeout_String
{
get { return Timeout.ToString(); }
set { Timeout = TimeSpan.Parse(value); }
}
}
```
your xml file might look like
```
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSqlQuery xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<SqlQuery name="EmployeeByEmployeeID" timeout="00:00:30" >
<Sql>
SELECT * From Employee WHERE EmployeeID = @T0
</Sql>
</SqlQuery>
<SqlQuery name="EmployeesForManager" timeout="00:05:00" obsolete="true" >
<Sql>
SELECT * From Employee WHERE ManagerID = @T0
</Sql>
</SqlQuery>
</ArrayOfSqlQuery>
```
|
270,612 |
<p>I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.</p>
<p>I am wrapping everything in this div:</p>
<pre><code>#scroll {
height:400px;
overflow:scroll;
}
</code></pre>
<p>Is there a way to keep it scrolled to the bottom by default using JS?</p>
<p>Is there a way to keep it scrolled to the bottom after an ajax request?</p>
|
[
{
"answer_id": 270628,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 12,
"selected": true,
"text": "<p>Here's what I use on my site:</p>\n\n<pre><code>var objDiv = document.getElementById(\"your_div\");\nobjDiv.scrollTop = objDiv.scrollHeight;\n</code></pre>\n"
},
{
"answer_id": 2664878,
"author": "andsien",
"author_id": 319963,
"author_profile": "https://Stackoverflow.com/users/319963",
"pm_score": 9,
"selected": false,
"text": "<p>This is much easier if you're using <a href=\"https://api.jquery.com/scrollTop/\" rel=\"noreferrer\">jQuery scrollTop</a>:</p>\n\n<pre><code>$(\"#mydiv\").scrollTop($(\"#mydiv\")[0].scrollHeight);\n</code></pre>\n"
},
{
"answer_id": 12391116,
"author": "DadViegas",
"author_id": 1354106,
"author_profile": "https://Stackoverflow.com/users/1354106",
"pm_score": 7,
"selected": false,
"text": "<p>using <a href=\"http://api.jquery.com/animate\" rel=\"noreferrer\">jQuery animate</a>:</p>\n\n<pre><code>$('#DebugContainer').stop().animate({\n scrollTop: $('#DebugContainer')[0].scrollHeight\n}, 800);\n</code></pre>\n"
},
{
"answer_id": 21048661,
"author": "Akira Yamamoto",
"author_id": 475876,
"author_profile": "https://Stackoverflow.com/users/475876",
"pm_score": 5,
"selected": false,
"text": "<pre><code>var mydiv = $(\"#scroll\");\nmydiv.scrollTop(mydiv.prop(\"scrollHeight\"));\n</code></pre>\n\n<p>Works from jQuery 1.6</p>\n\n<p><a href=\"https://api.jquery.com/scrollTop/\" rel=\"noreferrer\">https://api.jquery.com/scrollTop/</a></p>\n\n<p><a href=\"http://api.jquery.com/prop/\" rel=\"noreferrer\">http://api.jquery.com/prop/</a></p>\n"
},
{
"answer_id": 24139276,
"author": "Benny Neugebauer",
"author_id": 451634,
"author_profile": "https://Stackoverflow.com/users/451634",
"pm_score": 4,
"selected": false,
"text": "<p>If you don't want to rely on <code>scrollHeight</code>, the following code helps:</p>\n\n<pre><code>$('#scroll').scrollTop(1000000);\n</code></pre>\n"
},
{
"answer_id": 24555718,
"author": "Bruno Jennrich",
"author_id": 1557690,
"author_profile": "https://Stackoverflow.com/users/1557690",
"pm_score": 2,
"selected": false,
"text": "<p>small addendum: scrolls only, if last line is already visible. if scrolled a tiny bit, leaves the content where it is (attention: not tested with different font sizes. this may need some adjustments inside \">= comparison\"):</p>\n\n<pre><code>var objDiv = document.getElementById(id);\nvar doScroll=objDiv.scrollTop>=(objDiv.scrollHeight-objDiv.clientHeight); \n\n// add new content to div\n$('#' + id ).append(\"new line at end<br>\"); // this is jquery!\n\n// doScroll is true, if we the bottom line is already visible\nif( doScroll) objDiv.scrollTop = objDiv.scrollHeight;\n</code></pre>\n"
},
{
"answer_id": 25426631,
"author": "mylescc",
"author_id": 1863795,
"author_profile": "https://Stackoverflow.com/users/1863795",
"pm_score": 2,
"selected": false,
"text": "<p>Just as a bonus snippet. I'm using angular and was trying to scroll a message thread to the bottom when a user selected different conversations with users. In order to make sure that the scroll works after the new data had been loaded into the div with the ng-repeat for messages, just wrap the scroll snippet in a timeout.</p>\n\n<pre><code>$timeout(function(){\n var messageThread = document.getElementById('message-thread-div-id');\n messageThread.scrollTop = messageThread.scrollHeight;\n},0)\n</code></pre>\n\n<p>That will make sure that the scroll event is fired after the data has been inserted into the DOM.</p>\n"
},
{
"answer_id": 26293764,
"author": "tnt-rox",
"author_id": 913620,
"author_profile": "https://Stackoverflow.com/users/913620",
"pm_score": 6,
"selected": false,
"text": "<p>Newer method that works on <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView\" rel=\"noreferrer\">all current browsers</a>:</p>\n\n<pre><code>this.scrollIntoView(false);\n</code></pre>\n"
},
{
"answer_id": 27025520,
"author": "Muhammad Soliman",
"author_id": 1334561,
"author_profile": "https://Stackoverflow.com/users/1334561",
"pm_score": 3,
"selected": false,
"text": "<p>Using jQuery, <a href=\"http://api.jquery.com/scrolltop/\" rel=\"nofollow\">scrollTop</a> is used to set the vertical position of scollbar for any given element. there is also a nice <a href=\"https://github.com/flesler/jquery.scrollTo\" rel=\"nofollow\">jquery scrollTo plugin</a> used to scroll with animation and different options (<a href=\"http://demos.flesler.com/jquery/scrollTo/\" rel=\"nofollow\">demos</a>)</p>\n\n<pre><code>var myDiv = $(\"#div_id\").get(0);\nmyDiv.scrollTop = myDiv.scrollHeight;\n</code></pre>\n\n<p>if you want to use <a href=\"http://api.jquery.com/animate/\" rel=\"nofollow\">jQuery's animate method</a> to add animation while scrolling down, check the following snippet:</p>\n\n<pre><code>var myDiv = $(\"#div_id\").get(0);\nmyDiv.animate({\n scrollTop: myDiv.scrollHeight\n }, 500);\n</code></pre>\n"
},
{
"answer_id": 31979138,
"author": "Navaneeth",
"author_id": 4255204,
"author_profile": "https://Stackoverflow.com/users/4255204",
"pm_score": 2,
"selected": false,
"text": "<p>This will let you scroll all the way down regards the document height</p>\n\n<pre><code>$('html, body').animate({scrollTop:$(document).height()}, 1000);\n</code></pre>\n"
},
{
"answer_id": 32592634,
"author": "devonj",
"author_id": 4736349,
"author_profile": "https://Stackoverflow.com/users/4736349",
"pm_score": 3,
"selected": false,
"text": "<p>Found this really helpful, thank you.</p>\n\n<p>For the Angular 1.X folks out there: </p>\n\n<pre class=\"lang-js prettyprint-override\"><code>angular.module('myApp').controller('myController', ['$scope', '$document',\n function($scope, $document) {\n\n var overflowScrollElement = $document[0].getElementById('your_overflow_scroll_div');\n overflowScrollElement[0].scrollTop = overflowScrollElement[0].scrollHeight;\n\n }\n]);\n</code></pre>\n\n\n\n<p>Just because the wrapping in jQuery elements versus HTML DOM elements gets a little confusing with angular. </p>\n\n<p>Also for a chat application, I found making this assignment after your chats were loaded to be useful, you also might need to slap on short timeout as well. </p>\n"
},
{
"answer_id": 33031853,
"author": "Benkinass",
"author_id": 1348531,
"author_profile": "https://Stackoverflow.com/users/1348531",
"pm_score": 3,
"selected": false,
"text": "<p>I have encountered the same problem, but with an additional constraint: I had no control over the code that appended new elements to the scroll container. None of the examples I found here allowed me to do just that. Here is the solution I ended up with .</p>\n\n<p>It uses <code>Mutation Observers</code> (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver\" rel=\"noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver</a>) which makes it usable only on modern browsers (though polyfills exist)</p>\n\n<p>So basically the code does just that :</p>\n\n<pre><code>var scrollContainer = document.getElementById(\"myId\");\n\n// Define the Mutation Observer\nvar observer = new MutationObserver(function(mutations) {\n\n // Compute sum of the heights of added Nodes\n var newNodesHeight = mutations.reduce(function(sum, mutation) {\n return sum + [].slice.call(mutation.addedNodes)\n .map(function (node) { return node.scrollHeight || 0; })\n .reduce(function(sum, height) {return sum + height});\n }, 0);\n\n // Scroll to bottom if it was already scrolled to bottom\n if (scrollContainer.clientHeight + scrollContainer.scrollTop + newNodesHeight + 10 >= scrollContainer.scrollHeight) {\n scrollContainer.scrollTop = scrollContainer.scrollHeight;\n }\n\n});\n\n// Observe the DOM Element\nobserver.observe(scrollContainer, {childList: true});\n</code></pre>\n\n<p>I made a fiddle to demonstrate the concept : \n<a href=\"https://jsfiddle.net/j17r4bnk/\" rel=\"noreferrer\">https://jsfiddle.net/j17r4bnk/</a></p>\n"
},
{
"answer_id": 33193694,
"author": "Tho",
"author_id": 875775,
"author_profile": "https://Stackoverflow.com/users/875775",
"pm_score": 7,
"selected": false,
"text": "<p>Try the code below:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const scrollToBottom = (id) => {\n const element = document.getElementById(id);\n element.scrollTop = element.scrollHeight;\n}\n</code></pre>\n<p>You can also use Jquery to make the scroll smooth:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const scrollSmoothlyToBottom = (id) => {\n const element = $(`#${id}`);\n element.animate({\n scrollTop: element.prop("scrollHeight")\n }, 500);\n}\n</code></pre>\n<p>Here is the <a href=\"https://jsfiddle.net/9bazc6hx/3/\" rel=\"noreferrer\">demo</a></p>\n<p>Here's how it works:</p>\n<p><a href=\"https://jsfiddle.net/9bazc6hx/3/\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/IC85R.png\" alt=\"enter image description here\" /></a></p>\n<p>Ref: <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop\" rel=\"noreferrer\">scrollTop</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight\" rel=\"noreferrer\">scrollHeight</a>, <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/clientHeight\" rel=\"noreferrer\">clientHeight</a></p>\n"
},
{
"answer_id": 33398636,
"author": "John Dunne",
"author_id": 1351403,
"author_profile": "https://Stackoverflow.com/users/1351403",
"pm_score": 2,
"selected": false,
"text": "<p>You can also, using jQuery, attach an animation to <code>html,body</code> of the document via:</p>\n\n<p><code>$(\"html,body\").animate({scrollTop:$(\"#div-id\")[0].offsetTop}, 1000);</code></p>\n\n<p>which will result in a smooth scroll to the top of the div with id \"div-id\".</p>\n"
},
{
"answer_id": 38443916,
"author": "Lay Leangsros",
"author_id": 4466122,
"author_profile": "https://Stackoverflow.com/users/4466122",
"pm_score": 3,
"selected": false,
"text": "<p>Javascript or jquery:</p>\n\n<pre><code>var scroll = document.getElementById('messages');\n scroll.scrollTop = scroll.scrollHeight;\n scroll.animate({scrollTop: scroll.scrollHeight});\n</code></pre>\n\n<p>Css:</p>\n\n<pre><code> .messages\n {\n height: 100%;\n overflow: auto;\n }\n</code></pre>\n"
},
{
"answer_id": 41108721,
"author": "BrianLegg",
"author_id": 2921935,
"author_profile": "https://Stackoverflow.com/users/2921935",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an old question, but none of these solutions worked out for me. I ended up using offset().top to get the desired results. Here's what I used to gently <strong>scroll the screen down</strong> to the last message in my chat application:</p>\n\n<pre><code>$(\"#html, body\").stop().animate({\n scrollTop: $(\"#last-message\").offset().top\n}, 2000);\n</code></pre>\n\n<p>I hope this helps someone else.</p>\n"
},
{
"answer_id": 46915549,
"author": "Barath Sankar",
"author_id": 6801721,
"author_profile": "https://Stackoverflow.com/users/6801721",
"pm_score": 3,
"selected": false,
"text": "<p>Java Script:</p>\n\n<p><code>document.getElementById('messages').scrollIntoView(false);</code></p>\n\n<p>Scrolls to the last line of the content present.</p>\n"
},
{
"answer_id": 46958777,
"author": "aravk33",
"author_id": 8532064,
"author_profile": "https://Stackoverflow.com/users/8532064",
"pm_score": 1,
"selected": false,
"text": "<p>A very simple method to this is to set the <code>scroll to</code> to the height of the div.</p>\n\n<pre><code>var myDiv = document.getElementById(\"myDiv\");\nwindow.scrollTo(0, myDiv.innerHeight);\n</code></pre>\n"
},
{
"answer_id": 54501285,
"author": "mjaque",
"author_id": 1857487,
"author_profile": "https://Stackoverflow.com/users/1857487",
"pm_score": 2,
"selected": false,
"text": "<p>Scroll to the last element inside the div:</p>\n\n<pre><code>myDiv.scrollTop = myDiv.lastChild.offsetTop\n</code></pre>\n"
},
{
"answer_id": 55902894,
"author": "adl",
"author_id": 1112483,
"author_profile": "https://Stackoverflow.com/users/1112483",
"pm_score": 5,
"selected": false,
"text": "<p><strong>smooth</strong> scroll with Javascript:</p>\n\n<p><code>document.getElementById('messages').scrollIntoView({ behavior: 'smooth', block: 'end' });</code></p>\n"
},
{
"answer_id": 56880885,
"author": "Mahdi Bagheri",
"author_id": 8515569,
"author_profile": "https://Stackoverflow.com/users/8515569",
"pm_score": -1,
"selected": false,
"text": "<p>use :</p>\n\n<pre><code>var element= $('element');\nvar maxScrollTop = element[0].scrollHeight - element.outerHeight();\nelement.scrollTop(maxScrollTop);\n</code></pre>\n\n<p>or check scroll to bottom :</p>\n\n<pre><code> var element = $(element);\n var maxScrollTop = element[0].scrollHeight - element.outerHeight();\n element.on('scroll', function() {\n if ( element.scrollTop() >= maxScrollTop ) {\n alert('scroll to bottom');\n }\n });\n</code></pre>\n"
},
{
"answer_id": 58219558,
"author": "veritas",
"author_id": 2181576,
"author_profile": "https://Stackoverflow.com/users/2181576",
"pm_score": -1,
"selected": false,
"text": "<p>If this is being done for scrolling to the bottom of chat window, do the following</p>\n\n<p>The idea of scrolling to a particular div in the chat was the following </p>\n\n<p>1) Each chat div consisting of Person, time and message is run in a for loop with class chatContentbox </p>\n\n<p>2) querySelectorAll finds all such arrays. It could be 400 nodes (400 chats) </p>\n\n<p>3) go to the last one </p>\n\n<p>4) scrollIntoView() </p>\n\n<pre><code>let lastChatBox = document.querySelectorAll('.chatContentBox'); \nlastChatBox = lastChatBox[lastChatBox.length-1]; \nlastChatBox.scrollIntoView(); \n</code></pre>\n"
},
{
"answer_id": 59604580,
"author": "SeekLoad",
"author_id": 7371886,
"author_profile": "https://Stackoverflow.com/users/7371886",
"pm_score": -1,
"selected": false,
"text": "<p>Sometimes the most simple is the best solution:\nI do not know if this will help, it helped me to scroll it were ever I wanted too. The higher the \"y=\" is,the more down it scrolls and of course \"0\" means top, so there for example \"1000\" could be bottom, or \"2000\" or \"3000\" and so on, depending how long your page is.\nThis usually works in a button with onclick or onmouseover.</p>\n\n<pre><code>window.scrollTo(x=0,y=150);\n</code></pre>\n"
},
{
"answer_id": 60104604,
"author": "user2341537",
"author_id": 2341537,
"author_profile": "https://Stackoverflow.com/users/2341537",
"pm_score": -1,
"selected": false,
"text": "<p>Set the distance from the top of the scrollable element to be the total height of the element.</p>\n\n<pre><code>const element = this.shadowRoot.getElementById('my-scrollable-div')\nelement.scrollTop = element.scrollHeight\n</code></pre>\n"
},
{
"answer_id": 60254536,
"author": "moreirapontocom",
"author_id": 1202416,
"author_profile": "https://Stackoverflow.com/users/1202416",
"pm_score": 1,
"selected": false,
"text": "<p>On my Angular 6 application I just did this:</p>\n\n<pre><code>postMessage() {\n // post functions here\n let history = document.getElementById('history')\n let interval \n interval = setInterval(function() {\n history.scrollTop = history.scrollHeight\n clearInterval(interval)\n }, 1)\n}\n</code></pre>\n\n<p>The clearInterval(interval) function will stop the timer to allow manual scroll top / bottom.</p>\n"
},
{
"answer_id": 60606751,
"author": "Anatol",
"author_id": 11804213,
"author_profile": "https://Stackoverflow.com/users/11804213",
"pm_score": 3,
"selected": false,
"text": "<p>You can use the HTML DOM scrollIntoView Method like this:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>var element = document.getElementById(\"scroll\");\nelement.scrollIntoView();\n</code></pre>\n"
},
{
"answer_id": 61717100,
"author": "ngShravil.py",
"author_id": 6635464,
"author_profile": "https://Stackoverflow.com/users/6635464",
"pm_score": 3,
"selected": false,
"text": "<p>My Scenario: I had an list of string, in which I had to append a string given by a user and scroll to the end of the list automatically. I had fixed height of the display of the list, after which it should overflow.</p>\n\n<p>I tried @Jeremy Ruten's answer, it worked, but it was scrolling to the (n-1)th element. If anybody is facing this type of issue, you can use <code>setTimeOut()</code> method workaround. You need to modify the code to below:</p>\n\n<pre class=\"lang-js prettyprint-override\"><code>setTimeout(() => {\n var objDiv = document.getElementById('div_id');\n objDiv.scrollTop = objDiv.scrollHeight\n}, 0)\n</code></pre>\n\n<p>Here is the StcakBlitz link I have created which shows the problem and its solution : <a href=\"https://stackblitz.com/edit/angular-ivy-x9esw8\" rel=\"noreferrer\">https://stackblitz.com/edit/angular-ivy-x9esw8</a></p>\n"
},
{
"answer_id": 62789931,
"author": "Mike Taverne",
"author_id": 763546,
"author_profile": "https://Stackoverflow.com/users/763546",
"pm_score": 2,
"selected": false,
"text": "<p>Like you, I'm building a chat app and want the most recent message to scroll into view. This ultimately worked well for me:</p>\n<pre><code>//get the div that contains all the messages\nlet div = document.getElementById('message-container');\n\n//make the last element (a message) to scroll into view, smoothly!\ndiv.lastElementChild.scrollIntoView({ behavior: 'smooth' });\n</code></pre>\n"
},
{
"answer_id": 64230698,
"author": "jocassid",
"author_id": 3335674,
"author_profile": "https://Stackoverflow.com/users/3335674",
"pm_score": 0,
"selected": false,
"text": "<p>I use the difference between the Y coordinate of the first item div and the Y coordinate of the selected item div. Here is the JavaScript/JQuery code and the html:</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function scrollTo(event){\n // In my proof of concept, I had a few <button>s with value \n // attributes containing strings with id selector expressions\n // like \"#item1\".\n let selectItem = $($(event.target).attr('value'));\n let selectedDivTop = selectItem.offset().top;\n\n let scrollingDiv = selectItem.parent();\n\n let firstItem = scrollingDiv.children('div').first();\n let firstItemTop = firstItem.offset().top;\n\n let newScrollValue = selectedDivTop - firstItemTop;\n scrollingDiv.scrollTop(newScrollValue);\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div id=\"scrolling\" style=\"height: 2rem; overflow-y: scroll\">\n <div id=\"item1\">One</div>\n <div id=\"item2\">Two</div>\n <div id=\"item3\">Three</div>\n <div id=\"item4\">Four</div>\n <div id=\"item5\">Five</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 64701883,
"author": "Adonis Gaitatzis",
"author_id": 5671180,
"author_profile": "https://Stackoverflow.com/users/5671180",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo\" rel=\"nofollow noreferrer\">Element.scrollTo()</a> method.</p>\n<p>It can be animated using the built-in browser/OS animation, so it's super smooth.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function scrollToBottom() {\n const scrollContainer = document.getElementById('container');\n scrollContainer.scrollTo({\n top: scrollContainer.scrollHeight,\n left: 0,\n behavior: 'smooth'\n });\n}\n\n// initialize dummy content\nconst scrollContainer = document.getElementById('container');\nconst numCards = 100;\nlet contentInnerHtml = '';\nfor (let i=0; i<numCards; i++) {\n contentInnerHtml += `<div class=\"card mb-2\"><div class=\"card-body\">Card ${i + 1}</div></div>`;\n}\nscrollContainer.innerHTML = contentInnerHtml;</code></pre>\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code>.overflow-y-scroll {\n overflow-y: scroll;\n}</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\"/>\n\n<div class=\"d-flex flex-column vh-100\">\n <div id=\"container\" class=\"overflow-y-scroll flex-grow-1\"></div>\n <div>\n <button class=\"btn btn-primary\" onclick=\"scrollToBottom()\">Scroll to bottom</button>\n </div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 65371198,
"author": "Ahmet Şimşek",
"author_id": 3986712,
"author_profile": "https://Stackoverflow.com/users/3986712",
"pm_score": 5,
"selected": false,
"text": "<p>alternative solution</p>\n<pre class=\"lang-js prettyprint-override\"><code>function scrollToBottom(element) {\n element.scroll({ top: element.scrollHeight, behavior: 'smooth' });\n}\n</code></pre>\n"
},
{
"answer_id": 68585424,
"author": "Spankied",
"author_id": 8723748,
"author_profile": "https://Stackoverflow.com/users/8723748",
"pm_score": 1,
"selected": false,
"text": "<p>Css only:</p>\n<pre><code>.scroll-container {\n overflow-anchor: none;\n}\n</code></pre>\n<p>Makes it so the scroll bar doesn't stay anchored to the top when a child element is added. For example, when new message is added at the bottom of chat, scroll chat to new message.</p>\n"
},
{
"answer_id": 71930402,
"author": "Marcio Duarte",
"author_id": 2394994,
"author_profile": "https://Stackoverflow.com/users/2394994",
"pm_score": 3,
"selected": false,
"text": "<p>If your project targets <a href=\"https://caniuse.com/css-snappoints\" rel=\"noreferrer\">modern browsers</a>, you can now use <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap\" rel=\"noreferrer\">CSS Scroll Snap</a> to control the scrolling behavior, such as keeping any dynamically generated element at the bottom.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-css lang-css prettyprint-override\"><code> .wrapper > div {\n background-color: white;\n border-radius: 5px;\n padding: 5px 10px;\n text-align: center;\n font-family: system-ui, sans-serif;\n }\n\n .wrapper {\n display: flex;\n padding: 5px;\n background-color: #ccc;\n border-radius: 5px;\n flex-direction: column;\n gap: 5px;\n margin: 10px;\n max-height: 150px;\n\n /* Control snap from here */\n overflow-y: auto;\n overscroll-behavior-y: contain;\n scroll-snap-type: y mandatory;\n }\n\n .wrapper > div:last-child {\n scroll-snap-align: start;\n }</code></pre>\r\n<pre class=\"snippet-code-html lang-html prettyprint-override\"><code><div class=\"wrapper\">\n <div>01</div>\n <div>02</div>\n <div>03</div>\n <div>04</div>\n <div>05</div>\n <div>06</div>\n <div>07</div>\n <div>08</div>\n <div>09</div>\n <div>10</div>\n</div></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 72136483,
"author": "PanDe",
"author_id": 3964056,
"author_profile": "https://Stackoverflow.com/users/3964056",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use simple CSS to do this?</p>\n<p>The trick is to use display: flex; and flex-direction: column-reverse;</p>\n<pre><code>Here is a working example. https://codepen.io/jimbol/pen/YVJzBg\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258/"
] |
I am creating a chat using Ajax requests and I'm trying to get messages div to scroll to the bottom without much luck.
I am wrapping everything in this div:
```
#scroll {
height:400px;
overflow:scroll;
}
```
Is there a way to keep it scrolled to the bottom by default using JS?
Is there a way to keep it scrolled to the bottom after an ajax request?
|
Here's what I use on my site:
```
var objDiv = document.getElementById("your_div");
objDiv.scrollTop = objDiv.scrollHeight;
```
|
270,648 |
<p>How do you invoke a tkinter <code>event</code> from a separate object? </p>
<p>I'm looking for something like wxWidgets <code>wx.CallAfter</code>. For example, If I create an object, and pass to it my <code>Tk</code> root instance, and then try to call a method of that root window from my object, my app locks up.</p>
<p>The best I can come up with is to use the the <code>after</code> method and check the status from my separate object, but that seems wasteful.</p>
|
[
{
"answer_id": 276069,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 6,
"selected": true,
"text": "<p>To answer your specific question of \"How do you invoke a TkInter event from a separate object\", use the <code>event_generate</code> command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism. </p>\n\n<p>For example:</p>\n\n<pre><code>from tkinter import *\n\ndef doFoo(*args):\n print(\"Hello, world\")\n\nroot = Tk()\nroot.bind(\"<<Foo>>\", doFoo)\n\n# some time later, inject the \"<<Foo>>\" virtual event at the\n# tail of the event queue\nroot.event_generate(\"<<Foo>>\", when=\"tail\")\n</code></pre>\n\n<p>Note that the <code>event_generate</code> call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will <em>freeze the GUI</em>. </p>\n\n<p>I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.</p>\n\n<p>Here's an example of successfully accessing methods on a root window from some other object:</p>\n\n<pre><code>from tkinter import *\n\nclass myClass:\n def __init__(self, root):\n print(\"root background is %s\" % root.cget(\"background\"))\n\nroot = Tk()\nnewObj = myClass(root)\n</code></pre>\n"
},
{
"answer_id": 36778730,
"author": "user110954",
"author_id": 2787591,
"author_profile": "https://Stackoverflow.com/users/2787591",
"pm_score": 3,
"selected": false,
"text": "<p>Here below just some doc and link to better understand Bryan's answer above.</p>\n<p>function description from <a href=\"https://web.archive.org/web/20190527174904/http://infohost.nmt.edu:80/tcc/help/pubs/tkinter/web/universal.html\" rel=\"nofollow noreferrer\">New Mexico Tech</a> :</p>\n<p><code>w.event_generate(sequence, **kw)</code></p>\n<blockquote>\n<p>This method causes an event to trigger without any external stimulus. The handling of the event is the same as if it had been triggered by an external stimulus. The sequence argument describes the event to be triggered. You can set values for selected fields in the Event object by providing keyword=value arguments, where the keyword specifies the name of a field in the Event object.</p>\n</blockquote>\n<p>list and description of tcl/tk event attributes <a href=\"https://www.tcl.tk/man/tcl/TkCmd/event.htm\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270648",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16363/"
] |
How do you invoke a tkinter `event` from a separate object?
I'm looking for something like wxWidgets `wx.CallAfter`. For example, If I create an object, and pass to it my `Tk` root instance, and then try to call a method of that root window from my object, my app locks up.
The best I can come up with is to use the the `after` method and check the status from my separate object, but that seems wasteful.
|
To answer your specific question of "How do you invoke a TkInter event from a separate object", use the `event_generate` command. It allows you to inject events into the event queue of the root window. Combined with Tk's powerful virtual event mechanism it becomes a handy message passing mechanism.
For example:
```
from tkinter import *
def doFoo(*args):
print("Hello, world")
root = Tk()
root.bind("<<Foo>>", doFoo)
# some time later, inject the "<<Foo>>" virtual event at the
# tail of the event queue
root.event_generate("<<Foo>>", when="tail")
```
Note that the `event_generate` call will return immediately. It's not clear if that's what you want or not. Generally speaking you don't want an event based program to block waiting for a response to a specific event because it will *freeze the GUI*.
I'm not sure if this solves your problem though; without seeing your code I'm not sure what your real problem is. I can, for example, access methods of root in the constructor of an object where the root is passed in without the app locking up. This tells me there's something else going on in your code.
Here's an example of successfully accessing methods on a root window from some other object:
```
from tkinter import *
class myClass:
def __init__(self, root):
print("root background is %s" % root.cget("background"))
root = Tk()
newObj = myClass(root)
```
|
270,672 |
<p>Is there anyway to use unicode strings (most probably in UTF-8, but could be any encoding) in PostScript?</p>
<p>So far, i've been using this function to transforms fonts to Latin1 encoding:</p>
<pre><code>/latinize {
findfont
dup length dict begin
{ 1 index /FID ne {def}{pop pop} ifelse }forall
/Encoding ISOLatin1Encoding def
currentdict
end
definefont pop
}bind def
/HelveLat /Helvetica latinize
/HelveLatbold /Helvetica-Bold latinize
</code></pre>
<p>but i really don't like it.</p>
|
[
{
"answer_id": 920209,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 3,
"selected": false,
"text": "<p>Not really or in any simple "out of the box" way. See <a href=\"https://web.archive.org/web/20120322112530/http://en.wikibooks.org/wiki/PostScript_FAQ#Does_PostScript_support_unicode_for_CJK_fonts.3F\" rel=\"nofollow noreferrer\">this FAQ entry for details</a>.</p>\n"
},
{
"answer_id": 12524359,
"author": "luser droog",
"author_id": 733077,
"author_profile": "https://Stackoverflow.com/users/733077",
"pm_score": 2,
"selected": false,
"text": "<p>This may or may not fit your bill, but the interpreter that I wrote (<a href=\"http://code.google.com/p/xpost/\" rel=\"nofollow\">xpost</a>) uses Cairo for all its graphics and font functions, including <code>show</code>. So whatever support Cairo has to offer, xpost doesn't get in the way. But before you get too excited, it's a one-man project, and doesn't quite offer full Level-1 Postscript yet. </p>\n\n<p>Edit: The newest version does not support this. <a href=\"http://code.google.com/p/xpost/downloads/detail?name=xpost2g.zip\" rel=\"nofollow\">Here</a> is the last version that did (<a href=\"http://code.google.com/p/xpost/downloads/detail?name=xpost2.pdf\" rel=\"nofollow\">listing</a>).</p>\n\n<hr>\n\n<p>Here's my C code for the show operator itself.</p>\n\n<pre><code>OPFN_ void show(state *st, object s) {\n char str[s.u.c.n+1];\n memcpy(str, STR(s), s.u.c.n); str[s.u.c.n] = '\\0';\n //printf(\"showing (%s)\\n\", str);\n if (st->cr) {\n cairo_show_text(st->cr, str);\n cairo_surface_flush(st->surface);\n XFlush(st->dis);\n }\n}\n</code></pre>\n\n<p>And from the <a href=\"http://cairographics.org/manual/\" rel=\"nofollow\">Cairo docs</a>:</p>\n\n<blockquote>\n <p>cairo_show_text ()</p>\n \n <p>void cairo_show_text (cairo_t *cr,<br>\n const char *utf8);</p>\n \n <p>A drawing operator that generates the shape from a string of UTF-8 characters, rendered according to the current font_face, font_size (font_matrix), and font_options.</p>\n \n <p>This function first computes a set of glyphs for the string of text. The first glyph is placed so that its origin is at the current point. The origin of each subsequent glyph is offset from that of the previous glyph by the advance values of the previous glyph.</p>\n \n <p>After this call the current point is moved to the origin of where the next glyph would be placed in this same progression. That is, the current point will be at the origin of the final glyph offset by its advance values. This allows for easy display of a single logical string with multiple calls to cairo_show_text().</p>\n \n <p>Note: The cairo_show_text() function call is part of what the cairo designers call the \"toy\" text API. It is convenient for short demos and simple programs, but it is not expected to be adequate for serious text-using applications. See cairo_show_glyphs() for the \"real\" text display API in cairo. </p>\n \n <p><a href=\"http://www.cairographics.org/manual/cairo-text.html#cairo-show-text\" rel=\"nofollow\">http://www.cairographics.org/manual/cairo-text.html#cairo-show-text</a></p>\n</blockquote>\n\n<p>So it's UTF-8 in Postscript, near as I can figure! :)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11649/"
] |
Is there anyway to use unicode strings (most probably in UTF-8, but could be any encoding) in PostScript?
So far, i've been using this function to transforms fonts to Latin1 encoding:
```
/latinize {
findfont
dup length dict begin
{ 1 index /FID ne {def}{pop pop} ifelse }forall
/Encoding ISOLatin1Encoding def
currentdict
end
definefont pop
}bind def
/HelveLat /Helvetica latinize
/HelveLatbold /Helvetica-Bold latinize
```
but i really don't like it.
|
Not really or in any simple "out of the box" way. See [this FAQ entry for details](https://web.archive.org/web/20120322112530/http://en.wikibooks.org/wiki/PostScript_FAQ#Does_PostScript_support_unicode_for_CJK_fonts.3F).
|
270,674 |
<p>I've generated a pdf using iTextSharp and I can preview it very well in ASP.Net but I need to send it directly to printer without a preview. I want the user to click the print button and automatically the document prints.</p>
<p>I know that a page can be sent directly to printer using the javascript window.print() but I don't know how to make it for a PDF.</p>
<p>Edit: it is not embedded, I generate it like this;</p>
<pre><code> ...
FileStream stream = new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create);
Document pdf = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
pdf.Add(new Paragraph(member.ToString()));
pdf.Close();
Response.Redirect("~1.pdf");
...
</code></pre>
<p>And here I am.</p>
|
[
{
"answer_id": 270733,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 1,
"selected": false,
"text": "<p>Is the pdf embedded in the page with embedd-tag or just opened in a frame or how are you showing it?</p>\n\n<p>If its embedded, just make sure that the object is selected and then do a print().</p>\n\n<p>Get the ref to the embedded document. </p>\n\n<pre><code>var x = document.getElementById(\"mypdfembeddobject\"); \nx.click();\nx.setActive();\nx.focus();\nx.print();\n</code></pre>\n"
},
{
"answer_id": 270759,
"author": "Stefan",
"author_id": 19307,
"author_profile": "https://Stackoverflow.com/users/19307",
"pm_score": 0,
"selected": false,
"text": "<p>ALso, try this gem:</p>\n\n<pre><code><link ref=\"mypdf\" media=\"print\" href=\"mypdf.pdf\">\n</code></pre>\n\n<p>I havent tested it, but what I have read about it, it can be used in this way to let the mypdf.pdf be printed instead of page content whatever method you are using to print the page.</p>\n\n<p>Search for media=\"print\" to check out more.</p>\n"
},
{
"answer_id": 270848,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>You can embed javascript in the pdf, so that the user gets a print dialog as soon as their browser loads the pdf.</p>\n\n<p>I'm not sure about iTextSharp, but the javascript that I use is</p>\n\n<pre><code>var pp = this.getPrintParams();\npp.interactive = pp.constants.interactionLevel.automatic;\nthis.print(pp);\n</code></pre>\n\n<p>For iTextSharp, check out <a href=\"http://itextsharp.sourceforge.net/examples/Chap1106.cs\" rel=\"nofollow noreferrer\">http://itextsharp.sourceforge.net/examples/Chap1106.cs</a></p>\n"
},
{
"answer_id": 271257,
"author": "Nelson Miranda",
"author_id": 1130097,
"author_profile": "https://Stackoverflow.com/users/1130097",
"pm_score": 3,
"selected": false,
"text": "<p>Finally I made it, but I had to use an IFRAME, I defined an IFrame in the aspx and didn't set the src property, in the cs file I made generated the pdf file and set the src property of the iFrame as the generated pdf file name, like this;</p>\n\n<pre><code>Document pdf = new Document(PageSize.LETTER);\nPdfWriter writer = PdfWriter.GetInstance(pdf, \nnew FileStream(Request.PhysicalApplicationPath + \"~1.pdf\", FileMode.Create));\npdf.Open();\n\n//This action leads directly to printer dialogue\nPdfAction jAction = PdfAction.JavaScript(\"this.print(true);\\r\", writer);\nwriter.AddJavaScript(jAction);\n\npdf.Add(new Paragraph(\"My first PDF on line\"));\npdf.Close();\n\n//Open the pdf in the frame\nframe1.Attributes[\"src\"] = \"~1.pdf\";\n</code></pre>\n\n<p>And that made the trick, however, I think that i should implement your solution Stefan, the problem is that I'm new to asp.net and javascript and if I don't have a complete source code I could not code your suggestion but at least is the first step, I was very surprised how much code in html and javascript i need to learn. Thnx. </p>\n"
},
{
"answer_id": 6749843,
"author": "frenchone",
"author_id": 461581,
"author_profile": "https://Stackoverflow.com/users/461581",
"pm_score": 1,
"selected": false,
"text": "<p>It's a little more tricky if you're using pdfsharp but quite doable</p>\n\n<pre><code>PdfDocument document = new PdfDocument();\nPdfPage page = document.AddPage(); \nXGraphics gfx = XGraphics.FromPdfPage(page); \nXFont font = new XFont(\"Verdana\", 20, XFontStyle.BoldItalic); \n// Draw the text \ngfx.DrawString(\"Hello, World!\", font, XBrushes.Black, \n new XRect(0, 0, page.Width, page.Height), \n XStringFormats.Center); \n\n// real stuff starts here\n\n// current version of pdfsharp doesn't support actions \n// http://www.pdfsharp.net/wiki/WorkOnPdfObjects-sample.ashx\n// so we got to get close to the metal see chapter 12.6.4 of \n// http://partners.adobe.com/public/developer/pdf/index_reference.html\nPdfDictionary dict = new PdfDictionary(document); // \ndict.Elements[\"/S\"] = new PdfName(\"/JavaScript\"); // \ndict.Elements[\"/JS\"] = new PdfString(\"this.print(true);\\r\");\ndocument.Internals.AddObject(dict);\ndocument.Internals.Catalog.Elements[\"/OpenAction\"] = \n PdfInternals.GetReference(dict);\ndocument.Save(Server.MapPath(\"2.pdf\"));\nframe1.Attributes[\"src\"] = \"2.pdf\"; \n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/270674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1130097/"
] |
I've generated a pdf using iTextSharp and I can preview it very well in ASP.Net but I need to send it directly to printer without a preview. I want the user to click the print button and automatically the document prints.
I know that a page can be sent directly to printer using the javascript window.print() but I don't know how to make it for a PDF.
Edit: it is not embedded, I generate it like this;
```
...
FileStream stream = new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create);
Document pdf = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(pdf, stream);
pdf.Open();
pdf.Add(new Paragraph(member.ToString()));
pdf.Close();
Response.Redirect("~1.pdf");
...
```
And here I am.
|
Finally I made it, but I had to use an IFRAME, I defined an IFrame in the aspx and didn't set the src property, in the cs file I made generated the pdf file and set the src property of the iFrame as the generated pdf file name, like this;
```
Document pdf = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(pdf,
new FileStream(Request.PhysicalApplicationPath + "~1.pdf", FileMode.Create));
pdf.Open();
//This action leads directly to printer dialogue
PdfAction jAction = PdfAction.JavaScript("this.print(true);\r", writer);
writer.AddJavaScript(jAction);
pdf.Add(new Paragraph("My first PDF on line"));
pdf.Close();
//Open the pdf in the frame
frame1.Attributes["src"] = "~1.pdf";
```
And that made the trick, however, I think that i should implement your solution Stefan, the problem is that I'm new to asp.net and javascript and if I don't have a complete source code I could not code your suggestion but at least is the first step, I was very surprised how much code in html and javascript i need to learn. Thnx.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.