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
|
---|---|---|---|---|---|---|
280,834 |
<p>I would like to know if it is possible, to select certain columns from one table, and another column from a second table, which would relate to a non imported column in the first table. I have to obtain this data from access, and do not know if this is possible with Access, or SQL in general.</p>
|
[
{
"answer_id": 280844,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 2,
"selected": false,
"text": "<p>What you are looking for are JOINs:</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Join_(SQL)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Join_(SQL)</a></p>\n\n<p>You need primary keys for the referenced data sets and foreign keys in the first table.</p>\n"
},
{
"answer_id": 280848,
"author": "Noah Goodrich",
"author_id": 20178,
"author_profile": "https://Stackoverflow.com/users/20178",
"pm_score": 4,
"selected": true,
"text": "<p>Assuming the following table structure:</p>\n\n<pre><code>CREATE TABLE tbl_1 (\n pk_1 int,\n field_1 varchar(25),\n field_2 varchar(25)\n);\n\nCREATE TABLE tbl_2 (\n pk_2 int,\n fk_1 int,\n field_3 varchar(25),\n field_4 varchar(25)\n);\n</code></pre>\n\n<p>You could use the following:</p>\n\n<pre><code>SELECT t1.field_1, t2.field_3\nFROM tbl_1 t1\nINNER JOIN tbl_2 t2 ON t1.pk_1 = t2.fk_1\nWHERE t2.field_3 = \"Some String\"\n</code></pre>\n\n<p>In regard to Bill's post, there are two ways to create JOIN's within SQL queries:</p>\n\n<ul>\n<li><p>Implicit - The join is created using\nthe WHERE clause of the query with multiple tables being specified in the FROM clause</p></li>\n<li><p>Explicit - The join is created using\n the appropriate type of JOIN clause\n (INNER, LEFT, RIGHT, FULL)</p></li>\n</ul>\n\n<p>It is always recommended that you use the explicit JOIN syntax as implicit joins can present problems once the query becomes more complex. </p>\n\n<p>For example, if you later add an explicit join to a query that already uses an implicit join with multiple tables referenced in the FROM clause, the first table referenced in the FROM clause will not be visible to the explicitly joined table.</p>\n"
},
{
"answer_id": 280850,
"author": "Daniel M",
"author_id": 36559,
"author_profile": "https://Stackoverflow.com/users/36559",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not 100% sure I understand your question.</p>\n\n<p>Is the following true:</p>\n\n<p>Your first table is imported from somewhere else. \nYou are only importing some columns.\nYou want to build a query which references a column which you haven't imported.</p>\n\n<p>If this is true, it's just not possible. As far as the Access query engine in concerned the non-imported columns don't exist.</p>\n\n<p>Why not just import them as well?</p>\n"
},
{
"answer_id": 280855,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>But primary keys make the query more efficient</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I would like to know if it is possible, to select certain columns from one table, and another column from a second table, which would relate to a non imported column in the first table. I have to obtain this data from access, and do not know if this is possible with Access, or SQL in general.
|
Assuming the following table structure:
```
CREATE TABLE tbl_1 (
pk_1 int,
field_1 varchar(25),
field_2 varchar(25)
);
CREATE TABLE tbl_2 (
pk_2 int,
fk_1 int,
field_3 varchar(25),
field_4 varchar(25)
);
```
You could use the following:
```
SELECT t1.field_1, t2.field_3
FROM tbl_1 t1
INNER JOIN tbl_2 t2 ON t1.pk_1 = t2.fk_1
WHERE t2.field_3 = "Some String"
```
In regard to Bill's post, there are two ways to create JOIN's within SQL queries:
* Implicit - The join is created using
the WHERE clause of the query with multiple tables being specified in the FROM clause
* Explicit - The join is created using
the appropriate type of JOIN clause
(INNER, LEFT, RIGHT, FULL)
It is always recommended that you use the explicit JOIN syntax as implicit joins can present problems once the query becomes more complex.
For example, if you later add an explicit join to a query that already uses an implicit join with multiple tables referenced in the FROM clause, the first table referenced in the FROM clause will not be visible to the explicitly joined table.
|
280,846 |
<p><strong>Mark Up</strong></p>
<pre><code><%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Zuhaib.test" %>
<!-- Put IE into quirks mode -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="css/general.css" rel="stylesheet" type="text/css" />
<link href="css/outbound.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server" class="wrapper">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="left">
</div>
<div id="right">
</div>
</form>
</body>
</html>
</code></pre>
<p><strong>CSS</strong></p>
<pre><code>html, body
{
margin:0;
padding:0;
border:0;
overflow:hidden;
width:100%;
height:100%;
}
* html body
{
height:100%;
width:100%;
}
*{
margin:0;
padding:0;
}
.wrapper
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
height:100%;
width:100%;
}
* html .wrapper
{
width:100%;
height:100%;
}
#left{
float:left;
height:100%;
width:100px;
overflow:hidden;
background-color:Blue;
}
* html #left{
height:100%;
width:100px;
}
#right{
margin-left:100px;
height:100%;
background-color:Red;
}
* html #right{
height:100%;
}
</code></pre>
<p><strong>Result in IE && FF</strong><br>
<a href="http://img139.imageshack.us/img139/9871/ie3pxgapnl4.jpg" rel="nofollow noreferrer">Resutls in IE & FF http://img139.imageshack.us/img139/9871/ie3pxgapnl4.jpg</a><br>
The result is same with both IE 6 & 7. How can I remove the gap between the divs?</p>
<p><strong>Udate</strong><br>
I have two divs each with 100% height. the left div is a fixed width floating div. Even after giving correct margin-left to the right div, there remains a gap (3px) between the two divs. Where as in firefox it renders correctly.</p>
<p>The reason I have used quirk mode is to able to get 100% height for the divs</p>
<p>Can this gap be eliminated? Or is there a better way to do two column 100% height layout with pure css?</p>
|
[
{
"answer_id": 280933,
"author": "postback",
"author_id": 32849,
"author_profile": "https://Stackoverflow.com/users/32849",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the comment on top of the page\nThe \"Put IE into quirks mode\" thing</p>\n\n<p>You are using a lot of 'hacks'. By that I mean the CSS selectors that begin with * html</p>\n\n<p>I'm not saying that is the cause of the problem, but it is not good practice and is error prone.</p>\n\n<p>1) try using conditional comments for the browser that has the gap problem instead of using those hacks\n2) try editing your question by providing information about the version of IE you're testing against (my guess is IE 6 or even lower).</p>\n"
},
{
"answer_id": 280947,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 4,
"selected": true,
"text": "<p>As already said, your code is full of hacks. Please remove especially the unnecessary definitions. If a browser does not support <em>cascading</em> style sheets, it will not support CSS anyway.</p>\n\n<p>That being said, why not use position: absolute; for #right?</p>\n\n<p>As in</p>\n\n<pre><code>#right{\n position: absolute;\n left: 100px;\n padding-left: -100px;\n width: 100%;\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 287410,
"author": "infoxicated",
"author_id": 37380,
"author_profile": "https://Stackoverflow.com/users/37380",
"pm_score": 2,
"selected": false,
"text": "<p>To be honest, if you're filling up the whole body with these divs, then you're better off giving one of them a transparent background and setting the background color of the body to the desired color, masking the problem.</p>\n\n<p>Especially if, in trying to solve the IE issue, you're introducing a plague of CSS hacks into what should be nice and clean code considering the simple layout you're shooting for.</p>\n"
},
{
"answer_id": 11905015,
"author": "David Eison",
"author_id": 72670,
"author_profile": "https://Stackoverflow.com/users/72670",
"pm_score": 1,
"selected": false,
"text": "<p>The actual problem is the whitespace between the closing div tag and the next opening div tag. If you put them together on the same line with no space between them, or fill in the white space with a comment, the whitespace will be gone. </p>\n\n<pre><code><div id=\"left\">\n</div><div id=\"right\">\n</div> \n</code></pre>\n\n<p>or</p>\n\n<pre><code> <div id=\"left\">\n </div><!-- IE doesn't ignore whitespace between divs\n --><div id=\"right\">\n </div> \n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25138/"
] |
**Mark Up**
```
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="test.aspx.cs" Inherits="Zuhaib.test" %>
<!-- Put IE into quirks mode -->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
<title></title>
<link href="css/general.css" rel="stylesheet" type="text/css" />
<link href="css/outbound.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form id="form1" runat="server" class="wrapper">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div id="left">
</div>
<div id="right">
</div>
</form>
</body>
</html>
```
**CSS**
```
html, body
{
margin:0;
padding:0;
border:0;
overflow:hidden;
width:100%;
height:100%;
}
* html body
{
height:100%;
width:100%;
}
*{
margin:0;
padding:0;
}
.wrapper
{
position:fixed;
top:0px;
bottom:0px;
left:0px;
right:0px;
height:100%;
width:100%;
}
* html .wrapper
{
width:100%;
height:100%;
}
#left{
float:left;
height:100%;
width:100px;
overflow:hidden;
background-color:Blue;
}
* html #left{
height:100%;
width:100px;
}
#right{
margin-left:100px;
height:100%;
background-color:Red;
}
* html #right{
height:100%;
}
```
**Result in IE && FF**
[Resutls in IE & FF http://img139.imageshack.us/img139/9871/ie3pxgapnl4.jpg](http://img139.imageshack.us/img139/9871/ie3pxgapnl4.jpg)
The result is same with both IE 6 & 7. How can I remove the gap between the divs?
**Udate**
I have two divs each with 100% height. the left div is a fixed width floating div. Even after giving correct margin-left to the right div, there remains a gap (3px) between the two divs. Where as in firefox it renders correctly.
The reason I have used quirk mode is to able to get 100% height for the divs
Can this gap be eliminated? Or is there a better way to do two column 100% height layout with pure css?
|
As already said, your code is full of hacks. Please remove especially the unnecessary definitions. If a browser does not support *cascading* style sheets, it will not support CSS anyway.
That being said, why not use position: absolute; for #right?
As in
```
#right{
position: absolute;
left: 100px;
padding-left: -100px;
width: 100%;
...
}
```
|
280,864 |
<p>Does anyone know of an open source web service/wcf service that can stream media content to clients? In particular I am looking for something that could access my music collection and stream it to a client (could be a client browser, win mobile app or even iphone application).</p>
<p>I guess it would have to be WCF based as I'm not sure that webservices do streaming really well. Also Windows Media Streaming Services is not the best way to go as the service should operate from a vista/xp machine (preferably). </p>
<p>If not, does anyone know the best way to start going about creating something like this - I'm not sure I know where to start with this one, although I can see many many uses for such a service!</p>
|
[
{
"answer_id": 280933,
"author": "postback",
"author_id": 32849,
"author_profile": "https://Stackoverflow.com/users/32849",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the comment on top of the page\nThe \"Put IE into quirks mode\" thing</p>\n\n<p>You are using a lot of 'hacks'. By that I mean the CSS selectors that begin with * html</p>\n\n<p>I'm not saying that is the cause of the problem, but it is not good practice and is error prone.</p>\n\n<p>1) try using conditional comments for the browser that has the gap problem instead of using those hacks\n2) try editing your question by providing information about the version of IE you're testing against (my guess is IE 6 or even lower).</p>\n"
},
{
"answer_id": 280947,
"author": "phihag",
"author_id": 35070,
"author_profile": "https://Stackoverflow.com/users/35070",
"pm_score": 4,
"selected": true,
"text": "<p>As already said, your code is full of hacks. Please remove especially the unnecessary definitions. If a browser does not support <em>cascading</em> style sheets, it will not support CSS anyway.</p>\n\n<p>That being said, why not use position: absolute; for #right?</p>\n\n<p>As in</p>\n\n<pre><code>#right{\n position: absolute;\n left: 100px;\n padding-left: -100px;\n width: 100%;\n ...\n}\n</code></pre>\n"
},
{
"answer_id": 287410,
"author": "infoxicated",
"author_id": 37380,
"author_profile": "https://Stackoverflow.com/users/37380",
"pm_score": 2,
"selected": false,
"text": "<p>To be honest, if you're filling up the whole body with these divs, then you're better off giving one of them a transparent background and setting the background color of the body to the desired color, masking the problem.</p>\n\n<p>Especially if, in trying to solve the IE issue, you're introducing a plague of CSS hacks into what should be nice and clean code considering the simple layout you're shooting for.</p>\n"
},
{
"answer_id": 11905015,
"author": "David Eison",
"author_id": 72670,
"author_profile": "https://Stackoverflow.com/users/72670",
"pm_score": 1,
"selected": false,
"text": "<p>The actual problem is the whitespace between the closing div tag and the next opening div tag. If you put them together on the same line with no space between them, or fill in the white space with a comment, the whitespace will be gone. </p>\n\n<pre><code><div id=\"left\">\n</div><div id=\"right\">\n</div> \n</code></pre>\n\n<p>or</p>\n\n<pre><code> <div id=\"left\">\n </div><!-- IE doesn't ignore whitespace between divs\n --><div id=\"right\">\n </div> \n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/445/"
] |
Does anyone know of an open source web service/wcf service that can stream media content to clients? In particular I am looking for something that could access my music collection and stream it to a client (could be a client browser, win mobile app or even iphone application).
I guess it would have to be WCF based as I'm not sure that webservices do streaming really well. Also Windows Media Streaming Services is not the best way to go as the service should operate from a vista/xp machine (preferably).
If not, does anyone know the best way to start going about creating something like this - I'm not sure I know where to start with this one, although I can see many many uses for such a service!
|
As already said, your code is full of hacks. Please remove especially the unnecessary definitions. If a browser does not support *cascading* style sheets, it will not support CSS anyway.
That being said, why not use position: absolute; for #right?
As in
```
#right{
position: absolute;
left: 100px;
padding-left: -100px;
width: 100%;
...
}
```
|
280,872 |
<p>I'm trying to write a <a href="/questions/tagged/vba" class="post-tag" title="show questions tagged 'vba'" rel="tag">vba</a> macro for a group tha</p>
<ul>
<li>has one workbook where they daily create new worksheets, and also have</li>
<li><em>Sheet 1</em>, <em>Sheet 2</em> and <em>Sheet 3</em> at the end of their long list of sheets. </li>
</ul>
<p>I need to create a external cell reference in a new column in a different workbook where this information is being summarized.</p>
<p>So I need to know how to get the <strong>last non-empty sheet</strong> so I can grab this data and place it appropriately in the summary.</p>
|
[
{
"answer_id": 280979,
"author": "dbb",
"author_id": 25675,
"author_profile": "https://Stackoverflow.com/users/25675",
"pm_score": 4,
"selected": true,
"text": "<p>This function works through the sheets from right to left until it finds a non-blank sheet, and returns its name</p>\n\n<pre><code>Function GetLastNonEmptySheetName() As String\nDim i As Long\nFor i = Worksheets.Count To 1 Step -1\n If Sheets(i).UsedRange.Cells.Count > 1 Then\n GetLastNonEmptySheetName = Sheets(i).Name\n Exit Function\n End If\nNext i\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 8061601,
"author": "brettdj",
"author_id": 641067,
"author_profile": "https://Stackoverflow.com/users/641067",
"pm_score": 1,
"selected": false,
"text": "<p>The method above will ignore a sheet with a single cell entry, while that may seem to be a quibble, a <code>Find</code> looking for a non-blank cell will give more certainty.</p>\n\n<p>The <code>xlFormulas</code> argument in the <code>Find</code> method will find hidden cells (but not filtered cells) whereas <code>xlValues</code> won't.</p>\n\n<pre><code>Sub FindLastSht()\n Dim lngCnt As Long\n Dim rng1 As Range\n Dim strSht As String\n With ActiveWorkbook\n For lngCnt = .Worksheets.Count To 1 Step -1\n Set rng1 = .Sheets(lngCnt).Cells.Find(\"*\", , xlFormulas)\n If Not rng1 Is Nothing Then\n strSht = .Sheets(lngCnt).Name\n Exit For\n End If\n Next lngCnt\n If Len(strSht) > 0 Then\n MsgBox \"Last used sheet in \" & .Name & \" is \" & strSht\n Else\n MsgBox \"No data is contained in \" & .Name\n End If\n End With\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280872",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26140/"
] |
I'm trying to write a [vba](/questions/tagged/vba "show questions tagged 'vba'") macro for a group tha
* has one workbook where they daily create new worksheets, and also have
* *Sheet 1*, *Sheet 2* and *Sheet 3* at the end of their long list of sheets.
I need to create a external cell reference in a new column in a different workbook where this information is being summarized.
So I need to know how to get the **last non-empty sheet** so I can grab this data and place it appropriately in the summary.
|
This function works through the sheets from right to left until it finds a non-blank sheet, and returns its name
```
Function GetLastNonEmptySheetName() As String
Dim i As Long
For i = Worksheets.Count To 1 Step -1
If Sheets(i).UsedRange.Cells.Count > 1 Then
GetLastNonEmptySheetName = Sheets(i).Name
Exit Function
End If
Next i
End Function
```
|
280,879 |
<p>In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.</p>
<p>But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?</p>
<p>The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.</p>
|
[
{
"answer_id": 280886,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>If you are already using jQuery in a pre-1.9 version AND you don't need to detect IE 11, you can do this:</p>\n\n<pre><code>if (jQuery.browser.msie == true) { \nif (jQuery.browser.version == 7.0)\n // .. do something for 7.0\nelse \n // .. do something for < 7.0\n}\n</code></pre>\n"
},
{
"answer_id": 280889,
"author": "Winston Smith",
"author_id": 35086,
"author_profile": "https://Stackoverflow.com/users/35086",
"pm_score": 2,
"selected": false,
"text": "<p>The Navigator object contains all the information about the user's browser:</p>\n\n<p>eg:</p>\n\n<p>var browser=navigator.appName;</p>\n\n<p>var b_version=navigator.appVersion;</p>\n\n<p>var version=parseFloat(b_version);</p>\n\n<p>See:</p>\n\n<p><a href=\"http://www.w3schools.com/js/js_browser.asp\" rel=\"nofollow noreferrer\">http://www.w3schools.com/js/js_browser.asp</a></p>\n"
},
{
"answer_id": 280925,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 2,
"selected": false,
"text": "<p>If you are checking for a certain functionality, you should check for it directly, e.g. <code>if (window.focus) {window.focus();}</code> <strong>Browser detection is never reliable enough.</strong></p>\n\n<p>For more details on object vs browser detection, <a href=\"http://www.quirksmode.org/js/support.html\" rel=\"nofollow noreferrer\">check out this article at Quirksmode</a>.</p>\n\n<p>On the other hand, if the feature you need IS the browser type and version, e.g. for statistical purposes, go with <code>navigator.appName</code> and <code>navigator.appVersion</code>. (Beware though - many less popular browsers masquerade themselves as MSIE 6 or 7, as certain sites block anything that's not IE on the premise that \"all the modern browsers are IE, right?\" (hint: not anymore).)</p>\n"
},
{
"answer_id": 280949,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 4,
"selected": false,
"text": "<p>If you really want to be sure you are using IE and a specific version then you could obviously use IE's conditional tags to only run certain code within IE. It's not really that pretty but at least you can be sure that it is really IE and not some spoofed version.</p>\n\n<pre><code><script>\n var isIE = false;\n var version = -1;\n</script>\n<!--[if IE 6]>\n <script>\n isIE = true;\n version = 6\n </script>\n<![endif]-->\n<!--[if IE 7]>\n <script>\n isIE = true;\n version = 7\n </script>\n<![endif]-->\n</code></pre>\n\n<p>It's pretty self explanatory. In IE6 <code>isIE</code> is <code>true</code> and <code>version</code> is <code>6</code>, In IE7 <code>isIE</code> is <code>true</code> and <code>version</code> is <code>7</code> otherwise <code>isIE</code> is false and <code>version</code> is <code>-1</code></p>\n\n<p>Alternatively you could just roll your own solution using code plagarised from jQuery.</p>\n\n<pre><code>var userAgent = navigator.userAgent.toLowerCase();\nvar version = (userAgent.match( /.+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/ ) || [])[1],\nvar isIE = /msie/.test( userAgent ) && !/opera/.test( userAgent ), \n</code></pre>\n"
},
{
"answer_id": 281176,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 0,
"selected": false,
"text": "<p>This is the script I use and it seems to work well enough:</p>\n\n<pre><code>// Returns 0 if the browser is anything but IE\nfunction getIEVersion() {\n var ua = window.navigator.userAgent;\n var ie = ua.indexOf(\"MSIE \");\n return ((ie > 0) ? parseInt(ua.substring(ie+5, ua.indexOf(\".\", ie))) : 0);\n}\n</code></pre>\n\n<p>Hope that helps someone...</p>\n"
},
{
"answer_id": 281215,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 2,
"selected": false,
"text": "<p>This is probably going to get voted down, because it's not directly answering the question, but... You should <strong>not</strong> be writing browser-specific code. There's very little you can't do while coding for most widely-accepted browsers.</p>\n\n<p>EDIT: The only time I found it useful to have conditional comments was when I needed to include ie6.css or ie7.css.</p>\n"
},
{
"answer_id": 281291,
"author": "kmilo",
"author_id": 14015,
"author_profile": "https://Stackoverflow.com/users/14015",
"pm_score": 5,
"selected": true,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ms537509.aspx\" rel=\"noreferrer\">detecting Internet Explorer More Effectively</a> at msdn:</p>\n\n<pre><code>function getInternetExplorerVersion()\n// Returns the version of Internet Explorer or a -1\n// (indicating the use of another browser).\n{\n var rv = -1; // Return value assumes failure.\n if (navigator.appName == 'Microsoft Internet Explorer')\n {\n var ua = navigator.userAgent;\n var re = new RegExp(\"MSIE ([0-9]{1,}[\\.0-9]{0,})\");\n if (re.exec(ua) != null)\n rv = parseFloat( RegExp.$1 );\n }\n return rv;\n}\n\nfunction checkVersion()\n{\n var msg = \"You're not using Internet Explorer.\";\n var ver = getInternetExplorerVersion();\n\n if ( ver > -1 )\n {\n if ( ver >= 6.0 ) \n msg = \"You're using a recent copy of Internet Explorer.\"\n else\n msg = \"You should upgrade your copy of Internet Explorer.\";\n }\n alert( msg );\n}\n</code></pre>\n"
},
{
"answer_id": 281293,
"author": "Illandril",
"author_id": 17887,
"author_profile": "https://Stackoverflow.com/users/17887",
"pm_score": 0,
"selected": false,
"text": "<p>This should give you more details than you'll want:</p>\n\n<pre><code>var agent = navigator.userAgent;\nvar msiePattern = /.*MSIE ((\\d+).\\d+).*/\nif( msiePattern.test( agent ) ) {\n var majorVersion = agent.replace(msiePattern,\"$2\");\n var fullVersion = agent.replace(msiePattern,\"$1\");\n var majorVersionInt = parseInt( majorVersion );\n var fullVersionFloat = parseFloat( fullVersion );\n}\n</code></pre>\n"
},
{
"answer_id": 282214,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 0,
"selected": false,
"text": "<p>As no-one seems to have said it yet:</p>\n\n<blockquote>\n <p>The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.</p>\n</blockquote>\n\n<p>You can easily put a conditional comment — a JScript conditional comment, not an HTML one — inside a function:</p>\n\n<pre><code>function something() {\n var IE_WIN= false;\n var IE_WIN_7PLUS= false;\n /*@cc_on\n @if (@_win32)\n IE_WIN= true;\n @if (@_jscript_version>=5.7)\n IE_WIN_7PLUS = true;\n @end\n @end @*/\n ...\n}\n</code></pre>\n\n<p>It's more typical to do the test once at global level though, and just check the stored flags thereafter.</p>\n\n<p>CCs are more reliable than sifting through the mess that the User-Agent string has become these days. String matching methods on navigator.userAgent can misidentify spoofing browsers such as Opera.</p>\n\n<p>Of course capability sniffing is much better for cross-browser code where it's possible, but for some cases — usually bug fix workarounds — you do need to identify IE specifically, and CCs are probably the best way to do that today.</p>\n"
},
{
"answer_id": 3831044,
"author": "Mike Ruhlin",
"author_id": 453031,
"author_profile": "https://Stackoverflow.com/users/453031",
"pm_score": 2,
"selected": false,
"text": "<p>So IE8 compatibility view mode reports itself as IE7 even though it doesn't always behave the same. And for that, I give you this monster:</p>\n\n<pre><code> // IE8's \"Compatibility mode\" is anything but. Oh well, at least it doesn't take 40 lines of code to detect and work around it.\n// Oh wait:\n/*\n * Author: Rob Reid\n * CreateDate: 20-Mar-09\n * Description: Little helper function to return details about IE 8 and its various compatibility settings either use as it is\n * or incorporate into a browser object. Remember browser sniffing is not the best way to detect user-settings as spoofing is\n * very common so use with caution.\n*/\nfunction IEVersion(){\n var _n=navigator,_w=window,_d=document;\n var version=\"NA\";\n var na=_n.userAgent;\n var ieDocMode=\"NA\";\n var ie8BrowserMode=\"NA\";\n // Look for msie and make sure its not opera in disguise\n if(/msie/i.test(na) && (!_w.opera)){\n // also check for spoofers by checking known IE objects\n if(_w.attachEvent && _w.ActiveXObject){ \n // Get version displayed in UA although if its IE 8 running in 7 or compat mode it will appear as 7\n version = (na.match( /.+ie\\s([\\d.]+)/i ) || [])[1];\n // Its IE 8 pretending to be IE 7 or in compat mode \n if(parseInt(version)==7){ \n // documentMode is only supported in IE 8 so we know if its here its really IE 8\n if(_d.documentMode){\n version = 8; //reset? change if you need to\n // IE in Compat mode will mention Trident in the useragent\n if(/trident\\/\\d/i.test(na)){\n ie8BrowserMode = \"Compat Mode\";\n // if it doesn't then its running in IE 7 mode\n }else{\n ie8BrowserMode = \"IE 7 Mode\";\n }\n }\n }else if(parseInt(version)==8){\n // IE 8 will always have documentMode available\n if(_d.documentMode){ ie8BrowserMode = \"IE 8 Mode\";}\n }\n // If we are in IE 8 (any mode) or previous versions of IE we check for the documentMode or compatMode for pre 8 versions \n ieDocMode = (_d.documentMode) ? _d.documentMode : (_d.compatMode && _d.compatMode==\"CSS1Compat\") ? 7 : 5;//default to quirks mode IE5 \n }\n }\n\n return {\n \"UserAgent\" : na,\n \"Version\" : version,\n \"BrowserMode\" : ie8BrowserMode,\n \"DocMode\": ieDocMode\n } \n}\nvar ieVersion = IEVersion();\nvar IsIE8 = ieVersion.Version != \"NA\" && ieVersion.Version >= 8;\n</code></pre>\n"
},
{
"answer_id": 17086279,
"author": "Jerad Rutnam",
"author_id": 2482093,
"author_profile": "https://Stackoverflow.com/users/2482093",
"pm_score": 1,
"selected": false,
"text": "<p>Well... here is what I came up after thinking for a while. just wanted to find a simple solution.</p>\n\n<pre><code>if (navigator.appName == 'Microsoft Internet Explorer') {\n // Take navigator appversion to an array & split it \n var appVersion = navigator.appVersion.split(';');\n // Get the part that you want from the above array \n var verNumber = appVersion[1];\n\n alert(verNumber);\n}\n</code></pre>\n\n<p>It returns ex:- MSIE 10.0, MSIE 9.0, MSIE 8.0</p>\n\n<p>further extend, if you want to check if it's \"lower than\" or \"greater than\" IE version, you can slightly modify </p>\n\n<pre><code>if (navigator.appName == 'Microsoft Internet Explorer') {\n var appVersion = navigator.appVersion.split(';');\n var verNumber = appVersion[1];\n // Reaplce \"MSIE \" from the srting and parse it to integer value \n var IEversion = parseInt(verNumber.replace('MSIE ', ''));\n\n if(IEversion <= 9){\n alert(verNumber);\n }\n}\n</code></pre>\n\n<p>got the base idea from <a href=\"http://www.w3schools.com/js/js_window_navigator.asp\" rel=\"nofollow\">w3schools</a>, hope this will help some one... :D</p>\n"
},
{
"answer_id": 22380361,
"author": "user3415643",
"author_id": 3415643,
"author_profile": "https://Stackoverflow.com/users/3415643",
"pm_score": 0,
"selected": false,
"text": "<pre><code><script>\n alert(\"It is \" + isIE());\n\n //return ie number as int else return false\n function isIE() {\n var myNav = navigator.userAgent.toLowerCase();\n if (myNav.indexOf('msie') != -1) //ie less than ie11 (6-10)\n {\n return parseInt(myNav.split('msie')[1]);\n }\n else \n {\n //Is the version more than ie11? Then return false else return ie int number\n return (!!(myNav.match(/trident/) && !myNav.match(/msie/)) == false)?false : parseInt(myNav.split('rv:')[1].substring(0, 2)); \n }\n }\n</script>\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280879",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In some existing code there is a test to see if the user is running IE, by checking if the object Browser.Engine.trident is defined and returns true.
But how can I determine if the user is running IE6 (or earlier) or IE7 (or later)?
The test is needed inside a JavaScript function so a conditional comment doesn't seem suitable.
|
From [detecting Internet Explorer More Effectively](http://msdn.microsoft.com/en-us/library/ms537509.aspx) at msdn:
```
function getInternetExplorerVersion()
// Returns the version of Internet Explorer or a -1
// (indicating the use of another browser).
{
var rv = -1; // Return value assumes failure.
if (navigator.appName == 'Microsoft Internet Explorer')
{
var ua = navigator.userAgent;
var re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
if (re.exec(ua) != null)
rv = parseFloat( RegExp.$1 );
}
return rv;
}
function checkVersion()
{
var msg = "You're not using Internet Explorer.";
var ver = getInternetExplorerVersion();
if ( ver > -1 )
{
if ( ver >= 6.0 )
msg = "You're using a recent copy of Internet Explorer."
else
msg = "You should upgrade your copy of Internet Explorer.";
}
alert( msg );
}
```
|
280,891 |
<p>I've decided to reimplement the datetime picker, as a standard datetime picker isn't nullable. The user wants to start with a blank field and type (not select) the date.</p>
<p>I've created a user control to do just that, but if the user control is near the edge of the form, it will be cut off on the form boundry. The standard datetime picker doesn't suffer from this problem.</p>
<p>Here is a picture showing the problem. My user control is on the left, the standard datetimepicker is on the right:</p>
<p><a href="http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg">alt text http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg</a></p>
<p>As you can see, the standard control will display over the form AND application boundry. How do I get the month picker in my control to do the same thing?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 280905,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 2,
"selected": false,
"text": "<p>The screenshots looks like a Windows Forms applications, so my answer is for winforms.</p>\n\n<p>I guess the best solution would be to create a customcontrol that itself uses the datetime picker that already has the behavior.</p>\n\n<p>Show a empty textbox until it gets clicked, then display the datetimepicker.</p>\n\n<p>That would save you a bunch of code..</p>\n"
},
{
"answer_id": 280932,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure, but a quick look at the DateTimePicker class on Reflector takes me to the <code>SafeNativeMethods.SetWindowPos</code> internal class.</p>\n\n<p>You can override the <code>SetBoundsCore</code> from the base Control class or, like Tigraine stated, create a custom control based on the DateTimePicker.</p>\n\n<p>Hope it helps,\nBruno Figueiredo</p>\n"
},
{
"answer_id": 282008,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this when trying to implement a custom control and discovered that it's a remarkably hard problem. There's no built-in functionality within the <code>Windows.Forms</code> model to support controls whose display area extends outside the client area of their container. </p>\n\n<p>You basically have to either use the Windows API or draw your controls inside a Form with AlwaysOnTop set. Both approaches are harder than they should be. I ended up redesigning my control so that instead of displaying its expanded contents in a dropdown it used a modal dialog. This was a pretty unsatisfying solution, but I spent a couple of weeks trying other approaches and could never get anything that worked consistently across all use cases (like disappearing when the application loses focus).</p>\n"
},
{
"answer_id": 282117,
"author": "Dan R",
"author_id": 24222,
"author_profile": "https://Stackoverflow.com/users/24222",
"pm_score": 0,
"selected": false,
"text": "<p>The reason that your control gets chopped off is because it is a child control of the form that you reside on. Any control on the form must be contained by the form, hence it gets chopped off.</p>\n\n<p>I haven't done this in .Net, but had a similar problem in VB6. The solution then was to set the parent of the popup window (the calendar in your case) to be the desktop. This will allow it to extend beyond the boundaries of your form. You'll have to do some P/Invoke magic to find the hWnd of the popup, and another P/Invoke to set the parent.</p>\n"
},
{
"answer_id": 282217,
"author": "Jesper Palm",
"author_id": 36455,
"author_profile": "https://Stackoverflow.com/users/36455",
"pm_score": 6,
"selected": true,
"text": "<p>The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.</p>\n\n<pre><code>/// <summary>\n/// A simple popup window that can host any System.Windows.Forms.Control\n/// </summary>\npublic class PopupWindow : System.Windows.Forms.ToolStripDropDown\n{\n private System.Windows.Forms.Control _content;\n private System.Windows.Forms.ToolStripControlHost _host;\n\n public PopupWindow(System.Windows.Forms.Control content)\n {\n //Basic setup...\n this.AutoSize = false;\n this.DoubleBuffered = true;\n this.ResizeRedraw = true;\n\n this._content = content;\n this._host = new System.Windows.Forms.ToolStripControlHost(content);\n\n //Positioning and Sizing\n this.MinimumSize = content.MinimumSize;\n this.MaximumSize = content.Size;\n this.Size = content.Size;\n content.Location = Point.Empty;\n\n //Add the host to the list\n this.Items.Add(this._host);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>PopupWindow popup = new PopupWindow(MyControlToHost);\npopup.Show(new Point(100,100));\n...\npopup.Close();\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29830/"
] |
I've decided to reimplement the datetime picker, as a standard datetime picker isn't nullable. The user wants to start with a blank field and type (not select) the date.
I've created a user control to do just that, but if the user control is near the edge of the form, it will be cut off on the form boundry. The standard datetime picker doesn't suffer from this problem.
Here is a picture showing the problem. My user control is on the left, the standard datetimepicker is on the right:
[alt text http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg](http://img50.imageshack.us/img50/9104/datetimepickervu6.jpg)
As you can see, the standard control will display over the form AND application boundry. How do I get the month picker in my control to do the same thing?
Thanks!
|
The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.
```
/// <summary>
/// A simple popup window that can host any System.Windows.Forms.Control
/// </summary>
public class PopupWindow : System.Windows.Forms.ToolStripDropDown
{
private System.Windows.Forms.Control _content;
private System.Windows.Forms.ToolStripControlHost _host;
public PopupWindow(System.Windows.Forms.Control content)
{
//Basic setup...
this.AutoSize = false;
this.DoubleBuffered = true;
this.ResizeRedraw = true;
this._content = content;
this._host = new System.Windows.Forms.ToolStripControlHost(content);
//Positioning and Sizing
this.MinimumSize = content.MinimumSize;
this.MaximumSize = content.Size;
this.Size = content.Size;
content.Location = Point.Empty;
//Add the host to the list
this.Items.Add(this._host);
}
}
```
Usage:
```
PopupWindow popup = new PopupWindow(MyControlToHost);
popup.Show(new Point(100,100));
...
popup.Close();
```
|
280,892 |
<p>I'm looking to write a small proxy server for kicks and giggles.</p>
<p>Apart from the options in libWWW, can anyone recommend any opensource options for the HTTP server and client code? Thinking of a library of some kind similar to libWWW.</p>
<p>Chosen language is C/C++ but open to Java, C#, Python... etc. :-)</p>
|
[
{
"answer_id": 280905,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 2,
"selected": false,
"text": "<p>The screenshots looks like a Windows Forms applications, so my answer is for winforms.</p>\n\n<p>I guess the best solution would be to create a customcontrol that itself uses the datetime picker that already has the behavior.</p>\n\n<p>Show a empty textbox until it gets clicked, then display the datetimepicker.</p>\n\n<p>That would save you a bunch of code..</p>\n"
},
{
"answer_id": 280932,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not 100% sure, but a quick look at the DateTimePicker class on Reflector takes me to the <code>SafeNativeMethods.SetWindowPos</code> internal class.</p>\n\n<p>You can override the <code>SetBoundsCore</code> from the base Control class or, like Tigraine stated, create a custom control based on the DateTimePicker.</p>\n\n<p>Hope it helps,\nBruno Figueiredo</p>\n"
},
{
"answer_id": 282008,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into this when trying to implement a custom control and discovered that it's a remarkably hard problem. There's no built-in functionality within the <code>Windows.Forms</code> model to support controls whose display area extends outside the client area of their container. </p>\n\n<p>You basically have to either use the Windows API or draw your controls inside a Form with AlwaysOnTop set. Both approaches are harder than they should be. I ended up redesigning my control so that instead of displaying its expanded contents in a dropdown it used a modal dialog. This was a pretty unsatisfying solution, but I spent a couple of weeks trying other approaches and could never get anything that worked consistently across all use cases (like disappearing when the application loses focus).</p>\n"
},
{
"answer_id": 282117,
"author": "Dan R",
"author_id": 24222,
"author_profile": "https://Stackoverflow.com/users/24222",
"pm_score": 0,
"selected": false,
"text": "<p>The reason that your control gets chopped off is because it is a child control of the form that you reside on. Any control on the form must be contained by the form, hence it gets chopped off.</p>\n\n<p>I haven't done this in .Net, but had a similar problem in VB6. The solution then was to set the parent of the popup window (the calendar in your case) to be the desktop. This will allow it to extend beyond the boundaries of your form. You'll have to do some P/Invoke magic to find the hWnd of the popup, and another P/Invoke to set the parent.</p>\n"
},
{
"answer_id": 282217,
"author": "Jesper Palm",
"author_id": 36455,
"author_profile": "https://Stackoverflow.com/users/36455",
"pm_score": 6,
"selected": true,
"text": "<p>The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.</p>\n\n<pre><code>/// <summary>\n/// A simple popup window that can host any System.Windows.Forms.Control\n/// </summary>\npublic class PopupWindow : System.Windows.Forms.ToolStripDropDown\n{\n private System.Windows.Forms.Control _content;\n private System.Windows.Forms.ToolStripControlHost _host;\n\n public PopupWindow(System.Windows.Forms.Control content)\n {\n //Basic setup...\n this.AutoSize = false;\n this.DoubleBuffered = true;\n this.ResizeRedraw = true;\n\n this._content = content;\n this._host = new System.Windows.Forms.ToolStripControlHost(content);\n\n //Positioning and Sizing\n this.MinimumSize = content.MinimumSize;\n this.MaximumSize = content.Size;\n this.Size = content.Size;\n content.Location = Point.Empty;\n\n //Add the host to the list\n this.Items.Add(this._host);\n }\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre><code>PopupWindow popup = new PopupWindow(MyControlToHost);\npopup.Show(new Point(100,100));\n...\npopup.Close();\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm looking to write a small proxy server for kicks and giggles.
Apart from the options in libWWW, can anyone recommend any opensource options for the HTTP server and client code? Thinking of a library of some kind similar to libWWW.
Chosen language is C/C++ but open to Java, C#, Python... etc. :-)
|
The ToolStripDropDown control has this functionallity so by inheriting from it we can make a simple PopupWindow.
```
/// <summary>
/// A simple popup window that can host any System.Windows.Forms.Control
/// </summary>
public class PopupWindow : System.Windows.Forms.ToolStripDropDown
{
private System.Windows.Forms.Control _content;
private System.Windows.Forms.ToolStripControlHost _host;
public PopupWindow(System.Windows.Forms.Control content)
{
//Basic setup...
this.AutoSize = false;
this.DoubleBuffered = true;
this.ResizeRedraw = true;
this._content = content;
this._host = new System.Windows.Forms.ToolStripControlHost(content);
//Positioning and Sizing
this.MinimumSize = content.MinimumSize;
this.MaximumSize = content.Size;
this.Size = content.Size;
content.Location = Point.Empty;
//Add the host to the list
this.Items.Add(this._host);
}
}
```
Usage:
```
PopupWindow popup = new PopupWindow(MyControlToHost);
popup.Show(new Point(100,100));
...
popup.Close();
```
|
280,894 |
<p>I have an access database, with a query made. I need to automate it so that each night this query can run and export to a tab delimited csv file. It is not possible to export a query to a csv file from within access. My question is, are there any tools that can select certain tables, or perform an sql query on an mdb file, and export to a csv file?</p>
|
[
{
"answer_id": 280900,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>VBScript works quite well with the Jet engine. However, I do not see why you say \" It is not possible to export a query to a csv file from within access.\"</p>\n\n<pre><code> Sub TransferCSV()\n\n DoCmd.TransferText acExportDelim, , \"PutNameOfQueryHere\", \"C:\\PutPathAnd\\FilenameHere.csv\", True\n\n End Sub\n</code></pre>\n\n<p>Is the usual way in VBA.</p>\n\n<p>EDIT:\nIt is possible to run a VBScript file (.vbs) from the command line. Here is some sample VBScript to output a tab delimited file.</p>\n\n<pre><code>db = \"C:\\Docs\\LTD.mdb\"\nTextExportFile = \"C:\\Docs\\Exp.txt\"\n\nSet cn = CreateObject(\"ADODB.Connection\")\nSet rs = CreateObject(\"ADODB.Recordset\")\n\ncn.Open _\n \"Provider = Microsoft.Jet.OLEDB.4.0; \" & _\n \"Data Source =\" & db\n\nstrSQL = \"SELECT * FROM tblMembers\"\n\nrs.Open strSQL, cn, 3, 3\n\nSet fs = CreateObject(\"Scripting.FileSystemObject\")\n\nSet f = fs.CreateTextFile(TextExportFile, True)\n\na = rs.GetString\n\nf.WriteLine a\n\nf.Close\n</code></pre>\n"
},
{
"answer_id": 280903,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>SQL Server Integration Services is able to do the transformation that you are talking about. Don't be fooled by the name, because you don't need SQL Server in order to automate and run the packages.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/ms141026.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms141026.aspx</a></p>\n"
},
{
"answer_id": 280965,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 3,
"selected": true,
"text": "<p>Actually, you can export a query to a csv file from within Access.</p>\n\n<p>You can do this with a Macro using the TransferText method.</p>\n\n<p>Macro:</p>\n\n<pre><code> Name = ExportQuery\n Action = TransferText\n Transfer Type = Export Delimited\n Table Name = [name of your Access query]\n File Name = [path of output file]\n Has Field Names = [Yes or No, as desired]\n</code></pre>\n\n<p>You can execute the macro from the command line like this:</p>\n\n<pre><code>\"[your MS Office path]\\msaccess.exe\" [your databse].mdb /excl /X ExportQuery /runtime\n</code></pre>\n\n<p>Since you're having trouble with TransferText in a macro try this:</p>\n\n<p>1) Create a Module named \"ExportQuery\". In this module, create a function called \"ExportQuery\":</p>\n\n<pre><code>Function ExportQuery()\n DoCmd.TransferText acExportDelim, , \"[your query]\", \"[output file].csv\"\nEnd Function\n</code></pre>\n\n<p>2) Create a Macro named RunExportQuery:</p>\n\n<pre><code>Action = RunCode\nFunction Name = ExportQuery ()\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
I have an access database, with a query made. I need to automate it so that each night this query can run and export to a tab delimited csv file. It is not possible to export a query to a csv file from within access. My question is, are there any tools that can select certain tables, or perform an sql query on an mdb file, and export to a csv file?
|
Actually, you can export a query to a csv file from within Access.
You can do this with a Macro using the TransferText method.
Macro:
```
Name = ExportQuery
Action = TransferText
Transfer Type = Export Delimited
Table Name = [name of your Access query]
File Name = [path of output file]
Has Field Names = [Yes or No, as desired]
```
You can execute the macro from the command line like this:
```
"[your MS Office path]\msaccess.exe" [your databse].mdb /excl /X ExportQuery /runtime
```
Since you're having trouble with TransferText in a macro try this:
1) Create a Module named "ExportQuery". In this module, create a function called "ExportQuery":
```
Function ExportQuery()
DoCmd.TransferText acExportDelim, , "[your query]", "[output file].csv"
End Function
```
2) Create a Macro named RunExportQuery:
```
Action = RunCode
Function Name = ExportQuery ()
```
|
280,904 |
<p>I hope this is a simple enough question for any SQL people out there...</p>
<p>We have a table which hold system configuration data, and this is tied to a history table via triggers so we can track who changed what, and when. </p>
<p>I have a requirement to add another value in to this table, but it is one that will change frequently from code, and has a requirement that we don't track it's history (we don't want to clog the table with many thousands of updates per day.</p>
<p>At present, our trigger is a little like this...</p>
<pre><code>CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
</code></pre>
<p>I'd like to be able to add some logic to stop it creating the record if an Attribute colum value is prefixed with a specific string (e.g. "NoHist_")</p>
<p>Given that I have almost no experience working with triggers, I was wondering how it would be best to implement this... I have tried a where clause like the following</p>
<pre><code>where I.Attribute NOT LIKE 'NoHist_%'
</code></pre>
<p>but it doesn't seem to work. The value is still copied over into the history table.</p>
<p>Any help you could offer would be appreciated.</p>
<hr>
<p>OK - as predicted by Cade Roux, this fail spectacularly on multiple updates. I'm going to have to take a new approach to this. Does anyone have any other suggestions, please?</p>
<hr>
<p>Guys - Please educate me here... Why would LEFT() be preferable to LIKE in this scenario? I know I've accepted the answer, but I'd like to know for my own education. </p>
|
[
{
"answer_id": 280956,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 7,
"selected": true,
"text": "<p>Given that a WHERE clause did not work, maybe this will:</p>\n\n<pre><code>CREATE TRIGGER \n [dbo].[SystemParameterInsertUpdate]\nON \n [dbo].[SystemParameter]\nFOR INSERT, UPDATE \nAS\n BEGIN\n SET NOCOUNT ON\n\n If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'\n Begin\n Return\n End\n\n INSERT INTO SystemParameterHistory \n (\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate\n )\n SELECT\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate\n FROM Inserted AS I\nEND\n</code></pre>\n"
},
{
"answer_id": 280975,
"author": "Matty",
"author_id": 26241,
"author_profile": "https://Stackoverflow.com/users/26241",
"pm_score": 3,
"selected": false,
"text": "<p>How about this?</p>\n\n<pre><code>CREATE TRIGGER \n[dbo].[SystemParameterInsertUpdate]\nON \n[dbo].[SystemParameter]\nFOR INSERT, UPDATE \nAS\nBEGIN\nSET NOCOUNT ON\n IF (LEFT((SELECT Attribute FROM INSERTED), 7) <> 'NoHist_') \n BEGIN\n INSERT INTO SystemParameterHistory \n (\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate\n )\n SELECT\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate\n FROM Inserted AS I\nEND\nEND\n</code></pre>\n"
},
{
"answer_id": 281008,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 3,
"selected": false,
"text": "<p>Your where clause should have worked. I am at a loss as to why it didn't. Let me show you how I would have figured out the problem with the where clause as it might help you for the future.</p>\n\n<p>When I create triggers, I start at the query window by creating a temp table called #inserted (and or #deleted) with all the columns of the table. Then I popultae it with typical values (Always multiple records and I try to hit the test cases in the values)</p>\n\n<p>Then I write my triggers logic and I can test without it actually being in a trigger. In a case like your where clause not doing what was expected, I could easily test by commenting out the insert to see what the select was returning. I would then probably be easily able to see what the problem was. I assure you that where clasues do work in triggers if they are written correctly.</p>\n\n<p>Once I know that the code works properly for all the cases, I global replace #inserted with inserted and add the create trigger code around it and voila, a tested trigger.</p>\n\n<p>AS I said in a comment, I have a concern that the solution you picked will not work properly in a multiple record insert or update. Triggers should always be written to account for that as you cannot predict if and when they will happen (and they do happen eventually to pretty much every table.)</p>\n"
},
{
"answer_id": 281140,
"author": "Daniel M",
"author_id": 36559,
"author_profile": "https://Stackoverflow.com/users/36559",
"pm_score": -1,
"selected": false,
"text": "<p>Using LIKE will give you options for defining what the rest of the string should look like, but if the rule is just starts with 'NoHist_' it doesn't really matter.</p>\n"
},
{
"answer_id": 281849,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 3,
"selected": false,
"text": "<p>The <code>_</code> character is also a wildcard, BTW, but I'm not sure why this wasn't working for you:</p>\n\n<pre><code>CREATE TRIGGER \n [dbo].[SystemParameterInsertUpdate]\nON \n [dbo].[SystemParameter]\nFOR INSERT, UPDATE \nAS\n BEGIN\n SET NOCOUNT ON\n INSERT INTO SystemParameterHistory \n (\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate\n )\n SELECT\n I.Attribute,\n I.ParameterValue,\n I.ParameterDescription,\n I.ChangeDate\n FROM Inserted AS I\n WHERE I.Attribute NOT LIKE 'NoHist[_]%'\nEND\n</code></pre>\n"
},
{
"answer_id": 562458,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>For triggers in general, you need to use a cursor to handle inserts or updates of multiple rows. For example:</p>\n\n<pre><code>DECLARE @Attribute;\nDECLARE @ParameterValue;\nDECLARE mycursor CURSOR FOR SELECT Attribute, ParameterValue FROM inserted;\nOPEN mycursor;\nFETCH NEXT FROM mycursor into @Attribute, @ParameterValue;\nWHILE @@FETCH_STATUS = 0\nBEGIN\n\nIf @Attribute LIKE 'NoHist_%'\n Begin\n Return\n End\n\netc.\n\nFETCH NEXT FROM mycursor into @Attribute, @ParameterValue;\nEND\n</code></pre>\n\n<p>Triggers, at least in SQL Server, are a big pain and I avoid using them at all.</p>\n"
},
{
"answer_id": 3631976,
"author": "QuintessentialSolutions",
"author_id": 438470,
"author_profile": "https://Stackoverflow.com/users/438470",
"pm_score": 2,
"selected": false,
"text": "<pre><code>CREATE TRIGGER\n [dbo].[SystemParameterInsertUpdate]\nON \n [dbo].[SystemParameter]\nFOR INSERT, UPDATE \nAS\n BEGIN\n SET NOCOUNT ON \n\n DECLARE @StartRow int\n DECLARE @EndRow int\n DECLARE @CurrentRow int\n\n SET @StartRow = 1\n SET @EndRow = (SELECT count(*) FROM inserted)\n SET @CurrentRow = @StartRow\n\n WHILE @CurrentRow <= @EndRow BEGIN\n\n IF (SELECT Attribute FROM (SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', Attribute FROM inserted) AS INS WHERE RowNum = @CurrentRow) LIKE 'NoHist_%' BEGIN\n\n INSERT INTO SystemParameterHistory(\n Attribute,\n ParameterValue,\n ParameterDescription,\n ChangeDate)\n SELECT\n I.Attribute,\n I.ParameterValue,\n I.ParameterDescription,\n I.ChangeDate\n FROM\n (SELECT Attribute, ParameterValue, ParameterDescription, ChangeDate FROM (\n SELECT ROW_NUMBER() OVER (ORDER BY Attribute ASC) AS 'RowNum', * \n FROM inserted)\n AS I \n WHERE RowNum = @CurrentRow\n\n END --END IF\n\n SET @CurrentRow = @CurrentRow + 1\n\n END --END WHILE\nEND --END TRIGGER\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280904",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/377/"
] |
I hope this is a simple enough question for any SQL people out there...
We have a table which hold system configuration data, and this is tied to a history table via triggers so we can track who changed what, and when.
I have a requirement to add another value in to this table, but it is one that will change frequently from code, and has a requirement that we don't track it's history (we don't want to clog the table with many thousands of updates per day.
At present, our trigger is a little like this...
```
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
```
I'd like to be able to add some logic to stop it creating the record if an Attribute colum value is prefixed with a specific string (e.g. "NoHist\_")
Given that I have almost no experience working with triggers, I was wondering how it would be best to implement this... I have tried a where clause like the following
```
where I.Attribute NOT LIKE 'NoHist_%'
```
but it doesn't seem to work. The value is still copied over into the history table.
Any help you could offer would be appreciated.
---
OK - as predicted by Cade Roux, this fail spectacularly on multiple updates. I'm going to have to take a new approach to this. Does anyone have any other suggestions, please?
---
Guys - Please educate me here... Why would LEFT() be preferable to LIKE in this scenario? I know I've accepted the answer, but I'd like to know for my own education.
|
Given that a WHERE clause did not work, maybe this will:
```
CREATE TRIGGER
[dbo].[SystemParameterInsertUpdate]
ON
[dbo].[SystemParameter]
FOR INSERT, UPDATE
AS
BEGIN
SET NOCOUNT ON
If (SELECT Attribute FROM INSERTED) LIKE 'NoHist_%'
Begin
Return
End
INSERT INTO SystemParameterHistory
(
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
)
SELECT
Attribute,
ParameterValue,
ParameterDescription,
ChangeDate
FROM Inserted AS I
END
```
|
280,909 |
<p>Is there a programmatic method to set CPU affinity for a process in c/c++ for the Linux operating system?</p>
|
[
{
"answer_id": 280924,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 7,
"selected": true,
"text": "<p>You need to use <a href=\"http://linux.die.net/man/2/sched_setaffinity\" rel=\"noreferrer\"><code>sched_setaffinity(2)</code></a>.</p>\n\n<p>For example, to run on CPUs 0 and 2 only:</p>\n\n<pre><code>#define _GNU_SOURCE\n#include <sched.h>\n\ncpu_set_t mask;\nCPU_ZERO(&mask);\nCPU_SET(0, &mask);\nCPU_SET(2, &mask);\nint result = sched_setaffinity(0, sizeof(mask), &mask);\n</code></pre>\n\n<p>(<code>0</code> for the first parameter means the current process, supply a PID if it's some other process you want to control).</p>\n\n<p>See also <a href=\"https://linux.die.net/man/3/sched_getcpu\" rel=\"noreferrer\"><code>sched_getcpu(3)</code></a>.</p>\n"
},
{
"answer_id": 280939,
"author": "puetzk",
"author_id": 14312,
"author_profile": "https://Stackoverflow.com/users/14312",
"pm_score": 4,
"selected": false,
"text": "<p>Use sched_setaffinity at the process level, or <a href=\"http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_attr_setaffinity_np.3.html\" rel=\"noreferrer\">pthread_attr_setaffinity_np</a> for individual threads.</p>\n"
},
{
"answer_id": 280996,
"author": "thAAAnos",
"author_id": 36557,
"author_profile": "https://Stackoverflow.com/users/36557",
"pm_score": 2,
"selected": false,
"text": "<p>In short </p>\n\n<pre><code>unsigned long mask = 7; /* processors 0, 1, and 2 */\nunsigned int len = sizeof(mask);\nif (sched_setaffinity(0, len, &mask) < 0) {\n perror(\"sched_setaffinity\");\n}\n</code></pre>\n\n<p>Look in <a href=\"http://www.linuxjournal.com/article/6799\" rel=\"nofollow noreferrer\" title=\"CPU Affinity\">CPU Affinity</a> for more details</p>\n"
},
{
"answer_id": 41299791,
"author": "Amiri",
"author_id": 7030791,
"author_profile": "https://Stackoverflow.com/users/7030791",
"pm_score": 3,
"selected": false,
"text": "<p>I have done many effort to realize what is happening so I add this answer for helping people like me(I use <code>gcc</code> compiler in linux mint)</p>\n<pre><code>#include <sched.h> \ncpu_set_t mask;\n\ninline void assignToThisCore(int core_id)\n{\n CPU_ZERO(&mask);\n CPU_SET(core_id, &mask);\n sched_setaffinity(0, sizeof(mask), &mask);\n}\nint main(){\n //cal this:\n assignToThisCore(2);//assign to core 0,1,2,...\n\n return 0;\n}\n</code></pre>\n<p>But don't forget to add this options to the compiler command : <code>-D _GNU_SOURCE</code>\nBecause operating system might assign a process to the particular core, you can add this <code>GRUB_CMDLINE_LINUX_DEFAULT="quiet splash isolcpus=2,3"</code> to the grub file located in <code>/etc/default</code> and the run <code> sudo update-grub</code> in terminal to reserve the cores you want</p>\n<p><strong>UPDATE:</strong>\nIf you want to assign more cores you can follow this piece of code:</p>\n<pre><code>inline void assignToThisCores(int core_id1, int core_id2)\n{\n CPU_ZERO(&mask1);\n CPU_SET(core_id1, &mask1);\n CPU_SET(core_id2, &mask1);\n sched_setaffinity(0, sizeof(mask1), &mask1);\n //__asm__ __volatile__ ( "vzeroupper" : : : ); // It is hear because of that bug which dirtied the AVX registers, so, if you rely on AVX uncomment it.\n}\n</code></pre>\n"
},
{
"answer_id": 54478296,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 2,
"selected": false,
"text": "<p><strong><code>sched_setaffinity</code> + <code>sched_getaffinity</code> minimal C runnable example</strong></p>\n<p>This example was extracted from my answer at: <a href=\"https://stackoverflow.com/questions/10490756/how-to-use-sched-getaffinity-and-sched-setaffinity-in-linux-from-c/50117787#50117787\">How to use sched_getaffinity and sched_setaffinity in Linux from C?</a> I believe the questions are not duplicates since that one is a subset of this one, as it asks about <code>sched_getaffinity</code> only, and does not mention C++.</p>\n<p>In this example, we get the affinity, modify it, and check if it has taken effect with <a href=\"https://stackoverflow.com/a/16574301/895245\"><code>sched_getcpu()</code></a>.</p>\n<p>main.c</p>\n<pre><code>#define _GNU_SOURCE\n#include <assert.h>\n#include <sched.h>\n#include <stdbool.h>\n#include <stdio.h>\n#include <stdlib.h>\n#include <unistd.h>\n\nvoid print_affinity() {\n cpu_set_t mask;\n long nproc, i;\n\n if (sched_getaffinity(0, sizeof(cpu_set_t), &mask) == -1) {\n perror("sched_getaffinity");\n assert(false);\n }\n nproc = sysconf(_SC_NPROCESSORS_ONLN);\n printf("sched_getaffinity = ");\n for (i = 0; i < nproc; i++) {\n printf("%d ", CPU_ISSET(i, &mask));\n }\n printf("\\n");\n}\n\nint main(void) {\n cpu_set_t mask;\n\n print_affinity();\n printf("sched_getcpu = %d\\n", sched_getcpu());\n CPU_ZERO(&mask);\n CPU_SET(0, &mask);\n if (sched_setaffinity(0, sizeof(cpu_set_t), &mask) == -1) {\n perror("sched_setaffinity");\n assert(false);\n }\n print_affinity();\n /* TODO is it guaranteed to have taken effect already? Always worked on my tests. */\n printf("sched_getcpu = %d\\n", sched_getcpu());\n return EXIT_SUCCESS;\n}\n</code></pre>\n<p><a href=\"https://github.com/cirosantilli/linux-kernel-module-cheat/blob/4aff114c4c654014a97ef23b1513dda5409e79f3/userland/linux/sched_getaffinity.c\" rel=\"nofollow noreferrer\">GitHub upstream</a>.</p>\n<p>Compile and run:</p>\n<pre><code>gcc -ggdb3 -O0 -std=c99 -Wall -Wextra -pedantic -o main.out main.c\n./main.out\n</code></pre>\n<p>Sample output:</p>\n<pre><code>sched_getaffinity = 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 \nsched_getcpu = 9\nsched_getaffinity = 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \nsched_getcpu = 0\n</code></pre>\n<p>Which means that:</p>\n<ul>\n<li>initially, all of my 16 cores were enabled, and the process was randomly running on core 9 (the 10th one)</li>\n<li>after we set the affinity to only the first core, the process was moved necessarily to core 0 (the first one)</li>\n</ul>\n<p>It is also fun to run this program through <code>taskset</code>:</p>\n<pre><code>taskset -c 1,3 ./a.out\n</code></pre>\n<p>Which gives output of form:</p>\n<pre><code>sched_getaffinity = 0 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 \nsched_getcpu = 2\nsched_getaffinity = 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 \nsched_getcpu = 0\n</code></pre>\n<p>and so we see that it limited the affinity from the start.</p>\n<p>This works because the affinity is inherited by child processes, which <code>taskset</code> is forking: <a href=\"https://stackoverflow.com/questions/8336191/how-to-prevent-inheriting-cpu-affinity-by-child-forked-process\">How to prevent inheriting CPU affinity by child forked process?</a></p>\n<p><strong>Python: <code>os.sched_getaffinity</code> and <code>os.sched_setaffinity</code></strong></p>\n<p>See: <a href=\"https://stackoverflow.com/questions/1006289/how-to-find-out-the-number-of-cpus-using-python/55423170#55423170\">How to find out the number of CPUs using python</a></p>\n<p>Tested in Ubuntu 16.04.</p>\n"
},
{
"answer_id": 64960466,
"author": "Rachid K.",
"author_id": 14393739,
"author_profile": "https://Stackoverflow.com/users/14393739",
"pm_score": 0,
"selected": false,
"text": "<p>It is also possible to make it through the shell without any modification in the programs with the <a href=\"https://man7.org/linux/man-pages/man7/cgroups.7.html\" rel=\"nofollow noreferrer\">cgroups</a> and the <em>cpuset</em> sub-system. Cgroups (v1 at least) are typically mounted on <em>/sys/fs/cgroup</em> under which the <em>cpuset</em> sub-system resides. For example:</p>\n<pre><code>$ ls -l /sys/fs/cgroup/\ntotal 0\ndrwxr-xr-x 15 root root 380 nov. 22 20:00 ./\ndrwxr-xr-x 8 root root 0 nov. 22 20:00 ../\ndr-xr-xr-x 2 root root 0 nov. 22 20:00 blkio/\n[...]\nlrwxrwxrwx 1 root root 11 nov. 22 20:00 cpuacct -> cpu,cpuacct/\ndr-xr-xr-x 2 root root 0 nov. 22 20:00 cpuset/\ndr-xr-xr-x 5 root root 0 nov. 22 20:00 devices/\ndr-xr-xr-x 3 root root 0 nov. 22 20:00 freezer/\n[...]\n</code></pre>\n<p>Under <em>cpuset</em>, the <em>cpuset.cpus</em> defines the range of CPUs on which the processes belonging to this cgroup are allowed to run. Here, at the top level, all the CPUs are configured for all the processes of the system. Here, the system has 8 CPUs:</p>\n<pre><code>$ cd /sys/fs/cgroup/cpuset\n$ cat cpuset.cpus\n0-7\n</code></pre>\n<p>The list of processes belonging to this cgroup is listed in the <em>cgroup.procs</em> file:</p>\n<pre><code>$ cat cgroup.procs\n1\n2\n3\n[...]\n12364\n12423\n12424\n12425\n[...]\n</code></pre>\n<p>It is possible to create a child cgroup into which a subset of CPUs are allowed. For example, let's define a sub-cgroup with CPU cores 1 and 3:</p>\n<pre><code>$ pwd\n/sys/fs/cgroup/cpuset\n$ sudo mkdir subset1\n$ cd subset1\n$ pwd\n/sys/fs/cgroup/cpuset/subset1\n$ ls -l \ntotal 0\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cgroup.clone_children\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cgroup.procs\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.cpu_exclusive\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.cpus\n-r--r--r-- 1 root root 0 nov. 22 23:28 cpuset.effective_cpus\n-r--r--r-- 1 root root 0 nov. 22 23:28 cpuset.effective_mems\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.mem_exclusive\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.mem_hardwall\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.memory_migrate\n-r--r--r-- 1 root root 0 nov. 22 23:28 cpuset.memory_pressure\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.memory_spread_page\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.memory_spread_slab\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.mems\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.sched_load_balance\n-rw-r--r-- 1 root root 0 nov. 22 23:28 cpuset.sched_relax_domain_level\n-rw-r--r-- 1 root root 0 nov. 22 23:28 notify_on_release\n-rw-r--r-- 1 root root 0 nov. 22 23:28 tasks\n$ cat cpuset.cpus\n\n$ sudo sh -c "echo 1,3 > cpuset.cpus"\n$ cat cpuset.cpus \n1,3\n</code></pre>\n<p>The <em>cpuset.mems</em> files must be filled before moving any process into this cgroup. Here we move the current shell into this new cgroup (we merely write the pid of the process to move into the <em>cgroup.procs</em> file):</p>\n<pre><code>$ cat cgroup.procs\n\n$ echo $$\n4753\n$ sudo sh -c "echo 4753 > cgroup.procs"\nsh: 1: echo: echo: I/O error\n$ cat cpuset.mems\n\n$ sudo sh -c "echo 0 > cpuset.mems"\n$ cat cpuset.mems\n0\n$ sudo sh -c "echo 4753 > cgroup.procs"\n$ cat cgroup.procs\n4753\n12569\n</code></pre>\n<p>The latter shows that the current shell (pid#4753) is now located in the newly created cgroup (the second pid 12569 is the <em>cat</em>'s command one as being the child of the current shell, it inherits its cgroups). With a formatted <em>ps</em> command, it is possible to verify on which CPU the processes are running (<em>PSR</em> column):</p>\n<pre><code>$ ps -o pid,ppid,psr,command\n PID PPID PSR COMMAND\n 4753 2372 3 bash\n 12672 4753 1 ps -o pid,ppid,psr,command\n</code></pre>\n<p>We can see that the current shell is running on CPU#3 and its child (<em>ps</em> command) which inherits the its cgroups is running on CPU#1.</p>\n<p>As a conclusion, instead of using <em>sched_setaffinity()</em> or any <em>pthread</em> service, it is possible to create a <em>cpuset</em> hierarchy in the cgroups tree and move the processes into them by writing their pids in the corresponding <em>cgroup.procs</em> files.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7362/"
] |
Is there a programmatic method to set CPU affinity for a process in c/c++ for the Linux operating system?
|
You need to use [`sched_setaffinity(2)`](http://linux.die.net/man/2/sched_setaffinity).
For example, to run on CPUs 0 and 2 only:
```
#define _GNU_SOURCE
#include <sched.h>
cpu_set_t mask;
CPU_ZERO(&mask);
CPU_SET(0, &mask);
CPU_SET(2, &mask);
int result = sched_setaffinity(0, sizeof(mask), &mask);
```
(`0` for the first parameter means the current process, supply a PID if it's some other process you want to control).
See also [`sched_getcpu(3)`](https://linux.die.net/man/3/sched_getcpu).
|
280,940 |
<p>I am programming in C against a third party library (in HP/Mercury Loadrunner) that allows a varargs-style variable size argument list for one of it's functions. I want to call this function but I do not know up front how many arguments I will have. </p>
<p>There is a function made by one of my predecessors that serves somewhat but the problem here is that this function assumes the worst case scenario (over 3000 arguments) and hand-codes for that.</p>
<p>To illuminate, here's the (beginning of) the code. The function we call is <code>web_submit_data()</code>. It will HTTP post a set of form data. This implementation came about when dealing with dynamically generated forms with an arbitrary number of fields.
(Cleaned up a fair bit from the original, which hand coded indexes by hand as well..)</p>
<hr>
<pre><code>web_submit_data_buffer_gazillion_items( const char *bufferName, const char *bufferValue)
{
const int size = 129;
int i = 0;
int j = 11;
web_submit_data(&bufferName[i++ * size], //"some form"
&bufferName[i++ * size], //"Action=https://blah.blah/form");
&bufferName[i++ * size], //"Method=POST");
&bufferName[i++ * size], //"TargetFrame=");
&bufferName[i++ * size], //"RecContentType=text/html");
&bufferName[i++ * size], //"Referer=https://blah.blah/index.html");
&bufferName[i++ * size], //"Snapshot=t1.inf");
&bufferName[i++ * size], //"Mode=HTML");
ITEMDATA, // missing in action: indexes 8 through 10
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
..
(repeat the last 3 lines ad nauseum)
..
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size]);
}
</code></pre>
<p>Now I have found an external library that might work (<a href="http://www.dyncall.org" rel="noreferrer">http://www.dyncall.org</a>) but I would much rather not a) be completely processor dependant and b) attempt to teach Loadrunner about linking in external sources..</p>
<p>Edit:
The original function used hardcoded indexes instead of using a variable. Can still revert to that if it turns out to be too unpredictable. However, as I am unlikely to run this with a different compiler or hardware / OS I doubt that really is worth it.</p>
<p>Also: I don't have control over the implementation of web_submit_data(). So just pushing the problem down one level isn't going to cut it..</p>
<p>Another thing to note: The spec for <code>web_submit_data()</code> uses a constant called LAST to mark the end of the argument list. The original implementation doesn't use it. Presumably the callsite does ..</p>
|
[
{
"answer_id": 280993,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 2,
"selected": false,
"text": "<p>There is no portable way to build up an argument list for a variable argument function in C at run time. There are a few implementation-dependent <a href=\"http://c-faq.com/varargs/wacky.html\" rel=\"nofollow noreferrer\">tricks</a> out there, the dyncall library you found looks like a good one and probably more portable than most.</p>\n"
},
{
"answer_id": 281029,
"author": "pnkfelix",
"author_id": 36585,
"author_profile": "https://Stackoverflow.com/users/36585",
"pm_score": 1,
"selected": false,
"text": "<p>Note: the code is already compiler-dependent (though perhaps not processor-dependent), because the invocation of <code>web_submit_data</code> assumes there that the argument subexpressions in a procedure call are evaluated from left-to-right order, but the C language leaves the order of argument evaluation unspecified.</p>\n\n<p>See for reference: <a href=\"http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Evaluation_strategy#Call_by_value</a> </p>\n\n<p>So perhaps the non-portable solution is not going to make things significantly worse for you.</p>\n"
},
{
"answer_id": 281055,
"author": "Ben Collins",
"author_id": 3279,
"author_profile": "https://Stackoverflow.com/users/3279",
"pm_score": 1,
"selected": false,
"text": "<p>Can you restructure your code so that this isn't necessary? Perhaps you could take the incoming buffer and make it more deterministic:</p>\n\n<pre><code>struct form_field\n{\n char[FIELD_NAME_MAX] name;\n char[FIELD_VALUE_MAX] val;\n};\n\nweb_submit_data_buffer_gazillion_items( const char *bufferName, const char *bufferValue)\n{\n /*\n loop over bufferName somehow, either with a known size or terminating record,\n and build an array of form_field records\n */\n //loop\n {\n // build array of records\n }\n\n\n web_submit_data(record_array, array_len);\n\n}\n</code></pre>\n\n<p>Sorry this couldn't be more fleshed out - my wife called me in for breakfast. :-)</p>\n"
},
{
"answer_id": 281153,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 1,
"selected": false,
"text": "<p>Write it once with the preprocessor and never look back.</p>\n\n<pre><code>#define WEB_SUBMIT_BUFFER(name, val) \\\n do { \\\n const int size = 129; \\\n int i = 0; \\\n int j = 11; \\\n web_submit_data(&(name)[i++ * size], \\\n &(name)[i++ * size], \\\n /* etc ad nauseum */ \\\n } while (0)\n</code></pre>\n\n<p>Or if the number of arguments is fixed for each specific call, write a script to generate preprocessor defines to hide how heinous that call is.</p>\n\n<pre><code>#define WEB_SUBMIT_BUFFER_32(name, val) \\\n do { \\\n const int size = 129; \\\n int i = 0; \\\n int j = 11; \\\n web_submit_data(&(name)[i++ * size], \\\n &(name)[i++ * size], \\\n /* 32 times */ \\\n } while (0)\n#define WEB_SUBMIT_BUFFER_33(name, val) ...\n#define WEB_SUBMIT_BUFFER_34(name, val) /* etc */\n</code></pre>\n"
},
{
"answer_id": 281603,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 1,
"selected": false,
"text": "<p>Note that the code sample you posted has undefined behavior - the commas that separate function parameters are not sequence points (those commas are not the comma operator), so modifying <code>i</code> and or <code>j</code> multiple times in the function call argument list results in undefined behavior. </p>\n\n<p>This is not to mention that the evaluation order of function call arguments is not specified by the standard - so even if you did the modification of <code>i</code> and <code>j</code> using functions to evaluate the arguments (function calls themselves are sequence points), you would be pretty much passing the pointers in an indeterminate order.</p>\n\n<p>Also, I don't see how <code>web_submit_data()</code> knows how many arguments it's been passed - I don't see a count or a definitive sentinel argument at the end. But I guess your example may be just that - an example that might not have complete, accurate details. On the other hand, it's <code>web_submit_data()</code>'s problem anyway, right? </p>\n"
},
{
"answer_id": 281731,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 2,
"selected": false,
"text": "<p>Since it's generally not a problem to pass <em>more</em> arguments to a function taking variable arguments than the function expects (see footnote #1), you can do something like the following:</p>\n\n<pre><code>// you didn't give a clear specification of what you want/need, so this \n// example may not be quite what you want as I've had to guess at\n// some of the specifications. Hopefully the comments will make clear\n// what I may have assumed.\n//\n// NOTE: while I have compiled this example, I have not tested it,\n// so there is a distinct possiblity of bugs (particularly\n// off-by-one errors). Check me on this stuff, please.\n\n// I made these up so I could compile the example\n#define ITEMDATA ((char const*) NULL)\n#define ENDITEM ((char const*) 0xffffffff)\n\nvoid web_submit_data_wrapper( const char*bufferName, \n const char* bufferValue, \n size_t headerCount, // number of header pointers to pass (8 in your example)\n size_t itemStartIndex, // index where items start in the buffers (11 in your example)\n size_t itemCount, // number of items to pass (unspecified in your example)\n size_t dataSize ) // size of each header or item (129 in your example)\n{\n // kMaxVarArgs would be 3000 or a gazillion in your case\n\n // size_t const kMaxVarArgs = 20; // I'd prefer to use this in C++\n #define kMaxVarArgs (20)\n\n typedef char const* char_ptr_t;\n typedef char_ptr_t char_ptr_array_t[kMaxVarArgs];\n\n char_ptr_array_t varargs = {0};\n\n size_t idx = 0;\n\n // build up the array of pararmeters we'll pass to the variable arg list\n\n // first the headers\n while (headerCount--) {\n varargs[idx++] = &bufferName[idx * dataSize];\n }\n\n // mark the end of the header data\n varargs[idx++] = ITEMDATA;\n\n // now the \"items\"\n while (itemCount--) {\n varargs[idx++] = &bufferName[itemStartIndex * dataSize];\n varargs[idx++] = &bufferValue[itemStartIndex * dataSize];\n varargs[idx++] = ENDITEM;\n\n ++itemStartIndex;\n }\n\n // the thing after the last item \n // (I'm not sure what this is from your example)\n varargs[idx] = &bufferName[itemStartIndex * dataSize];\n\n // now call the target function - the fact that we're passing more arguments\n // than necessary should not matter due to the way VA_ARGS are handled \n // but see the Footnote in the SO answer for a disclaimer\n\n web_submit_data( \n varargs[0],\n varargs[1],\n varargs[2],\n\n //... ad nasuem until\n\n varargs[kMaxVarArgs-1]\n );\n\n}\n</code></pre>\n\n<hr>\n\n<p>Footnote #1: If you think about how the macros in <code>stdargs.h</code> act this becomes clear. However, I do not claim that this technique would be standards compliant. In fact, in recent history the stackoverflow answers I've posted where I;ve made this disclaimer have in fact been found to be non-standards compliant (usually by the ever vigilant <a href=\"https://stackoverflow.com/users/34509/litb\">litb</a>). So use this technique at your own risk, and verify, verify, verify).</p>\n"
},
{
"answer_id": 283358,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 1,
"selected": false,
"text": "<p>There are two way to pass a variable number of arguments: to a function that accepts \"...\" or to a function that accepts va_list.</p>\n\n<p>You can not dynamically define the number of arguments for the \"...\" interface, but you should be able to do so for the va_list one. Google for va_start, va_end, and va_list.</p>\n"
},
{
"answer_id": 283436,
"author": "Sherm Pendley",
"author_id": 27631,
"author_profile": "https://Stackoverflow.com/users/27631",
"pm_score": 3,
"selected": false,
"text": "<p>In CamelBones I use <a href=\"http://sourceware.org/libffi/\" rel=\"noreferrer\">libffi</a> to call objc_msgSend(), which is a varargs function. Works a treat.</p>\n"
},
{
"answer_id": 283458,
"author": "Ben",
"author_id": 36522,
"author_profile": "https://Stackoverflow.com/users/36522",
"pm_score": 3,
"selected": false,
"text": "<p>Variable length arguments are basically just a pointer to a bunch of packed data that is passed to the required function. It is the responsibility of the called function to interpret this packed data.</p>\n\n<p>The architecture safe way to do this is to use the va_list macros (that n-alexander mentioned), otherwise you may run into issues with how various data types are padded in memory.</p>\n\n<p>The proper way to design varargs functions is to actually have two versions, one that accepts the '...', which in turn extracts the va_list and passes it to a function that takes a va_list. This way you can dynamically construct the arguments if you need to and can instead call the va_list version of the function.</p>\n\n<p>Most standard IO functions have varargs versions: vprintf for printf, vsprintf for sprintf... you get the idea. See if your library implements a function named \"vweb_submit_data\" or something to that effect. If they don't, email them and tell them to fix their library.</p>\n\n<p>3000 lines of the same thing (even if it is preprocessor induced) makes me cringe</p>\n"
},
{
"answer_id": 14524792,
"author": "James Pulley",
"author_id": 691105,
"author_profile": "https://Stackoverflow.com/users/691105",
"pm_score": 0,
"selected": false,
"text": "<p>I know this is an old thread, but I just ran across it. The proper way to handle variable length submit form data in LoadRunner is to use a web_custom_request(). You build the name|value pair structure for the variable length of the arguments as a string and pass it in as a part of the function. </p>\n\n<p>Record the one call as a web_custom_request() and the structure of the argument string for the name|value pairs will become obvious. Simply use any C string handling functions you wish to construct the string in question and include it as a part of the argument list for the web_custom_request().</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280940",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36574/"
] |
I am programming in C against a third party library (in HP/Mercury Loadrunner) that allows a varargs-style variable size argument list for one of it's functions. I want to call this function but I do not know up front how many arguments I will have.
There is a function made by one of my predecessors that serves somewhat but the problem here is that this function assumes the worst case scenario (over 3000 arguments) and hand-codes for that.
To illuminate, here's the (beginning of) the code. The function we call is `web_submit_data()`. It will HTTP post a set of form data. This implementation came about when dealing with dynamically generated forms with an arbitrary number of fields.
(Cleaned up a fair bit from the original, which hand coded indexes by hand as well..)
---
```
web_submit_data_buffer_gazillion_items( const char *bufferName, const char *bufferValue)
{
const int size = 129;
int i = 0;
int j = 11;
web_submit_data(&bufferName[i++ * size], //"some form"
&bufferName[i++ * size], //"Action=https://blah.blah/form");
&bufferName[i++ * size], //"Method=POST");
&bufferName[i++ * size], //"TargetFrame=");
&bufferName[i++ * size], //"RecContentType=text/html");
&bufferName[i++ * size], //"Referer=https://blah.blah/index.html");
&bufferName[i++ * size], //"Snapshot=t1.inf");
&bufferName[i++ * size], //"Mode=HTML");
ITEMDATA, // missing in action: indexes 8 through 10
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
..
(repeat the last 3 lines ad nauseum)
..
&bufferName[j * size],&bufferValue[j++ * size], ENDITEM,
&bufferName[j * size]);
}
```
Now I have found an external library that might work (<http://www.dyncall.org>) but I would much rather not a) be completely processor dependant and b) attempt to teach Loadrunner about linking in external sources..
Edit:
The original function used hardcoded indexes instead of using a variable. Can still revert to that if it turns out to be too unpredictable. However, as I am unlikely to run this with a different compiler or hardware / OS I doubt that really is worth it.
Also: I don't have control over the implementation of web\_submit\_data(). So just pushing the problem down one level isn't going to cut it..
Another thing to note: The spec for `web_submit_data()` uses a constant called LAST to mark the end of the argument list. The original implementation doesn't use it. Presumably the callsite does ..
|
In CamelBones I use [libffi](http://sourceware.org/libffi/) to call objc\_msgSend(), which is a varargs function. Works a treat.
|
280,948 |
<p>I am setting-up my DataGridView like this:</p>
<pre><code> jobs = new List<DisplayJob>();
uxJobList.AutoGenerateColumns = false;
jobListBindingSource.DataSource = jobs;
uxJobList.DataSource = jobListBindingSource;
int newColumn;
newColumn = uxJobList.Columns.Add("Id", "Job No.");
uxJobList.Columns[newColumn].DataPropertyName = "Id";
uxJobList.Columns[newColumn].DefaultCellStyle.Format = Global.JobIdFormat;
uxJobList.Columns[newColumn].DefaultCellStyle.Font = new Font(uxJobList.DefaultCellStyle.Font, FontStyle.Bold);
uxJobList.Columns[newColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
uxJobList.Columns[newColumn].Width = 62;
uxJobList.Columns[newColumn].Resizable = DataGridViewTriState.False;
uxJobList.Columns[newColumn].SortMode = DataGridViewColumnSortMode.Automatic;
:
:
</code></pre>
<p>where the DisplayJob class looks like:</p>
<pre><code> public class DisplayJob
{
public DisplayJob(int id)
{
Id = id;
}
public DisplayJob(JobEntity job)
{
Id = job.Id;
Type = job.JobTypeDescription;
CreatedAt = job.CreatedAt;
StartedAt = job.StartedAt;
ExternalStatus = job.ExternalStatus;
FriendlyExternalStatus = job.FriendlyExternalStatus;
ExternalStatusFriendly = job.ExternalStatusFriendly;
CustomerName = job.Customer.Name;
CustomerKey = job.Customer.CustomerKey;
WorkAddress = job.WorkAddress;
CreatedBy = job.CreatedBy;
CancelledAt = job.CancelledAt;
ClosedAt = job.ClosedAt;
ReasonWaiting = job.ReasonWaiting;
CancelledBy = job.CancelledBy;
CancelledReason = job.CancelledReason;
DisplayCreator = Global.GetDisplayName(CreatedBy);
ActionRedoNeeded = job.ActionRedoNeeded;
if (job.Scheme != null)
{
SchemeCode = job.Scheme.Code;
}
}
public int Id { get; private set; }
public string Type { get; private set; }
public DateTime CreatedAt { get; private set; }
public DateTime? StartedAt { get; private set; }
public string ExternalStatus { get; private set; }
public string FriendlyExternalStatus { get; private set; }
public string ExternalStatusFriendly { get; private set; }
public string CustomerName { get; private set; }
public string CustomerKey { get; private set; }
public string WorkAddress { get; private set; }
public string CreatedBy { get; private set; }
public DateTime? CancelledAt { get; private set; }
public DateTime? ClosedAt { get; private set; }
public string CancelledBy { get; private set; }
public string ReasonWaiting { get; private set; }
public string DisplayCreator { get; private set; }
public string CancelledReason { get; private set; }
public string SchemeCode { get; private set; }
public bool ActionRedoNeeded { get; private set; }
}
</code></pre>
<p>However the column sorting does not work. What is the best way to get this working?</p>
|
[
{
"answer_id": 280958,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 1,
"selected": false,
"text": "<p>I believe that your class must implement the <code>IComparable</code> interface.</p>\n\n<p>Hope it helps,</p>\n\n<p>Bruno Figueiredo</p>\n"
},
{
"answer_id": 280968,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 2,
"selected": false,
"text": "<p>One of the easiest ways is to use the <a href=\"http://blw.sourceforge.net/\" rel=\"nofollow noreferrer\">BindingListView</a> class to wrap your list of DisplayJobs. The class implements some of the required interfaces that enable sorting and filtering in a DataGridView. That's the quick way. It works pretty well, though -- the only caveat is that if you cast things out of the DataGridView you need to cast to the wrapper object (ObjectView) instead of the actual item (DisplayJob).</p>\n\n<p>The less lazy way is to create a custom collection time that implements IBindingList, implementing the sort methods there.</p>\n"
},
{
"answer_id": 280992,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 4,
"selected": true,
"text": "<p>If you want to support sorting and searching on the collection, all <strong>it takes it to derive a class from your BindingList parameterized type</strong>, and override a few base class methods and properties.</p>\n\n<p>The best way is to extend the BindingList and do those following things:</p>\n\n<pre><code>protected override bool SupportsSearchingCore\n{\n get\n {\n return true;\n }\n}\n\nprotected override bool SupportsSortingCore\n{\n get { return true; }\n}\n</code></pre>\n\n<p>You will also need to implement the sort code:</p>\n\n<pre><code>ListSortDirection sortDirectionValue;\nPropertyDescriptor sortPropertyValue;\n\nprotected override void ApplySortCore(PropertyDescriptor prop, \n ListSortDirection direction)\n{\n sortedList = new ArrayList();\n\n // Check to see if the property type we are sorting by implements\n // the IComparable interface.\n Type interfaceType = prop.PropertyType.GetInterface(\"IComparable\");\n\n if (interfaceType != null)\n {\n // If so, set the SortPropertyValue and SortDirectionValue.\n sortPropertyValue = prop;\n sortDirectionValue = direction;\n\n unsortedItems = new ArrayList(this.Count);\n\n // Loop through each item, adding it the the sortedItems ArrayList.\n foreach (Object item in this.Items) {\n sortedList.Add(prop.GetValue(item));\n unsortedItems.Add(item);\n }\n // Call Sort on the ArrayList.\n sortedList.Sort();\n T temp;\n\n // Check the sort direction and then copy the sorted items\n // back into the list.\n if (direction == ListSortDirection.Descending)\n sortedList.Reverse();\n\n for (int i = 0; i < this.Count; i++)\n {\n int position = Find(prop.Name, sortedList[i]);\n if (position != i) {\n temp = this[i];\n this[i] = this[position];\n this[position] = temp;\n }\n }\n\n isSortedValue = true;\n\n // Raise the ListChanged event so bound controls refresh their\n // values.\n OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));\n }\n else\n // If the property type does not implement IComparable, let the user\n // know.\n throw new NotSupportedException(\"Cannot sort by \" + prop.Name +\n \". This\" + prop.PropertyType.ToString() + \n \" does not implement IComparable\");\n}\n</code></pre>\n\n<p>If you need more information you can always go there and get all explication about <a href=\"http://msdn.microsoft.com/en-us/library/aa480736.aspx\" rel=\"nofollow noreferrer\">how to extend the binding list</a>.</p>\n"
},
{
"answer_id": 281973,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 3,
"selected": false,
"text": "<p>Daok's solution is the right one. It's also very often more work than it's worth. </p>\n\n<p>The lazy man's way to get the functionality you want is to create and populate a DataTable off of your business objects, and bind the DataGridView to that.</p>\n\n<p>There are a lot of use cases that this approach won't handle (like, editing), and it obviously wastes time and space. As I said, it's lazy. </p>\n\n<p>But it's easy to write, and the resulting code is a damn sight less mysterious than an implementation of <code>IBindingList</code>. </p>\n\n<p>Also, you're already writing a lot of the code anyway, or similar code at least: the code you write to define the DataTable frees you from having to write code to create the columns of the DataGridView, since the DataGridView will construct its columns off of the DataTable when you bind it.</p>\n"
},
{
"answer_id": 2115736,
"author": "Martijn Boeker",
"author_id": 226103,
"author_profile": "https://Stackoverflow.com/users/226103",
"pm_score": 2,
"selected": false,
"text": "<p>The MS article suggested by Daok got me on the right track, but I wasn't satisfied with MSs implementation of SortableSearchableList. I find that implementation very strange and it didn't work well when there are duplicate values in a column. It also doesn't override IsSortedCore, which seems required by the DataGridView. If IsSortedCore is not overriden, the search glyph doesn't appear and toggling between ascending and descending doesn't work.</p>\n\n<p>See my version of SortableSearchableList below. In ApplySortCore() it sorts using a Comparison delegate set to an anonymous method. This version also supports setting custom comparisons for a particular property, which can be added by a derived class using AddCustomCompare().</p>\n\n<p>I'm not sure if the copyright notice still applies, but I just left it in. </p>\n\n<pre><code>//---------------------------------------------------------------------\n// Copyright (C) Microsoft Corporation. All rights reserved.\n// \n//THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY\n//KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE\n//IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A\n//PARTICULAR PURPOSE.\n//---------------------------------------------------------------------\n\nusing System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Reflection;\nusing System.Collections;\n\nnamespace SomethingSomething\n{\n /// <summary>\n /// Supports sorting of list in data grid view.\n /// </summary>\n /// <typeparam name=\"T\">Type of object to be displayed in data grid view.</typeparam>\n public class SortableSearchableList<T> : BindingList<T>\n {\n #region Data Members\n\n private ListSortDirection _sortDirectionValue;\n private PropertyDescriptor _sortPropertyValue = null;\n\n /// <summary>\n /// Dictionary from property name to custom comparison function.\n /// </summary>\n private Dictionary<string, Comparison<T>> _customComparisons = new Dictionary<string, Comparison<T>>();\n\n #endregion\n\n #region Constructors\n\n /// <summary>\n /// Default constructor.\n /// </summary>\n public SortableSearchableList()\n {\n }\n\n #endregion\n\n #region Properties\n\n /// <summary>\n /// Indicates if sorting is supported.\n /// </summary>\n protected override bool SupportsSortingCore\n {\n get\n {\n return true;\n }\n }\n\n /// <summary>\n /// Indicates if list is sorted.\n /// </summary>\n protected override bool IsSortedCore\n {\n get\n {\n return _sortPropertyValue != null;\n }\n }\n\n /// <summary>\n /// Indicates which property the list is sorted.\n /// </summary>\n protected override PropertyDescriptor SortPropertyCore\n {\n get\n {\n return _sortPropertyValue;\n }\n }\n\n /// <summary>\n /// Indicates in which direction the list is sorted on.\n /// </summary>\n protected override ListSortDirection SortDirectionCore\n {\n get\n {\n return _sortDirectionValue;\n }\n }\n\n #endregion\n\n #region Methods \n\n /// <summary>\n /// Add custom compare method for property.\n /// </summary>\n /// <param name=\"propertyName\"></param>\n /// <param name=\"compareProperty\"></param>\n protected void AddCustomCompare(string propertyName, Comparison<T> comparison)\n {\n _customComparisons.Add(propertyName, comparison);\n }\n\n /// <summary>\n /// Apply sort.\n /// </summary>\n /// <param name=\"prop\"></param>\n /// <param name=\"direction\"></param>\n protected override void ApplySortCore(PropertyDescriptor prop, ListSortDirection direction)\n {\n Comparison<T> comparison;\n if (!_customComparisons.TryGetValue(prop.Name, out comparison))\n {\n // Check to see if the property type we are sorting by implements\n // the IComparable interface.\n Type interfaceType = prop.PropertyType.GetInterface(\"IComparable\");\n if (interfaceType != null)\n {\n comparison = delegate(T t1, T t2)\n {\n IComparable val1 = (IComparable)prop.GetValue(t1);\n IComparable val2 = (IComparable)prop.GetValue(t2);\n return val1.CompareTo(val2);\n };\n }\n else\n {\n // Last option: convert to string and compare.\n comparison = delegate(T t1, T t2)\n {\n string val1 = prop.GetValue(t1).ToString();\n string val2 = prop.GetValue(t2).ToString();\n return val1.CompareTo(val2);\n };\n }\n }\n\n if (comparison != null)\n {\n // If so, set the SortPropertyValue and SortDirectionValue.\n _sortPropertyValue = prop;\n _sortDirectionValue = direction;\n\n // Create sorted list.\n List<T> _sortedList = new List<T>(this); \n _sortedList.Sort(comparison);\n\n // Reverse order if needed.\n if (direction == ListSortDirection.Descending)\n {\n _sortedList.Reverse();\n }\n\n // Update list.\n int count = this.Count;\n for (int i = 0; i < count; i++)\n {\n this[i] = _sortedList[i];\n }\n\n // Raise the ListChanged event so bound controls refresh their\n // values.\n OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));\n }\n }\n\n // Method below was in the original implementation from MS. Don't know what it's for.\n // -- Martijn Boeker, Jan 21, 2010\n\n //protected override void RemoveSortCore()\n //{\n // //int position;\n // //object temp;\n // //// Ensure the list has been sorted.\n // //if (unsortedItems != null)\n // //{\n // // // Loop through the unsorted items and reorder the\n // // // list per the unsorted list.\n // // for (int i = 0; i < unsortedItems.Count; )\n // // {\n // // position = this.Find(SortPropertyCore.Name,\n // // unsortedItems[i].GetType().\n // // GetProperty(SortPropertyCore.Name).\n // // GetValue(unsortedItems[i], null));\n // // if (position >= 0 && position != i)\n // // {\n // // temp = this[i];\n // // this[i] = this[position];\n // // this[position] = (T)temp;\n // // i++;\n // // }\n // // else if (position == i)\n // // i++;\n // // else\n // // // If an item in the unsorted list no longer exists, delete it.\n // // unsortedItems.RemoveAt(i);\n // // }\n // // OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));\n // //}\n //}\n\n /// <summary>\n /// Ability to search an item.\n /// </summary>\n protected override bool SupportsSearchingCore\n {\n get\n {\n return true;\n }\n }\n\n /// <summary>\n /// Finds an item in the list.\n /// </summary>\n /// <param name=\"prop\"></param>\n /// <param name=\"key\"></param>\n /// <returns></returns>\n protected override int FindCore(PropertyDescriptor prop, object key)\n {\n // Implementation not changed from MS example code.\n\n // Get the property info for the specified property.\n PropertyInfo propInfo = typeof(T).GetProperty(prop.Name);\n T item;\n\n if (key != null)\n {\n // Loop through the the items to see if the key\n // value matches the property value.\n for (int i = 0; i < Count; ++i)\n {\n item = (T)Items[i];\n if (propInfo.GetValue(item, null).Equals(key))\n return i;\n }\n }\n return -1;\n }\n\n /// <summary>\n /// Finds an item in the list.\n /// </summary>\n /// <param name=\"prop\"></param>\n /// <param name=\"key\"></param>\n /// <returns></returns>\n private int Find(string property, object key)\n {\n // Implementation not changed from MS example code.\n\n // Check the properties for a property with the specified name.\n PropertyDescriptorCollection properties =\n TypeDescriptor.GetProperties(typeof(T));\n PropertyDescriptor prop = properties.Find(property, true);\n\n // If there is not a match, return -1 otherwise pass search to\n // FindCore method.\n if (prop == null)\n return -1;\n else\n return FindCore(prop, key);\n }\n\n #endregion\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2136930,
"author": "CXRom",
"author_id": 258917,
"author_profile": "https://Stackoverflow.com/users/258917",
"pm_score": 0,
"selected": false,
"text": "<p>Martijn excelent code but only one detail u need to validate null cells or empty :)</p>\n\n<pre><code>if (!_customComparisons.TryGetValue(prop.Name, out comparison))\n{\n // Check to see if the property type we are sorting by implements\n // the IComparable interface.\n Type interfaceType = prop.PropertyType.GetInterface(\"IComparable\");\n if (interfaceType != null)\n {\n comparison = delegate(T t1, T t2)\n {\n IComparable val1 = (IComparable)prop.GetValue(t1) ?? \"\";\n IComparable val2 = (IComparable)prop.GetValue(t2) ?? \"\";\n return val1.CompareTo(val2);\n };\n }\n else\n {\n // Last option: convert to string and compare.\n comparison = delegate(T t1, T t2)\n {\n string val1 = (prop.GetValue(t1) ?? \"\").ToString();\n string val2 = (prop.GetValue(t2) ?? \"\").ToString();\n return val1.CompareTo(val2);\n };\n }\n}\n</code></pre>\n\n<p>That's all luck</p>\n"
},
{
"answer_id": 2137687,
"author": "Joe H",
"author_id": 95659,
"author_profile": "https://Stackoverflow.com/users/95659",
"pm_score": 1,
"selected": false,
"text": "<p>I'd recommend replacing:</p>\n\n<pre><code>jobs = new List<DisplayJob>();\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>jobs = new SortableBindingList<DisplayJob>();\n</code></pre>\n\n<p>The code for SortableBindingList is here: <a href=\"http://www.timvw.be/presenting-the-sortablebindinglistt/\" rel=\"nofollow noreferrer\">http://www.timvw.be/presenting-the-sortablebindinglistt/</a></p>\n\n<p>I've used code based on this in production without any problems. It's only limitation is that it is not a stable sort.</p>\n\n<p>If you want the sort to be stable, replace:</p>\n\n<pre><code>itemsList.Sort(delegate(T t1, T t2)\n{\n object value1 = prop.GetValue(t1);\n object value2 = prop.GetValue(t2);\n\n return reverse * Comparer.Default.Compare(value1, value2);\n});\n</code></pre>\n\n<p>with an insertion sort:</p>\n\n<pre><code>int j;\nT index;\nfor (int i = 0; i < itemsList.Count; i++)\n{\n index = itemsList[i];\n j = i;\n\n while ((j > 0) && (reverse * Comparer.Default.Compare(prop.GetValue(itemsList[j - 1]), prop.GetValue(index)) > 0))\n {\n itemsList[j] = itemsList[j - 1];\n j = j - 1;\n }\n\n itemsList[j] = index;\n}\n</code></pre>\n"
},
{
"answer_id": 5662644,
"author": "grabah",
"author_id": 437931,
"author_profile": "https://Stackoverflow.com/users/437931",
"pm_score": 0,
"selected": false,
"text": "<p>Did you tried setting SortMemberPath for every column?</p>\n\n<p><code>uxJobList.Columns[newColumn].SortMemberPath=\"Id\";</code></p>\n\n<p>and instead of List im just using ObservableCollection</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18349/"
] |
I am setting-up my DataGridView like this:
```
jobs = new List<DisplayJob>();
uxJobList.AutoGenerateColumns = false;
jobListBindingSource.DataSource = jobs;
uxJobList.DataSource = jobListBindingSource;
int newColumn;
newColumn = uxJobList.Columns.Add("Id", "Job No.");
uxJobList.Columns[newColumn].DataPropertyName = "Id";
uxJobList.Columns[newColumn].DefaultCellStyle.Format = Global.JobIdFormat;
uxJobList.Columns[newColumn].DefaultCellStyle.Font = new Font(uxJobList.DefaultCellStyle.Font, FontStyle.Bold);
uxJobList.Columns[newColumn].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
uxJobList.Columns[newColumn].Width = 62;
uxJobList.Columns[newColumn].Resizable = DataGridViewTriState.False;
uxJobList.Columns[newColumn].SortMode = DataGridViewColumnSortMode.Automatic;
:
:
```
where the DisplayJob class looks like:
```
public class DisplayJob
{
public DisplayJob(int id)
{
Id = id;
}
public DisplayJob(JobEntity job)
{
Id = job.Id;
Type = job.JobTypeDescription;
CreatedAt = job.CreatedAt;
StartedAt = job.StartedAt;
ExternalStatus = job.ExternalStatus;
FriendlyExternalStatus = job.FriendlyExternalStatus;
ExternalStatusFriendly = job.ExternalStatusFriendly;
CustomerName = job.Customer.Name;
CustomerKey = job.Customer.CustomerKey;
WorkAddress = job.WorkAddress;
CreatedBy = job.CreatedBy;
CancelledAt = job.CancelledAt;
ClosedAt = job.ClosedAt;
ReasonWaiting = job.ReasonWaiting;
CancelledBy = job.CancelledBy;
CancelledReason = job.CancelledReason;
DisplayCreator = Global.GetDisplayName(CreatedBy);
ActionRedoNeeded = job.ActionRedoNeeded;
if (job.Scheme != null)
{
SchemeCode = job.Scheme.Code;
}
}
public int Id { get; private set; }
public string Type { get; private set; }
public DateTime CreatedAt { get; private set; }
public DateTime? StartedAt { get; private set; }
public string ExternalStatus { get; private set; }
public string FriendlyExternalStatus { get; private set; }
public string ExternalStatusFriendly { get; private set; }
public string CustomerName { get; private set; }
public string CustomerKey { get; private set; }
public string WorkAddress { get; private set; }
public string CreatedBy { get; private set; }
public DateTime? CancelledAt { get; private set; }
public DateTime? ClosedAt { get; private set; }
public string CancelledBy { get; private set; }
public string ReasonWaiting { get; private set; }
public string DisplayCreator { get; private set; }
public string CancelledReason { get; private set; }
public string SchemeCode { get; private set; }
public bool ActionRedoNeeded { get; private set; }
}
```
However the column sorting does not work. What is the best way to get this working?
|
If you want to support sorting and searching on the collection, all **it takes it to derive a class from your BindingList parameterized type**, and override a few base class methods and properties.
The best way is to extend the BindingList and do those following things:
```
protected override bool SupportsSearchingCore
{
get
{
return true;
}
}
protected override bool SupportsSortingCore
{
get { return true; }
}
```
You will also need to implement the sort code:
```
ListSortDirection sortDirectionValue;
PropertyDescriptor sortPropertyValue;
protected override void ApplySortCore(PropertyDescriptor prop,
ListSortDirection direction)
{
sortedList = new ArrayList();
// Check to see if the property type we are sorting by implements
// the IComparable interface.
Type interfaceType = prop.PropertyType.GetInterface("IComparable");
if (interfaceType != null)
{
// If so, set the SortPropertyValue and SortDirectionValue.
sortPropertyValue = prop;
sortDirectionValue = direction;
unsortedItems = new ArrayList(this.Count);
// Loop through each item, adding it the the sortedItems ArrayList.
foreach (Object item in this.Items) {
sortedList.Add(prop.GetValue(item));
unsortedItems.Add(item);
}
// Call Sort on the ArrayList.
sortedList.Sort();
T temp;
// Check the sort direction and then copy the sorted items
// back into the list.
if (direction == ListSortDirection.Descending)
sortedList.Reverse();
for (int i = 0; i < this.Count; i++)
{
int position = Find(prop.Name, sortedList[i]);
if (position != i) {
temp = this[i];
this[i] = this[position];
this[position] = temp;
}
}
isSortedValue = true;
// Raise the ListChanged event so bound controls refresh their
// values.
OnListChanged(new ListChangedEventArgs(ListChangedType.Reset, -1));
}
else
// If the property type does not implement IComparable, let the user
// know.
throw new NotSupportedException("Cannot sort by " + prop.Name +
". This" + prop.PropertyType.ToString() +
" does not implement IComparable");
}
```
If you need more information you can always go there and get all explication about [how to extend the binding list](http://msdn.microsoft.com/en-us/library/aa480736.aspx).
|
280,953 |
<p>Could anyboby help me with the alternative solution in C# regarding <strong>AddressOf operator in VB6</strong>? AddressOf returns a long value. What way can I get the output in C#?</p>
|
[
{
"answer_id": 280959,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 3,
"selected": false,
"text": "<p>C# has special syntax for assigning functions to delegates/events. Just use <code><delegate> += <function>;</code></p>\n\n<p>If you're actually trying to get the address for some other use, you're out of luck. One of the things about managed code is that these addresses aren't necessarily fixed. While it would be unlikely that most functions would ever change there are circumstances where it's possible.</p>\n"
},
{
"answer_id": 280966,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 2,
"selected": false,
"text": "<p>Apparently, this can be done (though I'm not sure where you'd need it). \nHere's the <a href=\"http://msdn.microsoft.com/en-us/library/zcbcf4ta(VS.80).aspx\" rel=\"nofollow noreferrer\">MSDN page</a>.</p>\n"
},
{
"answer_id": 280967,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 0,
"selected": false,
"text": "<pre><code>EventHandler handler1 = this.button1_Click;\nEventHandler handler2 = new EventHandler( this.button1_Click );\n...\n...\n...\nvoid button1_Click( object sender, EventArgs e ){\n // ....\n}\n</code></pre>\n\n<p>Both notation are equivalent.</p>\n"
},
{
"answer_id": 281106,
"author": "John Rudy",
"author_id": 14048,
"author_profile": "https://Stackoverflow.com/users/14048",
"pm_score": 4,
"selected": false,
"text": "<p>Expanding on Harper Shelby's answer, yes it can be done, but it's generally a code smell to do so in .NET.</p>\n\n<p>To get the address of a variable in C#, you can use C-style pointer (*) /address (&) / dereference (->) syntax. In order to do this, you will have to compile the app with the /unsafe compiler switch, as you're bouncing out of the safety net of managed code as soon as you start dealing with memory addresses directly.</p>\n\n<p>The sample from MSDN tells most of the story:</p>\n\n<pre><code>int number;\nint* p = &number;\nConsole.WriteLine(\"Value pointed to by p: {0}\", p->ToString());\n</code></pre>\n\n<p>This assigns the address of the <code>number</code> variable to the pointer-to-an-int <code>p</code>. </p>\n\n<p>There are some catches to this:</p>\n\n<ol>\n<li>The variable whose address you are fetching must be initialized. Not a problem for value types, which default, but it is an issue for reference types.</li>\n<li>In .NET, variables can move in memory without you being aware of it. If you need to deal with the address of a variable, you really want to use <a href=\"http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx\" rel=\"noreferrer\"><code>fixed</code></a> to pin the variable in RAM.</li>\n<li>& can only be applied to a variable, not a constant nor a value. (In other words, you cannot use a construct like <code>int* p = &GetSomeInt();</code>)</li>\n<li>Again, your code must be compiled in unsafe mode, which flags the CLR that you will be using features outside the managed code \"safety net.\"</li>\n</ol>\n\n<p>Generally, my advice in this world is to seriously consider <em>why</em> you think you need to do this in the .NET world. One of .NET's missions was to shield developers from going against the metal, and this feature is counter to that mission. It exists for those (rare) scenarios where it is needed; if you find yourself frivolously using this simply because you can, you're probably mis-using it and introducing code smell.</p>\n\n<p>Avoid it if possible, but know how to use it if you absolutely must.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Could anyboby help me with the alternative solution in C# regarding **AddressOf operator in VB6**? AddressOf returns a long value. What way can I get the output in C#?
|
Expanding on Harper Shelby's answer, yes it can be done, but it's generally a code smell to do so in .NET.
To get the address of a variable in C#, you can use C-style pointer (\*) /address (&) / dereference (->) syntax. In order to do this, you will have to compile the app with the /unsafe compiler switch, as you're bouncing out of the safety net of managed code as soon as you start dealing with memory addresses directly.
The sample from MSDN tells most of the story:
```
int number;
int* p = &number;
Console.WriteLine("Value pointed to by p: {0}", p->ToString());
```
This assigns the address of the `number` variable to the pointer-to-an-int `p`.
There are some catches to this:
1. The variable whose address you are fetching must be initialized. Not a problem for value types, which default, but it is an issue for reference types.
2. In .NET, variables can move in memory without you being aware of it. If you need to deal with the address of a variable, you really want to use [`fixed`](http://msdn.microsoft.com/en-us/library/f58wzh21(VS.80).aspx) to pin the variable in RAM.
3. & can only be applied to a variable, not a constant nor a value. (In other words, you cannot use a construct like `int* p = &GetSomeInt();`)
4. Again, your code must be compiled in unsafe mode, which flags the CLR that you will be using features outside the managed code "safety net."
Generally, my advice in this world is to seriously consider *why* you think you need to do this in the .NET world. One of .NET's missions was to shield developers from going against the metal, and this feature is counter to that mission. It exists for those (rare) scenarios where it is needed; if you find yourself frivolously using this simply because you can, you're probably mis-using it and introducing code smell.
Avoid it if possible, but know how to use it if you absolutely must.
|
280,969 |
<p>I need to grab the folder name of a currently executing batch file. I have been trying to loop over the current directory using the following syntax (which is wrong at present):</p>
<pre><code>set mydir = %~p0
for /F "delims=\" %i IN (%mydir%) DO @echo %i
</code></pre>
<p>Couple of issues in that I cannot seem to pass the 'mydir' variable value in as the search string. It only seems to work if I pass in commands; I have the syntax wrong and cannot work out why.</p>
<p>My thinking was to loop over the folder string with a '\' delimiter but this is causing problems too. If I set a variable on each loop then the last value set will be the current folder name. For example, given the following path:</p>
<blockquote>
<p>C:\Folder1\Folder2\Folder3\Archive.bat</p>
</blockquote>
<p>I would expect to parse out the value 'Folder3'.</p>
<p>I need to parse that value out as its name will be part of another folder I am going to create further down in the batch file.</p>
<p>Many thanks if anyone can help. I may be barking up the wrong tree completely so any other approaches would be greatly received also.</p>
|
[
{
"answer_id": 281001,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "<p>In batch files in the FOR command you'll need to prepend %whatever with an extra % (e.g. %%whatever).\n<br><br>\n'echo %~p0' will print the currently directory of the batch file.</p>\n"
},
{
"answer_id": 281073,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 4,
"selected": true,
"text": "<p>You were pretty close to it :) This should work:</p>\n\n<pre><code>@echo OFF\nset mydir=\"%~p0\"\nSET mydir=%mydir:\\=;%\n\nfor /F \"tokens=* delims=;\" %%i IN (%mydir%) DO call :LAST_FOLDER %%i\ngoto :EOF\n\n:LAST_FOLDER\nif \"%1\"==\"\" (\n @echo %LAST%\n goto :EOF\n)\n\nset LAST=%1\nSHIFT\n\ngoto :LAST_FOLDER\n</code></pre>\n\n<p>For some reason the for command doesn't like '\\' as a delimiter, so I converted all '\\' to ';' first (<code>SET mydir=%mydir:\\=;%</code>)</p>\n"
},
{
"answer_id": 281130,
"author": "Tim Peel",
"author_id": 31412,
"author_profile": "https://Stackoverflow.com/users/31412",
"pm_score": 0,
"selected": false,
"text": "<p>This is what we had in the end (little bit more crude and can only go so deep :)</p>\n\n<pre><code>@echo off\nfor /f \"tokens=1-10 delims=\\\" %%A in ('echo %~p0') do (\n if NOT .%%A==. set new=%%A\n if NOT .%%B==. set new=%%B\n if NOT .%%C==. set new=%%C\n if NOT .%%D==. set new=%%D\n if NOT .%%E==. set new=%%E\n if NOT .%%F==. set new=%%F\n if NOT .%%G==. set new=%%G\n if NOT .%%H==. set new=%%H\n if NOT .%%I==. set new=%%I\n if NOT .%%J==. set new=%%J\n)\n\n@echo %new%\n</code></pre>\n"
},
{
"answer_id": 281284,
"author": "Tim Peel",
"author_id": 31412,
"author_profile": "https://Stackoverflow.com/users/31412",
"pm_score": 1,
"selected": false,
"text": "<p>Slight alteration for if any of the folders have spaces in their names - replace space to ':' before and after operation:</p>\n\n<pre><code>set mydir=\"%~p0\"\nset mydir=%mydir:\\=;%\nset mydir=%mydir: =:%\n\nfor /F \"tokens=* delims=;\" %%i IN (%mydir%) DO call :LAST_FOLDER %%i\ngoto :EOF\n\n:LAST_FOLDER\nif \"%1\"==\"\" (\n set LAST=%LAST::= %\n goto :EOF\n)\n\nset LAST=%1\nSHIFT\n\ngoto :LAST_FOLDER\n</code></pre>\n"
},
{
"answer_id": 3025534,
"author": "ahains",
"author_id": 98722,
"author_profile": "https://Stackoverflow.com/users/98722",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know if it's the version of windows I'm on (win2k3), but the FOR loop isn't giving me anything useful for trying to iterate through a single string.\nAccording to my observation (and the FOR /? info) you get one iteration for each line of input to FOR, and there is no way to change this to iterate within a line. You can break into multiple tokens for a given line, but it is only one invocation of the FOR loop body.</p>\n\n<p>I do think the CALL :LABEL approach in these answers does a great job. Something I didn't know until looking at this was that \";\" and \",\" are both recognized as argument separators. So once you replace backslashes with semicolons, you can call your label and iterate through with SHIFT.</p>\n\n<p>So working off of what is posted by others here, I have the below solution. Instead of grabbing the last folder name, I actually wanted to find everything up until some known directory name.. this is what is implemented below.</p>\n\n<pre><code>@echo off\nif \"%1\"==\"\" goto :USAGE\n\nset FULLPATH=%~f1\nset STOPDIR=%2\nset PATHROOT=\n\n:: Replace backslashes with semicolons\nset FULLPATH=%FULLPATH:\\=;%\n\n:: Iterate through path (the semicolons cause each dir name to be a new argument)\ncall :LOOP %FULLPATH%\ngoto :EOF\n\n:LOOP\n\n::Exit loop if reached the end of the path, or the stop dir\nif \"%1\"==\"\" (goto :EOF)\nif \"%1\"==\"%STOPDIR%\" (goto :EOF)\n\n::If this is the first segment of the path, set value directly. Else append.\nif not defined PATHROOT (set PATHROOT=%1) else (set PATHROOT=%PATHROOT%\\%1)\n\n::shift the arguments - the next path segment becomes %i\nSHIFT\n\ngoto :LOOP\n\n:USAGE\necho Usage:\necho %~0 ^<full path to parse^> ^<dir name to stop at^>\necho E.g. for a command:\necho %~0 c:\\root1\\child1\\child2 child2\necho The value of c:\\root1\\child1 would be assigned to env variable PATHROOT\n</code></pre>\n"
},
{
"answer_id": 3176320,
"author": "John Dove",
"author_id": 383261,
"author_profile": "https://Stackoverflow.com/users/383261",
"pm_score": 2,
"selected": false,
"text": "<p>This question's a little old, but I've looked for a solution more than once so here's a completely new take on it that I've just put together.</p>\n\n<p>The trick is that we take the desired path, back up one level to create a folder mask for substitution and then replace the folder mask with nothing.</p>\n\n<p>To test it, simple copy and paste into a command script (.cmd) in any directory, then run it. It will spit out only the deepest directory you're currently in.</p>\n\n<p>Notes:</p>\n\n<ul>\n<li>Replace %~dp0 with whatever path you like (as it is, it will return the deepest folder the batch file is run from. This is not the same as %cd%.)</li>\n<li>When specifying the 'pathtofind' variable ensure there are no quotes e.g. c:\\some path and not \"c:\\some path\".</li>\n<li>The original idea for folder masking is mine</li>\n<li>Spaces in the path are no problem</li>\n<li>Folder depth is not a problem</li>\n<li>It was made possible by the genius of this batch scripting tip <a href=\"http://www.dostips.com/DtCodeBatchFiles.php#Batch.FindAndReplace\" rel=\"nofollow noreferrer\">http://www.dostips.com/DtCodeBatchFiles.php#Batch.FindAndReplace</a></li>\n</ul>\n\n<p>Hope this helps someone else.</p>\n\n<pre><code>@echo off\nset pathtofind=%~dp0\nif not exist %pathtofind% echo Path does not exist&pause>nul&goto :eof\n\ncd /d %pathtofind%\nset path1=%cd%\ncd ..\nset path2=%cd%\n\ncall set \"path3=%%path1:%path2%\\=%%\"\n\necho %path3%\n\npause>nul\n</code></pre>\n"
},
{
"answer_id": 3544114,
"author": "jeth",
"author_id": 427944,
"author_profile": "https://Stackoverflow.com/users/427944",
"pm_score": -1,
"selected": false,
"text": "<p>Unfortunatelly, this is working great only when put on some depth but have problems with being on the very top of the mountain... Putting this program into \"C:\\Windows\" e.g. will result with... \"C:\\Windows\", not expected \"Windows\". Still great job, and still damage can be repaired. My approach:</p>\n\n<pre><code>@echo off\nset pathtofind=%~dp0\nif not exist %pathtofind% echo Path does not exist&pause>nul&goto :eof\n\ncd /d %pathtofind%\nset path1=%cd%\ncd ..\nset path2=%cd%\nset path4=%~dp1\ncall set \"path3=%%path1:%path2%\\=%%\"\ncall set \"path5=%%path3:%path4%*\\=%%\"\necho %path5%\n\npause>nul\n</code></pre>\n\n<p>And it's working just fine for me now, thanks for the idea, I was looking for something like that for some time.</p>\n"
},
{
"answer_id": 3962928,
"author": "auvixa",
"author_id": 479739,
"author_profile": "https://Stackoverflow.com/users/479739",
"pm_score": 1,
"selected": false,
"text": "<p>Sheesh guys, what a mess. This is pretty easy, and it's faster to do this in memory without CD.</p>\n\n<p>This gets the last two directories of a path. Modify it as required to get the last tokens of any line. My original code I based this on has more complexity for my own purposes.</p>\n\n<p>Fyi, this probably doesn't allow paths with exclamation marks since I'm using enabledelayedexpansion, but that could be fixed.</p>\n\n<p>It also won't work on a plain drive root. This could be averted in a number of ways. Check what the input path ends with, or a counter, or modifying the token and check behaviour, etc.</p>\n\n<pre><code>@echo off&setlocal enableextensions,enabledelayedexpansion\n\ncall :l_truncpath \"C:\\Windows\\temp\"\n\n----------\n\n:l_truncpath\nset \"_pathtail=%~1\"\n:l_truncpathloop\nfor /f \"delims=\\ tokens=1*\" %%x in (\"!_pathtail!\") do (\nif \"%%y\"==\"\" (\nset \"_result=!_path!\\!_pathtail!\"\necho:!_result!\nexit/b\n)\nset \"_path=%%x\"\nset \"_pathtail=%%y\"\n)\ngoto l_truncpathloop\n</code></pre>\n"
},
{
"answer_id": 4587447,
"author": "Jonathan",
"author_id": 561648,
"author_profile": "https://Stackoverflow.com/users/561648",
"pm_score": 4,
"selected": false,
"text": "<p>After struggling with some of these suggestions, I found an successfully used the following 1 liner (in windows 2008)</p>\n\n<pre><code>for %%a in (!FullPath!) do set LastFolder=%%~nxa\n</code></pre>\n"
},
{
"answer_id": 7990167,
"author": "djangofan",
"author_id": 118228,
"author_profile": "https://Stackoverflow.com/users/118228",
"pm_score": 2,
"selected": false,
"text": "<p>3 lines of script gets the result...</p>\n\n<p>Found 2 additional ways to accomplish the goal, and unlike the other answers to this question, it requires no batch \"functions\", no delayed expansion, and also does not have the limitation that Tim Peel's answer has with directory deepness :</p>\n\n<pre><code>@echo off\nSET CDIR=%~p0\nSET CDIR=%CDIR:~1,-1%\nSET CDIR=%CDIR:\\=,%\nSET CDIR=%CDIR: =#%\nFOR %%a IN (%CDIR%) DO SET \"CNAME=%%a\"\nECHO Current directory path: %CDIR%\nSET CNAME=%CNAME:#= %\nECHO Current directory name: %CNAME%\npause\n</code></pre>\n\n<p>REVISION: after my new revsion, here is an example output:</p>\n\n<pre><code>Current directory path: Documents#and#Settings,username,.sqldeveloper,tmp,my_folder,MY.again\nCurrent directory name: MY.again\nPress any key to continue . . .\n</code></pre>\n\n<p>This means that the script doesn't handle '#' or ',' in a folder name but can be adjusted to do so.</p>\n\n<p>ADDENDUM: After asking someone in the <a href=\"http://www.dostips.com/forum/viewforum.php\" rel=\"nofollow\">dostips</a> forum, found an even easier way to do it:</p>\n\n<pre><code>@echo off\nSET \"CDIR=%~dp0\"\n:: for loop requires removing trailing backslash from %~dp0 output\nSET \"CDIR=%CDIR:~0,-1%\"\nFOR %%i IN (\"%CDIR%\") DO SET \"PARENTFOLDERNAME=%%~nxi\"\nECHO Parent folder: %PARENTFOLDERNAME%\nECHO Full path: %~dp0\npause>nul\n</code></pre>\n"
},
{
"answer_id": 10536346,
"author": "foo2",
"author_id": 1387325,
"author_profile": "https://Stackoverflow.com/users/1387325",
"pm_score": 2,
"selected": false,
"text": "<p>To return to the original poster's issue:</p>\n\n<blockquote>\n <p>For example, given the following path:\n C:\\Folder1\\Folder2\\Folder3\\Archive.bat\n I would expect to parse out the value 'Folder3'.</p>\n</blockquote>\n\n<p>The simple solution for that is:</p>\n\n<pre><code>for /D %%I in (\"C:\\Folder1\\Folder2\\Folder3\\Archive.bat\\..\") do echo parentdir=%%~nxI\n</code></pre>\n\n<p>will give 'Folder3'. The file/path does not need to exist. Of course, .... for the parent's parent dir, or ...... for the one above that (and so on) work too. </p>\n"
},
{
"answer_id": 12566010,
"author": "Paul Margetts",
"author_id": 1694535,
"author_profile": "https://Stackoverflow.com/users/1694535",
"pm_score": 3,
"selected": false,
"text": "<p>I found this old thread when I was looking to find the last segment of the current directory.\nThe previous writers answers lead me to the following:</p>\n\n<pre><code>FOR /D %%I IN (\"%CD%\") DO SET _LAST_SEGMENT_=%%~nxI\nECHO Last segment = \"%_LAST_SEGMENT_%\"\n</code></pre>\n\n<p>As previous have explained, don't forget to put quotes around any paths create with %_LAST_SEGMENT_% (just as I did with %CD% in my example).</p>\n\n<p>Hope this helps someone...</p>\n"
},
{
"answer_id": 58246152,
"author": "Super_PDX",
"author_id": 12167722,
"author_profile": "https://Stackoverflow.com/users/12167722",
"pm_score": 1,
"selected": false,
"text": "<p>I modified <a href=\"https://stackoverflow.com/a/4587447/12167722\">answer</a> given by <a href=\"https://stackoverflow.com/users/561648/jonathan\">@Jonathan</a>, since it did not work for me in a batch file, but this below does work, and also supports folders with spaces in it.:</p>\n\n<pre><code>for %%a in (\"%CD%\") do set LastFolder=%%~nxa\necho %LastFolder%\n</code></pre>\n\n<p>This takes the current directory and <strong>echoes the last, deepest folder,</strong> as in below example, if the folder is this:</p>\n\n<pre><code>C:\\Users\\SuperPDX\\OneDrive\\Desktop Environment\\\n</code></pre>\n\n<p>The batch code echoes this: <strong>Desktop Environment</strong></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280969",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31412/"
] |
I need to grab the folder name of a currently executing batch file. I have been trying to loop over the current directory using the following syntax (which is wrong at present):
```
set mydir = %~p0
for /F "delims=\" %i IN (%mydir%) DO @echo %i
```
Couple of issues in that I cannot seem to pass the 'mydir' variable value in as the search string. It only seems to work if I pass in commands; I have the syntax wrong and cannot work out why.
My thinking was to loop over the folder string with a '\' delimiter but this is causing problems too. If I set a variable on each loop then the last value set will be the current folder name. For example, given the following path:
>
> C:\Folder1\Folder2\Folder3\Archive.bat
>
>
>
I would expect to parse out the value 'Folder3'.
I need to parse that value out as its name will be part of another folder I am going to create further down in the batch file.
Many thanks if anyone can help. I may be barking up the wrong tree completely so any other approaches would be greatly received also.
|
You were pretty close to it :) This should work:
```
@echo OFF
set mydir="%~p0"
SET mydir=%mydir:\=;%
for /F "tokens=* delims=;" %%i IN (%mydir%) DO call :LAST_FOLDER %%i
goto :EOF
:LAST_FOLDER
if "%1"=="" (
@echo %LAST%
goto :EOF
)
set LAST=%1
SHIFT
goto :LAST_FOLDER
```
For some reason the for command doesn't like '\' as a delimiter, so I converted all '\' to ';' first (`SET mydir=%mydir:\=;%`)
|
280,971 |
<p>Within my InfoPath form (which has to be loaded within a SharePoint Portal by the browser)I have a repeating table containing multiple fields. Now I would like to make the first textfield autoincrement starting by 1. How exactly can I do this?</p>
<p>I have already heard of a way by using the "count" function but this produces errors or in best case a static number which unfortunately does not count.
The function I have added for the field is "count(.) + 1"</p>
<p>Any suggestions?</p>
|
[
{
"answer_id": 281227,
"author": "Alex",
"author_id": 35999,
"author_profile": "https://Stackoverflow.com/users/35999",
"pm_score": 2,
"selected": true,
"text": "<p>Let's say your repeating group is called \"item\" and your autoincrement field is called \"index\". The default value of the index field should be</p>\n\n<pre><code>count(/my:myFields/my:item)\n</code></pre>\n\n<p>This should count correctly for you.</p>\n"
},
{
"answer_id": 415516,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect you really want position(). Count is just going to return the total count of nodes that match the xpath expression you give it.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280971",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25428/"
] |
Within my InfoPath form (which has to be loaded within a SharePoint Portal by the browser)I have a repeating table containing multiple fields. Now I would like to make the first textfield autoincrement starting by 1. How exactly can I do this?
I have already heard of a way by using the "count" function but this produces errors or in best case a static number which unfortunately does not count.
The function I have added for the field is "count(.) + 1"
Any suggestions?
|
Let's say your repeating group is called "item" and your autoincrement field is called "index". The default value of the index field should be
```
count(/my:myFields/my:item)
```
This should count correctly for you.
|
280,990 |
<p>I have a snippet looking something like the below.</p>
<pre><code>string bodyTypeAssemblyQualifiedName = "XXX.XX.XI.CustomerPayment.Schemas.r1.CustomerPayments_v01, XXX.XX.XI.CustomerPaym" +
"ent.Schemas.r1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ac564f277cd4488" +
"e";
</code></pre>
<p>I'd like use regular expression in C# to get it to: </p>
<pre><code>string bodyTypeAssemblyQualifiedName = null;
</code></pre>
<p>I've tried using a RegEx like the below but it doesn't match the newlines ...</p>
<pre><code>bodyTypeAssemblyQualifiedName\s=\s(?<location>.*?);
</code></pre>
|
[
{
"answer_id": 281014,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>You can try</p>\n\n<pre><code>bodyTypeAssemblyQualifiedName\\s=\\s(?<location>[.\\n]*?);\n</code></pre>\n\n<p>Or you set the <code>RegexOptions.Singleline</code> for your pattern.</p>\n\n<blockquote>\n <p><strong>RegexOptions.Singleline</strong> - Specifies single-line mode. Changes the meaning of the dot (.) so it matches every character (instead of every character except \\n). </p>\n</blockquote>\n"
},
{
"answer_id": 281031,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>This works:</p>\n\n<blockquote>\n <p>(?<=string\\sbodyTypeAssemblyQualifiedName\\s=\\s)(?s:[^;]*)(?=;)</p>\n</blockquote>\n\n<p>Which is the equivalent of:</p>\n\n<ol>\n<li>After the string \"string\nbodyTypeAssemblyQualifiedName = \"</li>\n<li>Turn on single line (treat \\r\\n as\nany other character) ( this is what\n(?s: ) does)</li>\n<li>match every character that is not a semicolon</li>\n<li>until a single semicolon is reached</li>\n</ol>\n"
},
{
"answer_id": 281183,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 1,
"selected": false,
"text": "<p>@Will, by replacing the dot with a negated character class, you eliminated the need for the single-line modifier. And if I'm reading the question right, you don't need to use lookarounds either.</p>\n\n<pre><code>bodyTypeAssemblyQualifiedName\\s+=\\s+(?<location>[^;]+);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/280990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a snippet looking something like the below.
```
string bodyTypeAssemblyQualifiedName = "XXX.XX.XI.CustomerPayment.Schemas.r1.CustomerPayments_v01, XXX.XX.XI.CustomerPaym" +
"ent.Schemas.r1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=ac564f277cd4488" +
"e";
```
I'd like use regular expression in C# to get it to:
```
string bodyTypeAssemblyQualifiedName = null;
```
I've tried using a RegEx like the below but it doesn't match the newlines ...
```
bodyTypeAssemblyQualifiedName\s=\s(?<location>.*?);
```
|
This works:
>
> (?<=string\sbodyTypeAssemblyQualifiedName\s=\s)(?s:[^;]\*)(?=;)
>
>
>
Which is the equivalent of:
1. After the string "string
bodyTypeAssemblyQualifiedName = "
2. Turn on single line (treat \r\n as
any other character) ( this is what
(?s: ) does)
3. match every character that is not a semicolon
4. until a single semicolon is reached
|
281,015 |
<p>Hi would like to send an email alert after checking the result of a query which will return the numbers of rows in a table. Does anyone have any ideas how I could do this in SQL Server 2000 in 2005 I would use a maintenence plan but not sure how in 2000?</p>
|
[
{
"answer_id": 281026,
"author": "Cade Roux",
"author_id": 18255,
"author_profile": "https://Stackoverflow.com/users/18255",
"pm_score": 0,
"selected": false,
"text": "<p>Because SQLMail is so useless for real world usage (MAPI, etc), we ended up using <a href=\"http://www.sqlanswers.com/\" rel=\"nofollow noreferrer\">SQLAnswersMail</a> which is very powerful and easy to use.</p>\n"
},
{
"answer_id": 281083,
"author": "Valerion",
"author_id": 16156,
"author_profile": "https://Stackoverflow.com/users/16156",
"pm_score": 1,
"selected": false,
"text": "<p>I did this a few years ago - hastily adapted from a MS Knowledgebase article. I changed the params to be hardcoded variables. I've removed the identifying servernames/email addresses etc etc from here but you should be able to figure it out!</p>\n\n<p>CREATE PROCEDURE [dbo].[usp_SendSuccessMail]\n--Adapted from a Microsoft KnowledgeBase article, Jan 16th 2006.</p>\n\n<pre><code>-- @From varchar(100) ,\n -- @To varchar(100) ,\n -- @Subject varchar(100)=\" \",\n --@Body varchar(4000) =\" \"\n/*********************************************************************\n\nThis stored procedure takes the parameters and sends an e-mail.\nAll the mail configurations are hard-coded in the stored procedure.\nComments are added to the stored procedure where necessary.\nReferences to the CDOSYS objects are at the following MSDN Web site:\nhttp://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_messaging.asp\n\n***********************************************************************/\n AS\n Declare @From varchar(100) --origninally passed as parameter above. We want to hard-code it.\n Declare @To varchar(100) --origninally passed as parameter above. We want to hard-code it.\n Declare @Subject varchar(100) --origninally passed as parameter above. We want to hard-code it.\n Declare @Body varchar(4000) --origninally passed as parameter above. We want to hard-code it.\n Declare @iMsg int\n Declare @hr int\n Declare @source varchar(255)\n Declare @description varchar(500)\n Declare @output varchar(1000)\n Set @From = '[email protected]'\n Set @To = '[email protected]'\n Set @Subject = 'Whatever Subject You Want'\n Set @Body = 'Some useful text'\n\n\n--************* Create the CDO.Message Object ************************\n EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT\n IF @hr <>0 BEGIN\nprint 'sp_OACreate failed'\n END\n\n--***************Configuring the Message Object ******************\n-- This is to configure a remote SMTP server.\n-- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp\n EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields(\"http://schemas.microsoft.com/cdo/configuration/sendusing\").Value','2'\n-- This is to configure the Server Name or IP address.\n-- Replace MailServerName by the name or IP of your SMTP Server.\n EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields(\"http://schemas.microsoft.com/cdo/configuration/smtpserver\").Value', 'mail.xxxxxxxxxx.com'\n-- Save the configurations to the message object.\n EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null\n-- Set the e-mail parameters.\n EXEC @hr = sp_OASetProperty @iMsg, 'To', @To\n EXEC @hr = sp_OASetProperty @iMsg, 'From', @From\n EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject\n-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.\n EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body\n EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL\n IF @hr <>0\n BEGIN\n EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT\n IF @hr = 0\n BEGIN\n SELECT @output = ' Source: ' + @source\n PRINT @output\n SELECT @output = ' Description: ' + @description\n PRINT @output\n END\n\n END\n\n-- Do some error handling after each step if you have to.\n-- Clean up the objects created.\n send_cdosysmail_cleanup:\nIf (@iMsg IS NOT NULL) -- if @iMsg is NOT NULL then destroy it\nBEGIN\n EXEC @hr=sp_OADestroy @iMsg\n\nEND\nELSE\nBEGIN\n PRINT ' sp_OADestroy skipped because @iMsg is NULL.'\n\n RETURN\nEND\n</code></pre>\n\n<p>GO</p>\n"
},
{
"answer_id": 281217,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps CDOSYS will serve your needs, check the links below</p>\n\n<ul>\n<li><a href=\"http://code.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SQL2000CDOSysMail&referringTitle=DiskSpaceMon\" rel=\"nofollow noreferrer\">Configuring SQL Server 2000\nNotification with CDOSys</a></li>\n<li><a href=\"http://support.microsoft.com/kb/312839\" rel=\"nofollow noreferrer\">How to send e-mail without using SQL Mail in SQL Server?</a> </li>\n</ul>\n"
},
{
"answer_id": 297457,
"author": "beach",
"author_id": 53892,
"author_profile": "https://Stackoverflow.com/users/53892",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>xp_smtp_sendmail\n</code></pre>\n\n<p><a href=\"http://www.sqldev.net/xp/xpsmtp.htm\" rel=\"nofollow noreferrer\">Link</a></p>\n\n<p><a href=\"http://www.sqldev.net/xp/xpsmtp.htm\" rel=\"nofollow noreferrer\">http://www.sqldev.net/xp/xpsmtp.htm</a></p>\n\n<p>I've used it before in production and it works great.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Hi would like to send an email alert after checking the result of a query which will return the numbers of rows in a table. Does anyone have any ideas how I could do this in SQL Server 2000 in 2005 I would use a maintenence plan but not sure how in 2000?
|
I did this a few years ago - hastily adapted from a MS Knowledgebase article. I changed the params to be hardcoded variables. I've removed the identifying servernames/email addresses etc etc from here but you should be able to figure it out!
CREATE PROCEDURE [dbo].[usp\_SendSuccessMail]
--Adapted from a Microsoft KnowledgeBase article, Jan 16th 2006.
```
-- @From varchar(100) ,
-- @To varchar(100) ,
-- @Subject varchar(100)=" ",
--@Body varchar(4000) =" "
/*********************************************************************
This stored procedure takes the parameters and sends an e-mail.
All the mail configurations are hard-coded in the stored procedure.
Comments are added to the stored procedure where necessary.
References to the CDOSYS objects are at the following MSDN Web site:
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_messaging.asp
***********************************************************************/
AS
Declare @From varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare @To varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare @Subject varchar(100) --origninally passed as parameter above. We want to hard-code it.
Declare @Body varchar(4000) --origninally passed as parameter above. We want to hard-code it.
Declare @iMsg int
Declare @hr int
Declare @source varchar(255)
Declare @description varchar(500)
Declare @output varchar(1000)
Set @From = '[email protected]'
Set @To = '[email protected]'
Set @Subject = 'Whatever Subject You Want'
Set @Body = 'Some useful text'
--************* Create the CDO.Message Object ************************
EXEC @hr = sp_OACreate 'CDO.Message', @iMsg OUT
IF @hr <>0 BEGIN
print 'sp_OACreate failed'
END
--***************Configuring the Message Object ******************
-- This is to configure a remote SMTP server.
-- http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cdosys/html/_cdosys_schema_configuration_sendusing.asp
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/sendusing").Value','2'
-- This is to configure the Server Name or IP address.
-- Replace MailServerName by the name or IP of your SMTP Server.
EXEC @hr = sp_OASetProperty @iMsg, 'Configuration.fields("http://schemas.microsoft.com/cdo/configuration/smtpserver").Value', 'mail.xxxxxxxxxx.com'
-- Save the configurations to the message object.
EXEC @hr = sp_OAMethod @iMsg, 'Configuration.Fields.Update', null
-- Set the e-mail parameters.
EXEC @hr = sp_OASetProperty @iMsg, 'To', @To
EXEC @hr = sp_OASetProperty @iMsg, 'From', @From
EXEC @hr = sp_OASetProperty @iMsg, 'Subject', @Subject
-- If you are using HTML e-mail, use 'HTMLBody' instead of 'TextBody'.
EXEC @hr = sp_OASetProperty @iMsg, 'TextBody', @Body
EXEC @hr = sp_OAMethod @iMsg, 'Send', NULL
IF @hr <>0
BEGIN
EXEC @hr = sp_OAGetErrorInfo NULL, @source OUT, @description OUT
IF @hr = 0
BEGIN
SELECT @output = ' Source: ' + @source
PRINT @output
SELECT @output = ' Description: ' + @description
PRINT @output
END
END
-- Do some error handling after each step if you have to.
-- Clean up the objects created.
send_cdosysmail_cleanup:
If (@iMsg IS NOT NULL) -- if @iMsg is NOT NULL then destroy it
BEGIN
EXEC @hr=sp_OADestroy @iMsg
END
ELSE
BEGIN
PRINT ' sp_OADestroy skipped because @iMsg is NULL.'
RETURN
END
```
GO
|
281,017 |
<p>(Warning - asp newbie) I have an aspx file with the tag</p>
<pre><code> <%@ Page Language=VB ... %>
</code></pre>
<p>right at the beginning of the file.</p>
<p>When calling this from my IIS server (<a href="http://localhost/myservice/default.aspx" rel="noreferrer">http://localhost/myservice/default.aspx</a>), this gives me the error </p>
<blockquote>
<p>This page contains the following
errors: </p>
<p>error on line 1 at column 2:
StartTag: invalid element name<br>
Below is a rendering of the page up to
the first error.</p>
</blockquote>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 281039,
"author": "Daan",
"author_id": 7922,
"author_profile": "https://Stackoverflow.com/users/7922",
"pm_score": 4,
"selected": true,
"text": "<p>It appears as if the browser tries to display what it thinks is an XML file, since it gives an error on the second character of the first line. So I think the file is not parsed, but simply returned as is immediately. Check if your IIS server is configured correctly and that it actually parses your ASP tags before returning the page.</p>\n"
},
{
"answer_id": 281056,
"author": "Epaga",
"author_id": 6583,
"author_profile": "https://Stackoverflow.com/users/6583",
"pm_score": 3,
"selected": false,
"text": "<p>When I went into the ASP.NET tab for the virtual directory I noticed the ASP.NET version was not selected (it was an empty combo box). Choosing the .NET framework version did the trick. Thanks.</p>\n"
},
{
"answer_id": 1855518,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Similar to the previous comment, in my setup too the ASP.NET version was not selected. But after selecting the version i got the following error while accessing the aspx file.\nWindows XP, IIS 5.1.\nException Details: System.Web.Hosting.HostingEnvironmentException: Failed to access IIS metabase. </p>\n\n<p>Executed the following commands, aspnet_iis -i\nand aspnet_iis -ga </p>\n\n<p>resolved the issue.</p>\n"
},
{
"answer_id": 2326330,
"author": "Noor Muhammad",
"author_id": 280358,
"author_profile": "https://Stackoverflow.com/users/280358",
"pm_score": 2,
"selected": false,
"text": "<p>When i did this. It worked fine.</p>\n\n<p>Go to this directroy in command prompt C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727 \nRun this command \nAspnet_regiis -I </p>\n\n<p>this will install aspnet</p>\n"
},
{
"answer_id": 18865075,
"author": "Vineeth Vijayan",
"author_id": 2477235,
"author_profile": "https://Stackoverflow.com/users/2477235",
"pm_score": 1,
"selected": false,
"text": "<p>Try this :</p>\n\n<p>To install and enable ASP.NET:</p>\n\n<p>Click Start, and then click Control Panel.\nClick Add or Remove Programs.\nClick Add/Remove Windows components.\nDouble-click Application Server, and then click Details.\nClick to select the ASP.NET check box, and then click OK.\nClick Next.\nClick Finish.</p>\n"
},
{
"answer_id": 25513979,
"author": "Jared Beach",
"author_id": 1834329,
"author_profile": "https://Stackoverflow.com/users/1834329",
"pm_score": 1,
"selected": false,
"text": "<p>For me, the problem was that I was viewing the .svc file using my local file path mapped to a server in my browser when I meant to be using the verbatim path to my server.</p>\n"
},
{
"answer_id": 65036058,
"author": "Victor Muñoz",
"author_id": 8325863,
"author_profile": "https://Stackoverflow.com/users/8325863",
"pm_score": 0,
"selected": false,
"text": "<p>For me, the problem was in the serialization that responded to client.</p>\n<p>My problem was in the xml tags spaces:</p>\n<pre><code> - < tag > text < / tag > ---> wrong\n\n - <tag> text </tag> ----> good.\n\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281017",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6583/"
] |
(Warning - asp newbie) I have an aspx file with the tag
```
<%@ Page Language=VB ... %>
```
right at the beginning of the file.
When calling this from my IIS server (<http://localhost/myservice/default.aspx>), this gives me the error
>
> This page contains the following
> errors:
>
>
> error on line 1 at column 2:
> StartTag: invalid element name
>
> Below is a rendering of the page up to
> the first error.
>
>
>
What am I doing wrong?
|
It appears as if the browser tries to display what it thinks is an XML file, since it gives an error on the second character of the first line. So I think the file is not parsed, but simply returned as is immediately. Check if your IIS server is configured correctly and that it actually parses your ASP tags before returning the page.
|
281,020 |
<p>I want to call some RESTful web services from a J2ME client running on a MIDP enabled mobile device. I read the MIDP api for HTTPConnections and thought this is just crying out for a simple wrapper to hide all those unpleasant byte arrays and such like. Before I write my own I wondered whether there was a good open source library already available.</p>
<p>-FE- </p>
|
[
{
"answer_id": 284676,
"author": "rupello",
"author_id": 635,
"author_profile": "https://Stackoverflow.com/users/635",
"pm_score": 0,
"selected": false,
"text": "<p>I don't know of any such library, but found some <a href=\"http://mobile-j2me.blogspot.com/\" rel=\"nofollow noreferrer\">succinct example</a>s of accessing various RESTful web services</p>\n"
},
{
"answer_id": 287057,
"author": "darius",
"author_id": 5896,
"author_profile": "https://Stackoverflow.com/users/5896",
"pm_score": 4,
"selected": true,
"text": "<p>You might want to check out this little gem, Mobile Ajax for Java ME:</p>\n\n<p><a href=\"https://meapplicationdevelopers.java.net/mobileajax.html\" rel=\"nofollow noreferrer\">https://meapplicationdevelopers.java.net/mobileajax.html</a></p>\n\n<p>One part is (from the site):</p>\n\n<blockquote>\n <p>Asynchronous I/O for Java ME</p>\n \n <p>This library provides the equivalent\n of XmlHttpRequest for Java ME with\n some additional functionality useful\n for invoking RESTful web services.</p>\n \n <p>It is layered on top of the\n com.sun.me.web.path library. Features\n include -</p>\n\n<pre><code>* Asynchronous versions of HTTP Get and Post\n* HTTP Basic Authentication\n* Multipart MIME (sender only)\n* Progress listeners\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 294174,
"author": "user38051",
"author_id": 38051,
"author_profile": "https://Stackoverflow.com/users/38051",
"pm_score": 0,
"selected": false,
"text": "<p>We ended up writing our own simple wrapper api for a variety of reasons not the least of which was the fact that the Sony Ericsson K750 that we were developing for had a weird bug (that SE refused to fix) where if you tried to get/use a connection when the device was off network, more than about 20 times, the internal connection pool would get hosed and never recover unless you restarted the app.</p>\n"
},
{
"answer_id": 15472720,
"author": "pram",
"author_id": 851328,
"author_profile": "https://Stackoverflow.com/users/851328",
"pm_score": 1,
"selected": false,
"text": "<p>LWUIT 1.5 now includes classes for accessing REST, using OAuth2, JSON, etc.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281020",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32747/"
] |
I want to call some RESTful web services from a J2ME client running on a MIDP enabled mobile device. I read the MIDP api for HTTPConnections and thought this is just crying out for a simple wrapper to hide all those unpleasant byte arrays and such like. Before I write my own I wondered whether there was a good open source library already available.
-FE-
|
You might want to check out this little gem, Mobile Ajax for Java ME:
<https://meapplicationdevelopers.java.net/mobileajax.html>
One part is (from the site):
>
> Asynchronous I/O for Java ME
>
>
> This library provides the equivalent
> of XmlHttpRequest for Java ME with
> some additional functionality useful
> for invoking RESTful web services.
>
>
> It is layered on top of the
> com.sun.me.web.path library. Features
> include -
>
>
>
> ```
> * Asynchronous versions of HTTP Get and Post
> * HTTP Basic Authentication
> * Multipart MIME (sender only)
> * Progress listeners
>
> ```
>
>
|
281,041 |
<p>I am not that hot at regular expressions and it has made my little mind melt some what.</p>
<p>I am trying to find all the tables names in a query. So say I have the query:</p>
<pre><code>SELECT one, two, three FROM table1, table2 WHERE X=Y
</code></pre>
<p>I would like to pull out "table1, table2" or "table1" and "table2"</p>
<p>But what if there is no where statement. It could be the end of the file, or there could be a group by or an order by etc. I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.</p>
<p>Is this a doable Regex expression? Am I being a Regex pleb?</p>
<p>(P.S. this will be done in C# but presume that doesn't matter much).</p>
|
[
{
"answer_id": 281053,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 1,
"selected": false,
"text": "<p>It's definitely not easy.</p>\n\n<p>Consider subqueries.</p>\n\n<pre><code>select\n *\nfrom\n A\n join (\n select\n top 5 *\n from\n B)\n on B.ID = A.ID\nwhere\n A.ID in (\n select\n ID\n from\n C\n where C.DOB = A.DOB)\n</code></pre>\n\n<p>There are three tables used in this query.</p>\n"
},
{
"answer_id": 281057,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 1,
"selected": false,
"text": "<p>I think it would be easier to tokenize the string and look for SQL keywords that could bound the table names. You know the names will follow <code>FROM</code>, but they could be followed by <code>WHERE</code>, <code>GROUP BY</code>, <code>HAVING</code>, or no keyword at all if they're at the end of the query.</p>\n"
},
{
"answer_id": 281059,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>RegEx isn't very good at this, as it's a lot more complicated than it appears:</p>\n\n<ul>\n<li>What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway.</li>\n<li>What about nested queries?</li>\n<li>What if there is no table (selecting a constant)</li>\n<li>What about line breaks and other whitespace formatting?</li>\n<li>Alias names?</li>\n</ul>\n\n<p>I could go on.</p>\n\n<p>What you can do is look for an sql parser, and run your query through that.</p>\n"
},
{
"answer_id": 281098,
"author": "Stefan Gehrig",
"author_id": 11354,
"author_profile": "https://Stackoverflow.com/users/11354",
"pm_score": 3,
"selected": false,
"text": "<p>Everything said about the usefulness of such a regex in the SQL context. If you insist on a regex and your SQL statements always look like the one you showed (that means no subqueries, joins, and so on), you could use</p>\n\n<pre><code>FROM\\s+([^ ,]+)(?:\\s*,\\s*([^ ,]+))*\\s+ \n</code></pre>\n"
},
{
"answer_id": 281238,
"author": "Jon",
"author_id": 6486,
"author_profile": "https://Stackoverflow.com/users/6486",
"pm_score": 2,
"selected": false,
"text": "<p>I found this site that has a GREAT parser!</p>\n\n<p><a href=\"http://www.sqlparser.com/\" rel=\"nofollow noreferrer\">http://www.sqlparser.com/</a></p>\n\n<p>well worth it. Works a treat.</p>\n"
},
{
"answer_id": 2253513,
"author": "MrEdmundo",
"author_id": 52026,
"author_profile": "https://Stackoverflow.com/users/52026",
"pm_score": 2,
"selected": false,
"text": "<p>I'm pretty late to the party however I thought I would share a regex I am currently using to analyse all our database objects and I disagree with the sentiment that it is not possible to do this using one.</p>\n\n<p>The regex has a few assumptions </p>\n\n<p>1) You are not using the A,B join syntax style</p>\n\n<p>2) Whatever regex parser you are using supports ignore case. </p>\n\n<p>3) You're analyzing, selects, joins, updates, deletes and truncates. It doesn't support the aforementioned MERGE/NATURAL because we don't use them, however I'm sure further support wouldn't be difficult to add.</p>\n\n<p>I am keen to know what type of transaction the table is part of so I have included Named Capture groups to tell me. </p>\n\n<p>Now I've not used regex for a long time so there are probably improvements that can be made however so far in all my testing this is accurate.</p>\n\n<pre><code>\\bjoin\\s+(?<Retrieve>[a-zA-Z\\._\\d]+)\\b|\\bfrom\\s+(?<Retrieve>[a-zA-Z\\._\\d]+)\\b|\\bupdate\\s+(?<Update>[a-zA-Z\\._\\d]+)\\b|\\binsert\\s+(?:\\binto\\b)?\\s+(?<Insert>[a-zA-Z\\._\\d]+)\\b|\\btruncate\\s+table\\s+(?<Delete>[a-zA-Z\\._\\d]+)\\b|\\bdelete\\s+(?:\\bfrom\\b)?\\s+(?<Delete>[a-zA-Z\\._\\d]+)\\b\n</code></pre>\n"
},
{
"answer_id": 2253587,
"author": "JohnFx",
"author_id": 30018,
"author_profile": "https://Stackoverflow.com/users/30018",
"pm_score": 1,
"selected": false,
"text": "<p>Constructing a regular expression is going to be the least of your problems. Depending on the flavor of SQL you expect to support with this code, the number of ways you can reference a table in a SQL statement is staggering. </p>\n\n<p>PLUS, if the query includes a reference to a view or UDF, the information about what underlying tables won't even be in the string at all making it completely impractical to get that information by parsing it. Also, you'd need to be smart about detecting temporary tables and excluding them from your results.</p>\n\n<p>If you must do this, a better approach would be to make use of the APIs to the particular database engine that the SQL was intended for. For example you could create a view based on the query and then use the DB Server api to detect dependencies for that view. The DB engine is going to be able to parse it much more reliably than you ever will without an enormous effort to reverse engineer the query engine.</p>\n\n<p>If, by chance, you are working with SQL Server, here is an article about detecting dependencies on that platform: <a href=\"https://web.archive.org/web/1/http://blogs.techrepublic%2ecom%2ecom/datacenter/?p=277\" rel=\"nofollow noreferrer\">Finding Dependencies in SQL Server 2005</a></p>\n"
},
{
"answer_id": 3780365,
"author": "Psymon25",
"author_id": 456396,
"author_profile": "https://Stackoverflow.com/users/456396",
"pm_score": 0,
"selected": false,
"text": "<p>This will pull out a table name on an insert Into query:</p>\n\n<pre><code>(?<=(INTO)\\s)[^\\s]*(?=\\(())\n</code></pre>\n\n<p>The Following will do the same but with a select including joins</p>\n\n<pre><code>(?<=(from|join)\\s)[^\\s]*(?=\\s(on|join|where))\n</code></pre>\n\n<p>Finally going back to an insert if you want to return just the values that are held in an insert query use the following Regex</p>\n\n<pre><code>(?i)(?<=VALUES[ ]*\\().*(?=\\))\n</code></pre>\n\n<p>I know this is an old thread but it may assist someone else looking around</p>\n\n<p>Enjoy</p>\n"
},
{
"answer_id": 6221794,
"author": "Mauro",
"author_id": 678455,
"author_profile": "https://Stackoverflow.com/users/678455",
"pm_score": 0,
"selected": false,
"text": "<p>I tried all the above but none worked since I use a wide variety of queries. I'm working with PHP though and used a PEAR library called SQL_Parser, but hope my solution helps. Also, I was having trouble with apostrophes and MySQL reserved sencences so I decided to strip off all the fields section from the query before parsing it. </p>\n\n<pre><code>function getQueryTable ($query) {\n require_once \"SQL/Parser.php\";\n $parser = new SQL_Parser();\n $parser->setDialect('MySQL');\n\n // Stripping fields section\n $queryType = substr(strtoupper($query),0,6); \n if($queryType == 'SELECT') { $query = \"SELECT * \".stristr($query, \"FROM\"); }\n if ($havingPos = stripos($query, 'HAVING')) { $query = substr($query, 0, $havingPos); }\n\n\n $struct = $parser->parse($query);\n\n $tableReferences = $struct[0]['from']['table_references']['table_factors'];\n\n foreach ((Array) $tableReferences as $ref) {\n $tables[] = ($ref['database'] ? $ref['database'].'.' : $ref['database']).$ref['table'];\n }\n\n return $tables;\n\n}\n</code></pre>\n"
},
{
"answer_id": 7909505,
"author": "itsjavi",
"author_id": 1015501,
"author_profile": "https://Stackoverflow.com/users/1015501",
"pm_score": 0,
"selected": false,
"text": "<p>In PHP, I use this function, it returns an array with the table names used in a sql statement:</p>\n\n<pre><code>function sql_query_get_tables($statement){\n preg_match_all(\"/(from|into|update|join) [\\\\'\\\\´]?([a-zA-Z0-9_-]+)[\\\\'\\\\´]?/i\",\n $statement, $matches);\n if(!empty($matches)){\n return array_unique($matches[2]);\n }else return array();\n}\n</code></pre>\n\n<p>Notice that it does not work with a,b joins or schema.tablename naming</p>\n\n<p>I hope it works for you</p>\n"
},
{
"answer_id": 10885156,
"author": "Will",
"author_id": 487176,
"author_profile": "https://Stackoverflow.com/users/487176",
"pm_score": 2,
"selected": false,
"text": "<p>One workaround is to implement a naming convention on tables and views. Then the SQL statement can be parsed on the naming prefix.</p>\n\n<p>For example:</p>\n\n<pre><code>SELECT tbltable1.one, tbltable1.two, tbltable2.three\nFROM tbltable1\n INNER JOIN tbltable2\n ON tbltable1.one = tbltable2.three\n</code></pre>\n\n<p>Split whitespace to array:</p>\n\n<p><code>(\"SELECT\",\"tbltable1.one,\",\"tbltable1.two,\",\"tbltable2.three\",\"FROM\",\"tbltable1\",\"INNER\",\"JOIN\",\"tbltable2\",\"ON\",\"tbltable1.one\",\"=\",\"tbltable2.three\")</code></p>\n\n<p>Get left of elements to period:</p>\n\n<p><code>(\"SELECT\",\"tbltable1\",\"tbltable1\",\"tbltable2\",\"FROM\",\"tbltable1\",\"INNER\",\"JOIN\",\"tbltable2\",\"ON\",\"tbltable1\",\"=\",\"tbltable2\")</code></p>\n\n<p>Remove elements with symbols:</p>\n\n<p><code>(\"SELECT\",\"tbltable1\",\"tbltable1\",\"tbltable2\",\"FROM\",\"tbltable1\",\"INNER\",\"JOIN\",\"tbltable2\",\"ON\",\"tbltable1\",\"tbltable2\")</code></p>\n\n<p>Reduce to unique values:</p>\n\n<p><code>(\"SELECT\",\"tbltable1\",\"tbltable2\",\"FROM\",\"INNER\",\"JOIN\",\"ON\")</code></p>\n\n<p>Filter on Left 3 characters = <code>\"tbl\"</code></p>\n\n<p><code>(\"tbltable1\",\"tbltable2\")</code></p>\n"
},
{
"answer_id": 34907041,
"author": "user3398001",
"author_id": 3398001,
"author_profile": "https://Stackoverflow.com/users/3398001",
"pm_score": 0,
"selected": false,
"text": "<p>I used this code as an Excel macro to parse the select and extract table names.</p>\n\n<p>My parsing assumes that the syntax <code>select from a , b , c</code> is not used.</p>\n\n<p>Just run it against your <code>SQL</code> query and if you are not satisfied with the result you should be only a few lines of codes away from the result you expect. Just debug and modify the code accordingly.</p>\n\n<pre><code>Sub get_tables()\n sql_query = Cells(5, 1).Value\n tables = \"\"\n\n 'get all tables after from\n sql_from = sql_query\n\n While InStr(1, UCase(sql_from), UCase(\"from\")) > 0\n\n i = InStr(1, UCase(sql_from), UCase(\"from\"))\n sql_from = Mid(sql_from, i + 5, Len(sql_from) - i - 5)\n i = InStr(1, UCase(sql_from), UCase(\" \"))\n\n While i = 1\n\n sql_from = Mid(sql_from, 2, Len(sql_from) - 1)\n i = InStr(1, UCase(sql_from), UCase(\" \"))\n\n end\n\n i = InStr(1, sql_join, Chr(9))\n\n While i = 1\n\n sql_join = Mid(sql_join, 2, Len(sql_join) - 1)\n i = InStr(1, sql_join, Chr(9))\n\n end\n\n a = InStr(1, UCase(sql_from), UCase(\" \"))\n b = InStr(1, sql_from, Chr(10))\n c = InStr(1, sql_from, Chr(13))\n d = InStr(1, sql_from, Chr(9))\n\n MinC = a\n\n If MinC > b And b > 0 Then MinC = b\n If MinC > c And c > 0 Then MinC = c\n If MinC > d And d > 0 Then MinC = d\n\n tables = tables + \"[\" + Mid(sql_from, 1, MinC - 1) + \"]\"\n\n end\n\n 'get all tables after join\n sql_join = sql_query\n\n While InStr(1, UCase(sql_join), UCase(\"join\")) > 0\n\n i = InStr(1, UCase(sql_join), UCase(\"join\"))\n sql_join = Mid(sql_join, i + 5, Len(sql_join) - i - 5)\n i = InStr(1, UCase(sql_join), UCase(\" \"))\n\n While i = 1\n\n sql_join = Mid(sql_join, 2, Len(sql_join) - 1)\n i = InStr(1, UCase(sql_join), UCase(\" \"))\n\n end\n\n i = InStr(1, sql_join, Chr(9))\n\n While i = 1\n\n sql_join = Mid(sql_join, 2, Len(sql_join) - 1)\n i = InStr(1, sql_join, Chr(9))\n\n end\n\n a = InStr(1, UCase(sql_join), UCase(\" \"))\n b = InStr(1, sql_join, Chr(10))\n c = InStr(1, sql_join, Chr(13))\n d = InStr(1, sql_join, Chr(9))\n\n MinC = a\n\n If MinC > b And b > 0 Then MinC = b\n If MinC > c And c > 0 Then MinC = c\n If MinC > d And d > 0 Then MinC = d\n\n tables = tables + \"[\" + Mid(sql_join, 1, MinC - 1) + \"]\"\n\n end\n\n tables = Replace(tables, \")\", \"\")\n tables = Replace(tables, \"(\", \"\")\n tables = Replace(tables, \" \", \"\")\n tables = Replace(tables, Chr(10), \"\")\n tables = Replace(tables, Chr(13), \"\")\n tables = Replace(tables, Chr(9), \"\")\n tables = Replace(tables, \"[]\", \"\")\n\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6486/"
] |
I am not that hot at regular expressions and it has made my little mind melt some what.
I am trying to find all the tables names in a query. So say I have the query:
```
SELECT one, two, three FROM table1, table2 WHERE X=Y
```
I would like to pull out "table1, table2" or "table1" and "table2"
But what if there is no where statement. It could be the end of the file, or there could be a group by or an order by etc. I know "most" of the time this will not be an issue but I don't like the idea of coding for "most" situations and knowing I have left a hole that could cause things to go wrong later.
Is this a doable Regex expression? Am I being a Regex pleb?
(P.S. this will be done in C# but presume that doesn't matter much).
|
RegEx isn't very good at this, as it's a lot more complicated than it appears:
* What if they use LEFT/RIGHT INNER/OUTER/CROSS/MERGE/NATURAL joins instead of the a,b syntax? The a,b syntax should be avoided anyway.
* What about nested queries?
* What if there is no table (selecting a constant)
* What about line breaks and other whitespace formatting?
* Alias names?
I could go on.
What you can do is look for an sql parser, and run your query through that.
|
281,045 |
<p>This is a question that was sparked by <a href="https://stackoverflow.com/users/3631/rob-walker">Rob Walker</a>'s answer <a href="https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466">here</a>.</p>
<p>Suppose I declare a class/struct like so:</p>
<pre><code>struct
{
char A;
int B;
char C;
int D;
};
</code></pre>
<p>Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I had always assumed that the compiler can do whatever it wants with them.</p>
<p>This leads into my next question. If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:</p>
<pre><code>struct
{
char A;
char C;
int B;
int D;
};
</code></pre>
<p>(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)</p>
<h3>Related topics</h3>
<ul>
<li><a href="https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs">Why doesn't GCC optimize structs?</a></li>
</ul>
|
[
{
"answer_id": 281064,
"author": "Chris Young",
"author_id": 9417,
"author_profile": "https://Stackoverflow.com/users/9417",
"pm_score": 2,
"selected": false,
"text": "<p>I cannot speak for C++, but in C the order is guaranteed to be the same order in memory as declared in the struct.</p>\n"
},
{
"answer_id": 281065,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<p>The data members are arranged in the order declared. The compiler is free to intersperse padding to arrange the memory alignment it likes (and you'll find that many compilers have a boatload a alignment specification options---useful if mixing bits compiled by different programs.). </p>\n\n<p>See also <a href=\"https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs\">Why doesn't GCC optimize structs?</a>.</p>\n\n<hr>\n\n<p>It appears that this answer is somewhat obsolete for C++. You learn something everyday. Thanks aib, Nemanja.</p>\n"
},
{
"answer_id": 281069,
"author": "Nemanja Trifunovic",
"author_id": 8899,
"author_profile": "https://Stackoverflow.com/users/8899",
"pm_score": 2,
"selected": false,
"text": "<p>Basically, you can count on that only for the classes with a <a href=\"http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2102.html\" rel=\"nofollow noreferrer\">standard layout</a>. Strictly speaking, standard layout is a C++0x thing, but it is really just standardizing existing practice/</p>\n"
},
{
"answer_id": 281082,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 7,
"selected": true,
"text": "<p>C99 §6.7.2.1 clause 13 states:</p>\n\n<blockquote>\n <p>Within a structure object, the\n non-bit-field members and the units in\n which bit-fields reside have addresses\n that increase in the order in which\n they are declared.</p>\n</blockquote>\n\n<p>and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1.</p>\n\n<p>C++ is a bit more complicated. In the 1998 and 2003 standards, there is §9.2 clause 12 (clause 15 in C++11):</p>\n\n<blockquote>\n <p>Nonstatic data members of a\n (non-union) class declared without an\n intervening access-specifier are\n allocated so that later members have\n higher addresses within a class\n object. The order of allocation of\n nonstatic data members separated by an\n access-specifier is unspecified\n (11.1). Implementation alignment\n requirements might cause two adjacent\n members not to be allocated\n immediately after each other; so might\n requirements for space for managing\n virtual functions (10.3) and virtual\n base classes (10.1).</p>\n</blockquote>\n"
},
{
"answer_id": 281091,
"author": "HUAGHAGUAH",
"author_id": 27233,
"author_profile": "https://Stackoverflow.com/users/27233",
"pm_score": 2,
"selected": false,
"text": "<p>Aside from padding for alignment, no structure optimization is allowed by any compiler (that I am aware of) for C or C++. I can't speak for C++ classes, as they may be another beast entirely.</p>\n\n<p>Consider your program is interfacing with system/library code on Windows but you want to use GCC. You would have to verify that GCC used an identical layout-optimization algorithm so all your structures would be packed correctly before sending them to the MS-compiled code.</p>\n"
},
{
"answer_id": 281154,
"author": "Jason Baker",
"author_id": 2147,
"author_profile": "https://Stackoverflow.com/users/2147",
"pm_score": 0,
"selected": false,
"text": "<p>While browsing the related topics at the right, I looked at <a href=\"https://stackoverflow.com/questions/127290/is-it-possible-to-subclass-a-c-struct-in-c-and-use-pointers-to-the-struct-in-c\">this question</a>. I figure this may be an interesting corner case when thinking about these issues (unless it's more common than I realize).</p>\n\n<p>To paraphrase, if you have a struct in C that looks something like this:</p>\n\n<pre><code>struct foo{};\n</code></pre>\n\n<p>and subclass it like so in C++ (using a separate compilation unit):</p>\n\n<pre><code>extern \"C\" foo;\nstruct bar: public foo{};\n</code></pre>\n\n<p>Then the memory alignment won't necessarily be the same for the reasons <a href=\"https://stackoverflow.com/questions/281045/do-classstruct-members-always-get-created-in-memory-in-the-order-they-were-decl#281082\">aib</a> mentions (even amongst compilers from the same vendor).</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
This is a question that was sparked by [Rob Walker](https://stackoverflow.com/users/3631/rob-walker)'s answer [here](https://stackoverflow.com/questions/36455/alignment-restrictions-for-mallocfree#36466).
Suppose I declare a class/struct like so:
```
struct
{
char A;
int B;
char C;
int D;
};
```
Is it safe to assume that these members will be declared in exactly that order in memory, or is this a compiler dependent thing? I'm asking because I had always assumed that the compiler can do whatever it wants with them.
This leads into my next question. If the above example causes memory alignment issues, why can the compiler not just turn that into something like this implicitly:
```
struct
{
char A;
char C;
int B;
int D;
};
```
(I'm primarily asking about C++, but I'd be interested to hear the C answer as well)
### Related topics
* [Why doesn't GCC optimize structs?](https://stackoverflow.com/questions/118068/why-doesnt-gcc-optimize-structs)
|
C99 §6.7.2.1 clause 13 states:
>
> Within a structure object, the
> non-bit-field members and the units in
> which bit-fields reside have addresses
> that increase in the order in which
> they are declared.
>
>
>
and goes on to say a bit more about padding and addresses. The C89 equivalent section is §6.5.2.1.
C++ is a bit more complicated. In the 1998 and 2003 standards, there is §9.2 clause 12 (clause 15 in C++11):
>
> Nonstatic data members of a
> (non-union) class declared without an
> intervening access-specifier are
> allocated so that later members have
> higher addresses within a class
> object. The order of allocation of
> nonstatic data members separated by an
> access-specifier is unspecified
> (11.1). Implementation alignment
> requirements might cause two adjacent
> members not to be allocated
> immediately after each other; so might
> requirements for space for managing
> virtual functions (10.3) and virtual
> base classes (10.1).
>
>
>
|
281,060 |
<p>I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "magic" value that I got lucky with and picked at random during a moment of frustration, the call works on my system, but fails on other ones. (see the code below)</p>
<p>Can anybody suggest what this magical offset is doing for me? By trial and error, I can find values that work on specific systems, but I can't find a general solution to this problem.</p>
<p>Thanks,
PaulH</p>
<pre><code>#define MAGIC_OFFSET (DWORD)0x01020000
LVHITTESTINFO hti = { 0 };
hti.pt = clientPoint;
LPVOID lpBuffer = ::VirtualAlloc( NULL, 1, MEM_RESERVE, PAGE_READWRITE );
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
lpBuffer = ::VirtualAlloc( (LPVOID)((DWORD)lpBuffer + MAGIC_OFFSET), sizeof( hti ), MEM_RESERVER, PAGE_READWRITE );
DWORD dwBuffer = (DWORD)lpBuffer + MAGIC_OFFSET - sizeof( hti );
if( !::WriteProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
if( ListView_HitTest( hWndListView, (LPVOID)dwBuffer ) < 0 )
return 0;
if( !::ReadProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
</code></pre>
<p>Clarification (added by Cd-MaN): this is on a Windows Mobile platform, probably non-x86 architecture. So the situation may be different (are there separate address spaces in ARM processors?).</p>
|
[
{
"answer_id": 281141,
"author": "Rob Walker",
"author_id": 3631,
"author_profile": "https://Stackoverflow.com/users/3631",
"pm_score": 2,
"selected": false,
"text": "<p>VirtualAlloc allocates memory in <strong>YOUR</strong> address space. It is absolutely not valid to use that address when writing the memory space of another process. You should be using <a href=\"http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx\" rel=\"nofollow noreferrer\">VirualAllocEx</a> instead and passing in the hProcess.</p>\n\n<p>You are just getting lucky and scribbling over some random piece of memory when it works.</p>\n\n<p>If specifying NULL to the first parameter of the VirtualAllocEx isn't supported when you are querying another process (no idea if it is or isn't) ... then you could use <a href=\"http://msdn.microsoft.com/en-us/library/aa366907(VS.85).aspx\" rel=\"nofollow noreferrer\">VirtualQueryEx</a> to map out the address space of the other process and find a valid free region to pass to VirtualAlloc.</p>\n\n<p>You will likely have to put this in a retry loop since the state of the other processes address space could change while you are looking for an empty spot.</p>\n"
},
{
"answer_id": 281180,
"author": "aib",
"author_id": 1088,
"author_profile": "https://Stackoverflow.com/users/1088",
"pm_score": 0,
"selected": false,
"text": "<p>You have to keep in mind that you're writing to the <em>virtual</em> address space of a program. On Windows, it often starts at an address like your magic number.</p>\n\n<p>Have you ever debugged a program? What do addresses look like?</p>\n\n<p>On my system, the executables are usually loaded around 00400000 or 01000000. It changes from executable to executable, and I believe Windows has the capability to change this address even on consecutive runs of the same executable.</p>\n\n<p>Furthermore, executables have sections which have their own (and comparatively smaller) offsets. For example, the code section is usually around +1000, then come the data, zeroed data sections, etc.</p>\n\n<p>What this all means is that if your executable has a base of 00400000 and its data section has an offset of +2000, the first byte of the data will be at 00402000. In order to read/write this byte, you will have to specify a base address of 00402000, not 2000 and definitely not 0.</p>\n\n<p>Try printing the value of a pointer. If the object pointed to has static lifetime, it will probably reside in the data section and you will get an address like 00402000. Then, if you WriteProcessMemory to that address, you will have modified the object.</p>\n\n<p>The various Win32 executable formats all contain this \"0040000\" base address as well as offsets of the various sections, but since such a hack reading another process' memory will probably be targeted at a specific version of a specific executable anyway, you might be better off just leaving the magic number as is.</p>\n"
},
{
"answer_id": 281822,
"author": "LanceSc",
"author_id": 10012,
"author_profile": "https://Stackoverflow.com/users/10012",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of <a href=\"http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx\" rel=\"nofollow noreferrer\">shared memory</a>, and I did a quick check to make sure these functions are supported by <a href=\"http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx\" rel=\"nofollow noreferrer\">Windows Mobile 5</a>.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281060",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57185/"
] |
I'm trying to read the data in a Win32 ListView owned by another process. Unfortunately, my WriteProcessMemory() call fails with the error "This function is not supported on this system." when I specify "NULL" for the base address in my VirtualAlloc() call. If, however, I offset that VirtualAlloc() address by some "magic" value that I got lucky with and picked at random during a moment of frustration, the call works on my system, but fails on other ones. (see the code below)
Can anybody suggest what this magical offset is doing for me? By trial and error, I can find values that work on specific systems, but I can't find a general solution to this problem.
Thanks,
PaulH
```
#define MAGIC_OFFSET (DWORD)0x01020000
LVHITTESTINFO hti = { 0 };
hti.pt = clientPoint;
LPVOID lpBuffer = ::VirtualAlloc( NULL, 1, MEM_RESERVE, PAGE_READWRITE );
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
lpBuffer = ::VirtualAlloc( (LPVOID)((DWORD)lpBuffer + MAGIC_OFFSET), sizeof( hti ), MEM_RESERVER, PAGE_READWRITE );
DWORD dwBuffer = (DWORD)lpBuffer + MAGIC_OFFSET - sizeof( hti );
if( !::WriteProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
if( ListView_HitTest( hWndListView, (LPVOID)dwBuffer ) < 0 )
return 0;
if( !::ReadProcessMemory( hProcess, (LPVOID)dwBuffer, (LPVOID)&hti, sizeof( hti ), NULL ) )
return 0;
::VirtualFree( lpBuffer, 0, MEM_RELEASE );
```
Clarification (added by Cd-MaN): this is on a Windows Mobile platform, probably non-x86 architecture. So the situation may be different (are there separate address spaces in ARM processors?).
|
Instead of trying to allocate memory in another process, why not use named shared memory instead. This article will take you through the basic setup of [shared memory](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx), and I did a quick check to make sure these functions are supported by [Windows Mobile 5](http://msdn.microsoft.com/en-us/library/aa366551(VS.85).aspx).
|
281,108 |
<p>I have a compiled AppleScript application which I have moved to my windows server. I'd like to then insert a text file into the application (which looks like a zip file on windows):</p>
<pre><code>myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt
</code></pre>
<p>So, I've precompiled the AppleScript to try to read from this text file and get the contents as a string. This is what I do:</p>
<pre><code>set theFolder to POSIX path of (the path to me)
set theFile to theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"
open for access theFile
set fileContents to (read theFile)
close access theFile
</code></pre>
<p>but this is the error I get:</p>
<blockquote>
<p>Can't make
"/Users/mike/Desktop/myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt"
into type file</p>
</blockquote>
|
[
{
"answer_id": 284311,
"author": "Mike Blandford",
"author_id": 28643,
"author_profile": "https://Stackoverflow.com/users/28643",
"pm_score": 3,
"selected": true,
"text": "<p>Ok, I figured it out, I changed the second line to this:</p>\n\n<pre><code>set theFile to (POSIX file (theFolder & \"Contents/Resources/MyNewDir/MyTxtFile.txt\"))\n</code></pre>\n"
},
{
"answer_id": 15752803,
"author": "Lri",
"author_id": 495470,
"author_profile": "https://Stackoverflow.com/users/495470",
"pm_score": 1,
"selected": false,
"text": "<p>There is also a single line version of read:</p>\n\n<pre><code>read POSIX file \"/tmp/test.txt\" as «class utf8»\n</code></pre>\n\n<p>Both versions use MacRoman unless you add <code>as «class utf8»</code>. (<code>as Unicode text</code> is UTF-16.)</p>\n"
},
{
"answer_id": 40123670,
"author": "Stephen W. Wright",
"author_id": 3143126,
"author_profile": "https://Stackoverflow.com/users/3143126",
"pm_score": 0,
"selected": false,
"text": "<p>Reading a file via a file path in a variable.</p>\n\n<p>The 1st two work. The 3rd, which stores the file name in variable does not.</p>\n\n<p>set myData to read file POSIX file ¬\n \"/Users/sww/Devel/afile.csv\"</p>\n\n<p>set myData to read file ¬\n \"Macintosh HD:Users:sww:Devel:afile.csv\"</p>\n\n<pre><code>set fRef to \"Macintosh HD:Users:sww:Devel:afile.csv\"\n\nset myData to read file fRef -- No good\n</code></pre>\n\n<p>To fix? Give the file reference as a string. </p>\n\n<pre><code>set myData to read file (fRef as string) -- OK\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281108",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28643/"
] |
I have a compiled AppleScript application which I have moved to my windows server. I'd like to then insert a text file into the application (which looks like a zip file on windows):
```
myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt
```
So, I've precompiled the AppleScript to try to read from this text file and get the contents as a string. This is what I do:
```
set theFolder to POSIX path of (the path to me)
set theFile to theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"
open for access theFile
set fileContents to (read theFile)
close access theFile
```
but this is the error I get:
>
> Can't make
> "/Users/mike/Desktop/myapplescript.app/Contents/Resources/MyNewDir/MyTxtFile.txt"
> into type file
>
>
>
|
Ok, I figured it out, I changed the second line to this:
```
set theFile to (POSIX file (theFolder & "Contents/Resources/MyNewDir/MyTxtFile.txt"))
```
|
281,111 |
<p>How do I replace text from one file with text from another file using vbscript?</p>
<p>The text being replaced is somewhere in the middle of the file. </p>
|
[
{
"answer_id": 281138,
"author": "Svante Svenson",
"author_id": 19707,
"author_profile": "https://Stackoverflow.com/users/19707",
"pm_score": 2,
"selected": false,
"text": "<p>filea.txt:\nhello cruel world</p>\n\n<p>fileb.txt:\ncruel</p>\n\n<p>filec.txt:\nhappy</p>\n\n<p>will make sResult = \"hello happy world\" after the following has executed.</p>\n\n<pre><code>Dim oFSO\nDim sFileAContents\nDim sFileBContents\nDim sFileCContents\nDim sResult\nSet oFSO = CreateObject(\"Scripting.FileSystemObject\")\nsFileAContents = oFSO.OpenTextFile(\"c:\\filea.txt\").ReadAll()\nsFileBContents = oFSO.OpenTextFile(\"c:\\fileb.txt\").ReadAll()\nsFileCContents = oFSO.OpenTextFile(\"c:\\filec.txt\").ReadAll()\nsResult = Replace(sFileAContents, sFileBContents, \"\")\n</code></pre>\n"
},
{
"answer_id": 11679819,
"author": "Kevin Fegan",
"author_id": 606539,
"author_profile": "https://Stackoverflow.com/users/606539",
"pm_score": 0,
"selected": false,
"text": "<p>FileToSearch is the file with the text you want to search for replacement<br>\nFileReplaceText is the file containing the replacement text </p>\n\n<p>Edit the value of the variable strTextToFind to contain the text you are searching for and replacing </p>\n\n<pre><code>Dim objFSO\nDim strFileToSearch\nDim strFileReplaceText\n\nDim strTextToFind\nDim strTextToSearch\nDim strTextReplaceText\nDim strFinalText\n\n strFileToSearch = \"C:\\FileToSearch.txt\"\n strFileReplaceText = \"C:\\FileReplaceText.txt\"\n\n strTextToFind = \"text to search for here\"\n\n Set objFSO = CreateObject(\"Scripting.FileSystemObject\") \n strTextToSearch = objFSO.OpenTextFile(strFileToSearch).ReadAll() \n strFileReplaceText = objFSO.OpenTextFile(strFileReplaceText).ReadAll() \n\n strFinalText = Replace(strTextToSearch, strTextToFind, strFileReplaceText) \n</code></pre>\n\n<p>If you want to write this final text back out to a file then add this code: </p>\n\n<pre><code>Const ForWriting = 2\nDim strFileFinalOutput\n\n strFileFinalOutput = \"C:\\FileFinalOutput.txt\"\n\n Set objTextFile = objFSO.OpenTextFile(strFileFinalOutput, ForWriting, True)\n objTextFile.Write strFinalText\n objTextFile.Close\n Set objTextFile = Nothing\n</code></pre>\n\n<p>This code reads the entire file into memory (.ReadAll) and may experience problems with very large files. In this case, the code can be edited to read/search/replace/write the data line by line.</p>\n\n<p>If the text you are searching for is not continuous and all on the same line then the search/replace process is more involded and this code will need additional work to handle it.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How do I replace text from one file with text from another file using vbscript?
The text being replaced is somewhere in the middle of the file.
|
filea.txt:
hello cruel world
fileb.txt:
cruel
filec.txt:
happy
will make sResult = "hello happy world" after the following has executed.
```
Dim oFSO
Dim sFileAContents
Dim sFileBContents
Dim sFileCContents
Dim sResult
Set oFSO = CreateObject("Scripting.FileSystemObject")
sFileAContents = oFSO.OpenTextFile("c:\filea.txt").ReadAll()
sFileBContents = oFSO.OpenTextFile("c:\fileb.txt").ReadAll()
sFileCContents = oFSO.OpenTextFile("c:\filec.txt").ReadAll()
sResult = Replace(sFileAContents, sFileBContents, "")
```
|
281,119 |
<p>Has anyone written a version of .Net's generic Queue that implements INotifyCollectionChanged, or is there one hidden deep in the .Net framework somewhere already?</p>
|
[
{
"answer_id": 281148,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": true,
"text": "<p>A quick search didn't show any results. But the interface is simple and it would be almost trivial to extend the Queue class and add support for the interface. Just override all methods thusly:</p>\n\n<pre><code>// this isn't the best code ever; refactor as desired\nprotected void OnCollectionChanged( NotifyCollectionChangedEventArgs ccea){\n var temp = CollectionChanged;\n if(temp != null) temp(this, ccea); \n}\n\n// and later in the class\n\npublic override SomeMethodThatAltersTheQueue(object something){\n // record state of collection prior to change\n base.SomeMethodThatAltersTheQueue(something)\n // create NotifyCollectionChangedEventArgs with prior state and new state\n OnCollectionChanged(ccea);\n}\n</code></pre>\n"
},
{
"answer_id": 1442099,
"author": "Ed Noepel",
"author_id": 175286,
"author_profile": "https://Stackoverflow.com/users/175286",
"pm_score": 0,
"selected": false,
"text": "<p>I used the same approach as Chris Wenham. Under load, performance suffers because new NotifyCollectionChangedEventArgs need to be allocated for each Enqueue/Dequeue.</p>\n\n<p>Regardless, in the Enqueue, send args with NotifyCollectionChangedAction.Add, the item added, and Count-1 as the index. In the Dequeue, send args with NotifyCollectionChangedAction.Remove, the item removed, and index 0.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281119",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5548/"
] |
Has anyone written a version of .Net's generic Queue that implements INotifyCollectionChanged, or is there one hidden deep in the .Net framework somewhere already?
|
A quick search didn't show any results. But the interface is simple and it would be almost trivial to extend the Queue class and add support for the interface. Just override all methods thusly:
```
// this isn't the best code ever; refactor as desired
protected void OnCollectionChanged( NotifyCollectionChangedEventArgs ccea){
var temp = CollectionChanged;
if(temp != null) temp(this, ccea);
}
// and later in the class
public override SomeMethodThatAltersTheQueue(object something){
// record state of collection prior to change
base.SomeMethodThatAltersTheQueue(something)
// create NotifyCollectionChangedEventArgs with prior state and new state
OnCollectionChanged(ccea);
}
```
|
281,123 |
<p>I have a loop (for item in @dataset) and I want, in each iteration, to get different data from another table and make some operations that will be printed in the view. I cant't get this data from the dataset used in the loop.</p>
<p>How can I do this according to MVC? I can put the code into the loop, in the view, but I think it's horrible.</p>
<p>Must I use a helper for do this, and call the function from the view? </p>
|
[
{
"answer_id": 281216,
"author": "IDBD",
"author_id": 7403,
"author_profile": "https://Stackoverflow.com/users/7403",
"pm_score": 1,
"selected": false,
"text": "<p>It is quite hard to tell about best solution for your problem without details about data and relations between your models(tables). The common idea is next: keep your views stupid. Get all data needed to render view inside your controllers action. Make all changes and calculations inside same action. Then in view use this data.</p>\n\n<p>btw, if you are talking about N+1 problem then read more about 'include' and 'joins' ActiveRecord parameters.</p>\n"
},
{
"answer_id": 281377,
"author": "mwilliams",
"author_id": 23909,
"author_profile": "https://Stackoverflow.com/users/23909",
"pm_score": 0,
"selected": false,
"text": "<ul>\n<li>Keep all the logic on your @dataset item inside the controller action</li>\n<li>Utilize methods in your models for the interaction with other model objects you need</li>\n<li>You should be left with only @dataset for your view that you can render in a partial.</li>\n</ul>\n\n<p>You would need to further explain your situation for any more of answer on that. What kind of operations and other models do you need to interact with? If you post your model associations I'm sure we could really square you away.</p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 281701,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 1,
"selected": false,
"text": "<p>If I was you I would create a separate class that encapsulates the dataset and contains all the logic involved in processing the dataset entries. This class could be iterable (respond to each). Then I would pass an instance of this class to the view and use only its methods there.</p>\n"
},
{
"answer_id": 282109,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 7,
"selected": true,
"text": "<p>If you have one table, and want to get data from another table, usually this is in the situation of a <code>has_many</code> relation. For example, we have <code>@people</code> (<code>Person</code> model), and each person <code>has_many</code> addresses (<code>Address</code> model). In those cases the best thing to do is this</p>\n\n<pre><code># Controller\n@people = Person.find(:all, :include => :addresses)\n...\n\n# View\[email protected] do |p|\n p.addresses.each do |address|\n ...\n</code></pre>\n\n<p>If your data is not just normal database tables (maybe you get it from a web service or so on), then a good thing to do is to build all the data in the controller ahead-of-time, then pass that to the view. Something like this</p>\n\n<pre><code># Controller\n@people = Person.find(:all)\[email protected] do |p|\n # attach loaded data to the person object in controller\n p.addresses = Address.load_from_somewhere_by_name(p.name)\n...\n</code></pre>\n\n<p>This way the view code stays clean, like this:</p>\n\n<pre><code># View\[email protected] do |p|\n p.addresses.each do |address|\n ...\n</code></pre>\n"
},
{
"answer_id": 6857064,
"author": "Nadeem Yasin",
"author_id": 867188,
"author_profile": "https://Stackoverflow.com/users/867188",
"pm_score": 1,
"selected": false,
"text": "<pre><code>Person(id, name, other fields...)\nEvent(id, title, ...)\nDate(id, date, time, event_id, ...)\nDisponibility(id, percent, date_id, person_id, ...)\n</code></pre>\n\n<p>Of course, all the relationships are defined in the Model.</p>\n\n<p>I have a view that shows all the dates for a event, it's easy. But I want, for each date, to print the data for all the people whose are available for that date. In my view, forgetting MVC design pattern, I could code something like this:</p>\n\n<pre><code><% for date in @Dates \n available = Disponibility.find_by_date_id(date.id)\n for item in available\n guy = Person.find_by_id(item.person_id)\n%>\n</code></pre>\n\n<p>Render date and people available...</p>\n\n<p>I want to avoid this in the view. I think the Orion Edwards' answer is the nearest for what I need, but, in that example, address is an empty field for Person table? Or how can I append a new attribute to Person class?</p>\n\n<p>Although, am I missing any SQL trick for do this?</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36599/"
] |
I have a loop (for item in @dataset) and I want, in each iteration, to get different data from another table and make some operations that will be printed in the view. I cant't get this data from the dataset used in the loop.
How can I do this according to MVC? I can put the code into the loop, in the view, but I think it's horrible.
Must I use a helper for do this, and call the function from the view?
|
If you have one table, and want to get data from another table, usually this is in the situation of a `has_many` relation. For example, we have `@people` (`Person` model), and each person `has_many` addresses (`Address` model). In those cases the best thing to do is this
```
# Controller
@people = Person.find(:all, :include => :addresses)
...
# View
@people.each do |p|
p.addresses.each do |address|
...
```
If your data is not just normal database tables (maybe you get it from a web service or so on), then a good thing to do is to build all the data in the controller ahead-of-time, then pass that to the view. Something like this
```
# Controller
@people = Person.find(:all)
@people.each do |p|
# attach loaded data to the person object in controller
p.addresses = Address.load_from_somewhere_by_name(p.name)
...
```
This way the view code stays clean, like this:
```
# View
@people.each do |p|
p.addresses.each do |address|
...
```
|
281,133 |
<p>What would be the easiest way to move the mouse around (and possibly click) using Python on OS X? </p>
<p>This is just for rapid prototyping, it doesn't have to be elegant.</p>
|
[
{
"answer_id": 281330,
"author": "Ben",
"author_id": 36522,
"author_profile": "https://Stackoverflow.com/users/36522",
"pm_score": 4,
"selected": true,
"text": "<p>I dug through the source code of Synergy to find the call that generates mouse events:</p>\n\n<pre><code>#include <ApplicationServices/ApplicationServices.h>\n\nint to(int x, int y)\n{\n CGPoint newloc;\n CGEventRef eventRef;\n newloc.x = x;\n newloc.y = y;\n\n eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,\n kCGMouseButtonCenter);\n //Apparently, a bug in xcode requires this next line\n CGEventSetType(eventRef, kCGEventMouseMoved);\n CGEventPost(kCGSessionEventTap, eventRef);\n CFRelease(eventRef);\n\n return 0;\n}\n</code></pre>\n\n<p>Now to write Python bindings!</p>\n"
},
{
"answer_id": 281366,
"author": "Jeremy",
"author_id": 1114,
"author_profile": "https://Stackoverflow.com/users/1114",
"pm_score": 3,
"selected": false,
"text": "<p>When I wanted to do it, I installed <a href=\"http://www.jython.org/Project/\" rel=\"noreferrer\">Jython</a> and used the <a href=\"http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html\" rel=\"noreferrer\"><code>java.awt.Robot</code></a> class. If you need to make a CPython script this is obviously not suitable, but when you the flexibility to choose anything it is a nice cross-platform solution.</p>\n\n<pre><code>import java.awt\n\nrobot = java.awt.Robot()\n\nrobot.mouseMove(x, y)\nrobot.mousePress(java.awt.event.InputEvent.BUTTON1_MASK)\nrobot.mouseRelease(java.awt.event.InputEvent.BUTTON1_MASK)\n</code></pre>\n"
},
{
"answer_id": 292117,
"author": "Rizwan Kassim",
"author_id": 35335,
"author_profile": "https://Stackoverflow.com/users/35335",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way? Compile <a href=\"http://web.archive.org/web/20100328083020/http://www.macosxhints.com/article.php?story=2008051406323031\" rel=\"nofollow noreferrer\">this</a> Cocoa app and pass it your mouse movements.</p>\n\n<p>Here is the code:</p>\n\n<pre><code>// File:\n// click.m\n//\n// Compile with:\n// gcc -o click click.m -framework ApplicationServices -framework Foundation\n//\n// Usage:\n// ./click -x pixels -y pixels\n// At the given coordinates it will click and release.\n\n#import <Foundation/Foundation.h>\n#import <ApplicationServices/ApplicationServices.h>\n\nint main(int argc, char **argv) {\n NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];\n NSUserDefaults *args = [NSUserDefaults standardUserDefaults];\n\n\n // grabs command line arguments -x and -y\n //\n int x = [args integerForKey:@\"x\"];\n int y = [args integerForKey:@\"y\"];\n\n // The data structure CGPoint represents a point in a two-dimensional\n // coordinate system. Here, X and Y distance from upper left, in pixels.\n //\n CGPoint pt;\n pt.x = x;\n pt.y = y;\n\n\n // https://stackoverflow.com/questions/1483567/cgpostmouseevent-replacement-on-snow-leopard\n CGEventRef theEvent = CGEventCreateMouseEvent(NULL, kCGEventLeftMouseDown, pt, kCGMouseButtonLeft);\n CGEventSetType(theEvent, kCGEventLeftMouseDown);\n CGEventPost(kCGHIDEventTap, theEvent);\n CFRelease(theEvent);\n\n [pool release];\n return 0;\n}\n</code></pre>\n\n<blockquote>\n <p>App called click that invokes CGPostMouseEvent from the CGRemoteOperation.h header file. It takes coordinates as command line arguments, moves the mouse to that position, then clicks and releases the mouse button.</p>\n \n <p>Save the above code as click.m, open Terminal, and switch to the folder where you saved the source. Then compile the program by typing <code>gcc -o click click.m -framework ApplicationServices -framework Foundation</code>. Don't be intimidated by needing to compile this as there are more comments than code. It is a very short program that does one simple task. </p>\n</blockquote>\n\n<hr>\n\n<p>Another way? Import <a href=\"http://developer.apple.com/cocoa/pyobjc.html\" rel=\"nofollow noreferrer\">pyobjc</a> to access some of the OSX framework and access the mouse that way. (see the code from the first example for ideas).</p>\n"
},
{
"answer_id": 664417,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>Just try this code:</p>\n\n<pre><code>#!/usr/bin/python\n\nimport objc\n\nclass ETMouse(): \n def setMousePosition(self, x, y):\n bndl = objc.loadBundle('CoreGraphics', globals(), \n '/System/Library/Frameworks/ApplicationServices.framework')\n objc.loadBundleFunctions(bndl, globals(), \n [('CGWarpMouseCursorPosition', 'v{CGPoint=ff}')])\n CGWarpMouseCursorPosition((x, y))\n\nif __name__ == \"__main__\":\n et = ETMouse()\n et.setMousePosition(200, 200)\n</code></pre>\n\n<p>it works in OSX leopard 10.5.6</p>\n"
},
{
"answer_id": 8202674,
"author": "Mike Rhodes",
"author_id": 290514,
"author_profile": "https://Stackoverflow.com/users/290514",
"pm_score": 5,
"selected": false,
"text": "<p>Try the code at <a href=\"http://web.archive.org/web/20111229234504/http://www.geekorgy.com:80/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/\" rel=\"noreferrer\">this page</a>. It defines a couple of functions, <code>mousemove</code> and <code>mouseclick</code>, which hook into Apple's integration between Python and the platform's Quartz libraries.</p>\n<p>This code works on 10.6, and I'm using it on 10.7. The nice thing about this code is that it generates mouse events, which some solutions don't. I use it to control BBC iPlayer by sending mouse events to known button positions in their Flash player (very brittle I know). The mouse move events, in particular, are required as otherwise the Flash player never hides the mouse cursor. Functions like <code>CGWarpMouseCursorPosition</code> will not do this.</p>\n<pre><code>from Quartz.CoreGraphics import CGEventCreateMouseEvent\nfrom Quartz.CoreGraphics import CGEventPost\nfrom Quartz.CoreGraphics import kCGEventMouseMoved\nfrom Quartz.CoreGraphics import kCGEventLeftMouseDown\nfrom Quartz.CoreGraphics import kCGEventLeftMouseUp\nfrom Quartz.CoreGraphics import kCGMouseButtonLeft\nfrom Quartz.CoreGraphics import kCGHIDEventTap\n\ndef mouseEvent(type, posx, posy):\n theEvent = CGEventCreateMouseEvent(\n None, \n type, \n (posx,posy), \n kCGMouseButtonLeft)\n CGEventPost(kCGHIDEventTap, theEvent)\n\ndef mousemove(posx,posy):\n mouseEvent(kCGEventMouseMoved, posx,posy);\n\ndef mouseclick(posx,posy):\n # uncomment this line if you want to force the mouse \n # to MOVE to the click location first (I found it was not necessary).\n #mouseEvent(kCGEventMouseMoved, posx,posy);\n mouseEvent(kCGEventLeftMouseDown, posx,posy);\n mouseEvent(kCGEventLeftMouseUp, posx,posy);\n</code></pre>\n<p>Here is the code example from above page:</p>\n<pre><code>##############################################################\n# Python OSX MouseClick\n# (c) 2010 Alex Assouline, GeekOrgy.com\n##############################################################\nimport sys\ntry:\n xclick=intsys.argv1\n yclick=intsys.argv2\n try:\n delay=intsys.argv3\n except:\n delay=0\nexcept:\n print "USAGE mouseclick [int x] [int y] [optional delay in seconds]"\n exit\nprint "mouse click at ", xclick, ",", yclick," in ", delay, "seconds"\n# you only want to import the following after passing the parameters check above, because importing takes time, about 1.5s\n# (why so long!, these libs must be huge : anyone have a fix for this ?? please let me know.)\nimport time\nfrom Quartz.CoreGraphics import CGEventCreateMouseEvent\nfrom Quartz.CoreGraphics import CGEventPost\nfrom Quartz.CoreGraphics import kCGEventMouseMoved\nfrom Quartz.CoreGraphics import kCGEventLeftMouseDown\nfrom Quartz.CoreGraphics import kCGEventLeftMouseDown\nfrom Quartz.CoreGraphics import kCGEventLeftMouseUp\nfrom Quartz.CoreGraphics import kCGMouseButtonLeft\nfrom Quartz.CoreGraphics import kCGHIDEventTap\ndef mouseEventtype, posx, posy:\n theEvent = CGEventCreateMouseEventNone, type, posx,posy, kCGMouseButtonLeft\n CGEventPostkCGHIDEventTap, theEvent\ndef mousemoveposx,posy:\n mouseEventkCGEventMouseMoved, posx,posy;\ndef mouseclickposx,posy:\n #mouseEvent(kCGEventMouseMoved, posx,posy); #uncomment this line if you want to force the mouse to MOVE to the click location first (i found it was not necesary).\n mouseEventkCGEventLeftMouseDown, posx,posy;\n mouseEventkCGEventLeftMouseUp, posx,posy;\ntime.sleepdelay;\nmouseclickxclick, yclick;\nprint "done."\n</code></pre>\n"
},
{
"answer_id": 10696392,
"author": "dfred",
"author_id": 1128898,
"author_profile": "https://Stackoverflow.com/users/1128898",
"pm_score": 1,
"selected": false,
"text": "<p>The python script from <a href=\"http://www.geekorgy.com/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/\" rel=\"nofollow\">geekorgy.com</a> is great except I ran into a few snags since I installed a newer version of python. So here are some tips to others who may be looking for a solution.</p>\n\n<p>If you installed Python 2.7 on your Mac OS 10.6 you have a few options to get python to import from Quartz.CoreGraphics:</p>\n\n<p><strong>A)</strong> In the terminal, <strong>type <code>python2.6</code></strong> instead of just <code>python</code> before the path to the script</p>\n\n<p><strong>B)</strong> You can <strong>install PyObjC</strong> by doing the following:</p>\n\n<ol>\n<li>Install easy_install from <a href=\"http://pypi.python.org/pypi/setuptools\" rel=\"nofollow\">http://pypi.python.org/pypi/setuptools</a></li>\n<li>In the terminal, type <code>which python</code> and copy the path up through <code>2.7</code></li>\n<li><p>Then type <code>easy_install –-prefix /Path/To/Python/Version pyobjc==2.3</code> </p>\n\n<p>**ie. <code>easy_install –-prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc==2.3</code></p></li>\n<li>Inside the script type <code>import objc</code> at the top</li>\n<li><p>If easy_install doesn't work the first time you might need to install the core first:</p>\n\n<p>**ie. <code>easy_install --prefix /Library/Frameworks/Python.framework/Versions/2.7 pyobjc-core==2.3</code></p></li>\n</ol>\n\n<p><strong>C)</strong> You can <strong>reset your python path</strong> to the original Mac OS python:</p>\n\n<ul>\n<li>In the terminal, type: <code>defaults write com.apple.versioner.python Version 2.6</code></li>\n</ul>\n\n<p>***Also, a quick way to find out the (x,y) coordinates on the screen:</p>\n\n<ol>\n<li>Press <code>Command+Shift+4</code> (screen grab selection)</li>\n<li>The cursor then shows the coordinates</li>\n<li>Then hit Esc to get out of it.</li>\n</ol>\n"
},
{
"answer_id": 17578617,
"author": "Gwen",
"author_id": 2383522,
"author_profile": "https://Stackoverflow.com/users/2383522",
"pm_score": 2,
"selected": false,
"text": "<p>Your best bet is to use the <a href=\"https://pypi.python.org/pypi/autopy/0.51\" rel=\"nofollow\">AutoPy package</a>. It's extremely simple to use, and cross-platform to boot.</p>\n\n<p>To move the cursor to position (200,200):</p>\n\n<pre><code>import autopy\nautopy.mouse.move(200,200)\n</code></pre>\n"
},
{
"answer_id": 42749433,
"author": "GJ.",
"author_id": 303295,
"author_profile": "https://Stackoverflow.com/users/303295",
"pm_score": 5,
"selected": false,
"text": "<p>The <a href=\"https://pypi.python.org/pypi/pynput\" rel=\"noreferrer\"><code>pynput</code></a> library seems like the best currently maintained library. It allows you to control and monitor input devices.</p>\n\n<p>Here is the example for controlling the mouse:</p>\n\n<pre><code>from pynput.mouse import Button, Controller\n\nmouse = Controller()\n\n# Read pointer position\nprint('The current pointer position is {0}'.format(\n mouse.position))\n\n# Set pointer position\nmouse.position = (10, 20)\nprint('Now we have moved it to {0}'.format(\n mouse.position))\n\n# Move pointer relative to current position\nmouse.move(5, -5)\n\n# Press and release\nmouse.press(Button.left)\nmouse.release(Button.left)\n\n# Double click; this is different from pressing and releasing\n# twice on Mac OSX\nmouse.click(Button.left, 2)\n\n# Scroll two steps down\nmouse.scroll(0, 2)\n</code></pre>\n"
},
{
"answer_id": 44202804,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>CoreGraphics</code> from Quartz library, for example:</p>\n\n<pre><code>from Quartz.CoreGraphics import CGEventCreate\nfrom Quartz.CoreGraphics import CGEventGetLocation\nourEvent = CGEventCreate(None);\ncurrentpos = CGEventGetLocation(ourEvent);\nmousemove(currentpos.x,currentpos.y)\n</code></pre>\n\n<p><sup>Source: <a href=\"http://web.archive.org/web/20120417231126/http://www.geekorgy.com:80/index.php/2010/06/python-mouse-click-and-move-mouse-in-apple-mac-osx-snow-leopard-10-6-x/\" rel=\"nofollow noreferrer\">Tony comment at Geekorgy page</a>.</sup></p>\n"
},
{
"answer_id": 44230608,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 0,
"selected": false,
"text": "<p>Here is the complete example using <code>Quartz</code> library:</p>\n\n<pre><code>#!/usr/bin/python\nimport sys\nfrom AppKit import NSEvent\nimport Quartz\n\nclass Mouse():\n down = [Quartz.kCGEventLeftMouseDown, Quartz.kCGEventRightMouseDown, Quartz.kCGEventOtherMouseDown]\n up = [Quartz.kCGEventLeftMouseUp, Quartz.kCGEventRightMouseUp, Quartz.kCGEventOtherMouseUp]\n [LEFT, RIGHT, OTHER] = [0, 1, 2]\n\n def position(self):\n point = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )\n return point.x, point.y\n\n def location(self):\n loc = NSEvent.mouseLocation()\n return loc.x, Quartz.CGDisplayPixelsHigh(0) - loc.y\n\n def move(self, x, y):\n moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, (x, y), 0)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)\n\n def press(self, x, y, button=1):\n event = Quartz.CGEventCreateMouseEvent(None, Mouse.down[button], (x, y), button - 1)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)\n\n def release(self, x, y, button=1):\n event = Quartz.CGEventCreateMouseEvent(None, Mouse.up[button], (x, y), button - 1)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, event)\n\n def click(self, button=LEFT):\n x, y = self.position()\n self.press(x, y, button)\n self.release(x, y, button)\n\n def click_pos(self, x, y, button=LEFT):\n self.move(x, y)\n self.click(button)\n\n def to_relative(self, x, y):\n curr_pos = Quartz.CGEventGetLocation( Quartz.CGEventCreate(None) )\n x += current_position.x;\n y += current_position.y;\n return [x, y]\n\n def move_rel(self, x, y):\n [x, y] = to_relative(x, y)\n moveEvent = Quartz.CGEventCreateMouseEvent(None, Quartz.kCGEventMouseMoved, Quartz.CGPointMake(x, y), 0)\n Quartz.CGEventPost(Quartz.kCGHIDEventTap, moveEvent)\n</code></pre>\n\n<p><sup>Above code is based on these original files: <a href=\"https://github.com/MichaelLeith/pyInputSim/blob/master/src/OSX/Mouse.py\" rel=\"nofollow noreferrer\"><code>Mouse.py</code></a><a href=\"https://github.com/OzTamir/PebbleMouse/blob/master/Server/mouseUtils.py\" rel=\"nofollow noreferrer\"><code>mouseUtils.py</code></a>.</sup></p>\n\n<p>Here is the demo code using above class:</p>\n\n<pre><code># DEMO\nif __name__ == '__main__':\n mouse = Mouse()\n if sys.platform == \"darwin\":\n print(\"Current mouse position: %d:%d\" % mouse.position())\n print(\"Moving to 100:100...\");\n mouse.move(100, 100)\n print(\"Clicking 200:200 position with using the right button...\");\n mouse.click_pos(200, 200, mouse.RIGHT)\n elif sys.platform == \"win32\":\n print(\"Error: Platform not supported!\")\n</code></pre>\n\n<p>You can combine both code blocks into one file, give execution permission and run it as a shell script.</p>\n"
},
{
"answer_id": 49514242,
"author": "biendltb",
"author_id": 6088342,
"author_profile": "https://Stackoverflow.com/users/6088342",
"pm_score": 4,
"selected": false,
"text": "<p>The easiest way is using PyAutoGUI.<br></p>\n<p>Installation:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>pip install pyautogui\n</code></pre>\n<p>Examples:<br></p>\n<ul>\n<li><p>To get mouse position:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>>>> pyautogui.position()\n(187, 567)\n</code></pre>\n</li>\n<li><p>To move the mouse to a specific position:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>>>> pyautogui.moveTo(100,200)\n</code></pre>\n</li>\n<li><p>To trigger a mouse click: </p>\n<pre class=\"lang-sh prettyprint-override\"><code>>>> pyautogui.click()\n</code></pre>\n</li>\n</ul>\n<p>More details: <a href=\"http://pyautogui.readthedocs.io/en/latest/\" rel=\"noreferrer\">PyAutoGUI</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281133",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36522/"
] |
What would be the easiest way to move the mouse around (and possibly click) using Python on OS X?
This is just for rapid prototyping, it doesn't have to be elegant.
|
I dug through the source code of Synergy to find the call that generates mouse events:
```
#include <ApplicationServices/ApplicationServices.h>
int to(int x, int y)
{
CGPoint newloc;
CGEventRef eventRef;
newloc.x = x;
newloc.y = y;
eventRef = CGEventCreateMouseEvent(NULL, kCGEventMouseMoved, newloc,
kCGMouseButtonCenter);
//Apparently, a bug in xcode requires this next line
CGEventSetType(eventRef, kCGEventMouseMoved);
CGEventPost(kCGSessionEventTap, eventRef);
CFRelease(eventRef);
return 0;
}
```
Now to write Python bindings!
|
281,135 |
<p>My code:</p>
<pre><code> string input1;
input1 = Console.ReadLine();
Console.WriteLine("byte output");
byte[] bInput1 = Encoding.Unicode.GetBytes(input1);
for (int x = 0; x < bInput1.Length; x++)
Console.WriteLine("{0} = {1}", x, bInput1[x]);
</code></pre>
<p>outputs: </p>
<p>104
0
101
0
108
0
108
0
111
0</p>
<p>for the input "hello"</p>
<p>Is there a reference to the character map where I can make sense of this?</p>
|
[
{
"answer_id": 281152,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 3,
"selected": false,
"text": "<p>You should read \"The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)\" at <a href=\"http://www.joelonsoftware.com/articles/Unicode.html\" rel=\"nofollow noreferrer\">http://www.joelonsoftware.com/articles/Unicode.html</a></p>\n\n<p>You can find a list of all Unicode characters at <a href=\"http://www.unicode.org\" rel=\"nofollow noreferrer\">http://www.unicode.org</a> but don't expect to be able to read the files there without learning a lot about text encoding issues.</p>\n"
},
{
"answer_id": 281235,
"author": "Bradley Grainger",
"author_id": 23633,
"author_profile": "https://Stackoverflow.com/users/23633",
"pm_score": 2,
"selected": false,
"text": "<p>At <a href=\"http://www.unicode.org/charts/\" rel=\"nofollow noreferrer\">http://www.unicode.org/charts/</a> you can find all the Unicode code charts. <a href=\"http://www.unicode.org/charts/PDF/U0000.pdf\" rel=\"nofollow noreferrer\">http://www.unicode.org/charts/PDF/U0000.pdf</a> shows that the code point for 'h' is U+0068. (Another great tool for viewing this data is <a href=\"http://www.babelstone.co.uk/Software/BabelMap.html\" rel=\"nofollow noreferrer\">BabelMap</a>.)</p>\n\n<p>The exact details of UTF-16 encoding can be found at <a href=\"http://unicode.org/faq/utf_bom.html#6\" rel=\"nofollow noreferrer\">http://unicode.org/faq/utf_bom.html#6</a> and <a href=\"http://www.ietf.org/rfc/rfc2781.txt\" rel=\"nofollow noreferrer\">http://www.ietf.org/rfc/rfc2781.txt</a>. In short, U+0068 is encoded (in UTF-16LE) as 0x68 0x00. In decimal, this is the first two bytes you see: 104 0. </p>\n\n<p>The other characters are encoded similarly.</p>\n\n<p>Finally, a great reference (when trying to understand the various Unicode specifications), apart from the <a href=\"http://www.unicode.org/versions/Unicode5.1.0/\" rel=\"nofollow noreferrer\">Unicode Standard</a> itself, is the <a href=\"http://unicode.org/glossary/\" rel=\"nofollow noreferrer\">Unicode Glossary</a>.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281135",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
My code:
```
string input1;
input1 = Console.ReadLine();
Console.WriteLine("byte output");
byte[] bInput1 = Encoding.Unicode.GetBytes(input1);
for (int x = 0; x < bInput1.Length; x++)
Console.WriteLine("{0} = {1}", x, bInput1[x]);
```
outputs:
104
0
101
0
108
0
108
0
111
0
for the input "hello"
Is there a reference to the character map where I can make sense of this?
|
You should read "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" at <http://www.joelonsoftware.com/articles/Unicode.html>
You can find a list of all Unicode characters at <http://www.unicode.org> but don't expect to be able to read the files there without learning a lot about text encoding issues.
|
281,136 |
<p>Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?</p>
<pre><code>god* _god = NULL;
extern "C"
{
int set_log_level(int level)
{
if(_god == NULL) return -1;
_stb->log_level(level);
return 0;
}
int god_init(){
if(_god == NULL){
_god = new god(); //Magic happens here
}
}
}
</code></pre>
<p>Provided that I perform a lock synchronization at the beginning of every function, and considering that God itself can new/malloc other things, but those things will never be returned themselves to the caller (God mallocs only for internal use), what is the simplest way of doing this, if possible.</p>
<p>How can that be extended to an arbitrary number of programs linked to this shared library?</p>
|
[
{
"answer_id": 281168,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 1,
"selected": false,
"text": "<p>This isn't the correct approach at all. By doing what you suggest, the variable, yes, is global to the library, and thus the program, but the data is private to the actual running process. You won't be able to share the values across running programs. @grieve is referring to a global accessed by multiple threads, but threads share the same parent process instance.</p>\n\n<p>Across actual processes, you need to break out to an OS specific shared memory facility.\nTake a look at <a href=\"http://en.wikipedia.org/wiki/Shared_memory\" rel=\"nofollow noreferrer\">Shared Memory</a> for details. It's a doable issue, but it's not particularly trivial to pull off. You'll also need a interprocess synchronization system like Semaphores as well to coordinate usage.</p>\n"
},
{
"answer_id": 281249,
"author": "thAAAnos",
"author_id": 36557,
"author_profile": "https://Stackoverflow.com/users/36557",
"pm_score": 0,
"selected": false,
"text": "<p>I have feeling that <em>god</em> will be a server of some kind. Consider using a proper client/server architecture, so as to keep god away from the masses.</p>\n"
},
{
"answer_id": 281266,
"author": "Chris Morley",
"author_id": 36034,
"author_profile": "https://Stackoverflow.com/users/36034",
"pm_score": 3,
"selected": true,
"text": "<p><a href=\"http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html\" rel=\"nofollow noreferrer\">Boost Interprocess</a> library has high(er) level, portable shared memory objects.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281136",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21648/"
] |
Is it possible to share a single 'god' instance among everyone that links to this code, to be placed in a shared object?
```
god* _god = NULL;
extern "C"
{
int set_log_level(int level)
{
if(_god == NULL) return -1;
_stb->log_level(level);
return 0;
}
int god_init(){
if(_god == NULL){
_god = new god(); //Magic happens here
}
}
}
```
Provided that I perform a lock synchronization at the beginning of every function, and considering that God itself can new/malloc other things, but those things will never be returned themselves to the caller (God mallocs only for internal use), what is the simplest way of doing this, if possible.
How can that be extended to an arbitrary number of programs linked to this shared library?
|
[Boost Interprocess](http://www.boost.org/doc/libs/1_37_0/doc/html/interprocess.html) library has high(er) level, portable shared memory objects.
|
281,167 |
<p>I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.</p>
<p>The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...</p>
<p>Thanks</p>
<p>PG</p>
<pre><code>SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
</code></pre>
<hr>
<p><strong>EDIT</strong></p>
<p>The Hold up seems to be in the union query that forms the QryAllTransactons query.</p>
<pre><code>SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
</code></pre>
<p>I've done a fair bit of work with simple union queries, but never had this before...</p>
|
[
{
"answer_id": 281214,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>At first, try compacting and repairing the .mdb file.</p>\n\n<p>Then, simplify your WHERE clause:</p>\n\n<pre><code>WHERE\n [drawername] Like Nz(Forms!FrmSearchCompany!SearchName, \"\") & \"*\"\n And \n [Drawerpostcode] Like Nz(Forms!FrmSearchCompany!Searchpostcode, \"\") & \"*\"\n And \n [drawersortcode] Like Nz(Forms!FrmSearchCompany!Searchsortcode, \"\") & \"*\"\n And \n [draweraccountno] Like Nz(Forms!FrmSearchCompany!Searchaccount, \"\") & \"*\"\n And \n [tpcchequenumber] Like Nz(Forms!FrmSearchCompany!Searchcheque, \"\") & \"*\"\n</code></pre>\n\n<p>Does it still run slowly?</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>As it turned out, the question was not clear in that it is an up-sized Access Database with an SQL Server back end-and an Access Project front-end.</p>\n\n<p>This sheds a different light on the whole problem.</p>\n\n<p>Can you explain in more detail <em>how</em> this whole query is intended to be used? </p>\n\n<p>If you use it to populate the RecordSource of some Form or Report, I think you will be able to refactor the whole thing like this:</p>\n\n<ul>\n<li>make a view on the SQL server that returns the right data</li>\n<li>query that view with a SQL server syntax, not with Access syntax</li>\n<li>let the server sort it out</li>\n</ul>\n"
},
{
"answer_id": 281750,
"author": "Tom H",
"author_id": 5696608,
"author_profile": "https://Stackoverflow.com/users/5696608",
"pm_score": 0,
"selected": false,
"text": "<p>How many rows are in QryAllTransactons?</p>\n\n<p>If your result returns 0 rows then Access may be able to see that immediately and stop, but if it returns even a single row then it needs to pull in the entire resultset of QryAllTransactons so that it can do the join internally. That would be my first guess as to what is happening.</p>\n\n<p>Your best bet it usually to do joins on SQL Server. Try creating a view that does the LEFT OUTER JOIN and query against that.</p>\n\n<p>Your goal, even when Access is running on the SQL Server itself and minimizes network traffic, is to only send to Access what it absolutely needs. Otherwise a large table will still take up memory, etc.</p>\n"
},
{
"answer_id": 281797,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried running each of the subqueries in the union? Usually optimizers don't spend much time trying to inspect efficiencies between union elements - each one runs on its own merits.</p>\n\n<p>Given that fact, you could also put the \"IF\" logic into the procedural code and run each of the tests in some likely order of discovery, without significant additional overhead from more calls.</p>\n"
},
{
"answer_id": 281839,
"author": "VVS",
"author_id": 21038,
"author_profile": "https://Stackoverflow.com/users/21038",
"pm_score": 0,
"selected": false,
"text": "<p>Get rid of those like operators.</p>\n\n<p>In your case you don't need them. Just check if the field starts with a given value which you can achive whith something like this:</p>\n\n<pre><code>Left([field], Len(value)) = value\n</code></pre>\n\n<p>This method applied to your query would look like this (did some reformatting for better readability):</p>\n\n<pre><code>SELECT\n TabDrawer.DrawerName, \n TabDrawer.DrawerSortCode, \n TabDrawer.DrawerAccountNo, \n TabDrawer.DrawerPostCode, \n QryAllTransactons.TPCChequeNumber, \n TabDrawer.DrawerRef\nFROM\n TabDrawer \n LEFT JOIN QryAllTransactons \n ON TabDrawer.DrawerRef = QryAllTransactons.TpcDrawer\nWHERE \n (Forms!FrmSearchCompany!SearchName Is Null \n Or Left([drawername], Len(Forms!FrmSearchCompany!SearchName)) = Forms!FrmSearchCompany!SearchName)\nAnd\n (Forms!FrmSearchCompany.SearchPostcode Is Null \n Or Left([Drawerpostcode], Len(Forms!FrmSearchCompany!Searchpostcode)) = Forms!FrmSearchCompany!Searchpostcode) \nAnd \n (Forms!FrmSearchCompany!SearchSortCode Is Null \n Or Left([drawersortcode], Len(Forms!FrmSearchCompany!Searchsortcode)) = Forms!FrmSearchCompany!Searchsortcode) \nAnd \n (Forms!FrmSearchCompany!Searchaccount Is Null \n Or Left([draweraccountno], Len(Forms!FrmSearchCompany!Searchaccount)) = Forms!FrmSearchCompany!Searchaccount) \nAnd \n (Forms!FrmSearchCompany!Searchcheque Is Null \n Or Left([tpcchequenumber], Len(Forms!FrmSearchCompany!Searchcheque)) = Forms!FrmSearchCompany!Searchcheque)\n</code></pre>\n\n<p>Note that you're comparing case sensitive. I'm not totally sure if the like operator in MS-Access is case insensitive. Convert both strings to upper- or lowercase, if needed.</p>\n"
},
{
"answer_id": 282273,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 3,
"selected": true,
"text": "<p>Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.</p>\n\n<p>Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance.</p>\n"
},
{
"answer_id": 303605,
"author": "HLGEM",
"author_id": 9034,
"author_profile": "https://Stackoverflow.com/users/9034",
"pm_score": 0,
"selected": false,
"text": "<p>When you upsized did you make sure the tables were properly indexed? Indexes will speed queries tremendously if used properly (note they may also slow down inserts/updates/deletes, so choose carefully what to index)</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281167",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30140/"
] |
I've got a particular SQL statement which takes about 30 seconds to perform, and I'm wondering if anyone can see a problem with it, or where I need additional indexing.
The code is on a subform in Access, which shows results dependent on the content of five fields in the master form. There are nearly 5000 records in the table that's being queried. The Access project is stored and run from a terminal server session on the actual SQL server, so I don't think it's a network issue, and there's another form which is very similar that uses the same type of querying...
Thanks
PG
```
SELECT TabDrawer.DrawerName, TabDrawer.DrawerSortCode, TabDrawer.DrawerAccountNo, TabDrawer.DrawerPostCode, QryAllTransactons.TPCChequeNumber, tabdrawer.drawerref
FROM TabDrawer LEFT JOIN QryAllTransactons ON TabDrawer.DrawerRef=QryAllTransactons.tpcdrawer
WHERE (Forms!FrmSearchCompany!SearchName Is Null
Or [drawername] Like Forms!FrmSearchCompany!SearchName & "*")
And (Forms!FrmSearchCompany.SearchPostcode Is Null
Or [Drawerpostcode] Like Forms!FrmSearchCompany!Searchpostcode & "*")
And (Forms!FrmSearchCompany!SearchSortCode Is Null
Or [drawersortcode] Like Forms!FrmSearchCompany!Searchsortcode & "*")
And (Forms!FrmSearchCompany!Searchaccount Is Null
Or [draweraccountno] Like Forms!FrmSearchCompany!Searchaccount & "*")
And (Forms!FrmSearchCompany!Searchcheque Is Null
Or [tpcchequenumber] Like Forms!FrmSearchCompany!Searchcheque & "*");
");
```
---
**EDIT**
The Hold up seems to be in the union query that forms the QryAllTransactons query.
```
SELECT
"TPC" AS Type,
TabTPC.TPCRef,
TabTPC.TPCBranch,
TabTPC.TPCDate,
TabTPC.TPCChequeNumber,
TabTPC.TPCChequeValue,
TabTPC.TPCFee,
TabTPC.TPCAction,
TabTPC.TPCMember,
tabtpc.tpcdrawer,
TabTPC.TPCUser,
TabTPC.TPCDiscount,
tabcustomers.*
FROM
TabTPC
INNER JOIN TabCustomers ON TabTPC.TPCMember = TabCustomers.CustomerID
UNION ALL
SELECT
"CTP" AS Type,
TabCTP.CTPRef,
TabCTP.CTPBranch,
TabCTP.CTPDate,
TabCTP.CTPChequeNumb,
TabCTP.CTPAmount,
TabCTP.CTPFee,
TabCTP.CTPAction,
TabCTP.CTPMember,
0 as CTPXXX,
TabCTP.CTPUser,
TabCTP.CTPDiscount,
TABCUSTOMERS.*
FROM
TabCTP
INNER JOIN TabCustomers ON Tabctp.ctpMember = TabCustomers.CustomerID;
```
I've done a fair bit of work with simple union queries, but never had this before...
|
Two things. Since this is an Access database with a SQL Server backend, you may find a considerable speed improvement by converting this to a stored proc.
Second, do you really need to return all those fields, especially in the tabCustomers table? Never return more fields than you actually intend to use and you will improve performance.
|
281,177 |
<p>Is it a good practice to comment code that is removed? For example:</p>
<pre><code>// Code to do {task} was removed by Ajahn on 10/10/08 because {reason}.
</code></pre>
<p>Someone in my developer group during a peer review made a note that we should comment the lines of code to be removed. I thought this was a terrible suggestion, since it clutters the code with useless comments. Which one of us is right?</p>
|
[
{
"answer_id": 281185,
"author": "David Koelle",
"author_id": 2197,
"author_profile": "https://Stackoverflow.com/users/2197",
"pm_score": 8,
"selected": true,
"text": "<p>Generally, code that is removed should not be commented, precisely because it clutters the codebase (and, why would one comment on something that doesn't exist?).</p>\n\n<p>Your defect tracking system or source control management tools are where such comments belong.</p>\n"
},
{
"answer_id": 281186,
"author": "Burkhard",
"author_id": 12860,
"author_profile": "https://Stackoverflow.com/users/12860",
"pm_score": 2,
"selected": false,
"text": "<p>The question is, why do you remove code?</p>\n\n<p>Is it useless? Was it a mistake to put it there in the first place?</p>\n\n<p>No comments needed from my point of view.</p>\n"
},
{
"answer_id": 281187,
"author": "Avi",
"author_id": 1605,
"author_profile": "https://Stackoverflow.com/users/1605",
"pm_score": 4,
"selected": false,
"text": "<p>I agree that it is not a good idea to leave code removed in comments.</p>\n\n<p>Code history should be viewed through a version control system, which is where old code can be found, as well as the reason it was removed.</p>\n"
},
{
"answer_id": 281188,
"author": "Ryan Lundy",
"author_id": 5486,
"author_profile": "https://Stackoverflow.com/users/5486",
"pm_score": 2,
"selected": false,
"text": "<p>It's useful when debugging, but there's no reason to <em>check in</em> code that way. The whole point of source control is being able to recover old versions without cluttering up the code with commented-out code.</p>\n"
},
{
"answer_id": 281191,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 3,
"selected": false,
"text": "<p>You should delete the code always.</p>\n\n<p>As for being able to see old/removed code, that's what revision control is.</p>\n"
},
{
"answer_id": 281192,
"author": "pgras",
"author_id": 12719,
"author_profile": "https://Stackoverflow.com/users/12719",
"pm_score": 0,
"selected": false,
"text": "<p>I also think it's a terrible suggestion :)</p>\n\n<p>You should use source control and if you remove some code you can add a comment when you commit. So you still have the code history if you want...</p>\n"
},
{
"answer_id": 281193,
"author": "grieve",
"author_id": 34329,
"author_profile": "https://Stackoverflow.com/users/34329",
"pm_score": 1,
"selected": false,
"text": "<p>If you are removing code. You should not comment it that you removed it. This is the entire purpose of source control (You are using source control? Right?), and as you state the comment just clutters up the code.</p>\n"
},
{
"answer_id": 281194,
"author": "LeppyR64",
"author_id": 16592,
"author_profile": "https://Stackoverflow.com/users/16592",
"pm_score": 1,
"selected": false,
"text": "<p>I agree that it's a terrible suggestion. That's why you have Source Control that has revisions. If you need to go back and see what was changed between two revisions, diff the two revisions.</p>\n"
},
{
"answer_id": 281197,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>I would suggest that, yes it's good practice to comment on code that has been removed but <strong>not in the code itself</strong>.</p>\n\n<p>To further clarify this position, you should be using a source code control system (SCCS) that allows some form of check-in comment. That is where you should place the comments about why code was removed. The SCCS will provide the full contextual history of what has happened to the code, including what has been removed. By adding check-in comments you further clarify that history.</p>\n\n<p>Adding comments in the code directly simply leads to clutter.</p>\n"
},
{
"answer_id": 281198,
"author": "Brian Knoblauch",
"author_id": 15689,
"author_profile": "https://Stackoverflow.com/users/15689",
"pm_score": 2,
"selected": false,
"text": "<p>The recent consensus (from other discussions on here) is that the code should just be removed.</p>\n\n<p>I personally will comment out code and tag it with a date or a reason. If it's old/stale and I'm passing through the file, then I strip it out. Version control makes going back easy, but not as easy as uncommenting...</p>\n"
},
{
"answer_id": 281199,
"author": "LuRsT",
"author_id": 36532,
"author_profile": "https://Stackoverflow.com/users/36532",
"pm_score": 0,
"selected": false,
"text": "<p>I comment unnused code because you never know when will you have to fallback on the ancient code, and maybe the old code will help other people to understand it, if it was simpler back then.</p>\n"
},
{
"answer_id": 281200,
"author": "John Topley",
"author_id": 1450,
"author_profile": "https://Stackoverflow.com/users/1450",
"pm_score": 1,
"selected": false,
"text": "<p>I hate seeing code that's cluttered with commented out code. Delete the code and write a commit message that says why it was removed. You do use source control, don't you?</p>\n\n<p>Don't litter active code with dead code.</p>\n"
},
{
"answer_id": 281201,
"author": "Nir",
"author_id": 3509,
"author_profile": "https://Stackoverflow.com/users/3509",
"pm_score": 3,
"selected": false,
"text": "<p>Depends on the reason for removal.</p>\n\n<p>I think of comments as hints for people maintaining the code in the future, if the information that the code was there but was removed can be helpful to someone maintaining the code (maybe as a \"don't do that\" sign) then it should be there.</p>\n\n<p>Otherwise adding detailed comments with names and dates on every code change just make the whole thing unreadable.</p>\n"
},
{
"answer_id": 281202,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 1,
"selected": false,
"text": "<p>I'll add my voice to the consensus: put the comments on why code was deleted in the source control repository, not in the code.</p>\n"
},
{
"answer_id": 281203,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": "<p>I agree with you Andrew; IMO this is why you use version control. With good checkin/commit comments and a diff tool you can always find out why lines were removed.</p>\n"
},
{
"answer_id": 281205,
"author": "DilbertDave",
"author_id": 31580,
"author_profile": "https://Stackoverflow.com/users/31580",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using any form of Source Control then this approach is somewhat redundant (as long as descriptive log messages are used)</p>\n"
},
{
"answer_id": 281206,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 2,
"selected": false,
"text": "<p>I think it's pretty useless and make the code less readable. Just think what it will be like after some monthes....</p>\n\n<pre><code>// removed because of this and that\n/* \n removed this stuff because my left leg...\n*/\n doSomething();\n// this piece of has been removed, we don't need it...\n</code></pre>\n\n<p>You'll spend half an hour to find out what's going on</p>\n"
},
{
"answer_id": 281209,
"author": "JoshFinnie",
"author_id": 33194,
"author_profile": "https://Stackoverflow.com/users/33194",
"pm_score": 2,
"selected": false,
"text": "<p>It sounds like you are trying to get around versioning your code. In theory, it sounds like a great idea, but in practice it can get very confusing very quickly. </p>\n\n<p>I highly recommend commenting code out for debugging or running other tests, but after the final decision has been made remove it from the file completely!</p>\n\n<p>Get a good versioning system in place and I think you'll find that the practice of commenting out changes is messy.</p>\n"
},
{
"answer_id": 281472,
"author": "buti-oxa",
"author_id": 2515,
"author_profile": "https://Stackoverflow.com/users/2515",
"pm_score": 5,
"selected": false,
"text": "<p>There are some (rare) situations when commenting code out (instead of deleting) is a good idea. Here's one. </p>\n\n<p>I had a line of code that seemed good and necessary. Later I realized that it is unnecessary and harmful. Instead of deleting the line, I commented it out, adding another comment: \"The line below is wrong for such and such reason\". Why?</p>\n\n<p>Because I am sure next reader of the code will first think that <em>not</em> having this line is an error and will try to add it back. (Even if the reader is me two years from now.) I don't expect him to consult source control first. I need to add comment to warn him of this tricky situation; and having wrong line and the reason why it is wrong happened to be the best way to do so.</p>\n"
},
{
"answer_id": 281477,
"author": "JW.",
"author_id": 4321,
"author_profile": "https://Stackoverflow.com/users/4321",
"pm_score": 2,
"selected": false,
"text": "<p>Nobody here has written much about <em>why</em> you shouldn't leave commented-out code, other than that it looks messy. I think the biggest reason is that the code is likely to stop working. Nobody's compiling it. Nobody's running it through unit tests. When people refactor the rest of the code, they're not refactoring it. So pretty soon, it's going to become useless. Or worse than useless -- someone might uncomment it, blindly trusting that it works.</p>\n\n<p>There <em>are</em> times when I'll comment out code, if we're still doing heavy design/development on a project. At this stage, I'm usually trying out several different designs, looking for the right approach. And sometimes the right approach is one I had already attempted earlier. So it's nice if that code isn't lost in the depths of source control. But once the design has been settled, I'll get rid of the old code.</p>\n"
},
{
"answer_id": 281543,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>In general I tend to comment very sparsely. I believe good code should be easy to read without much commenting.</p>\n\n<p>I also version my code. I suppose I could do diffs over the last twenty checkins to see if a particular line has changed for a particular reason. But that would be a huge waste of my time for most changes.</p>\n\n<p>So I try comment my code smartly. If some code is being deleted for a fairly obvious reason, I won't bother to comment the deletion. But if a piece of code is being deleted for a subtle reason (for example it performed a function that is now being handled by a different thread) I will comment-out or delete the code and add a banner comment why:</p>\n\n<pre><code> // this is now handled by the heartbeat thread\n // m_data.resort(m_ascending);\n</code></pre>\n\n<p>Or:</p>\n\n<pre><code> // don't re-sort here, as it is now handled by the heartbeat thread\n</code></pre>\n\n<p>Just last month, I encountered a piece of code that I had changed a year ago to fix a particular issue, but didn't add a comment explaining why. Here is the original code:</p>\n\n<pre><code> cutoff = m_previous_cutofftime;\n</code></pre>\n\n<p>And here is the code as it was initially fixed to use a correct cutoff time when resuming an interrupted state:</p>\n\n<pre><code> cutoff = (!ok_during) ? m_previous_cutofftime : 0;\n</code></pre>\n\n<p>Of course another unrelated issue came up, which happened to touch the same line of code, in this case reverting it back to its original state. So the new issue was now fixed, but the old issue suddenly became rebroken. D'oh!</p>\n\n<p>So now the checked-in code looks like this:</p>\n\n<pre><code> // this works for overlong events but not resuming\n// cutoff = m_previous_cutofftime;\n // this works for resuming but not overlong events\n// cutoff = (!ok_during) ? m_previous_cutofftime : 0;\n // this works for both\n cutoff = (!resuming || !ok_during) ? m_previous_cutofftime : 0;\n</code></pre>\n\n<p>Of course, YMMV.</p>\n"
},
{
"answer_id": 281643,
"author": "MikeJ",
"author_id": 10676,
"author_profile": "https://Stackoverflow.com/users/10676",
"pm_score": 1,
"selected": false,
"text": "<p>This is one of those \"broken\" windows thinkgs like compiler hints/warnings left unaddressed. it will hurt you one day and it promotes sloppiness in the team. </p>\n\n<p>The check in comment in version control can track what/why this code was removed - if the developer didnt leave a note, track them down and throttle them. </p>\n"
},
{
"answer_id": 281809,
"author": "DaveB",
"author_id": 36223,
"author_profile": "https://Stackoverflow.com/users/36223",
"pm_score": 2,
"selected": false,
"text": "<p>As the lone dissenting voice, I will say that there is a place for commenting out code in special circumstances. Sometimes, you'll have data that continues to exist that was run through that old code and the clearest thing to do is to leave that old code in with source. In such a case I'd probably leave little note indicating why the old code was simply commented out. Any programmers coming along after would be able to understand the still extant data, without having to psychically detect the need to check old versions.</p>\n\n<p>Usually though, I find commented out code completely odious and I often delete it when I come across it.</p>\n"
},
{
"answer_id": 281823,
"author": "Uri",
"author_id": 23072,
"author_profile": "https://Stackoverflow.com/users/23072",
"pm_score": 0,
"selected": false,
"text": "<p>There's a general \"clean code\" practice that says that one should never keep removed code around as commented out since it clutters and since your CVS/SVN would archive it anyway. </p>\n\n<p>While I do agree with the principle I do not think that it is an acceptable approach for all development situations. In my experience very few people keep track of all the changes in the code and every check-in. as a result, if there is no commented out code, they may never be aware that it has ever existed. </p>\n\n<p>Commenting code out like that could be a way of offering a general warning that it is about to be removed, but of course, there are no guarantees that interested parties would ever see that warning (though if they frequently work with that file, they will see it).</p>\n\n<p>I personally believe that the correct approach is to factor that code out to another private method, and then contact relevant stakeholders and notify them of the pending removal before actually getting rid of the function.</p>\n"
},
{
"answer_id": 282341,
"author": "The Sasquatch",
"author_id": 27630,
"author_profile": "https://Stackoverflow.com/users/27630",
"pm_score": 0,
"selected": false,
"text": "<p>Where I am at we comment out old code for one release cycle and then remove the comments after that. (It gives us quick fix ability if some of the new code is problematic and needs to be replaced with the old code.)</p>\n"
},
{
"answer_id": 317646,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "<p>A little anecdote, for fun: I was in a company, some years ago, knowing nothing of source code version control (they got such tool later...).<br>\nSo they had a rule, in our C sources: \"when you make a change, disable the old code with preprocessor macros\":</p>\n\n<pre><code>#ifdef OLD /* PL - 11/10/1989 */\nvoid Buggy()\n{\n// ...\n}\n#else\nvoid Good()\n{\n// ...\n}\n#end\n</code></pre>\n\n<p>No need to say, our sources quickly became unreadable! It was a nightmare to maintain...<br>\nThat's why I added to SciTE the capacity to jump between nested #ifdef / #else / #end and such... It can be still useful in more regular cases.<br>\nLater, I wrote a Visual Studio macro to happily get rid of old code, once we got our VCS!</p>\n\n<p>Now, like buti-oxa, sometime I felt the need to indicate why I removed some code. For the same reason, or because I remove old code which I feel is no longer needed, but I am not too sure (legacy, legacy...). Obviously not in all cases!<br>\nI don't leave such comment, actually, but I can understand the need.<br>\nAt worse, I would comment out in one version, and remove everything in the next version...<br>\nAt my current work, for important local changes, we leave the old code but can reactivate it by properties, in case of emergency. After testing it some time in production, we eventually remove the old code.</p>\n\n<p>Of course, VCS comments are the best option, but when the change is a few lines in a big file with other changes, referencing the little removal can be hard...</p>\n"
},
{
"answer_id": 317715,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In almost all cases old code should of course be removed and tracked in your RCS.</p>\n\n<p>Like all things though, I think that making the statement 'All deleted code will ALWAYS be removed' is an incorrect approach.</p>\n\n<p>The old code might want to be left in for a miriad of reasons. The prime reason to leave the code in is when you want any developer who is working in that section of code in the future to see the old code. </p>\n\n<p>Relying on source tracking obviously does not give this.</p>\n\n<p>So, I believe the correct answer is:</p>\n\n<p>-Delete old code unless leaving it in provides crucial information that the next developer in the code would require. Ie, remove it 99% of the time but don't make a draconian rule that would remove your ability to provide much needed documentation to the next developer when circumstances warrant it.</p>\n"
},
{
"answer_id": 333803,
"author": "John with waffle",
"author_id": 279,
"author_profile": "https://Stackoverflow.com/users/279",
"pm_score": 1,
"selected": false,
"text": "<p>If you are in the middle of major changes, and need to make a fix to existing functionality, commenting out the future code is a reasonable thing to do, provided you remark that this is future functionality, at least until we have futures friendly source control systems. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5831/"
] |
Is it a good practice to comment code that is removed? For example:
```
// Code to do {task} was removed by Ajahn on 10/10/08 because {reason}.
```
Someone in my developer group during a peer review made a note that we should comment the lines of code to be removed. I thought this was a terrible suggestion, since it clutters the code with useless comments. Which one of us is right?
|
Generally, code that is removed should not be commented, precisely because it clutters the codebase (and, why would one comment on something that doesn't exist?).
Your defect tracking system or source control management tools are where such comments belong.
|
281,210 |
<p>We have scalar functions in our database for returning things like "number of tasks for a customer" or "total invoice amount for a customer". </p>
<p>We are experimenting and looking to try to do this w/o stored procedures ... normally we would just call this function in our stored procedure and return it as a single value. </p>
<p>Is there a way to use or access scalar functions with LINQ to SQL? If so, I would be interested in see an example of how to ... if not, how would it be best to handle this type of situation ... if it is even doable.</p>
|
[
{
"answer_id": 281222,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>I believe <a href=\"http://msdn.microsoft.com/en-us/library/bb386973.aspx\" rel=\"nofollow noreferrer\">this MSDN documentation</a> is what you're after (as part of <a href=\"http://msdn.microsoft.com/en-us/library/bb546175.aspx\" rel=\"nofollow noreferrer\">this wider topic of calling user-defined functions in LINQ to SQL</a>). Can't say I've done it myself, but it sounds right...</p>\n"
},
{
"answer_id": 281224,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>LINQ-to-SQL supports use with UDFs, if that is what you mean. Just drag the UDF onto the designer surface and you're done. This creates a matching method on the data-context, marked <a href=\"http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.functionattribute.aspx\" rel=\"noreferrer\"><code>[Function(..., IsComposable=true)]</code></a> or similar, telling LINQ-to-SQL that it can use this in queries (note that EF doesn't support this usage).</p>\n\n<p>You would then use it in your query like:</p>\n\n<pre><code>var qry = from cust in ctx.Custs\n select new {Id = cust.Id, Value = ctx.GetTotalValue(cust.Id)};\n</code></pre>\n\n<p>which will become TSQL something like:</p>\n\n<pre><code>SELECT t1.Id, dbo.MyUdf(t1.Id)\nFROM CUSTOMER t1\n</code></pre>\n\n<p>(or there-abouts).</p>\n\n<p>The fact that it is composable means that you can use the value in queries - for example in a <code>Where()</code>/<code>WHERE</code> - and so reduce the data brought back from the server (although obviously the UDF will still need to be executed in some way).</p>\n\n<p><a href=\"http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/608b6b08532ed7eb/4cf42640934bf45e#bfc790be1a24e37a\" rel=\"noreferrer\">Here's a similar example</a>, showing a pseudo-UDF at use on a data-context, illustrating that the C# version of the method is not used.</p>\n\n<p>Actually, I'm currently looking at such UDFs to provide \"out of model\" data in a composable way - i.e. a particular part of the system needs access to some data (that happens to be in the same database) that isn't really part of the same model, but which I want to <code>JOIN</code> in interesting ways. I also have existing SPs for this purpose... so I'm looking at porting those SPs to tabular UDFs, which provides a level of contract/abstraction surrounding the out-of-model data. So because it isn't part of my model, I can only get it via the UDF - yet I retain the ability to compose this with my regular model.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
We have scalar functions in our database for returning things like "number of tasks for a customer" or "total invoice amount for a customer".
We are experimenting and looking to try to do this w/o stored procedures ... normally we would just call this function in our stored procedure and return it as a single value.
Is there a way to use or access scalar functions with LINQ to SQL? If so, I would be interested in see an example of how to ... if not, how would it be best to handle this type of situation ... if it is even doable.
|
LINQ-to-SQL supports use with UDFs, if that is what you mean. Just drag the UDF onto the designer surface and you're done. This creates a matching method on the data-context, marked [`[Function(..., IsComposable=true)]`](http://msdn.microsoft.com/en-us/library/system.data.linq.mapping.functionattribute.aspx) or similar, telling LINQ-to-SQL that it can use this in queries (note that EF doesn't support this usage).
You would then use it in your query like:
```
var qry = from cust in ctx.Custs
select new {Id = cust.Id, Value = ctx.GetTotalValue(cust.Id)};
```
which will become TSQL something like:
```
SELECT t1.Id, dbo.MyUdf(t1.Id)
FROM CUSTOMER t1
```
(or there-abouts).
The fact that it is composable means that you can use the value in queries - for example in a `Where()`/`WHERE` - and so reduce the data brought back from the server (although obviously the UDF will still need to be executed in some way).
[Here's a similar example](http://groups.google.co.uk/group/microsoft.public.dotnet.languages.csharp/browse_thread/thread/608b6b08532ed7eb/4cf42640934bf45e#bfc790be1a24e37a), showing a pseudo-UDF at use on a data-context, illustrating that the C# version of the method is not used.
Actually, I'm currently looking at such UDFs to provide "out of model" data in a composable way - i.e. a particular part of the system needs access to some data (that happens to be in the same database) that isn't really part of the same model, but which I want to `JOIN` in interesting ways. I also have existing SPs for this purpose... so I'm looking at porting those SPs to tabular UDFs, which provides a level of contract/abstraction surrounding the out-of-model data. So because it isn't part of my model, I can only get it via the UDF - yet I retain the ability to compose this with my regular model.
|
281,246 |
<p>I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly.</p>
<p><code>id ="SomeId"
classid = "CLSID:{GUID}"
codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"</code></p>
<p>Even a general working idea or method would be nice.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 281280,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 5,
"selected": true,
"text": "<p>I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.</p>\n\n<pre><code>// something akin to this:\ndocument.getElementById(myDivId).innerHTML = \"<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc\";\n</code></pre>\n\n<p>That should work, it does just fine for me - I use it to embed Windows Media Player in a page.</p>\n\n<hr>\n\n<p>UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's <code>innerHTML</code> property.</p>\n\n<hr>\n\n<p>UPDATE: Apparently you need more help than I thought you needed? Maybe this will help:</p>\n\n<p>Have your BODY tag look like this: <code><body onload=\"loadAppropriatePlugin()\"></code></p>\n\n<p>Have somewhere in your page, where you want this thing to load, an empty DIV tag with an <code>id</code> attribute of something like \"Foo\" or whatever.</p>\n\n<p>Have code like this in a <code><script></code> tag in your <code><head></code> section:</p>\n\n<pre><code>function getIEVersion() { // or something like this\n var ua = window.navigator.userAgent;\n var msie = ua.indexOf(\"MSIE \");\n return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(\".\", msie))) : 0);\n}\n\nfunction loadAppropriatePlugin() {\n if(getIEVersion() != 0) { // this means we are in IE\n document.getElementById(\"Foo\").innerHTML = \"<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc\";\n } else {\n // if you want to maybe do the same for FF and load that stuff...\n }\n}\n</code></pre>\n\n<p>Does that help?</p>\n"
},
{
"answer_id": 281287,
"author": "Andrew G. Johnson",
"author_id": 428190,
"author_profile": "https://Stackoverflow.com/users/428190",
"pm_score": -1,
"selected": false,
"text": "<p>Two ways.</p>\n\n<p>1) Just do a document.write where ever you want it</p>\n\n<pre><code><script type=\"text/javascript\">\n<!--\n document.write(\"<object id=\\\"SomeId\\\" classid=\\\"CLSID:{GUID}\\\" codebase=\\\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\\\"></object>\");\n-->\n</script>\n</code></pre>\n\n<p>2) Edit a tag's innerHTML property.</p>\n\n<pre><code><div id=\"my-div\"></div>\n<script type=\"text/javascript\">\n<!--\n document.getElementById(\"my-div\").innerHTML = \"<object id=\\\"SomeId\\\" classid=\\\"CLSID:{GUID}\\\" codebase=\\\"http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1\\\"></object>\";\n-->\n</script>\n</code></pre>\n\n<p><strong>EDIT:</strong> Just a note, it is best to not use JavaScript to do this, since people with JavaScript enabled will never see the object. It would be better to just place it in your HTML.</p>\n"
},
{
"answer_id": 2759283,
"author": "dgFish3r",
"author_id": 331562,
"author_profile": "https://Stackoverflow.com/users/331562",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var object = document.createelement('object')\nobject.setAttribute('id','name')\nobject.setAttribute('clssid','CLSID:{}')\n</code></pre>\n\n<p>And the same for other parameters.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281246",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1890/"
] |
I have to add either an embed tag for Firefox or an object tag for Internet Explorer with JavaScript to address the appropriate ActiveX / Plugin depending on the browser. The plugin could be missing and needs to get downloaded in this case. The dynamically added embed tag for Firefox works as expected. The dynamically added object tag for Internet Explorer seems to do nothing at all. The object tag needs the following attributes to function properly.
`id ="SomeId"
classid = "CLSID:{GUID}"
codebase = "http://www.MyActicexSource.com/MyCuteActivex.CAB#Version=2,0,0,1"`
Even a general working idea or method would be nice.
Thanks!
|
I needed to do this same thing and simply place all of the HTML needed for the OBJECT tag in a string in JavaScript and simply replace the innerHTML of a div tag with the OBJECT HTML and it works in IE just fine.
```
// something akin to this:
document.getElementById(myDivId).innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
```
That should work, it does just fine for me - I use it to embed Windows Media Player in a page.
---
UPDATE: You would run the above code after the page loads via an event handler that either runs on the page's load event or maybe in response to a user's click. The only thing you need to do is have an empty DIV tag or some other type of tag that would allow us to inject the HTML code via that element's `innerHTML` property.
---
UPDATE: Apparently you need more help than I thought you needed? Maybe this will help:
Have your BODY tag look like this: `<body onload="loadAppropriatePlugin()">`
Have somewhere in your page, where you want this thing to load, an empty DIV tag with an `id` attribute of something like "Foo" or whatever.
Have code like this in a `<script>` tag in your `<head>` section:
```
function getIEVersion() { // or something like this
var ua = window.navigator.userAgent;
var msie = ua.indexOf("MSIE ");
return ((msie > 0) ? parseInt(ua.substring(msie+5, ua.indexOf(".", msie))) : 0);
}
function loadAppropriatePlugin() {
if(getIEVersion() != 0) { // this means we are in IE
document.getElementById("Foo").innerHTML = "<OBJECT id='foo' classid='CLSID:22d6f312-b0f6-11d0-94ab-0080c74c7e95'.....etc";
} else {
// if you want to maybe do the same for FF and load that stuff...
}
}
```
Does that help?
|
281,257 |
<p>In an earlier question about <a href="https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form">how to return a string from a dialog window</a>, <strong>yapiskan</strong> suggested <a href="https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form#280731">overloading the child form's ShowDialog() method</a> to include an out parameter.</p>
<p>My question is whether or not this is a good approach in C#.</p>
<p>Here is some example code, based on yapiskan's suggestion. In the child form (in this example, it's a form with a textbox on it), you just need to add the ShowDialog overload and assign UI values to the out parameter:</p>
<pre><code>public DialogResult ShowDialog(out string s)
{
DialogResult result = this.ShowDialog();
s = this.textBox1.Text;
return result;
}
</code></pre>
<p>And to show the form and retrieve the entered text, you do this:</p>
<pre><code>using (CustomDialog frm = new CustomDialog())
{
string s;
if (frm.ShowDialog(out s) == DialogResult.OK)
{
// do something with s
}
}
</code></pre>
<p>One advantage I can think of is that this approach forces the user of the CustomDialog form to get the information it contains through the form's ShowDialog method (rather than from a who-knows-what-it's-called method like GetMyData() or something).</p>
|
[
{
"answer_id": 281262,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 4,
"selected": true,
"text": "<p>Better to have a Public property/method and get the information. </p>\n\n<p>What would you do if you would need 3..4..5 informations, having 5 parameters out? More clean to have accessors to get your information from the Dialog.</p>\n"
},
{
"answer_id": 281283,
"author": "Calanus",
"author_id": 445,
"author_profile": "https://Stackoverflow.com/users/445",
"pm_score": 2,
"selected": false,
"text": "<p>Personally I try to avoid out parameters wherever possible, although I understand that like GoTo they are sometimes a necessary evil. I would say that it would be much better to use properties or methods to return the information.</p>\n"
},
{
"answer_id": 281316,
"author": "Ali Ersöz",
"author_id": 4215,
"author_profile": "https://Stackoverflow.com/users/4215",
"pm_score": 1,
"selected": false,
"text": "<p>I prefer this one because I don't like the approach of getting result from a property or a method after you have done with the class. After dialog form was shown and closed I think the object should not be used any more because logically you have done with the dialog then why should I use its property or method to get the result?</p>\n"
},
{
"answer_id": 281953,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>In my experience, a custom modal dialog that collects only one piece of information is a pretty extreme outlier. Much more common are zero and many. </p>\n\n<p>And a dialog that collects many pieces of data is almost certain to be modified at some point to collect just one more. I'd much rather fix only the code that uses that one new piece of data than every single piece of code that uses the modified dialog.</p>\n\n<p>Also, think about how a developer uses IntelliSense to use your class. He's going to type this:</p>\n\n<pre><code>MyDialog d = new MyDialog();\nd.ShowDialog(\n</code></pre>\n\n<p>...and at that last keystroke, IntelliSense will pop up telling him that he now has to declare three new string variables to hold the out parameters. So he moves the cursor up, and starts typing:</p>\n\n<pre><code>string foo;\nstring\n</code></pre>\n\n<p>...and, what was the name of the second parameter again? So it's back down to the open paren, hit CTRL+SPACE, oh yeah, it's <code>bar</code>, back up to the previous line, etc.</p>\n\n<p>The problem with using properties on a custom dialog is that the Form class already has a million properties, and the three or four special ones that you're creating are going to get lost in the mix. To fix this, create a class for the dialog parameters and a <code>Parameters</code> property of that type on the custom dialog. That makes code like this easy to write:</p>\n\n<pre><code>MyDialog d = new MyDialog();\nd.Parameters.Foo = \"foo\";\nd.Parameters.Bar = \"bar\";\nd.Parameters.Baz = \"baz\";\n</code></pre>\n\n<p>because the parameter names pop up in IntelliSense, and you don't need to declare any variables to hold their values.</p>\n"
},
{
"answer_id": 281976,
"author": "Erik Forbes",
"author_id": 16942,
"author_profile": "https://Stackoverflow.com/users/16942",
"pm_score": 2,
"selected": false,
"text": "<p>My approach is typically to write a method that internally calls ShowDialog, then formats the output data appropriately. For (contrived) example:</p>\n\n<pre><code>public string GetFolderName(){\n if(this.ShowDialog() == DialogResult.OK) {\n return this.FolderName.Text;\n }\n return String.Empty;\n}\n</code></pre>\n\n<p>In most cases I make this method static, and instantiate the dialog itself from within the body of the method - that way the caller doesn't have to deal with form references, or the notion of having to chose which 'show' method to call.</p>\n\n<p>In the non-edge cases of having multiple output values, I typically construct a struct that holds these values, then have my 'Get' function return that struct.</p>\n\n<pre><code>public struct FolderData {\n public static FolderData Empty = new FolderData();\n\n public string FolderName {get; set;}\n public int FilesInFolder {get; set;}\n}\n\npublic FolderData GetFolderData(){\n if(this.ShowDialog() == DialogResult.OK) {\n return new FolderData {\n FolderName = this.FolderName.Text;\n FilesInFolder = int.Parse(this.FilesInFolder.Text);\n }\n }\n return FolderData.Empty;\n}\n</code></pre>\n"
},
{
"answer_id": 282046,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 1,
"selected": false,
"text": "<p>@Musigenesis, you really don't want to force client code to break when you change your dialog, and using an out parameter that is only sometimes valid isn't a good design. As @Daok says, when you have more than 1 value returned this starts to get messy and ugly fast.</p>\n\n<p>You also can't force client code to use the result any more than the .net framework ensures that you call properties on a file dialog. You're also not forcing the caller to do anything with the out parameter, all you've forced them to do is to accept a variable that they may not want to use.</p>\n\n<p>If the dialog is very generic this may not be applicable, but instead of chucking all sorts of properties to the dialog itself, have a single method that you use consistently throughout your application, and have that return a specific class that holds the relevant data.</p>\n\n<pre><code>public sealed class MySaveDialogResult\n{\n public static MySaveDialogResult NonOkResult(); // Null Object pattern\n public MySaveDialogResult( string filePath ) { ... }\n\n // encapsulate the dialog result\n public DialogResult DialogResult { get; private set; } \n // some property that was set in the dialog\n public string FilePath { get; private set; }\n // another property set in the dialog\n public bool AllowOVerwrite { get; private set; }\n}\n</code></pre>\n\n<p>and your dialog is</p>\n\n<pre><code>public MySaveDialog ...\n{\n public MySaveDialogResult GetDialogResult() { .... }\n}\n</code></pre>\n\n<p>The essence is a small immutable utility class that also implements null object pattern. The null object is returned whenever the dialog result wasn't OK. Obviously the above is a shot in the dark for your needs, so alter it at will, make inheritance hierarchies, etc. </p>\n\n<p>The main point is to have <code>GetDialogResult()</code>, a single method on the dialog, to returned a class that encapsulates all the relevant dialog data. </p>\n\n<hr>\n\n<p>edit:</p>\n\n<p>@yapiskan wonders why not just 'out' the <code>MyDialogResult</code> versus calling <code>GetDialogResult()</code>.</p>\n\n<p>IMO - The points are simply:</p>\n\n<ol>\n<li>That's not the convention</li>\n<li>A method call is trivially easy, and made easier when you follow the 'convention' argument as made above.</li>\n<li><code>out</code> is awkward to use. <code>GetDialogResult()</code> is not forcing the caller to write awkward code, and it doesn't force the user to consume the dialog result at the point of invoking the dialog.</li>\n<li><em>Normally</em> the dialog isn't re-instantiated or re-shown to get the result, it's already there. Show() and Hide() do just that.</li>\n</ol>\n\n<p>The reality is you're trading a method call for an awkward ShowDialog() syntax. Method calls are cheap, and you can't guarantee the caller will use your out parameter any more than you can guarantee they will call GetDialogResult(). So why bother. Make the thing easy to use, or don't overload ShowDialog in the first place.</p>\n\n<p>Maybe whatever you're sub-classing is funky and acts differently and it's not applicable to your situation, but general design is forms don't go away when you click OK, they go away when they are Disposed() of.</p>\n"
},
{
"answer_id": 284166,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 3,
"selected": false,
"text": "<p>It should not be OK since .net framework does not use this design. In the case of OpenFileDialog class, it has a parameterless ShowDialog() method returning a DialogResult. Once this method called, user is supposed to get the selected files by using the FileName, FileNames, SafeFileName and SafeFileNames methods.</p>\n\n<p>Let's assume that this implented in the \"out parameter\" way. I would have to write code like this just to get the SafeFileName:</p>\n\n<pre><code>string dummyFileName;\nstring[] dummyFileNames;\nstring safeFileName;\nstring[] dummySafeFileNames;\n\nmyDialog.ShowDialog(out dummyFileName, out dummyFileNames, out safeFileName, out dummySafeFileNames);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14606/"
] |
In an earlier question about [how to return a string from a dialog window](https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form), **yapiskan** suggested [overloading the child form's ShowDialog() method](https://stackoverflow.com/questions/280579/c-beginner-help-how-do-i-pass-a-value-from-a-child-back-to-the-parent-form#280731) to include an out parameter.
My question is whether or not this is a good approach in C#.
Here is some example code, based on yapiskan's suggestion. In the child form (in this example, it's a form with a textbox on it), you just need to add the ShowDialog overload and assign UI values to the out parameter:
```
public DialogResult ShowDialog(out string s)
{
DialogResult result = this.ShowDialog();
s = this.textBox1.Text;
return result;
}
```
And to show the form and retrieve the entered text, you do this:
```
using (CustomDialog frm = new CustomDialog())
{
string s;
if (frm.ShowDialog(out s) == DialogResult.OK)
{
// do something with s
}
}
```
One advantage I can think of is that this approach forces the user of the CustomDialog form to get the information it contains through the form's ShowDialog method (rather than from a who-knows-what-it's-called method like GetMyData() or something).
|
Better to have a Public property/method and get the information.
What would you do if you would need 3..4..5 informations, having 5 parameters out? More clean to have accessors to get your information from the Dialog.
|
281,264 |
<p>How do I remove empty elements from an array in JavaScript? </p>
<p>Is there a straightforward way, or do I need to loop through it and remove them manually?</p>
|
[
{
"answer_id": 281288,
"author": "Matty",
"author_id": 26241,
"author_profile": "https://Stackoverflow.com/users/26241",
"pm_score": -1,
"selected": false,
"text": "<p>Try this. Pass it your array and it will return with empty elements removed. *Updated to address the bug pointed out by Jason</p>\n\n<pre><code>function removeEmptyElem(ary) {\n for (var i = ary.length - 1; i >= 0; i--) {\n if (ary[i] == undefined) {\n ary.splice(i, 1);\n } \n }\n return ary;\n}\n</code></pre>\n"
},
{
"answer_id": 281306,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 3,
"selected": false,
"text": "<p>You may find it easier to loop over your array and build a new array out of the items you want to keep from the array than by trying to loop and splice as has been suggested, since modifying the length of the array while it is being looped over can introduce problems.</p>\n\n<p>You could do something like this:</p>\n\n<pre><code>function removeFalsyElementsFromArray(someArray) {\n var newArray = [];\n for(var index = 0; index < someArray.length; index++) {\n if(someArray[index]) {\n newArray.push(someArray[index]);\n }\n }\n return newArray;\n}\n</code></pre>\n\n<p>Actually here is a more generic solution:</p>\n\n<pre><code>function removeElementsFromArray(someArray, filter) {\n var newArray = [];\n for(var index = 0; index < someArray.length; index++) {\n if(filter(someArray[index]) == false) {\n newArray.push(someArray[index]);\n }\n }\n return newArray;\n}\n\n// then provide one or more filter functions that will \n// filter out the elements based on some condition:\nfunction isNullOrUndefined(item) {\n return (item == null || typeof(item) == \"undefined\");\n}\n\n// then call the function like this:\nvar myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];\nvar results = removeElementsFromArray(myArray, isNullOrUndefined);\n\n// results == [1,2,3,3,4,4,5,6]\n</code></pre>\n\n<p>You get the idea - you could then have other types of filter functions. Probably more than you need, but I was feeling generous... ;)</p>\n"
},
{
"answer_id": 281335,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 11,
"selected": true,
"text": "<p><strong>EDIT:</strong> This question was answered almost nine years ago when there were not many useful built-in methods in the <code>Array.prototype</code>.</p>\n\n<p>Now, certainly, I would recommend you to use the <code>filter</code> method.</p>\n\n<p>Take in mind that this method will return you <em>a new array</em> with the elements that pass the criteria of the callback function you provide to it.</p>\n\n<p>For example, if you want to remove <code>null</code> or <code>undefined</code> values: </p>\n\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>var array = [0, 1, null, 2, \"\", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];\r\n\r\nvar filtered = array.filter(function (el) {\r\n return el != null;\r\n});\r\n\r\nconsole.log(filtered);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>It will depend on what you consider to be \"empty\" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string.</p>\n\n<p>One typical pattern that I see often used is to remove elements that are <em>falsy</em>, which include an empty string <code>\"\"</code>, <code>0</code>, <code>NaN</code>, <code>null</code>, <code>undefined</code>, and <code>false</code>.</p>\n\n<p>You can pass to the <code>filter</code> method, the <code>Boolean</code> constructor function, or return the same element in the filter criteria function, for example:</p>\n\n<pre><code>var filtered = array.filter(Boolean);\n</code></pre>\n\n<p>Or</p>\n\n<pre><code>var filtered = array.filter(function(el) { return el; });\n</code></pre>\n\n<p>In both ways, this works because the <code>filter</code> method in the first case, calls the <code>Boolean</code> constructor as a function, converting the value, and in the second case, the <code>filter</code> method internally turns the return value of the callback implicitly to <code>Boolean</code>.</p>\n\n<p>If you are working with sparse arrays, and you are trying to get rid of the \"holes\", you can use the <code>filter</code> method passing a callback that returns true, for example:</p>\n\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>var sparseArray = [0, , , 1, , , , , 2, , , , 3],\r\n cleanArray = sparseArray.filter(function () { return true });\r\n\r\nconsole.log(cleanArray); // [ 0, 1, 2, 3 ]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><strong>Old answer:</strong> Don't do this!</p>\n\n<p>I use this method, extending the native Array prototype:</p>\n\n<pre><code>Array.prototype.clean = function(deleteValue) {\n for (var i = 0; i < this.length; i++) {\n if (this[i] == deleteValue) { \n this.splice(i, 1);\n i--;\n }\n }\n return this;\n};\n\ntest = new Array(\"\", \"One\", \"Two\", \"\", \"Three\", \"\", \"Four\").clean(\"\");\ntest2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];\ntest2.clean(undefined);\n</code></pre>\n\n<p>Or you can simply push the existing elements into other array:</p>\n\n<pre><code>// Will remove all falsy values: undefined, null, 0, false, NaN and \"\" (empty string)\nfunction cleanArray(actual) {\n var newArray = new Array();\n for (var i = 0; i < actual.length; i++) {\n if (actual[i]) {\n newArray.push(actual[i]);\n }\n }\n return newArray;\n}\n\ncleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);\n</code></pre>\n"
},
{
"answer_id": 281393,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 7,
"selected": false,
"text": "<p>If you've got Javascript 1.6 or later you can use <a href=\"https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter\" rel=\"noreferrer\"><code>Array.filter</code></a> using a trivial <code>return true</code> callback function, e.g.:</p>\n\n<pre><code>arr = arr.filter(function() { return true; });\n</code></pre>\n\n<p>since <code>.filter</code> automatically skips missing elements in the original array.</p>\n\n<p>The MDN page linked above also contains a nice error-checking version of <code>filter</code> that can be used in JavaScript interpreters that don't support the official version.</p>\n\n<p>Note that this will not remove <code>null</code> entries nor entries with an explicit <code>undefined</code> value, but the OP specifically requested \"missing\" entries.</p>\n"
},
{
"answer_id": 281638,
"author": "Joe Pineda",
"author_id": 21258,
"author_profile": "https://Stackoverflow.com/users/21258",
"pm_score": 1,
"selected": false,
"text": "<p>This works, I tested it in <a href=\"http://appjet.com/\" rel=\"nofollow noreferrer\">AppJet</a> (you can copy-paste the code on its IDE and press \"reload\" to see it work, don't need to create an account)</p>\n\n<pre><code>/* appjet:version 0.1 */\nfunction Joes_remove(someArray) {\n var newArray = [];\n var element;\n for( element in someArray){\n if(someArray[element]!=undefined ) {\n newArray.push(someArray[element]);\n }\n }\n return newArray;\n}\n\nvar myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];\n\nprint(\"Original array:\", myArray2);\nprint(\"Clenased array:\", Joes_remove(myArray2) );\n/*\nReturns: [1,2,3,3,0,4,4,5,6]\n*/\n</code></pre>\n"
},
{
"answer_id": 660553,
"author": "Erik Johansson",
"author_id": 15307,
"author_profile": "https://Stackoverflow.com/users/15307",
"pm_score": 4,
"selected": false,
"text": "<p>@Alnitak</p>\n\n<p>Actually Array.filter works on all browsers if you add some extra code. See below.</p>\n\n<pre><code>var array = [\"\",\"one\",0,\"\",null,0,1,2,4,\"two\"];\n\nfunction isempty(x){\nif(x!==\"\")\n return true;\n}\nvar res = array.filter(isempty);\ndocument.writeln(res.toJSONString());\n// gives: [\"one\",0,null,0,1,2,4,\"two\"] \n</code></pre>\n\n<p>This is the code you need to add for IE, but filter and Functional programmingis worth is imo.</p>\n\n<pre><code>//This prototype is provided by the Mozilla foundation and\n//is distributed under the MIT license.\n//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license\n\nif (!Array.prototype.filter)\n{\n Array.prototype.filter = function(fun /*, thisp*/)\n {\n var len = this.length;\n if (typeof fun != \"function\")\n throw new TypeError();\n\n var res = new Array();\n var thisp = arguments[1];\n for (var i = 0; i < len; i++)\n {\n if (i in this)\n {\n var val = this[i]; // in case fun mutates this\n if (fun.call(thisp, val, i, this))\n res.push(val);\n }\n }\n\n return res;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 2333725,
"author": "lcabral",
"author_id": 281178,
"author_profile": "https://Stackoverflow.com/users/281178",
"pm_score": -1,
"selected": false,
"text": "<p>Filtering out invalid entries with a regular expression</p>\n\n<pre><code>array = array.filter(/\\w/);\nfilter + regexp\n</code></pre>\n"
},
{
"answer_id": 2843625,
"author": "vsync",
"author_id": 104380,
"author_profile": "https://Stackoverflow.com/users/104380",
"pm_score": 11,
"selected": false,
"text": "<h2>A few simple ways:</h2>\n<pre class=\"lang-js prettyprint-override\"><code>var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];\n\narr.filter(n => n)\n// [1, 2, 3, -3, 4, 4, 5, 6]\n\narr.filter(Number) \n// [1, 2, 3, -3, 4, 4, 5, 6]\n\narr.filter(Boolean) \n// [1, 2, 3, -3, 4, 4, 5, 6]\n</code></pre>\n<p><strong>or - (only for <em>single</em> array items of type "text")</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); \n// output: ["1","2","3","4","5"]\n</code></pre>\n<p><strong>or - Classic way: simple iteration</strong></p>\n<pre class=\"lang-js prettyprint-override\"><code>var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],\n len = arr.length, i;\n\nfor(i = 0; i < len; i++ )\n arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array\n\narr.splice(0 , len); // cut the array and leave only the non-empty values\n// [1,2,3,3,[],Object{},5,6]\n</code></pre>\n<br/>\n<h2>jQuery:</h2>\n<pre class=\"lang-js prettyprint-override\"><code>var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];\n \narr = $.grep(arr, n => n == 0 || n);\n// [1, 2, 3, 3, 0, 4, 4, 5, 6]\n</code></pre>\n"
},
{
"answer_id": 4423182,
"author": "JessyNinja",
"author_id": 506411,
"author_profile": "https://Stackoverflow.com/users/506411",
"pm_score": 2,
"selected": false,
"text": "<p>What about that:</p>\n\n<pre><code>js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')\n1,2,3,3,0,4,4,5,6\n</code></pre>\n"
},
{
"answer_id": 5443800,
"author": "Tomás Senart",
"author_id": 138153,
"author_profile": "https://Stackoverflow.com/users/138153",
"pm_score": 6,
"selected": false,
"text": "<p>The clean way to do it.</p>\n\n<pre><code>var arr = [0,1,2,\"Thomas\",\"false\",false,true,null,3,4,undefined,5,\"end\"];\narr = arr.filter(Boolean);\n// [1, 2, \"Thomas\", \"false\", true, 3, 4, 5, \"end\"]\n</code></pre>\n"
},
{
"answer_id": 7924304,
"author": "lepe",
"author_id": 196507,
"author_profile": "https://Stackoverflow.com/users/196507",
"pm_score": 8,
"selected": false,
"text": "<p>If you need to remove ALL empty values (\"\", null, undefined and 0): </p>\n\n<pre><code>arr = arr.filter(function(e){return e}); \n</code></pre>\n\n<p>To remove empty values and Line breaks:</p>\n\n<pre><code>arr = arr.filter(function(e){ return e.replace(/(\\r\\n|\\n|\\r)/gm,\"\")});\n</code></pre>\n\n<p>Example:</p>\n\n<pre><code>arr = [\"hello\",0,\"\",null,undefined,1,100,\" \"] \narr.filter(function(e){return e});\n</code></pre>\n\n<p>Return:</p>\n\n<pre><code>[\"hello\", 1, 100, \" \"]\n</code></pre>\n\n<p><strong>UPDATE (based on Alnitak's comment)</strong></p>\n\n<p>In some situations you may want to keep \"0\" in the array and remove anything else (null, undefined and \"\"), this is one way:</p>\n\n<pre><code>arr.filter(function(e){ return e === 0 || e });\n</code></pre>\n\n<p>Return:</p>\n\n<pre><code>[\"hello\", 0, 1, 100, \" \"]\n</code></pre>\n"
},
{
"answer_id": 8566035,
"author": "Luis Perez",
"author_id": 984780,
"author_profile": "https://Stackoverflow.com/users/984780",
"pm_score": 4,
"selected": false,
"text": "<p>If using a library is an option I know underscore.js has a function called compact() <a href=\"http://documentcloud.github.com/underscore/\" rel=\"noreferrer\">http://documentcloud.github.com/underscore/</a> it also has several other useful functions related to arrays and collections.</p>\n\n<p>Here is an excerpt from their documentation:</p>\n\n<blockquote>\n <p>_.compact(array) </p>\n \n <p>Returns a copy of the array with all falsy values removed. In JavaScript, false, null, 0, \"\", undefined and NaN are all falsy.</p>\n \n <p>_.compact([0, 1, false, 2, '', 3]);</p>\n \n <p>=> [1, 2, 3]</p>\n</blockquote>\n"
},
{
"answer_id": 12091280,
"author": "Jason",
"author_id": 1584271,
"author_profile": "https://Stackoverflow.com/users/1584271",
"pm_score": -1,
"selected": false,
"text": "<p>I needed to do this same task and came upon this thread. I ended up using the array \"join\" to create a string using a \"_\" separator, then doing a bit of regex to:-</p>\n\n<pre><code>1. replace \"__\" or more with just one \"_\",\n2. replace preceding \"_\" with nothing \"\" and similarly \n3. replace and ending \"_\" with nothing \"\"\n</code></pre>\n\n<p>...then using array \"split\" to make a cleaned-up array:-</p>\n\n<pre><code>var myArr = new Array(\"\",\"\",\"a\",\"b\",\"\",\"c\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"e\",\"\");\nvar myStr = \"\";\n\nmyStr = myArr.join(\"_\");\n\nmyStr = myStr.replace(new RegExp(/__*/g),\"_\");\nmyStr = myStr.replace(new RegExp(/^_/i),\"\");\nmyStr = myStr.replace(new RegExp(/_$/i),\"\");\nmyArr = myStr.split(\"_\");\n\nalert(\"myArr=\" + myArr.join(\",\"));\n</code></pre>\n\n<p>...or in 1 line of code:-</p>\n\n<pre><code>var myArr = new Array(\"\",\"\",\"a\",\"b\",\"\",\"c\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"e\",\"\");\n\nmyArr = myArr.join(\"_\").replace(new RegExp(/__*/g),\"_\").replace(new RegExp(/^_/i),\"\").replace(new RegExp(/_$/i),\"\").split(\"_\");\n\nalert(\"myArr=\" + myArr.join(\",\"));\n</code></pre>\n\n<p>...or, extending the Array object :-</p>\n\n<pre><code>Array.prototype.clean = function() {\n return this.join(\"_\").replace(new RegExp(/__*/g),\"_\").replace(new RegExp(/^_/i),\"\").replace(new RegExp(/_$/i),\"\").split(\"_\");\n};\n\nvar myArr = new Array(\"\",\"\",\"a\",\"b\",\"\",\"c\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"\",\"e\",\"\");\n\nalert(\"myArr=\" + myArr.clean().join(\",\"));\n</code></pre>\n"
},
{
"answer_id": 13587612,
"author": "ELLIOTTCABLE",
"author_id": 31897,
"author_profile": "https://Stackoverflow.com/users/31897",
"pm_score": 2,
"selected": false,
"text": "<p>I'm simply adding my voice to the above “call ES5's <code>Array..filter()</code> with a global constructor” golf-hack, but I suggest using <code>Object</code> instead of <code>String</code>, <code>Boolean</code>, or <code>Number</code> as suggested above.</p>\n\n<p>Specifically, ES5's <code>filter()</code> already doesn't trigger for <code>undefined</code> elements within the array; so a function that universally returns <code>true</code>, which returns <em>all</em> elements <code>filter()</code> hits, will necessarily only return non-<code>undefined</code> elements:</p>\n\n<pre><code>> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})\n[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]\n</code></pre>\n\n<p>However, writing out <code>...(function(){return true;})</code> is longer than writing <code>...(Object)</code>; and the return-value of the <code>Object</code> constructor will be, under <em>any circumstances</em>, some sort of object. Unlike the primitive-boxing-constructors suggested above, no possible object-value is falsey, and thus in a boolean setting, <code>Object</code> is a short-hand for <code>function(){return true}</code>.</p>\n\n<pre><code>> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)\n[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]\n</code></pre>\n"
},
{
"answer_id": 13650939,
"author": "c4urself",
"author_id": 750979,
"author_profile": "https://Stackoverflow.com/users/750979",
"pm_score": 5,
"selected": false,
"text": "<p><strong>With Underscore/Lodash:</strong></p>\n\n<p>General use case:</p>\n\n<pre><code>_.without(array, emptyVal, otherEmptyVal);\n_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);\n</code></pre>\n\n<p>With empties:</p>\n\n<pre><code>_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');\n--> [\"foo\", \"bar\", \"baz\", \"foobar\"]\n</code></pre>\n\n<p>See <a href=\"https://lodash.com/docs#without\" rel=\"noreferrer\">lodash documentation for without</a>.</p>\n"
},
{
"answer_id": 13798078,
"author": "Andreas Louv",
"author_id": 887539,
"author_profile": "https://Stackoverflow.com/users/887539",
"pm_score": 7,
"selected": false,
"text": "<p>Simply one liner:</p>\n\n<pre><code>[1, false, \"\", undefined, 2].filter(Boolean); // [1, 2]\n</code></pre>\n\n<p>or using <a href=\"http://underscorejs.org/#filter\">underscorejs.org</a>:</p>\n\n<pre><code>_.filter([1, false, \"\", undefined, 2], Boolean); // [1, 2]\n// or even:\n_.compact([1, false, \"\", undefined, 2]); // [1, 2]\n</code></pre>\n"
},
{
"answer_id": 16752942,
"author": "GameAlchemist",
"author_id": 856501,
"author_profile": "https://Stackoverflow.com/users/856501",
"pm_score": 2,
"selected": false,
"text": "<p>Another way to do it is to take advantage of the length property of the array : pack the non-null items on the 'left' of the array, then reduce the length. \nIt is an in-place algorithm -does not allocates memory, too bad for the garbage collector-, and it has very good best/average/worst case behaviour.</p>\n\n<p>This solution, compared to others here, is between 2 to 50 times faster on Chrome, and 5 to 50 times faster on Firefox, as you might see here : <a href=\"http://jsperf.com/remove-null-items-from-array\" rel=\"nofollow\">http://jsperf.com/remove-null-items-from-array</a></p>\n\n<p>The code below adds the non-enumerable 'removeNull' method to the Array, which returns 'this' for daisy-chaining : </p>\n\n<pre><code>var removeNull = function() {\n var nullCount = 0 ;\n var length = this.length ;\n for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }\n // no item is null\n if (!nullCount) { return this}\n // all items are null\n if (nullCount == length) { this.length = 0; return this }\n // mix of null // non-null\n var idest=0, isrc=length-1;\n length -= nullCount ; \n while (true) {\n // find a non null (source) slot on the right\n while (!this[isrc]) { isrc--; nullCount--; } \n if (!nullCount) { break } // break if found all null\n // find one null slot on the left (destination)\n while ( this[idest]) { idest++ } \n // perform copy\n this[idest]=this[isrc];\n if (!(--nullCount)) {break}\n idest++; isrc --; \n }\n this.length=length; \n return this;\n}; \n\nObject.defineProperty(Array.prototype, 'removeNull', \n { value : removeNull, writable : true, configurable : true } ) ;\n</code></pre>\n"
},
{
"answer_id": 17474586,
"author": "A. Zalonis",
"author_id": 2455661,
"author_profile": "https://Stackoverflow.com/users/2455661",
"pm_score": -1,
"selected": false,
"text": "<p>Nice ... very nice \nWe can also replace all array values like this</p>\n\n<pre><code>Array.prototype.ReplaceAllValues = function(OldValue,newValue)\n{\n for( var i = 0; i < this.length; i++ ) \n {\n if( this[i] == OldValue ) \n {\n this[i] = newValue;\n }\n }\n};\n</code></pre>\n"
},
{
"answer_id": 24671138,
"author": "sqram",
"author_id": 93026,
"author_profile": "https://Stackoverflow.com/users/93026",
"pm_score": 2,
"selected": false,
"text": "<pre><code>foo = [0, 1, 2, "", , false, 3, "four", null]\n\nfoo.filter(e => e === 0 ? true : e)\n</code></pre>\n<p><strong>returns</strong></p>\n<pre><code>[0, 1, 2, 3, "four"]\n</code></pre>\n<p>If you're positive you won't have any 0's in your array, it can look a bit nicer:</p>\n<pre><code>foo.filter(e => e)\n</code></pre>\n"
},
{
"answer_id": 26497390,
"author": "Goku Nymbus",
"author_id": 2565512,
"author_profile": "https://Stackoverflow.com/users/2565512",
"pm_score": 2,
"selected": false,
"text": "<p>When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.</p>\n\n<pre><code>var stringObject = [\"\", \"some string yay\", \"\", \"\", \"Other string yay\"];\nstringObject = stringObject.filter(function(n){ return n.length > 0});\n</code></pre>\n\n<p>Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.</p>\n\n<p><strong>Returns</strong></p>\n\n<pre><code>[\"some string yay\", \"Other string yay\"]\n</code></pre>\n"
},
{
"answer_id": 26589651,
"author": "Nico Napoli",
"author_id": 566697,
"author_profile": "https://Stackoverflow.com/users/566697",
"pm_score": -1,
"selected": false,
"text": "<p>This is another way to do it:</p>\n\n<pre><code>var arr = [\"a\", \"b\", undefined, undefined, \"e\", undefined, \"g\", undefined, \"i\", \"\", \"k\"]\nvar cleanArr = arr.join('.').split(/\\.+/);\n</code></pre>\n"
},
{
"answer_id": 26820396,
"author": "Josh Bedo",
"author_id": 509754,
"author_profile": "https://Stackoverflow.com/users/509754",
"pm_score": 4,
"selected": false,
"text": "<p>Since nobody else mentioned it and most people have underscore included in their project you can also use <code>_.without(array, *values);</code>. </p>\n\n<pre><code>_.without([\"text\", \"string\", null, null, null, \"text\"], null)\n// => [\"text\", \"string\", \"text\"]\n</code></pre>\n"
},
{
"answer_id": 33089999,
"author": "rpearce",
"author_id": 680394,
"author_profile": "https://Stackoverflow.com/users/680394",
"pm_score": -1,
"selected": false,
"text": "<p>Here is an example using variadic behavior & ES2015 fat arrow expression:</p>\n\n<pre><code>Array.prototype.clean = function() {\n var args = [].slice.call(arguments);\n return this.filter(item => args.indexOf(item) === -1);\n};\n\n// Usage\nvar arr = [\"\", undefined, 3, \"yes\", undefined, undefined, \"\"];\narr.clean(undefined); // [\"\", 3, \"yes\", \"\"];\narr.clean(undefined, \"\"); // [3, \"yes\"];\n</code></pre>\n"
},
{
"answer_id": 34222552,
"author": "VIJAY P",
"author_id": 1936006,
"author_profile": "https://Stackoverflow.com/users/1936006",
"pm_score": 3,
"selected": false,
"text": "<p><strong>What about this(ES6) : To remove Falsy value from an array.</strong></p>\n\n<pre><code>var arr = [0,1,2,\"test\",\"false\",false,true,null,3,4,undefined,5,\"end\"];\n\narr.filter((v) => (!!(v)==true));\n\n//output:\n\n//[1, 2, \"test\", \"false\", true, 3, 4, 5, \"end\"]\n</code></pre>\n"
},
{
"answer_id": 35947346,
"author": "John Slegers",
"author_id": 1946501,
"author_profile": "https://Stackoverflow.com/users/1946501",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to remove empty elements, is to use <a href=\"https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter\" rel=\"nofollow\"><strong><code>Array.prototype.filter()</code></strong></a>, as already mentioned in other answers.</p>\n\n<p>Unfortunately, <code>Array.prototype.filter()</code> is not supported by IE<9. If you still need to support IE8 or an even older version of IE, you could use the following <a href=\"https://remysharp.com/2010/10/08/what-is-a-polyfill\" rel=\"nofollow\"><strong>polyfill</strong></a> to add support for <code>Array.prototype.filter()</code> in these browsers :</p>\n\n<pre><code>if (!Array.prototype.filter) {\n Array.prototype.filter = function(fun/*, thisArg*/) {\n 'use strict';\n if (this === void 0 || this === null) {\n throw new TypeError();\n }\n var t = Object(this);\n var len = t.length >>> 0;\n if (typeof fun !== 'function') {\n throw new TypeError();\n }\n var res = [];\n var thisArg = arguments.length >= 2 ? arguments[1] : void 0;\n for (var i = 0; i < len; i++) {\n if (i in t) {\n var val = t[i];\n if (fun.call(thisArg, val, i, t)) {\n res.push(val);\n }\n }\n }\n return res;\n };\n}\n</code></pre>\n"
},
{
"answer_id": 35988168,
"author": "cluster1",
"author_id": 2645857,
"author_profile": "https://Stackoverflow.com/users/2645857",
"pm_score": 1,
"selected": false,
"text": "<p>'Misusing' the for ... in (object-member) loop.\n => Only truthy values appear in the body of the loop.</p>\n\n<pre><code>// --- Example ----------\nvar field = [];\n\nfield[0] = 'One';\nfield[1] = 1;\nfield[3] = true;\nfield[5] = 43.68;\nfield[7] = 'theLastElement';\n// --- Example ----------\n\nvar originalLength;\n\n// Store the length of the array.\noriginalLength = field.length;\n\nfor (var i in field) {\n // Attach the truthy values upon the end of the array. \n field.push(field[i]);\n}\n\n// Delete the original range within the array so that\n// only the new elements are preserved.\nfield.splice(0, originalLength);\n</code></pre>\n"
},
{
"answer_id": 38359497,
"author": "siddhant narang",
"author_id": 5800860,
"author_profile": "https://Stackoverflow.com/users/5800860",
"pm_score": -1,
"selected": false,
"text": "<p>How about doing it this way \n</p>\n\n<pre><code>// Removes all falsy values \narr = arr.filter(function(array_val) { // creates an anonymous filter func\n var x = Boolean(array_val); // checks if val is null\n return x == true; // returns val to array if not null\n });\n</code></pre>\n"
},
{
"answer_id": 40784002,
"author": "Puni",
"author_id": 5101585,
"author_profile": "https://Stackoverflow.com/users/5101585",
"pm_score": 0,
"selected": false,
"text": "<p><strong>If anyone is looking for cleaning the whole Array or Object this might help</strong>.</p>\n\n<pre><code>var qwerty = {\n test1: null,\n test2: 'somestring',\n test3: 3,\n test4: {},\n test5: {\n foo: \"bar\"\n },\n test6: \"\",\n test7: undefined,\n test8: \" \",\n test9: true,\n test10: [],\n test11: [\"77\",\"88\"],\n test12: {\n foo: \"foo\",\n bar: {\n foo: \"q\",\n bar: {\n foo:4,\n bar:{}\n }\n },\n bob: {}\n }\n}\n\nvar asdfg = [,,\"\", \" \", \"yyyy\", 78, null, undefined,true, {}, {x:6}, [], [2,3,5]];\n\nfunction clean_data(obj) {\n for (var key in obj) {\n // Delete null, undefined, \"\", \" \"\n if (obj[key] === null || obj[key] === undefined || obj[key] === \"\" || obj[key] === \" \") {\n delete obj[key];\n }\n // Delete empty object\n // Note : typeof Array is also object\n if (typeof obj[key] === 'object' && Object.keys(obj[key]).length <= 0) {\n delete obj[key];\n }\n // If non empty object call function again\n if(typeof obj[key] === 'object'){\n clean_data(obj[key]);\n }\n }\n return obj;\n}\n\nvar objData = clean_data(qwerty);\nconsole.log(objData);\nvar arrayData = clean_data(asdfg);\nconsole.log(arrayData);\n</code></pre>\n\n<p><strong>Output:</strong></p>\n\n<p>Removes anything that is <code>null</code>, <code>undefined</code>, <code>\"\"</code>, <code>\" \"</code>, <code>empty object</code> or <code>empty array</code></p>\n\n<p>jsfiddle <a href=\"https://jsfiddle.net/Puni/besepud2/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 41430492,
"author": "Trevor",
"author_id": 2697942,
"author_profile": "https://Stackoverflow.com/users/2697942",
"pm_score": 0,
"selected": false,
"text": "<p>This one will only remove empty values and not falsey ones, which I think is more desirable.</p>\n\n<p>There is an option to also remove null values.</p>\n\n<p>This method should be much faster than using splice.</p>\n\n<pre><code> function cleanArray(a, removeNull) {\n var i, l, temp = [];\n l = a.length;\n if (removeNull) {\n for (i = 0; i < l; i++) {\n if (a[i] !== undefined && a[i] !== null) {\n temp.push(a[i]);\n }\n }\n } else {\n for (i = 0; i < l; i++) {\n if (a[i] !== undefined) {\n temp.push(a[i]);\n }\n }\n }\n a.length = 0;\n l = temp.length;\n for (i = 0; i < l; i++) {\n a[i] = temp[i];\n }\n temp.length = 0;\n return a;\n }\n var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '', 4, , 4, , 5, , 6, , , , ];\n cleanArray(myArray);\n myArray;\n</code></pre>\n"
},
{
"answer_id": 42961952,
"author": "ML13",
"author_id": 4352178,
"author_profile": "https://Stackoverflow.com/users/4352178",
"pm_score": 5,
"selected": false,
"text": "<p>Simple ES6</p>\n\n<pre><code>['a','b','',,,'w','b'].filter(v => v);\n</code></pre>\n"
},
{
"answer_id": 43090968,
"author": "KARTHIKEYAN.A",
"author_id": 4652706,
"author_profile": "https://Stackoverflow.com/users/4652706",
"pm_score": 2,
"selected": false,
"text": "<pre><code>var data = [null, 1,2,3];\nvar r = data.filter(function(i){ return i != null; })\n</code></pre>\n\n<hr>\n\n<pre><code>console.log(r) \n</code></pre>\n\n<blockquote>\n <p>[1,2,3]</p>\n</blockquote>\n"
},
{
"answer_id": 43109339,
"author": "Sandeep M",
"author_id": 3999929,
"author_profile": "https://Stackoverflow.com/users/3999929",
"pm_score": 1,
"selected": false,
"text": "<p>This might help you : <a href=\"https://lodash.com/docs/4.17.4#remove\" rel=\"nofollow noreferrer\">https://lodash.com/docs/4.17.4#remove</a></p>\n\n<pre><code>var details = [\n {\n reference: 'ref-1',\n description: 'desc-1',\n price: 1\n }, {\n reference: '',\n description: '',\n price: ''\n }, {\n reference: 'ref-2',\n description: 'desc-2',\n price: 200\n }, {\n reference: 'ref-3',\n description: 'desc-3',\n price: 3\n }, {\n reference: '',\n description: '',\n price: ''\n }\n ];\n\n scope.removeEmptyDetails(details);\n expect(details.length).toEqual(3);\n</code></pre>\n\n<hr>\n\n<pre><code>scope.removeEmptyDetails = function(details){\n _.remove(details, function(detail){\n return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));\n });\n };\n</code></pre>\n"
},
{
"answer_id": 47553243,
"author": "KARTHIKEYAN.A",
"author_id": 4652706,
"author_profile": "https://Stackoverflow.com/users/4652706",
"pm_score": 0,
"selected": false,
"text": "<p>use filter to remove empty string in array.</p>\n\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>var s = [ '1,201,karthikeyan,K201,HELPER,[email protected],8248606269,7/14/2017,45680,TN-KAR24,8,800,1000,200,300,Karthikeyan,11/24/2017,Karthikeyan,11/24/2017,AVAILABLE\\r',\r\n '' ]\r\nvar newArr = s.filter(function(entry) { return entry.trim() != ''; })\r\n\r\nconsole.log(newArr); </code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 48005993,
"author": "Gapur Kassym",
"author_id": 8179428,
"author_profile": "https://Stackoverflow.com/users/8179428",
"pm_score": 3,
"selected": false,
"text": "<p>You should use filter to get array without empty elements. Example on ES6 </p>\n\n<pre><code>const array = [1, 32, 2, undefined, 3];\nconst newArray = array.filter(arr => arr);\n</code></pre>\n"
},
{
"answer_id": 48163228,
"author": "tsh",
"author_id": 2045384,
"author_profile": "https://Stackoverflow.com/users/2045384",
"pm_score": 7,
"selected": false,
"text": "<p>For removing holes, you should use</p>\n<pre class=\"lang-js prettyprint-override\"><code>arr.filter(() => true)\narr.flat(0) // New in ES2019\n</code></pre>\n<p>For removing hole, null, and, undefined:</p>\n<pre class=\"lang-js prettyprint-override\"><code>arr.filter(x => x != null)\n</code></pre>\n<p>For removing hole, and, falsy (null, undefined, 0, -0, 0n, NaN, "", false, document.all) values:</p>\n<pre class=\"lang-js prettyprint-override\"><code>arr.filter(x => x)\n</code></pre>\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>arr = [, null, (void 0), 0, -0, 0n, NaN, false, '', 42];\nconsole.log(arr.filter(() => true)); // [null, (void 0), 0, -0, 0n, NaN, false, '', 42]\nconsole.log(arr.filter(x => x != null)); // [0, -0, 0n, NaN, false, \"\", 42]\nconsole.log(arr.filter(x => x)); // [42]</code></pre>\r\n</div>\r\n</div>\r\n</p>\n<p>Note:</p>\n<ul>\n<li>Holes are some array indexes without elements.</li>\n</ul>\n<pre class=\"lang-js prettyprint-override\"><code>arr = [, ,];\nconsole.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole\narr[42] = 42;\nconsole.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole\n\narr1 = [1, 2, 3];\narr1[0] = (void 0);\nconsole.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole\n\narr2 = [1, 2, 3];\ndelete arr2[0]; // NEVER do this please\nconsole.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole\n</code></pre>\n<ul>\n<li>All above methods are returning a copy of the given array, not modifying it in-place.</li>\n</ul>\n<pre><code>arr = [1, 3, null, 4];\nfiltered = arr.filter(x => x != null);\nconsole.log(filtered); // [1, 3, 4]\nconsole.log(arr); // [1, 3, null, 4]; not modified\n</code></pre>\n"
},
{
"answer_id": 48899849,
"author": "Jitendra virani",
"author_id": 7646491,
"author_profile": "https://Stackoverflow.com/users/7646491",
"pm_score": 1,
"selected": false,
"text": "<pre><code>var data= { \n myAction: function(array){\n return array.filter(function(el){\n return (el !== (undefined || null || ''));\n }).join(\" \");\n }\n}; \nvar string = data.myAction([\"I\", \"am\",\"\", \"working\", \"\", \"on\",\"\", \"nodejs\", \"\" ]);\nconsole.log(string);\n</code></pre>\n\n<p>Output: </p>\n\n<blockquote>\n <p>I am working on nodejs</p>\n</blockquote>\n\n<p>It will remove empty element from array and display other element.</p>\n"
},
{
"answer_id": 51264015,
"author": "Kanan Farzali",
"author_id": 2470558,
"author_profile": "https://Stackoverflow.com/users/2470558",
"pm_score": 5,
"selected": false,
"text": "<h1>ES6:</h1>\n\n<pre><code>let newArr = arr.filter(e => e);\n</code></pre>\n"
},
{
"answer_id": 52828995,
"author": "AmerllicA",
"author_id": 6877799,
"author_profile": "https://Stackoverflow.com/users/6877799",
"pm_score": 6,
"selected": false,
"text": "<p>Actually, you can use <code>ES6+</code> methods, assume the array is below:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];\n</code></pre>\n<p><del>And the answer could be one of these two ways:</del></p>\n<ul>\n<li><p><del>First way:</del></p>\n<pre class=\"lang-js prettyprint-override\"><code>const clearArray = arr.filter(i => i); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n</code></pre>\n</li>\n<li><p><del>Second way:</del></p>\n<pre class=\"lang-js prettyprint-override\"><code>const clearArray = arr.filter(Boolean); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]\n</code></pre>\n</li>\n</ul>\n<h4>Update 14th Oct 2022:</h4>\n<p>Those two answers aren't utterly correct, even in the given example, yeah, it works but pay attention to the number <code>0</code> in the given array, by both ways number zero is disappeared and it's obviously related to checking items by using boolean coercion.</p>\n<p>A completely correct way is to check nulish and remove them:</p>\n<pre class=\"lang-js prettyprint-override\"><code>const notNil = (i) => !(typeof i === 'undefined' || i === null);\n\nconst clearArray = arr.filter(i => isNil(i));\n</code></pre>\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>const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];\nconst notNil = (i) => !(typeof i === 'undefined' || i === null);\n\nconsole.log(\"Not nil: \", arr.filter(notNil));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 56886122,
"author": "Andrea Perdicchia",
"author_id": 2285574,
"author_profile": "https://Stackoverflow.com/users/2285574",
"pm_score": -1,
"selected": false,
"text": "<p>this is my solution for clean empty fields.</p>\n\n<p>Start from fees object:\nget only avail attribute (with map)\nfilter empty fields (with filter)\nparse results to integer (with map)</p>\n\n<pre><code>fees.map( ( e ) => e.avail ).filter( v => v!== '').map( i => parseInt( i ) );\n</code></pre>\n"
},
{
"answer_id": 57974884,
"author": "bittnkr",
"author_id": 9464885,
"author_profile": "https://Stackoverflow.com/users/9464885",
"pm_score": 0,
"selected": false,
"text": "<p>An in place solution:</p>\n\n<pre><code>function pack(arr) { // remove undefined values\n let p = -1\n for (let i = 0, len = arr.length; i < len; i++) {\n if (arr[i] !== undefined) { if (p >= 0) { arr[p] = arr[i]; p++ } }\n else if (p < 0) p = i\n }\n if (p >= 0) arr.length = p\n return arr\n}\n\nlet a = [1, 2, 3, undefined, undefined, 4, 5, undefined, null]\nconsole.log(JSON.stringify(a))\npack(a)\nconsole.log(JSON.stringify(a))\n</code></pre>\n"
},
{
"answer_id": 58968655,
"author": "Trung",
"author_id": 4038253,
"author_profile": "https://Stackoverflow.com/users/4038253",
"pm_score": -1,
"selected": false,
"text": "<pre><code>var a = [{a1: 1, children: [{a1: 2}, undefined, {a1: 3}]}, undefined, {a1: 5}, undefined, {a1: 6}]\nfunction removeNilItemInArray(arr) {\n if (!arr || !arr.length) return;\n for (let i = 0; i < arr.length; i++) {\n if (!arr[i]) {\n arr.splice(i , 1);\n continue;\n }\n removeNilItemInArray(arr[i].children);\n }\n}\nvar b = a;\nremoveNilItemInArray(a);\n// Always keep this memory zone\nconsole.log(b);\n</code></pre>\n"
},
{
"answer_id": 59905255,
"author": "Zalom",
"author_id": 3251051,
"author_profile": "https://Stackoverflow.com/users/3251051",
"pm_score": 2,
"selected": false,
"text": "<h2>Removing all empty elements</h2>\n\n<p>If an array contains empty Objects, Arrays, and Strings alongside other empty elements, we can remove them with:</p>\n\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>const arr = [ [], ['not', 'empty'], {}, { key: 'value' }, 0, 1, null, 2, \"\", \"here\", \" \", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ]\r\n\r\nlet filtered = JSON.stringify(\r\n arr.filter((obj) => {\r\n return ![null, undefined, ''].includes(obj)\r\n }).filter((el) => {\r\n return typeof el != \"object\" || Object.keys(el).length > 0\r\n })\r\n)\r\n\r\nconsole.log(JSON.parse(filtered))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<h2>Simple compacting (removing empty elements from an array)</h2>\n\n<p>With ES6:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const arr = [0, 1, null, 2, \"\", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]\r\n\r\nlet filtered = arr.filter((obj) => { return ![null, undefined].includes(obj) })\r\n\r\nconsole.log(filtered)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p>With plain Javascript -></p>\n\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>var arr = [0, 1, null, 2, \"\", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]\r\n\r\nvar filtered = arr.filter(function (obj) { return ![null, undefined].includes(obj) })\r\n\r\nconsole.log(filtered)</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 61928808,
"author": "Bhupesh Kumar",
"author_id": 13379286,
"author_profile": "https://Stackoverflow.com/users/13379286",
"pm_score": 1,
"selected": false,
"text": "<p>All the empty elements can be removed from an array by simply by using\n<code>array.filter(String);</code>\nIt returns all non empty elements of an array in javascript</p>\n"
},
{
"answer_id": 63564418,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 2,
"selected": false,
"text": "<p>You can use filter with index and <code>in</code> operator</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>let a = [1,,2,,,3];\nlet b = a.filter((x,i)=> i in a);\n\nconsole.log({a,b});</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68562363,
"author": "XDavidT",
"author_id": 7340422,
"author_profile": "https://Stackoverflow.com/users/7340422",
"pm_score": 0,
"selected": false,
"text": "<p>If you're using NodeJS, you can use <a href=\"https://www.npmjs.com/package/clean-deep\" rel=\"nofollow noreferrer\">clean-deep</a> package.\nUse <code>npm i clean-deep</code> before.</p>\n<pre><code>const cleanDeep = require('clean-deep');\nvar array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];\nconst filterd = cleanDeep(array);\nconsole.log(filterd);\n</code></pre>\n"
},
{
"answer_id": 68714483,
"author": "user3328281",
"author_id": 3328281,
"author_profile": "https://Stackoverflow.com/users/3328281",
"pm_score": 4,
"selected": false,
"text": "<p>To remove undefined elements from an array you can simply use</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>const array = [\n { name: \"tim\", age: 1 },\n undefined,\n { name: \"ewrfer\", age: 22 },\n { name: \"3tf5gh\", age: 56 },\n null,\n { name: \"kygm\", age: 19 },\n undefined,\n];\nconsole.log(array.filter(Boolean));</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 68852055,
"author": "Ashish Rawat",
"author_id": 2092405,
"author_profile": "https://Stackoverflow.com/users/2092405",
"pm_score": 2,
"selected": false,
"text": "<p>None of the answers above works best for all types. The below solution will remove null, undefined, <code>{}</code> <code>[]</code>, <code>NaN</code> and will preserve date string and what's best is it removes even from nested objects.</p>\n<pre><code>function removeNil(obj) {\n // recursively remove null and undefined from nested object too.\n return JSON.parse(JSON.stringify(obj), (k,v) => {\n if(v === null || v === '') return undefined;\n // convert date string to date.\n if (typeof v === "string" && /^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d.\\d\\d\\dZ$/.test(v))\n return new Date(v);\n // remove empty array and object.\n if(typeof v === 'object' && !Object.keys(v).length) return undefined;\n return v;\n });\n }\n</code></pre>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"true\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>function removeNil(obj) {\n // recursively remove null and undefined from nested object too.\n return JSON.parse(JSON.stringify(obj), (k,v) => {\n if(v === null || v === '') return undefined;\n // convert date string to date.\n if (typeof v === \"string\" && /^\\d\\d\\d\\d-\\d\\d-\\d\\dT\\d\\d:\\d\\d:\\d\\d.\\d\\d\\dZ$/.test(v))\n return new Date(v);\n // remove empty array and object.\n if(typeof v === 'object' && !Object.keys(v).length) return undefined;\n return v;\n });\n }\n \n const ob = {\n s: 'a',\n b: 43,\n countries: [ 'a', 'b', 'c' ],\n l: null,\n n: { ks: 'a', efe: null, ce: '' },\n d: new Date(),\n nan: NaN,\n k: undefined,\n emptyO: {},\n emptyArr: [],\n }\n \n const output = removeNil(ob);\n \n console.log(output);\n console.log('Tests: ', ob.countries.length, typeof(ob.d))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
},
{
"answer_id": 70167528,
"author": "hamza ahmad",
"author_id": 11882053,
"author_profile": "https://Stackoverflow.com/users/11882053",
"pm_score": -1,
"selected": false,
"text": "<pre><code>// recursive implementation\nfunction compact(arr) {\n const compactArray = [];\n //base case \n if(!arr.length) return []\n if(typeof arr[0] !== "undefined" \n && arr[0]!==null && arr[0] !== " " && \n arr[0]!== false &&\n arr[0]!== 0){\n compactArray.push(arr[0]);\n }\n return compactArray.concat(compact(arr.slice(1)))\n }\n \n compact([1,0,false,null,undefined,"banana"])`\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8954/"
] |
How do I remove empty elements from an array in JavaScript?
Is there a straightforward way, or do I need to loop through it and remove them manually?
|
**EDIT:** This question was answered almost nine years ago when there were not many useful built-in methods in the `Array.prototype`.
Now, certainly, I would recommend you to use the `filter` method.
Take in mind that this method will return you *a new array* with the elements that pass the criteria of the callback function you provide to it.
For example, if you want to remove `null` or `undefined` values:
```js
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
```
It will depend on what you consider to be "empty" for example, if you were dealing with strings, the above function wouldn't remove elements that are an empty string.
One typical pattern that I see often used is to remove elements that are *falsy*, which include an empty string `""`, `0`, `NaN`, `null`, `undefined`, and `false`.
You can pass to the `filter` method, the `Boolean` constructor function, or return the same element in the filter criteria function, for example:
```
var filtered = array.filter(Boolean);
```
Or
```
var filtered = array.filter(function(el) { return el; });
```
In both ways, this works because the `filter` method in the first case, calls the `Boolean` constructor as a function, converting the value, and in the second case, the `filter` method internally turns the return value of the callback implicitly to `Boolean`.
If you are working with sparse arrays, and you are trying to get rid of the "holes", you can use the `filter` method passing a callback that returns true, for example:
```js
var sparseArray = [0, , , 1, , , , , 2, , , , 3],
cleanArray = sparseArray.filter(function () { return true });
console.log(cleanArray); // [ 0, 1, 2, 3 ]
```
**Old answer:** Don't do this!
I use this method, extending the native Array prototype:
```
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);
```
Or you can simply push the existing elements into other array:
```
// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
var newArray = new Array();
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
```
|
281,275 |
<p>I have two STL containers that I want to merge, removing any elements that appear more than once. For example:</p>
<pre><code>typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
// c3 now contains the following 4 elements:
// 1, 2, 3, 4
</code></pre>
<p>std::unique seems to be for adjacent elements only, and in my case the containers could be in any order. I could do some <strong>std::set</strong> trickery I guess:</p>
<pre><code>container unique_merge(const container& c1, const container& c2)
{
std::set<container::value_type> s;
BOOST_FOREACH(const container::value_type& val, c1)
s.insert(val);
BOOST_FOREACH(const container::value_type& val, c2)
s.insert(val);
return container(s.begin(), s.end());
}
</code></pre>
<p>Is there a better way or have I missed something bleeding obvious?</p>
|
[
{
"answer_id": 281296,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 4,
"selected": true,
"text": "<p>For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N*log n).\nThe other option is to run std::sort on each list individually and then walk through them in parallel using <a href=\"http://msdn.microsoft.com/en-us/library/a20tb7e2.aspx\" rel=\"noreferrer\">std::set_union</a>, which removes duplicates for you. This will also be O(n*log n), so if you're worried about performance, you'll have to profile. If you're not, do whichever makes more sense to you.</p>\n\n<p>Edit:\n<code>set_union</code> will only work if there are no duplicates in the original lists, otherwise you'll have to go with <code>sort</code>, <code>merge</code>, <code>unique</code> and <code>erase</code>. The big O performance is still the same, with the same caveats about profiling.</p>\n\n<pre><code>template <typename container>\ncontainer unique_merge(container c1, container c2)\n{\n std::sort(c1.begin(), c1.end());\n std::sort(c2.begin(), c2.end());\n container mergeTarget;\n std::merge(c1.begin(), c1.end(), c2.begin(), c2.end(), \n std::insert_iterator(mergeTarget, mergeTarget.end())\n );\n std::erase(\n std::unique(mergeTarget.begin(), mergeTarget.end()), \n mergeTarget.end()\n );\n\n return mergeTarget;\n}\n</code></pre>\n"
},
{
"answer_id": 281309,
"author": "Uhall",
"author_id": 19129,
"author_profile": "https://Stackoverflow.com/users/19129",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <a href=\"https://en.cppreference.com/w/cpp/algorithm/set_union\" rel=\"nofollow noreferrer\">std::set_union algorithm</a> from the STL. You'll need to sort your input lists first though -- or create copies of your input lists, sort them, then use std::set_union.</p>\n"
},
{
"answer_id": 281326,
"author": "Chris Morley",
"author_id": 36034,
"author_profile": "https://Stackoverflow.com/users/36034",
"pm_score": 2,
"selected": false,
"text": "<p>You are going to need to either sort (either explicitly, or implicitly via a sorted container like set).</p>\n<p>There is a common idiom using std::sort/std::unique/std::erase to get unique elements in a container.</p>\n<p>So create a container with the contents of c1, append the contents of c2, then sort, move unique elements to the end, and erase them. Something like this:</p>\n<pre><code>container c(c1.begin(), c1.end());\nc.insert(c.end(), c2.begin(), c2.end());\nstd::sort(c.begin(), c.end());\nc.erase(std::unique(c.begin(), c.end()), c.end());\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
I have two STL containers that I want to merge, removing any elements that appear more than once. For example:
```
typedef std::list<int> container;
container c1;
container c2;
c1.push_back(1);
c1.push_back(2);
c1.push_back(3);
c2.push_back(2);
c2.push_back(3);
c2.push_back(4);
container c3 = unique_merge(c1, c2);
// c3 now contains the following 4 elements:
// 1, 2, 3, 4
```
std::unique seems to be for adjacent elements only, and in my case the containers could be in any order. I could do some **std::set** trickery I guess:
```
container unique_merge(const container& c1, const container& c2)
{
std::set<container::value_type> s;
BOOST_FOREACH(const container::value_type& val, c1)
s.insert(val);
BOOST_FOREACH(const container::value_type& val, c2)
s.insert(val);
return container(s.begin(), s.end());
}
```
Is there a better way or have I missed something bleeding obvious?
|
For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N\*log n).
The other option is to run std::sort on each list individually and then walk through them in parallel using [std::set\_union](http://msdn.microsoft.com/en-us/library/a20tb7e2.aspx), which removes duplicates for you. This will also be O(n\*log n), so if you're worried about performance, you'll have to profile. If you're not, do whichever makes more sense to you.
Edit:
`set_union` will only work if there are no duplicates in the original lists, otherwise you'll have to go with `sort`, `merge`, `unique` and `erase`. The big O performance is still the same, with the same caveats about profiling.
```
template <typename container>
container unique_merge(container c1, container c2)
{
std::sort(c1.begin(), c1.end());
std::sort(c2.begin(), c2.end());
container mergeTarget;
std::merge(c1.begin(), c1.end(), c2.begin(), c2.end(),
std::insert_iterator(mergeTarget, mergeTarget.end())
);
std::erase(
std::unique(mergeTarget.begin(), mergeTarget.end()),
mergeTarget.end()
);
return mergeTarget;
}
```
|
281,323 |
<p>I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005.</p>
<p>So, my query, without the additional column would be:</p>
<pre><code>"SELECT INTO [WebsiteHistory] FROM [Website]"
</code></pre>
<p>I want to populate the timestamp column as well, but am not sure how to best do this. I'd like to do something like:</p>
<pre><code>"SELECT Website.*, '" + DateTime.Now.ToShortDateString() + "' INTO [WebsiteHistory] FROM [Website]"
</code></pre>
<p>But that shouldn't work, especially if the timestamp column is not the last one. Is there any way to do this?</p>
|
[
{
"answer_id": 281336,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": true,
"text": "<p>Be warned. This works, but it is neither <em>nice</em> nor recommendable:</p>\n\n<pre><code>INSERT\n WebsiteHistory\nSELECT\n *,\n GETDATE()\nFROM\n Website\nWHERE\n Id = @WebsiteId\n</code></pre>\n\n<p>This assumes <code>WebsiteHistory</code> has the same structure as <code>Website</code> (you said it has), plus there is one additional <code>DATETIME</code> field.</p>\n\n<p>Better is this, because it is much more fail-safe (at the expense of being more verbose):</p>\n\n<pre><code>INSERT\n WebsiteHistory\n (\n Id,\n Field1,\n Field2,\n Field3,\n Field4,\n ModifiedDate\n )\nSELECT\n Id,\n Field1,\n Field2,\n Field3,\n Field4,\n GETDATE()\nFROM\n Website\nWHERE\n Id = @WebsiteId\n</code></pre>\n"
},
{
"answer_id": 281375,
"author": "Oddthinking",
"author_id": 8014,
"author_profile": "https://Stackoverflow.com/users/8014",
"pm_score": 0,
"selected": false,
"text": "<p>Look at the accepted answer for this question: <a href=\"https://stackoverflow.com/questions/205950/dynamically-look-up-column-names-for-a-table-while-in-an-sql-query\">Dynamically look up column names for a table while in an sql query</a></p>\n\n<p>It fetches the names of all the fields in the table to create a query customized to that table. You should be able to simply adapt the exact same technique to generate the right fields names here.</p>\n"
},
{
"answer_id": 281382,
"author": "Simon Keep",
"author_id": 1127460,
"author_profile": "https://Stackoverflow.com/users/1127460",
"pm_score": 2,
"selected": false,
"text": "<p>Can't you set a default constraint on the column that would automatically populate the timestamp column when a row is inserted to the table?</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281323",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2327/"
] |
I am attempting to insert a copy of a row from one table into another table with the same schema, with the addition of one column (a timestamp) to provide a "history" of the first table in MS Sql Server 2005.
So, my query, without the additional column would be:
```
"SELECT INTO [WebsiteHistory] FROM [Website]"
```
I want to populate the timestamp column as well, but am not sure how to best do this. I'd like to do something like:
```
"SELECT Website.*, '" + DateTime.Now.ToShortDateString() + "' INTO [WebsiteHistory] FROM [Website]"
```
But that shouldn't work, especially if the timestamp column is not the last one. Is there any way to do this?
|
Be warned. This works, but it is neither *nice* nor recommendable:
```
INSERT
WebsiteHistory
SELECT
*,
GETDATE()
FROM
Website
WHERE
Id = @WebsiteId
```
This assumes `WebsiteHistory` has the same structure as `Website` (you said it has), plus there is one additional `DATETIME` field.
Better is this, because it is much more fail-safe (at the expense of being more verbose):
```
INSERT
WebsiteHistory
(
Id,
Field1,
Field2,
Field3,
Field4,
ModifiedDate
)
SELECT
Id,
Field1,
Field2,
Field3,
Field4,
GETDATE()
FROM
Website
WHERE
Id = @WebsiteId
```
|
281,334 |
<p>I have a UL that looks like this:</p>
<pre><code><ul class="popular-pages">
<li><a href="region/us/california/">California</a></li>
<li><a href="region/us/michigan/">Michigan</a></li>
<li><a href="region/us/missouri/">Missouri</a></li>
<li><a href="region/us/new-york/">New York</a></li>
<li><a href="region/us/oregon/">Oregon</a></li>
<li><a href="region/us/oregon-washington/">Oregon; Washington</a></li>
<li><a href="region/us/pennsylvania/">Pennsylvania</a></li>
<li><a href="region/us/texas/">Texas</a></li>
<li><a href="region/us/virginia/">Virginia</a></li>
<li><a href="region/us/washington/">Washington</a></li>
</ul>
</code></pre>
<p>And CSS that looks like this:</p>
<pre><code>ul.popular-pages li a {
display:block;
float:left;
border-right:1px solid #b0b0b0;
border-bottom:1px solid #8d8d8d;
padding:10px;
background-color:#ebf4e0;
margin:2px; color:#526d3f
}
ul.popular-pages li a:hover {
text-decoration:none;
border-left:1px solid #b0b0b0;
border-top:1px solid #8d8d8d;
border-right:none;
border-bottom:none;
}
</code></pre>
<p>So it's working fine in modern browsers, but it's looking like this in IE6. Any suggestions?
<img src="https://thecleverest.com/Picture_26.png" alt="alt text"></p>
|
[
{
"answer_id": 281351,
"author": "Greg",
"author_id": 28002,
"author_profile": "https://Stackoverflow.com/users/28002",
"pm_score": 0,
"selected": false,
"text": "<p>What DOCTYPE are you using? DOCTYPE has an impact on how browsers render.</p>\n"
},
{
"answer_id": 281360,
"author": "Arief",
"author_id": 34096,
"author_profile": "https://Stackoverflow.com/users/34096",
"pm_score": 0,
"selected": false,
"text": "<p>try use this CSS hack for IE6. </p>\n\n<pre><code>*html ul.popular-pages li a { \n display:block; \n float:left; \n border-right:1px solid #b0b0b0; \n border-bottom:1px solid #8d8d8d; \n padding:10px; \n background-color:#ebf4e0; \n margin:2px; \n color:#526d3f \n}\n\n*html ul.popular-pages li a:hover { \n text-decoration:none; \n border-left:1px solid #b0b0b0; \n border-top:1px solid #8d8d8d; \n border-right:none; \n border-bottom:none;\n}\n</code></pre>\n\n<p>then adjust your CSS definition for IE6</p>\n"
},
{
"answer_id": 281391,
"author": "jishi",
"author_id": 33663,
"author_profile": "https://Stackoverflow.com/users/33663",
"pm_score": 3,
"selected": false,
"text": "<p>The reason for your layout is probably because you have the float on the anchor, move it to the list-item instead.</p>\n\n<pre>\n\nul.popular-pages li {\n float: left;\n}\n\n</pre>\n\n<p>Since you're not setting any width in your LI's, I suggest skipping the float and set display: inline on your LI's instead, if you want them on a row. </p>\n\n<p>Adjust with padding/margin to get appropriate spacing between them, and line-height to get correct behaviour for any eventual 2nd line.</p>\n\n<p>That way you won't have problem with your UL not taking up space, without the need of a hidden clear-element at the end of the list (which is your other alternative)</p>\n"
},
{
"answer_id": 281453,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>You're floating your elements, so their parent needs to clear/reset the flow via the <a href=\"http://www.google.com/search?q=css+clearfix\" rel=\"nofollow noreferrer\">clearfix</a> 'hack'.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281334",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a UL that looks like this:
```
<ul class="popular-pages">
<li><a href="region/us/california/">California</a></li>
<li><a href="region/us/michigan/">Michigan</a></li>
<li><a href="region/us/missouri/">Missouri</a></li>
<li><a href="region/us/new-york/">New York</a></li>
<li><a href="region/us/oregon/">Oregon</a></li>
<li><a href="region/us/oregon-washington/">Oregon; Washington</a></li>
<li><a href="region/us/pennsylvania/">Pennsylvania</a></li>
<li><a href="region/us/texas/">Texas</a></li>
<li><a href="region/us/virginia/">Virginia</a></li>
<li><a href="region/us/washington/">Washington</a></li>
</ul>
```
And CSS that looks like this:
```
ul.popular-pages li a {
display:block;
float:left;
border-right:1px solid #b0b0b0;
border-bottom:1px solid #8d8d8d;
padding:10px;
background-color:#ebf4e0;
margin:2px; color:#526d3f
}
ul.popular-pages li a:hover {
text-decoration:none;
border-left:1px solid #b0b0b0;
border-top:1px solid #8d8d8d;
border-right:none;
border-bottom:none;
}
```
So it's working fine in modern browsers, but it's looking like this in IE6. Any suggestions?

|
The reason for your layout is probably because you have the float on the anchor, move it to the list-item instead.
```
ul.popular-pages li {
float: left;
}
```
Since you're not setting any width in your LI's, I suggest skipping the float and set display: inline on your LI's instead, if you want them on a row.
Adjust with padding/margin to get appropriate spacing between them, and line-height to get correct behaviour for any eventual 2nd line.
That way you won't have problem with your UL not taking up space, without the need of a hidden clear-element at the end of the list (which is your other alternative)
|
281,355 |
<p>I have seen this in a lot of XML comments for classes in the .NET Framework BCL but have never been able to find documentation that explains what it does.</p>
<p>As an example, looking at System.Object reveals the following comments:</p>
<pre><code>namespace System
{
/// <summary>Supports all classes in the .NET Framework class hierarchy
/// and provides low-level services to derived classes. This is the
/// ultimate base class of all classes in the .NET Framework; it is the
/// root of the type hierarchy.</summary>
/// <filterpriority>1</filterpriority>
[System.Runtime.InteropServices.ClassInterfaceAttribute(2)]
public class Object
{
/// <summary>Determines whether the specified
/// <see cref="T:System.Object" />
/// instances are considered equal.</summary>
/// <returns>true if objA is the same instance as objB or
/// if both are null
/// references or if objA.Equals(objB) returns true;
/// otherwise, false.</returns>
/// <param name="objB">The second <see cref="T:System.Object" />
/// to compare. </param>
/// <param name="objA">The first <see cref="T:System.Object" />
/// to compare. </param>
/// <filterpriority>2</filterpriority>
public static bool Equals(object objA, object objB);
}
}
</code></pre>
|
[
{
"answer_id": 281457,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>Just a guess: the All vs Common tabs in intellisense?</p>\n"
},
{
"answer_id": 409009,
"author": "Øyvind Skaar",
"author_id": 49194,
"author_profile": "https://Stackoverflow.com/users/49194",
"pm_score": 3,
"selected": false,
"text": "<p>It is the same as decorating your member with EditorBrowsableAttribute. I would guess values 0,1 and 2 corresponds to Always, Advanced and Never.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1559/"
] |
I have seen this in a lot of XML comments for classes in the .NET Framework BCL but have never been able to find documentation that explains what it does.
As an example, looking at System.Object reveals the following comments:
```
namespace System
{
/// <summary>Supports all classes in the .NET Framework class hierarchy
/// and provides low-level services to derived classes. This is the
/// ultimate base class of all classes in the .NET Framework; it is the
/// root of the type hierarchy.</summary>
/// <filterpriority>1</filterpriority>
[System.Runtime.InteropServices.ClassInterfaceAttribute(2)]
public class Object
{
/// <summary>Determines whether the specified
/// <see cref="T:System.Object" />
/// instances are considered equal.</summary>
/// <returns>true if objA is the same instance as objB or
/// if both are null
/// references or if objA.Equals(objB) returns true;
/// otherwise, false.</returns>
/// <param name="objB">The second <see cref="T:System.Object" />
/// to compare. </param>
/// <param name="objA">The first <see cref="T:System.Object" />
/// to compare. </param>
/// <filterpriority>2</filterpriority>
public static bool Equals(object objA, object objB);
}
}
```
|
Just a guess: the All vs Common tabs in intellisense?
|
281,359 |
<p>I am binding a TreeView to an XMLDataSource, the databindings are being generated automatically and the XML looks like this:-</p>
<pre><code><Passengers>
<Passenger>
<PassengerName>Name1</PassengerName>
</Passenger>
<Passenger>
<PassengerName>Name2</PassengerName>
</Passenger>
<Passenger>
<PassengerName>Name3</PassengerName>
</Passenger>
</Passengers>
</code></pre>
<p>The TreeView displays the XML correctly but when I click on a node and the SelectedNodeChanged event fires the SelectedNode.DataPath is always the path to the first passenger in the list no matter which passenger node i click on.</p>
<p>Does anyone know how to get the datapath of the actual node i click on ?</p>
|
[
{
"answer_id": 281457,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 5,
"selected": true,
"text": "<p>Just a guess: the All vs Common tabs in intellisense?</p>\n"
},
{
"answer_id": 409009,
"author": "Øyvind Skaar",
"author_id": 49194,
"author_profile": "https://Stackoverflow.com/users/49194",
"pm_score": 3,
"selected": false,
"text": "<p>It is the same as decorating your member with EditorBrowsableAttribute. I would guess values 0,1 and 2 corresponds to Always, Advanced and Never.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281359",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am binding a TreeView to an XMLDataSource, the databindings are being generated automatically and the XML looks like this:-
```
<Passengers>
<Passenger>
<PassengerName>Name1</PassengerName>
</Passenger>
<Passenger>
<PassengerName>Name2</PassengerName>
</Passenger>
<Passenger>
<PassengerName>Name3</PassengerName>
</Passenger>
</Passengers>
```
The TreeView displays the XML correctly but when I click on a node and the SelectedNodeChanged event fires the SelectedNode.DataPath is always the path to the first passenger in the list no matter which passenger node i click on.
Does anyone know how to get the datapath of the actual node i click on ?
|
Just a guess: the All vs Common tabs in intellisense?
|
281,362 |
<p>I'm building a class that automatically loads a DB record, looks at each DB column name, and fills the associated textbox/label/literal/etc, if it has the same name. I got this idea from Rails, in case that helps clarify what I'm trying to do.</p>
<pre><code>public string presentData(Page thisForm)
{
// .. for each column name
// ... thisForm.FindControl() happens
}
</code></pre>
<p>I can't seem to find the Control I want this way, and there could quite possibly be a better way to do this.</p>
<p>Edit: If I can save on performance by doing it another way, definitely suggest it. I have large forms, and a recursive FindControl would cause a growth in performance time.</p>
|
[
{
"answer_id": 281376,
"author": "Erik Hesselink",
"author_id": 8071,
"author_profile": "https://Stackoverflow.com/users/8071",
"pm_score": 3,
"selected": true,
"text": "<p>FindControl is not recursive, so it only finds top level controls, not controls that are nested within other controls. See <a href=\"https://blog.codinghorror.com/recursive-pagefindcontrol/\" rel=\"nofollow noreferrer\">this article</a> for an example of a recursive version of FindControl.</p>\n"
},
{
"answer_id": 281449,
"author": "Dan Powley",
"author_id": 2761,
"author_profile": "https://Stackoverflow.com/users/2761",
"pm_score": 0,
"selected": false,
"text": "<p>Have you thought about filling your controls client side? JQuery might be a good place to start. You'd generate the Javascript/JQuery to do the populating on the server, then JQuery takes care of searching for the controls. Very efficient.</p>\n"
},
{
"answer_id": 281501,
"author": "John Chuckran",
"author_id": 25511,
"author_profile": "https://Stackoverflow.com/users/25511",
"pm_score": 1,
"selected": false,
"text": "<p>My suggestion is to use a BindingSource bound to a DataSet instead of recursively finding each control and setting its value.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/baya8sx4.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/baya8sx4.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/801dxw2t.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/801dxw2t.aspx</a></p>\n\n<p><a href=\"http://www.codeproject.com/KB/grid/BindSourceBindingNavCS.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/grid/BindSourceBindingNavCS.aspx</a></p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/fbk67b6z(VS.80).aspx?ppud=4\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/fbk67b6z(VS.80).aspx?ppud=4</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281362",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25538/"
] |
I'm building a class that automatically loads a DB record, looks at each DB column name, and fills the associated textbox/label/literal/etc, if it has the same name. I got this idea from Rails, in case that helps clarify what I'm trying to do.
```
public string presentData(Page thisForm)
{
// .. for each column name
// ... thisForm.FindControl() happens
}
```
I can't seem to find the Control I want this way, and there could quite possibly be a better way to do this.
Edit: If I can save on performance by doing it another way, definitely suggest it. I have large forms, and a recursive FindControl would cause a growth in performance time.
|
FindControl is not recursive, so it only finds top level controls, not controls that are nested within other controls. See [this article](https://blog.codinghorror.com/recursive-pagefindcontrol/) for an example of a recursive version of FindControl.
|
281,365 |
<p>If I have the following code,</p>
<pre><code>Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
</code></pre>
<p>Did I create a memory leak?
I guess so, but the word <em>erase</em> gives the feeling that it is deleting it. </p>
<p>Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?</p>
|
[
{
"answer_id": 281385,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": true,
"text": "<p>Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.</p>\n\n<p>It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared_ptr:</p>\n\n<pre><code>{ \n boost::shared_ptr<foo> f(new foo);\n\n std::vector< boost::shared_ptr<foo> > v;\n v.push_back(f);\n v.erase(v.begin());\n} /* if the last copy of foo goes out of scope, the memory is automatically freed */\n</code></pre>\n\n<p>The next C++ standard (called C++1x and C++0x commonly) will include <code>std::shared_ptr</code>. There, you will also be able to use <code>std::unique_ptr<T></code> which is faster, as it doesn't allow copying. Using <code>std::unique_ptr</code> with containers in c++0x is similar to the <code>ptr_container</code> library in boost.</p>\n"
},
{
"answer_id": 281412,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 1,
"selected": false,
"text": "<p>It is definitely not a mistake to point a pointer into a standard container (it's a mistake to make a container of auto_ptr's however). Yes, you do need to explicitly delete to free the memory pointed to by the individual elements, or you can use one of the boost <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/smart_ptr.htm\" rel=\"nofollow noreferrer\">smart pointers</a>.</p>\n"
},
{
"answer_id": 281414,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 2,
"selected": false,
"text": "<p>Another option is to use the Boost <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html\" rel=\"nofollow noreferrer\">Pointer Containers</a>. They are designed to do exactly what you want.</p>\n"
},
{
"answer_id": 281423,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 2,
"selected": false,
"text": "<p>Alternatively there is the boost::ptr_vector <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/ptr_container/doc/ptr_container.html\" rel=\"nofollow noreferrer\">container</a>.</p>\n\n<p>It knows it is holding pointers that it owns and thus auto deletes them.</p>\n\n<p>As a nice side affect, when accessing elements it returns a reference to the object not the pointer to make the code look nice.</p>\n\n<pre><code>Foo *f = new Foo();\nboost::ptr_vector<Foo> vect;\nvect.push_back(f);\n// do stuff\nvect.erase(f);\n</code></pre>\n"
},
{
"answer_id": 281536,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 1,
"selected": false,
"text": "<p>vector deletes the data it contains. Since your vector contains pointers, it only deletes the pointers, not the data they may or may not point to.</p>\n\n<p>It's a pretty general rule in C++ that memory is released where it was allocated. The vector did not allocate whatever your pointers point to, so it must not release it.</p>\n\n<p>You probably shouldn't store pointers in your vector in the first place.\nIn many cases, you would be better off with something like this:</p>\n\n<pre><code>vector<Foo> vect;\nvect.push_back(Foo());\n// do stuff\nvect.erase(f);\n</code></pre>\n\n<p>Of course this assumes that Foo is copyable, and that its copy constructor is not too expensive, but it avoids memory leaks, and you don't have to remember to delete the Foo object. Another approach would be to use smart pointers (such as Boost's shared_ptr), but you may not need pointer semantics at all, in which case the simple solution is the best one.</p>\n"
},
{
"answer_id": 281930,
"author": "David Rodríguez - dribeas",
"author_id": 36565,
"author_profile": "https://Stackoverflow.com/users/36565",
"pm_score": 1,
"selected": false,
"text": "<p>STL containers will not free your memory. The best advice is using smart pointers, knowing that std::auto_ptr will not fit inside containers. I would recommend boost::shared_ptr, or if your compiler vendor has support for TR1 extensions (many do) you can use std::tr1::shared_ptr.</p>\n\n<p>Also note that the vector will not even free the internal memory reserved for the pointer. std::vectors never downsize not even with a call to clear(). If you need to downsize a vector you will have to resort to creating another vector and swapping contents.</p>\n"
},
{
"answer_id": 283472,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>To clarify why the pointer is not deleted, consider</p>\n\n<pre><code>std::vector<char const*> strings;\nstrings.push_back(\"hello\");\nstrings.push_back(\"world\");\n// .erase should not call delete, pointers are to literals\n\nstd::vector<int*> arrays;\nstrings.push_back(new int[10]);\nstrings.push_back(new int[20]);\n// .erase should call delete[] instead of delete\n\nstd::vector<unsigned char*> raw;\nstrings.push_back(malloc(1000));\nstrings.push_back(malloc(2000));\n// .erase should call free() instead of delete\n</code></pre>\n\n<p>In general, <code>vector<T*>::erase</code> cannot guess how you'd dispose of a <code>T*</code>.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281365",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20986/"
] |
If I have the following code,
```
Foo *f = new Foo();
vector<Foo*> vect;
vect.push_back(f);
// do stuff
vect.erase(f);
```
Did I create a memory leak?
I guess so, but the word *erase* gives the feeling that it is deleting it.
Writing this, I am wondering if it is not a mistake to put a pointer in a STL vector. What do you think?
|
Yes, you created a memory leak by that. std::vector and other containers will just remove the pointer, they won't free the memory the pointer points to.
It's not unusual to put a pointer into a standard library container. The problem, however, is that you have to keep track of deleting it when removing it from the container. A better, yet simple, way to do the above, is to use boost::shared\_ptr:
```
{
boost::shared_ptr<foo> f(new foo);
std::vector< boost::shared_ptr<foo> > v;
v.push_back(f);
v.erase(v.begin());
} /* if the last copy of foo goes out of scope, the memory is automatically freed */
```
The next C++ standard (called C++1x and C++0x commonly) will include `std::shared_ptr`. There, you will also be able to use `std::unique_ptr<T>` which is faster, as it doesn't allow copying. Using `std::unique_ptr` with containers in c++0x is similar to the `ptr_container` library in boost.
|
281,373 |
<p>I am looking for a query that will work on Sharepoint 2003 to show me all the documents created/touched by a given userID.</p>
<p>I have found tables with the documents (Docs) and tables for users (UserInfo, UserData)
but the relationship between seems a bit odd - there are 99,000 records in our userdata table, and 12,000 records in userinfo - we have 400 users!</p>
<p>I suppose I was expecting a simple 1 to many relationship with a user table having 400 records and joining that to the documents table, but I see thats not the case.</p>
<p>Any help would be appreciated.</p>
<p>Edit:
Thanks Bjorn,
I have translated that query back to the Sharepoint 2003 structure:</p>
<pre><code>select
d.* from
userinfo u join userdata d
on u.tp_siteid = d.tp_siteid
and
u.tp_id = d.tp_author
where
u.tp_login = 'userid'
and
d.tp_iscurrent = 1
</code></pre>
<p>This gets me a list of siteid/listid/tp_id's I'll have to see if I can trace those back to a filename / path.
All: any additional help is still appreciated!</p>
|
[
{
"answer_id": 283290,
"author": "Bjørn Stærk",
"author_id": 36164,
"author_profile": "https://Stackoverflow.com/users/36164",
"pm_score": 2,
"selected": true,
"text": "<p>I've never looked at the database in SharePoint 2003, but in 2007 UserInfo is connected to Sites, which means that every user has a row in UserInfo for each site collection (or the equivalent 2003 concept). So to identify what a user does you need both the site id and the user's id within that site. In 2007, I would begin with something like this: </p>\n\n<pre><code>select d.* from userinfo u \njoin alluserdata d on u.tp_siteid = d.tp_siteid \nand u.tp_id = d.tp_author \nwhere u.tp_login = '[username]'\nand d.tp_iscurrentversion = 1\n</code></pre>\n\n<p>Update: As others write here, it is not recommended to go directly into the SharePoint database, but I would say use your head and be careful. Updates are an all-caps no-no, but selects depends on the context.</p>\n"
},
{
"answer_id": 311431,
"author": "Kasper",
"author_id": 23499,
"author_profile": "https://Stackoverflow.com/users/23499",
"pm_score": 1,
"selected": false,
"text": "<p>If you are going to use that query in Sharepoint you should know that creating views on the content database or quering directly against the database seems to be a big No-No. A workaround could be some custom code that iterates through the object model and writes the results to your own database. This could either be timer based or based on an eventtrigger.</p>\n"
},
{
"answer_id": 311448,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>DO NOT QUERY THE SHAREPOINT DATABASE DIRECTLY!</p>\n\n<p>I wonder if I made that clear enough? :)</p>\n\n<p>You really need to look at the object model available in C#, you will need to get an SPSite instance for a SiteCollection, and then iterate over the SPList instances that belong to the SPSite and the SPWeb objects.</p>\n\n<p>Once you have the SPList object, you will need to call GetListItems using a query that filters for the user you want.</p>\n\n<p>That is the supported way of doing what you want.</p>\n\n<p>You should never go to the database directly as SharePoint isn't designed for that at all and there is no guarantee (actually, there's a specific warning) that the structure of the database will be the same between versions and upgrades, and additionally when content is spread over several content databases in a farm there is no guarantee that a query that runs on one content database will do what you expect on another content database.</p>\n\n<p>When you look at the object model for iteration, also note that you will need to dispose() the SPSite and SPWeb objects that you create.</p>\n\n<p>Oh, and yes you may have 400 users, but I would bet that you have 30 sites. The information is repeated in the database per site... 30 x 400 = 12,000 entries in the database.</p>\n"
},
{
"answer_id": 1167018,
"author": "Mark Mascolino",
"author_id": 65164,
"author_profile": "https://Stackoverflow.com/users/65164",
"pm_score": 0,
"selected": false,
"text": "<p>You really shouldn't be doing SELECTs with Locks either i.e. adding WITH (NOLOCK) to your queries. Some parts of the system are very timeout sensitive and if you start introducing locks that the system wasn't expecting you can see the system freak out.</p>\n\n<p>But really, you should be doing this via the object model. Mess around with something like IronPython and experimentations with the OM are almost downright pleasant.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281373",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33186/"
] |
I am looking for a query that will work on Sharepoint 2003 to show me all the documents created/touched by a given userID.
I have found tables with the documents (Docs) and tables for users (UserInfo, UserData)
but the relationship between seems a bit odd - there are 99,000 records in our userdata table, and 12,000 records in userinfo - we have 400 users!
I suppose I was expecting a simple 1 to many relationship with a user table having 400 records and joining that to the documents table, but I see thats not the case.
Any help would be appreciated.
Edit:
Thanks Bjorn,
I have translated that query back to the Sharepoint 2003 structure:
```
select
d.* from
userinfo u join userdata d
on u.tp_siteid = d.tp_siteid
and
u.tp_id = d.tp_author
where
u.tp_login = 'userid'
and
d.tp_iscurrent = 1
```
This gets me a list of siteid/listid/tp\_id's I'll have to see if I can trace those back to a filename / path.
All: any additional help is still appreciated!
|
I've never looked at the database in SharePoint 2003, but in 2007 UserInfo is connected to Sites, which means that every user has a row in UserInfo for each site collection (or the equivalent 2003 concept). So to identify what a user does you need both the site id and the user's id within that site. In 2007, I would begin with something like this:
```
select d.* from userinfo u
join alluserdata d on u.tp_siteid = d.tp_siteid
and u.tp_id = d.tp_author
where u.tp_login = '[username]'
and d.tp_iscurrentversion = 1
```
Update: As others write here, it is not recommended to go directly into the SharePoint database, but I would say use your head and be careful. Updates are an all-caps no-no, but selects depends on the context.
|
281,380 |
<p>I am trying to format a date with: </p>
<pre><code><fmt:formatDate value="${newsletter.createdOn}" pattern="MM/dd/yyyy"/>
</code></pre>
<p>newsletter is an object with a <code>createdOn</code> property which is <code>java.util.Date</code>.</p>
<p>When I invoke the previous sentence I get: </p>
<p>According to the TLD, the attribute value does not accept expressions. </p>
<p>I am importing fmt with </p>
<pre><code><%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
</code></pre>
<p>Does anyone know how can I work around this problem?</p>
<p>I am using the jstl.jar coming with tomcat. </p>
<p>Under jstl.jar/META-INF/MANIFEST.MF stays: </p>
<pre><code>Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.3
Created-By: 1.4.2-b28 (Sun Microsystems Inc.)
Specification-Title: JavaServer Pages Standard Tag Library (JSTL)
Specification-Version: 1.1
Implementation-Title: JavaServer Pages Standard Tag Library API Refere
nce Implementation
Implementation-Version: 1.1.0-D13
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: javax.servlet.jsp.jstl
</code></pre>
<p>I am using Apache Tomcat Version 6.0.14</p>
|
[
{
"answer_id": 281406,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 1,
"selected": false,
"text": "<p>Are you sure you're not using the runtime versions of the tag lib? May we see the library import statement?</p>\n\n<p>I think <a href=\"https://stackoverflow.com/questions/281380/format-date-with-fmtformatdate-jsp#281422\">lucus</a> is onto something, according to this <a href=\"http://faq.javaranch.com/java/JstlTagLibDefinitions\" rel=\"nofollow noreferrer\">FAQ</a> on JavaRanch, that's a JSTL 1.0 declaration. You might want to update to 1.1. </p>\n\n<p>What's your environment, app server, and version?</p>\n"
},
{
"answer_id": 281422,
"author": "lucas",
"author_id": 31172,
"author_profile": "https://Stackoverflow.com/users/31172",
"pm_score": 5,
"selected": false,
"text": "<p>Try </p>\n\n<pre><code><%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %>\n</code></pre>\n"
},
{
"answer_id": 281425,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 0,
"selected": false,
"text": "<p>Are you using the <code>fmt-1_0-rt.tld</code> or <code>fmt-1_0.tld</code> taglib.</p>\n\n<p>The difference is the settings for <code>rtexprvalue</code></p>\n\n<p>In one, this is false, in the other it is true.</p>\n"
},
{
"answer_id": 281429,
"author": "Michael Glenn",
"author_id": 9424,
"author_profile": "https://Stackoverflow.com/users/9424",
"pm_score": 1,
"selected": false,
"text": "<p>Are you using JSTL 1.0 or 1.1? formatDate in 1.1 should accept expressions.</p>\n"
},
{
"answer_id": 281550,
"author": "Sergio del Amo",
"author_id": 2138,
"author_profile": "https://Stackoverflow.com/users/2138",
"pm_score": 1,
"selected": false,
"text": "<p>Apparently, i needed 1.1 but i had to change the library import statements for both c and fmt.<br>\nNow it works. Thanks for the help, and sorry for the confusion. </p>\n\n<pre><code><%@ taglib prefix=\"c\" uri=\"http://java.sun.com/jsp/jstl/core\" %>\n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt\" %>\n</code></pre>\n"
},
{
"answer_id": 281568,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://forums.java.net/jive/message.jspa?messageID=209779\" rel=\"noreferrer\">This guy</a> seems to have worked around the problem by extracting the TLD from the jar, modifying it, placing it in the WAR's WEB-INF directory, and adding an entry to his <code>web.xml</code> like this: </p>\n\n<pre><code><jsp-config>\n <taglib>\n <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>\n <taglib-location>/WEB-INF/fmt.tld</taglib-location>\n </taglib>\n</jsp-config>\n</code></pre>\n\n<p>In the end, he switched to the 1.1 declaration:</p>\n\n<pre><code><%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix=\"fmt\"/>\n</code></pre>\n"
},
{
"answer_id": 5088649,
"author": "oli",
"author_id": 629823,
"author_profile": "https://Stackoverflow.com/users/629823",
"pm_score": 1,
"selected": false,
"text": "<p>It just worked for me by adding \"_rt\" to taglib url like this:</p>\n\n<pre><code><%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jsp/jstl/fmt_rt\" %>\n</code></pre>\n\n<p>I found it in <a href=\"http://www.ibm.com/developerworks/java/library/j-jstl0211.html\" rel=\"nofollow\">this article</a></p>\n\n<p>have fun!</p>\n"
},
{
"answer_id": 10426775,
"author": "Gary",
"author_id": 1063158,
"author_profile": "https://Stackoverflow.com/users/1063158",
"pm_score": 2,
"selected": false,
"text": "<p>I encountered the same issue. </p>\n\n<p>I Changed \n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jstl/<strong>fmt</strong>\" %>\nto\n<%@ taglib prefix=\"fmt\" uri=\"http://java.sun.com/jstl/<strong>fmt_rt</strong>\" %>\nand it worked for me!</p>\n"
},
{
"answer_id": 24552697,
"author": "sumit",
"author_id": 3801459,
"author_profile": "https://Stackoverflow.com/users/3801459",
"pm_score": 0,
"selected": false,
"text": "<pre><code><%@ taglib uri=\"http://java.sun.com/jsp/jstl/fmt\" prefix='fmt'%>\n</code></pre>\n\n<p>is working for me.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281380",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
I am trying to format a date with:
```
<fmt:formatDate value="${newsletter.createdOn}" pattern="MM/dd/yyyy"/>
```
newsletter is an object with a `createdOn` property which is `java.util.Date`.
When I invoke the previous sentence I get:
According to the TLD, the attribute value does not accept expressions.
I am importing fmt with
```
<%@ taglib prefix="fmt" uri="http://java.sun.com/jstl/fmt" %>
```
Does anyone know how can I work around this problem?
I am using the jstl.jar coming with tomcat.
Under jstl.jar/META-INF/MANIFEST.MF stays:
```
Manifest-Version: 1.0
Ant-Version: Apache Ant 1.5.3
Created-By: 1.4.2-b28 (Sun Microsystems Inc.)
Specification-Title: JavaServer Pages Standard Tag Library (JSTL)
Specification-Version: 1.1
Implementation-Title: JavaServer Pages Standard Tag Library API Refere
nce Implementation
Implementation-Version: 1.1.0-D13
Implementation-Vendor: Sun Microsystems, Inc.
Implementation-Vendor-Id: com.sun
Extension-Name: javax.servlet.jsp.jstl
```
I am using Apache Tomcat Version 6.0.14
|
Try
```
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
```
|
281,383 |
<p>As the title suggests, I am having trouble maintaining my code on postback. I have a bunch of jQuery code in the Head section and this works fine until a postback occurs after which it ceases to function! </p>
<p>How can I fix this? Does the head not get read on postback, and is there a way in which I can force this to happen? </p>
<p>JavaScript is:</p>
<pre class="lang-html prettyprint-override"><code> <script type="text/javascript">
$(document).ready(function()
{
$('.tablesorter tbody tr').tablesorter();
$('.tablesearch tbody tr').quicksearch({
position: 'before',
attached: 'table.tablesearch',
stripeRowClass: ['odd', 'even'],
labelText: 'Search:',
delay: 100
});
});
</script>
</code></pre>
|
[
{
"answer_id": 281419,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 4,
"selected": true,
"text": "<p>If you just have that code hard coded into your page's head then a post back won't affect it. I would check the following by debugging (FireBug in FireFox is a good debugger):</p>\n\n<ul>\n<li>Verify the script is still in the head on postback.</li>\n<li>verify that the css classes are in fact attached to some element in the page.</li>\n<li>verify that the jquery code is executing after the browser is done loading on post back.</li>\n</ul>\n\n<p>EDIT: Are you using UpdatePanels for your post back? In other words is this an asynchronous postback or a normal full page refresh?</p>\n\n<p>EDIT EDIT: AHhhhh... Ok. So if you're using UpdatePanels then the document's ready state is already in the ready so that portion of jquery code won't be fired again. I would extract the jquery delegate out to a separate function that you can also call after the async postback.</p>\n"
},
{
"answer_id": 281448,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 1,
"selected": false,
"text": "<p>I'm guessing that the postback pre-empts the page's onLoad event, which jQuery needs to hook into to use it's .ready().</p>\n"
},
{
"answer_id": 281463,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li>Does the script exist in the HTML code after the postback?</li>\n<li>If so, does the code get executed? Test by commenting out your code and temporarily add <code>alert('test');</code></li>\n<li>If so, are the elements referenced by the code available on the page after postback? </li>\n</ol>\n"
},
{
"answer_id": 1462882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using $(document).ready you should put your code in a function called pageLoad(). The pageLoad() function is by convention wired up to be called whenever the page has a postback/asyncpostback.</p>\n"
},
{
"answer_id": 1462930,
"author": "Russ Cam",
"author_id": 1831,
"author_profile": "https://Stackoverflow.com/users/1831",
"pm_score": 2,
"selected": false,
"text": "<p>put your code in</p>\n\n<pre><code>function pageLoad(sender, args) {\n\n /* code here */\n\n}\n</code></pre>\n\n<p>instead of in <code>$(document).ready(function() { ... });</code></p>\n\n<p><code>pageLoad()</code> is a function that will execute after all postbacks, synchronous and asynchronous. See this answer for more details</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/1152946/how-to-have-a-javascript-callback-executed-after-an-update-panel-postback/1153002#1153002\"><strong>How to have a javascript callback executed after an update panel postback</strong></a></li>\n</ul>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281383",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35454/"
] |
As the title suggests, I am having trouble maintaining my code on postback. I have a bunch of jQuery code in the Head section and this works fine until a postback occurs after which it ceases to function!
How can I fix this? Does the head not get read on postback, and is there a way in which I can force this to happen?
JavaScript is:
```html
<script type="text/javascript">
$(document).ready(function()
{
$('.tablesorter tbody tr').tablesorter();
$('.tablesearch tbody tr').quicksearch({
position: 'before',
attached: 'table.tablesearch',
stripeRowClass: ['odd', 'even'],
labelText: 'Search:',
delay: 100
});
});
</script>
```
|
If you just have that code hard coded into your page's head then a post back won't affect it. I would check the following by debugging (FireBug in FireFox is a good debugger):
* Verify the script is still in the head on postback.
* verify that the css classes are in fact attached to some element in the page.
* verify that the jquery code is executing after the browser is done loading on post back.
EDIT: Are you using UpdatePanels for your post back? In other words is this an asynchronous postback or a normal full page refresh?
EDIT EDIT: AHhhhh... Ok. So if you're using UpdatePanels then the document's ready state is already in the ready so that portion of jquery code won't be fired again. I would extract the jquery delegate out to a separate function that you can also call after the async postback.
|
281,398 |
<p>I have an existing web app that allows users to "rate" items based on their difficulty. (0 through 15). Currently, I'm simply taking the average of each user's opinion and presenting the average straight from MySQL. However, it's becoming clear to me (and my users) that weighting the numbers would be more appropriate.</p>
<p>Oddly enough, a few hours of Google-ing hasn't turned up much. I did find two articles that showed site-wide ratings systems based off of "Bayesian filters" (which I partially understand). <a href="http://v3.siteframe.org/document.php?id=595" rel="nofollow noreferrer">Here</a>'s one example:</p>
<blockquote>
<p>The formula is:</p>
<p>WR=(V/(V+M)) * R + (M/(V+M)) * C</p>
<p>Where:</p>
<pre><code>* WR=Weighted Rating (The new rating)
* R=Average Rating (arithmetic mean) so far
* V=Number of ratings given
* M=Minimum number of ratings needed
* C=Arithmetic mean rating across the whole site
</code></pre>
</blockquote>
<p>I like the idea here of ramping up the weighting based on the total number of votes per item...however, because the difficulty levels on my site can range drastically from item to item, taking "C" (arithmetic mean rating across the whole site) is not valid. </p>
<p>so, a restate of my question:</p>
<p>Using MySQL, PHP, or both, I'm try to get from aritmetic mean:</p>
<pre><code>(5 + 5 + 4)/3 = 4.67 (rounded)
</code></pre>
<p>...to a weighted mean:</p>
<pre><code>rating / weight
5 / 2 (since it was given 2 times)
5 / 2
4 / 1
(sum[(rate * weight)])/(sum of weights)
(5 * 2) + (5 * 2) + (4 * 1) / (2 + 2 + 1)
(24)/(5)
= 4.8
</code></pre>
|
[
{
"answer_id": 281433,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 4,
"selected": true,
"text": "<p>This is a simple example about how to do it in MySQL directly. You of course would need to add a condition on the subquery to get only the votes for the relevant item instead of all the votes.</p>\n\n<pre>\n\nmysql> create table votes( vote int);\nQuery OK, 0 rows affected (0.01 sec)\n\nmysql> insert into votes values (5),(5),(4);\nQuery OK, 3 row affected (0.00 sec)\nRecords: 3 Duplicates: 0 Warnings: 0\n\nmysql> select * from votes;\n+------+\n| vote |\n+------+\n| 5 |\n| 5 |\n| 4 |\n+------+\n3 rows in set (0.00 sec)\n\nmysql> select vote,count(vote),vote*count(vote) from votes group by vote;\n+------+-------------+------------------+\n| vote | count(vote) | vote*count(vote) |\n+------+-------------+------------------+\n| 4 | 1 | 4 |\n| 5 | 4 | 20 |\n+------+-------------+------------------+\n2 rows in set (0.00 sec)\n\nmysql> select sum(vt)/sum(cnt) FROM (select \ncount(vote)*count(vote) as cnt,vote*count(vote)*count(vote) \nas vt from votes group by vote) a;\n+------------------+\n| sum(vt)/sum(cnt) |\n+------------------+\n| 4.8000 |\n+------------------+\n1 row in set (0.00 sec)\n\n\n</pre>\n"
},
{
"answer_id": 281499,
"author": "Dave DuPlantis",
"author_id": 8174,
"author_profile": "https://Stackoverflow.com/users/8174",
"pm_score": 0,
"selected": false,
"text": "<p>What made it clear that weighting would be more appropriate? What are you seeing in an arithmetic mean that isn't helpful to you? I'm curious because it seems like the answer you are seeking might not necessarily meet your needs the best. (Also, a 16-point scale is typically much larger than what most people need; people rarely differentiate between so many points and tend to cluster their responses around a select group of answers.)</p>\n\n<p>The concept you linked to pulls the mean toward the mean for the site; your mean simply pulls itself toward the most common response. Typically if you use a mean and wish to weight the responses, you would do so based on something about the respondents (putting more weight on responses from more knowledgeable people, people who frequent the site more, or other things like that). </p>\n\n<p>You might also consider using calculations other than mean scores, maybe a top-N-box percentage (percentage of respondents giving the top N difficulty ratings).</p>\n\n<p>Otherwise, the formula for your mean is sum(response * count * count) / sum(count * count) ...</p>\n\n<pre><code>select sum(response*ct*ct)/sum(ct*ct) from\n( select response, count(response) as ct from your_table group by response) data\n</code></pre>\n\n<p>Apologies if the syntax isn't exact, I don't have MySQL at work.</p>\n\n<p>Note that you may have to convert the sums from ints to floats; not sure exactly how that works in MySQL. In SQL Server, you have to cast one of the sums so it understands you don't want an integral mean.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24708/"
] |
I have an existing web app that allows users to "rate" items based on their difficulty. (0 through 15). Currently, I'm simply taking the average of each user's opinion and presenting the average straight from MySQL. However, it's becoming clear to me (and my users) that weighting the numbers would be more appropriate.
Oddly enough, a few hours of Google-ing hasn't turned up much. I did find two articles that showed site-wide ratings systems based off of "Bayesian filters" (which I partially understand). [Here](http://v3.siteframe.org/document.php?id=595)'s one example:
>
> The formula is:
>
>
> WR=(V/(V+M)) \* R + (M/(V+M)) \* C
>
>
> Where:
>
>
>
> ```
> * WR=Weighted Rating (The new rating)
> * R=Average Rating (arithmetic mean) so far
> * V=Number of ratings given
> * M=Minimum number of ratings needed
> * C=Arithmetic mean rating across the whole site
>
> ```
>
>
I like the idea here of ramping up the weighting based on the total number of votes per item...however, because the difficulty levels on my site can range drastically from item to item, taking "C" (arithmetic mean rating across the whole site) is not valid.
so, a restate of my question:
Using MySQL, PHP, or both, I'm try to get from aritmetic mean:
```
(5 + 5 + 4)/3 = 4.67 (rounded)
```
...to a weighted mean:
```
rating / weight
5 / 2 (since it was given 2 times)
5 / 2
4 / 1
(sum[(rate * weight)])/(sum of weights)
(5 * 2) + (5 * 2) + (4 * 1) / (2 + 2 + 1)
(24)/(5)
= 4.8
```
|
This is a simple example about how to do it in MySQL directly. You of course would need to add a condition on the subquery to get only the votes for the relevant item instead of all the votes.
```
mysql> create table votes( vote int);
Query OK, 0 rows affected (0.01 sec)
mysql> insert into votes values (5),(5),(4);
Query OK, 3 row affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> select * from votes;
+------+
| vote |
+------+
| 5 |
| 5 |
| 4 |
+------+
3 rows in set (0.00 sec)
mysql> select vote,count(vote),vote*count(vote) from votes group by vote;
+------+-------------+------------------+
| vote | count(vote) | vote*count(vote) |
+------+-------------+------------------+
| 4 | 1 | 4 |
| 5 | 4 | 20 |
+------+-------------+------------------+
2 rows in set (0.00 sec)
mysql> select sum(vt)/sum(cnt) FROM (select
count(vote)*count(vote) as cnt,vote*count(vote)*count(vote)
as vt from votes group by vote) a;
+------------------+
| sum(vt)/sum(cnt) |
+------------------+
| 4.8000 |
+------------------+
1 row in set (0.00 sec)
```
|
281,440 |
<pre>
create table person
(
name varchar(15),
attr1 varchar(15),
attr2 varchar(1),
attr3 char(1),
attr4 int
)
</pre>
<p>How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects? Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:</p>
<pre><code>@myResults = findAll(attr1 == 3 && attr2 =~ /abc/);
</code></pre>
|
[
{
"answer_id": 281459,
"author": "Dave Rolsky",
"author_id": 9832,
"author_profile": "https://Stackoverflow.com/users/9832",
"pm_score": 6,
"selected": true,
"text": "<p>Rule #1, don't write your own.</p>\n\n<p>There are quite a number of ORMs on CPAN, including ...</p>\n\n<ul>\n<li><a href=\"http://search.cpan.org/dist/DBIx-Class\" rel=\"noreferrer\">DBIx::Class</a> - probably #1 in popularity at the moment</li>\n<li><a href=\"http://search.cpan.org/dist/Rose-DB-Object\" rel=\"noreferrer\">Rose::DB::Object</a></li>\n<li><a href=\"http://search.cpan.org/dist/Fey-ORM\" rel=\"noreferrer\">Fey::ORM</a> - my own contribution, most notable for being <a href=\"http://moose.perl.org/\" rel=\"noreferrer\">Moose</a>-based, which means you get all the power of Moose in your ORM-based classes.</li>\n</ul>\n"
},
{
"answer_id": 664850,
"author": "Yann",
"author_id": 74011,
"author_profile": "https://Stackoverflow.com/users/74011",
"pm_score": 0,
"selected": false,
"text": "<p>(Chiming late) Data::ObjectDriver (also on CPAN) provides great flexibility especially if partitioning and caching is on the list of your requirements.</p>\n"
},
{
"answer_id": 665195,
"author": "singingfish",
"author_id": 36499,
"author_profile": "https://Stackoverflow.com/users/36499",
"pm_score": 0,
"selected": false,
"text": "<p>Of the suggestions I'd use DBIx::Class. Here's some code to introspect a 50 table legacy database (with relationships specified in the schema):</p>\n\n<pre><code>#!/usr/bin/perl\nuse warnings;\nuse strict;\nuse DBIx::Class::Schema::Loader qw/ make_schema_at /;\n\nmake_schema_at(\"Zotero::Schema\",\n {\n # components => ['InflateColumn::DateTime'],\n debug => 1,\n relationships => 1,\n dump_directory => './lib' ,\n },\n [\"dbi:SQLite:dbname=../zotero.sqlite\", \"\",\"\"]);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281440",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
```
create table person
(
name varchar(15),
attr1 varchar(15),
attr2 varchar(1),
attr3 char(1),
attr4 int
)
```
How I can use basic ORM in Perl by taking a simple table like the one above and mapping it to Perl objects? Next I'd like to perform basic operations like select results using some criteria system Perl like syntax. eg.:
```
@myResults = findAll(attr1 == 3 && attr2 =~ /abc/);
```
|
Rule #1, don't write your own.
There are quite a number of ORMs on CPAN, including ...
* [DBIx::Class](http://search.cpan.org/dist/DBIx-Class) - probably #1 in popularity at the moment
* [Rose::DB::Object](http://search.cpan.org/dist/Rose-DB-Object)
* [Fey::ORM](http://search.cpan.org/dist/Fey-ORM) - my own contribution, most notable for being [Moose](http://moose.perl.org/)-based, which means you get all the power of Moose in your ORM-based classes.
|
281,443 |
<p>The following source code alerts the following results:</p>
<p><strong>Internet Explorer 7</strong>: 29<br>
<strong>Firefox 3.0.3</strong>: 37 (correct)<br>
<strong>Safari 3.0.4 (523.12.9)</strong>: 38<br>
<strong>Google Chrome 0.3.154.9</strong>: 38 </p>
<p>Please ignore the following facts: </p>
<ul>
<li>Webkit (Safari/Chrome) browsers insert an extra text node at the end of the body tag</li>
<li>Internet Explorer doesn't have new lines in their whitespace nodes, like they should.</li>
<li>Internet Explorer has no beginning whitespace node (there is obvious whitespace before the <form> tag, but no text node to match)
</ul>
<p>Of the tags in the test page, the following tags have no whitespace text nodes inserted in the DOM after them: <code>form</code>, <code>input[@radio]</code>, <code>div</code>, <code>span</code>, <code>table</code>, <code>ul</code>, <code>a</code>.</p>
<p>My question is: <strong>What is it about these nodes that makes them the exception in Internet Explorer?</strong> Why is whitespace not inserted after these nodes, and is inserted in the others? </p>
<p>This behavior is the same if you switch the tag order, switch the doctype to XHTML (while still maintaining standards mode).</p>
<p>Here's a <a href="http://www.howtocreate.co.uk/wrongWithIE/?chapter=Empty+Space" rel="noreferrer">link that gives a little background information</a>, but no ideal solution. There might not be a solution to this problem, I'm just curious about the behavior.</p>
<p>Thanks Internet,
Zach</p>
<pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function countNodes()
{
alert(document.getElementsByTagName('body')[0].childNodes.length);
}
</script>
</head>
<body onload="countNodes()">
<form></form>
<input type="submit"/>
<input type="reset"/>
<input type="button"/>
<input type="text"/>
<input type="password"/>
<input type="file"/>
<input type="hidden"/>
<input type="checkbox"/>
<input type="radio"/>
<button></button>
<select></select>
<textarea></textarea>
<div></div>
<span></span>
<table></table>
<ul></ul>
<a></a>
</body>
</html>
</code></pre>
|
[
{
"answer_id": 281493,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 0,
"selected": false,
"text": "<p>Well... I'd say the reason it that it is IE. I don't think the programers had a specific intention to do it that way.</p>\n"
},
{
"answer_id": 281592,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 0,
"selected": false,
"text": "<p>I'm guessing that the <strong>table</strong> tag is different between browsers.</p>\n\n<p>e.g. which nodes does the default table auto-magically contain?</p>\n\n<pre><code><table>\n <thead>\n </thead>\n <tbody>\n </tbody>\n <tfoot>\n </tfoot>\n</table>\n</code></pre>\n"
},
{
"answer_id": 289083,
"author": "Ishmael",
"author_id": 8930,
"author_profile": "https://Stackoverflow.com/users/8930",
"pm_score": 0,
"selected": false,
"text": "<p>Why not just try walking the DOM and see what each browser thinks that the document contains? </p>\n\n<p>IE does a lot of \"optimization\" of the DOM. To get an impression of what this might look like, \"Select all\", \"Copy\" in IE, and then \"Paste Alternate\" in Visual Studio, You get the following:</p>\n\n<pre><code><INPUT value=\"Submit Query\" type=submit> \n<INPUT value=Reset type=reset> \n<INPUT type=button> \n<INPUT type=text> \n<INPUT value=\"\" type=password> \n<INPUT type=file> \n<INPUT type=hidden>\n<INPUT type=checkbox>\n<INPUT type=radio>\n<BUTTON type=submit></BUTTON> \n<SELECT></SELECT>\n<TEXTAREA></TEXTAREA> \n</code></pre>\n\n<p>So it nukes some of the empty tags and adds some default attributes.</p>\n"
},
{
"answer_id": 311923,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": true,
"text": "<p>IE tries to be helpful and hides text nodes that contain only whitespace.</p>\n\n<p>In the following:</p>\n\n<pre><code><p>\n<input>\n</p>\n</code></pre>\n\n<p>W3C DOM spec says that <code><p></code> has 3 child nodes (\"\\n\", <code><input></code> and \"\\n\"), IE will pretend there's only one.</p>\n\n<p>The solution is to skip <a href=\"https://developer.mozilla.org/en/DOM/element.nodeType\" rel=\"noreferrer\">text nodes</a> in all browsers:</p>\n\n<pre><code>var node = element.firstChild;\nwhile(node && node.nodeType == 3) node = node.nextSibling;\n</code></pre>\n\n<p>Popular JS frameworks have functions for such things.</p>\n"
},
{
"answer_id": 16311209,
"author": "kaimagpie",
"author_id": 2113751,
"author_profile": "https://Stackoverflow.com/users/2113751",
"pm_score": 0,
"selected": false,
"text": "<p>Zachleat, I think I've found a solution to the problem. (I've taken liberty of moving the form elements into the form tag.)</p>\n\n<pre><code><!DOCTYPE html PUBLIC \"-//W3C//DTD HTML 4.01//EN\" \"http://www.w3.org/TR/html4/strict.dtd\">\n<!--REF http://stackoverflow.com/questions/281443/inconsistent-whitespace-text-nodes-in-internet-explorer -->\n<html>\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\">\n<script type=\"text/javascript\">\n function countNodes()\n { alert(document.getElementsByTagName('form')[0].childNodes.length);\n };\n</script>\n</head>\n<body onload=\"countNodes()\">\n <form\n ><input type=\"submit\"/\n ><input type=\"reset\"/\n ><input type=\"button\"/\n ><input type=\"text\"/\n ><input type=\"password\"/\n ><input type=\"file\"/\n ><input type=\"hidden\"/\n ><input type=\"checkbox\"/\n ><input type=\"radio\"/\n ><button></button\n ><select></select\n ><textarea></textarea\n ><div></div\n ><span></span\n ><table></table\n ><ul></ul\n ><a></a\n ></form>\n</body>\n</html>\n</code></pre>\n\n<p>As you can see, I've split & strapped the closing gt (greater-than) brackets so they hug to the next tag, thus ensuring there are no ambiguous whitespaces.</p>\n\n<p>It was a nice surprise that it worked for all (4 desktop) browsers tried so far, all reporting the same number of DOM nodes.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16711/"
] |
The following source code alerts the following results:
**Internet Explorer 7**: 29
**Firefox 3.0.3**: 37 (correct)
**Safari 3.0.4 (523.12.9)**: 38
**Google Chrome 0.3.154.9**: 38
Please ignore the following facts:
* Webkit (Safari/Chrome) browsers insert an extra text node at the end of the body tag
* Internet Explorer doesn't have new lines in their whitespace nodes, like they should.
* Internet Explorer has no beginning whitespace node (there is obvious whitespace before the <form> tag, but no text node to match)
Of the tags in the test page, the following tags have no whitespace text nodes inserted in the DOM after them: `form`, `input[@radio]`, `div`, `span`, `table`, `ul`, `a`.
My question is: **What is it about these nodes that makes them the exception in Internet Explorer?** Why is whitespace not inserted after these nodes, and is inserted in the others?
This behavior is the same if you switch the tag order, switch the doctype to XHTML (while still maintaining standards mode).
Here's a [link that gives a little background information](http://www.howtocreate.co.uk/wrongWithIE/?chapter=Empty+Space), but no ideal solution. There might not be a solution to this problem, I'm just curious about the behavior.
Thanks Internet,
Zach
```
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
function countNodes()
{
alert(document.getElementsByTagName('body')[0].childNodes.length);
}
</script>
</head>
<body onload="countNodes()">
<form></form>
<input type="submit"/>
<input type="reset"/>
<input type="button"/>
<input type="text"/>
<input type="password"/>
<input type="file"/>
<input type="hidden"/>
<input type="checkbox"/>
<input type="radio"/>
<button></button>
<select></select>
<textarea></textarea>
<div></div>
<span></span>
<table></table>
<ul></ul>
<a></a>
</body>
</html>
```
|
IE tries to be helpful and hides text nodes that contain only whitespace.
In the following:
```
<p>
<input>
</p>
```
W3C DOM spec says that `<p>` has 3 child nodes ("\n", `<input>` and "\n"), IE will pretend there's only one.
The solution is to skip [text nodes](https://developer.mozilla.org/en/DOM/element.nodeType) in all browsers:
```
var node = element.firstChild;
while(node && node.nodeType == 3) node = node.nextSibling;
```
Popular JS frameworks have functions for such things.
|
281,456 |
<p>I need to convert several Java classes to C#, but I have faced few problems.</p>
<p>In Java I have following class hierarchy:</p>
<pre><code>public abstract class AbstractObject {
public String getId() {
return id;
}
}
public class ConcreteObject extends AbstractObject {
public void setId(String id) {
this.id= id;
}
}
</code></pre>
<p>There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy.</p>
<p>How to convert this to C# using properties? Is that possible?</p>
|
[
{
"answer_id": 281469,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>When you supply only the <code>get</code> portion of a property in .Net, you are explicitly telling the compiler that this property is read-only. It's a bigger deal than just not providing a <code>set</code>. This is evident in the vb version of the property syntax, where you must also explicitly declare the property is ReadOnly.</p>\n\n<p>What you might be able to do is provide both a getter and a setter, but throw a <code>NotImplementedException</code> in the abstract setter, decorate it with the appropriate attributes and document so that no one uses it unless the setter has been property overridden. Otherwise, you're probably better off keeping these as methods anyway, to avoid a disconnect between Java and .Net versions of the code.</p>\n"
},
{
"answer_id": 281505,
"author": "Ant",
"author_id": 11529,
"author_profile": "https://Stackoverflow.com/users/11529",
"pm_score": 3,
"selected": true,
"text": "<p>I would suggest using method calls as you've already outlined to make sure that the usage of the class is clear to the caller. If you're set on implementing it using properties, then you could do the following (some documentation for the new keyword can be found <a href=\"http://msdn.microsoft.com/en-us/library/6fawty39.aspx\" rel=\"nofollow noreferrer\" title=\"Versioning with the Override and New Keywords (C# Programming Guide)\">here</a>).</p>\n\n<pre><code>public abstract class AbstractObject {\n protected string id;\n public string Id\n {\n get { return id; }\n }\n}\n\npublic class ConcreteObject : AbstractObject\n{\n public new string Id\n {\n get { return base.Id; }\n set { id = value; }\n }\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281456",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22062/"
] |
I need to convert several Java classes to C#, but I have faced few problems.
In Java I have following class hierarchy:
```
public abstract class AbstractObject {
public String getId() {
return id;
}
}
public class ConcreteObject extends AbstractObject {
public void setId(String id) {
this.id= id;
}
}
```
There are implementation of AbstractObject which do not need to have setId() defined, so I cannot move it up in the hierarchy.
How to convert this to C# using properties? Is that possible?
|
I would suggest using method calls as you've already outlined to make sure that the usage of the class is clear to the caller. If you're set on implementing it using properties, then you could do the following (some documentation for the new keyword can be found [here](http://msdn.microsoft.com/en-us/library/6fawty39.aspx "Versioning with the Override and New Keywords (C# Programming Guide)")).
```
public abstract class AbstractObject {
protected string id;
public string Id
{
get { return id; }
}
}
public class ConcreteObject : AbstractObject
{
public new string Id
{
get { return base.Id; }
set { id = value; }
}
}
```
|
281,500 |
<p>I'm trying to connect to an MDF. I've even gone to the lengths of re-installing sql server express entirely (it is now the only flavor of SQL installed on my box, where previously I had 05 dev and express). I've verified that the paths are all correct, and thus far my google-fu hasn't helped.</p>
<p>The Full exception message is: </p>
<blockquote>
<p>Failed to generate a user instance of SQL Server due to a failure in
starting the process for the user instance. The connection will be
closed.</p>
</blockquote>
<p>The Connection string is:</p>
<pre><code><add name= "CustomerEntities"
connectionString="metadata=res://*/Data.CustomerModel.csdl|res://*/Data.CustomerModel.ssdl|res://*/Data.CustomerModel.msl;
provider=System.Data.SqlClient;
provider connection string='Data Source=.\SQLEXPRESS;
AttachDbFilename=\App_Data\CustomerDb.mdf;
Integrated Security=True;
User Instance=True'"
providerName="System.Data.EntityClient" />
</code></pre>
<h3>Additional info:</h3>
<p>Several of the references to this error I've found online do not apply to me. For example, one I've seen is where this error occurs when trying to start the user instance over remote desktop (I'm doing this locally). While another suggests that it has to do with leftover files from an old express installation ... I've looked in the prescribed locations and not found those artifacts. I also tried running <code>sp_configure 'user instances enabled', '1'</code>, but it said that it was already set to 1.</p>
|
[
{
"answer_id": 281530,
"author": "Jimoc",
"author_id": 24079,
"author_profile": "https://Stackoverflow.com/users/24079",
"pm_score": -1,
"selected": false,
"text": "<p>Have you tried to connect to the SQL Server instance by using SQL Management Studio?</p>\n\n<p>If this also doesn't allow you to connect then it could be because the SQL service is not starting correctly.</p>\n\n<p>Verify that the service is running by checking the services in the control panel.</p>\n"
},
{
"answer_id": 281626,
"author": "Joel Martinez",
"author_id": 5416,
"author_profile": "https://Stackoverflow.com/users/5416",
"pm_score": 7,
"selected": true,
"text": "<p>ok, it works now! guess it was a compound problem ... the steps I took to resolve it are as such:</p>\n\n<ol>\n<li>Changed the following property in the connection string (note the subtle difference): <code>AttachDbFilename=|DataDirectory|CustomerDb.mdf;</code></li>\n<li>Deleted the contents of the following directory: <code>c:\\Users\\<user name>\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS</code>. I thought I had looked for this before, but I had actually looked in the <code>Microsoft Sql Server</code> folder. Again, a subtle difference.</li>\n</ol>\n\n<p>Once I did these two things, the connection started working :-D</p>\n"
},
{
"answer_id": 7148232,
"author": "Derrick",
"author_id": 561759,
"author_profile": "https://Stackoverflow.com/users/561759",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to the other solutions here, this one may also be helpful. \nEnsure the Application Pool is running as network service, and not ApplicationPoolIdentity.</p>\n\n<p>This solution was found here: <a href=\"http://blogs.msdn.com/b/webdevelopertips/archive/2010/05/06/tip-106-did-you-know-how-to-create-the-aspnetdb-mdf-file.aspx\" rel=\"nofollow\">http://blogs.msdn.com/b/webdevelopertips/archive/2010/05/06/tip-106-did-you-know-how-to-create-the-aspnetdb-mdf-file.aspx</a></p>\n"
},
{
"answer_id": 10846381,
"author": "Jarnal",
"author_id": 1074889,
"author_profile": "https://Stackoverflow.com/users/1074889",
"pm_score": 0,
"selected": false,
"text": "<p>As noted by others, deleting the contents of directory: c:\\Users\\\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS solved it for me. A note that may help others, on Windows 7, browsing the c:\\users\\username dir from document browser does not show the the AppData folder which threw me off for a while (as I thought I did not have the AppData dir) until I discovered that it does indeed exist (but does not show in the document browser in Windows 7), you just have to type in the full path name to get to it. </p>\n"
},
{
"answer_id": 17092017,
"author": "Hamid Shahid",
"author_id": 94897,
"author_profile": "https://Stackoverflow.com/users/94897",
"pm_score": 0,
"selected": false,
"text": "<p>I started getting this error this morning in a test deployment environment. I was using SQL Server Express 2008 and the error I was getting was</p>\n<p>"Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed."</p>\n<p>Unsure about what caused it, I followed the instructions in this post and in other post about\ndeleting the "C:\\Users\\UserName\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS" directory, but to no avail.</p>\n<p>What did the trick for me was to change the connection string from</p>\n<pre><code>"Data Source=.\\SQLExpress;Initial Catalog=DBFilePath;Integrated Security=SSPI;MultipleActiveResultSets=true"\n</code></pre>\n<p>to</p>\n<pre><code>"Data Source=.\\SQLExpress;Initial Catalog=DBName;Integrated Security=SSPI;MultipleActiveResultSets=true" \n</code></pre>\n"
},
{
"answer_id": 20994845,
"author": "DSH",
"author_id": 3173120,
"author_profile": "https://Stackoverflow.com/users/3173120",
"pm_score": 3,
"selected": false,
"text": "<p>I experienced the same error when i moved the code from one machine to another. i am using VS2010 and SQLEXPRESS 2008 comes along with it.</p>\n\n<p>Trick , deleting all the contents from the following folde \"C:\\Users\\UserName\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS\" worked for me.</p>\n"
},
{
"answer_id": 24864601,
"author": "sohaiby",
"author_id": 1837838,
"author_profile": "https://Stackoverflow.com/users/1837838",
"pm_score": -1,
"selected": false,
"text": "<p>To fix this, please Open the SQL Server Management Studio Express. \nIn the query editor type this text: </p>\n\n<pre><code>sp_configure 'user instances enabled', 1;\n RECONFIGURE\n</code></pre>\n\n<p>Run it.\nThen restart the SQL Server database.</p>\n"
},
{
"answer_id": 34455302,
"author": "Boris Zinchenko",
"author_id": 348158,
"author_profile": "https://Stackoverflow.com/users/348158",
"pm_score": 3,
"selected": false,
"text": "<p>Even despite above answers solved the problem many people, I m still finding these falling short of the essence of the problem. Closest to it is the answer by @sohaiby above. But it wrongly refers to using Management Studio.</p>\n\n<p>The error message on top of this topic tells very clearly that the problem is with generating a user instance. What instance is and how it is used is described here in every detail:\n<a href=\"https://msdn.microsoft.com/en-us/library/ms254504(v=vs.110).aspx\" rel=\"noreferrer\">https://msdn.microsoft.com/en-us/library/ms254504(v=vs.110).aspx</a></p>\n\n<p>Personally, I encountered this problem when switching DB connection from windows authentication mode to SQL Server authentication. I solved it by just modifying a part of connection string to: <strong>\"User Instance=false;\"</strong> instead of \"User Instance=true;\", which worked fine with windows authentication.</p>\n\n<p>After I changed to \"User Instance=false;\" my connection worked fine without any additional manipulations. I cannot insist that it will work or will be suitable in all scenarios. However, I will definitely recommend trying it before other drastic methods described above, such as erasing SQL server work directories.</p>\n"
},
{
"answer_id": 40647738,
"author": "Kishan",
"author_id": 3678016,
"author_profile": "https://Stackoverflow.com/users/3678016",
"pm_score": 0,
"selected": false,
"text": "<p>I phase this problem with my mdf file in windows form application and i do just restart my computer and my problem is solve. </p>\n"
},
{
"answer_id": 60835076,
"author": "Harshil Parekh",
"author_id": 12971448,
"author_profile": "https://Stackoverflow.com/users/12971448",
"pm_score": 0,
"selected": false,
"text": "<p>Just go to web.config file. Change in 'Connection String'=\"....../.../......?.......; User Instance=<strong>True</strong>'\" to \"....../.../......?.......; User Instance=<strong>False</strong>'\"</p>\n\n<p>Yes this may cause some security issues, but for some school/college practical-project(Which was my case) this can run your project.</p>\n\n<p><strong>change from User Instance=True to User Instance=False ,</strong> in <strong>web.config</strong></p>\n"
},
{
"answer_id": 62834503,
"author": "Thamizh",
"author_id": 13116109,
"author_profile": "https://Stackoverflow.com/users/13116109",
"pm_score": 0,
"selected": false,
"text": "<p>I have faced the issue when i was using SqlLocalDB and SqlExpress.\n<strong>Cause of the issue:</strong>\nWhen I connect to localdb from Visual Studio, a LocalDB instance is started for it and runs as our Windows account. But when Web Application, running in IIS as "Network service" or "AppPoolIdentity", is connecting to LocalDB, another LocalDB instance is started for it and is running as "Network service" or "AppPoolIdentity". As a result, even though both Visual Studio and Web Application are using the same LocalDB connection string, they are connecting to different LocalDB instances. Obviously the database created from Visual Studio on our LocalDB instance will not be available in Web Application's LocalDB instance.\n<strong>Solution:</strong>\nSo, here i have list out the solutions for both cases (i.e) SqlExpress and LocalDB\n<strong>If we are using LocalDB as the datasource:</strong></p>\n<ol>\n<li>Set the application pool identity as "Network Service"</li>\n<li>Update the <strong>applicationHost.config</strong> file as to include the below highlighted settings:</li>\n</ol>\n<p><em><processModel identityType="NetworkService" <strong>loadUserProfile="true" setProfileEnvironment="true"</strong> /></em></p>\n<ol start=\"3\">\n<li>Change the SqlLocalDB as shared instance by running the below command in CMD.exe in admin mode\n<em>SqlLocalDB.exe share "MyLocalDB" "MySharedLocalDB"</em></li>\n</ol>\n<p>(Here "MyLocalDB" is my local db instance. You can find the same by executing the following command in CMD.exe in admin mode\n<em>SqlLocalDB.exe</em>)\nThus, my connection string is as follows:\n<add name="DefaultConnection" connectionString="<strong>Data Source=(localdb)\\ .\\MySharedLocalDB</strong>;AttachDbFilename=|DataDirectory|\\aspnet-DemoSite-20200716010415.mdf;Initial Catalog=aspnet-DemoSite-20200716010415;User ID=sa;Password=welcome123;<strong>User Instance=false</strong>"</p>\n<ol start=\"4\">\n<li>Since I host the application in IIS, i make sure that the account <em>"NT AUTHORITY\\NETWORK SERVICE"</em> have read/write access to the application root folder to avoid "Access Denied" exception and enable the account as System admin to access SqlInstance by executing the below SQL query\n<em>exec sp_addsrvrolemember 'NT AUTHORITY\\NETWORK SERVICE', sysadmin</em></li>\n</ol>\n<p><strong>If we are using SqlExpress as the datasource:</strong></p>\n<p>1.Make sure that the connection string has proper value as below:\n<add name="DefaultConnection" connectionString="<strong>Data Source=.\\SQLEXPRESS</strong>;AttachDbFilename=|DataDirectory|\\aspnet-DemoSite-20200716010415.mdf;Initial Catalog=aspnet-DemoSite-20200716010415;User ID=sa;Password=welcome123;User Instance=false"\n2.As highlighted above Jane, delete old files which located in C:\\Users<userName>\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS</p>\n"
},
{
"answer_id": 72172246,
"author": "iamdeed",
"author_id": 13058445,
"author_profile": "https://Stackoverflow.com/users/13058445",
"pm_score": 0,
"selected": false,
"text": "<p>I experienced a similar issue while running on IIS express, asp.net web application c# code that connects to local database .mdf file using SQLEXPRESS engine.\nI also tried to delete old files located in C:\\Users\\AppData\\Local\\Microsoft\\Microsoft SQL Server Data\\SQLEXPRESS this didn't work.\nHowever in visual studio in the applications web site properties on enabling Windows Authentication in properties setting (Enabled), the data Connection to the database worked.</p>\n<p><a href=\"https://i.stack.imgur.com/QLAhK.png\" rel=\"nofollow noreferrer\">Enable Windows Authentication on Visual Studio GUI</a></p>\n<p>for IIS enable Windows Authentication; by performing a server-side configuration with the IIS Manager</p>\n<ol>\n<li>In IIS Manager, select the IIS site under the Sites node of the\nConnections sidebar.</li>\n<li>Double-click Authentication in the IIS area.</li>\n<li>Select Anonymous Authentication. Select Disable in the Actions\nsidebar.</li>\n<li>Select Windows Authentication. Select Enable in the Actions\nsidebar.</li>\n</ol>\n<p>or in your web.config use the below configuration</p>\n<pre><code><system.webServer>\n <security>\n <authentication>\n <anonymousAuthentication enabled="false" />\n <windowsAuthentication enabled="true" />\n </authentication>\n </security>\n</system.webServer>\n</code></pre>\n<p>I use the below configuration for datasource connection to the database</p>\n<pre><code><add name="defaultConn" connectionString="Data Source=.\\SQLEXPRESS;AttachDbFileName=|DataDirectory|\\DB.mdf;Integrated Security=True;User Instance=False;Trusted_Connection=Yes" providerName="System.Data.SqlClient"/>\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5416/"
] |
I'm trying to connect to an MDF. I've even gone to the lengths of re-installing sql server express entirely (it is now the only flavor of SQL installed on my box, where previously I had 05 dev and express). I've verified that the paths are all correct, and thus far my google-fu hasn't helped.
The Full exception message is:
>
> Failed to generate a user instance of SQL Server due to a failure in
> starting the process for the user instance. The connection will be
> closed.
>
>
>
The Connection string is:
```
<add name= "CustomerEntities"
connectionString="metadata=res://*/Data.CustomerModel.csdl|res://*/Data.CustomerModel.ssdl|res://*/Data.CustomerModel.msl;
provider=System.Data.SqlClient;
provider connection string='Data Source=.\SQLEXPRESS;
AttachDbFilename=\App_Data\CustomerDb.mdf;
Integrated Security=True;
User Instance=True'"
providerName="System.Data.EntityClient" />
```
### Additional info:
Several of the references to this error I've found online do not apply to me. For example, one I've seen is where this error occurs when trying to start the user instance over remote desktop (I'm doing this locally). While another suggests that it has to do with leftover files from an old express installation ... I've looked in the prescribed locations and not found those artifacts. I also tried running `sp_configure 'user instances enabled', '1'`, but it said that it was already set to 1.
|
ok, it works now! guess it was a compound problem ... the steps I took to resolve it are as such:
1. Changed the following property in the connection string (note the subtle difference): `AttachDbFilename=|DataDirectory|CustomerDb.mdf;`
2. Deleted the contents of the following directory: `c:\Users\<user name>\AppData\Local\Microsoft\Microsoft SQL Server Data\SQLEXPRESS`. I thought I had looked for this before, but I had actually looked in the `Microsoft Sql Server` folder. Again, a subtle difference.
Once I did these two things, the connection started working :-D
|
281,503 |
<p>I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface.</p>
<p>I have an interface lets call it Account</p>
<pre><code>public interface Account {
public void doStuff();
}
</code></pre>
<p>Now I have two concrete implementors of Account
OverSeasAccount and OverDrawnAccount</p>
<pre><code>public class OverSeasAccount implements Account {
public void doStuff() {
//do overseas type stuff
}
}
</code></pre>
<p>AND</p>
<pre><code>public class OverDrawnAccount implements Account {
public void doStuff() {
//do overDrawn type stuff
}
}
</code></pre>
<p>I have a class called Work with a List</p>
<pre><code>private List<Account> accounts;
</code></pre>
<p>I am looking at discriminator fields but I seem to be only able do this for abstract classes. Is this the case? Any pointers appreciated. Can I use discriminators for interfaces? </p>
|
[
{
"answer_id": 281900,
"author": "Andrea Francia",
"author_id": 36131,
"author_profile": "https://Stackoverflow.com/users/36131",
"pm_score": 1,
"selected": false,
"text": "<p>You can also introduce an abstract class without removing the interface.</p>\n\n<pre><code>// not an entity\npublic interface Account {\n public void doStuff();\n}\n\n@Entity\npublic abstract class BaseAccount {\n public void doStuff();\n}\n\n\n@Entity\npublic class OverSeasAccount extends AbstractAccount {\n public void doStuff() { ... }\n}\n\n@Entity\npublic class OverDrawnAccount extends AbstractAccount {\n public void doStuff() { ... }\n}\n</code></pre>\n"
},
{
"answer_id": 282681,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": true,
"text": "<p>I think that it is possible to to make an interface the supertype of a mapping. You may not be able to use annotations though. Annotations play well with xml config files so you might have to add a hibernate config file to your project with the mappings that you need. But you will be able to keep the annotations for the rest of your project.</p>\n\n<p><a href=\"http://opensource.atlassian.com/projects/hibernate/browse/ANN-9\" rel=\"nofollow noreferrer\">This</a> issue discusses it more. It seems to end with a suggestion as to how to do it with annotations so who knows. I would suggest that xml is still safer for now This <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#inheritance-tableperclass\" rel=\"nofollow noreferrer\">page</a> of the docs explains the xml mapping needed.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281503",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3050/"
] |
I am having trouble creating a mapping when the List type is an interface. It looks like I need to create an abstract class and use the discriminator column is this the case? I would rather not have to as the abstract class will just contain an abstract method and I would rather just keep the interface.
I have an interface lets call it Account
```
public interface Account {
public void doStuff();
}
```
Now I have two concrete implementors of Account
OverSeasAccount and OverDrawnAccount
```
public class OverSeasAccount implements Account {
public void doStuff() {
//do overseas type stuff
}
}
```
AND
```
public class OverDrawnAccount implements Account {
public void doStuff() {
//do overDrawn type stuff
}
}
```
I have a class called Work with a List
```
private List<Account> accounts;
```
I am looking at discriminator fields but I seem to be only able do this for abstract classes. Is this the case? Any pointers appreciated. Can I use discriminators for interfaces?
|
I think that it is possible to to make an interface the supertype of a mapping. You may not be able to use annotations though. Annotations play well with xml config files so you might have to add a hibernate config file to your project with the mappings that you need. But you will be able to keep the annotations for the rest of your project.
[This](http://opensource.atlassian.com/projects/hibernate/browse/ANN-9) issue discusses it more. It seems to end with a suggestion as to how to do it with annotations so who knows. I would suggest that xml is still safer for now This [page](http://www.hibernate.org/hib_docs/v3/reference/en/html_single/#inheritance-tableperclass) of the docs explains the xml mapping needed.
|
281,512 |
<p>I am having issues converting a png to tiff. The conversion goes fine, but the image is huge. I think the issue is that I am not doing the compression correctly? Anyone have any suggestions??</p>
<p>Here is the code sample</p>
<pre><code>public static void test() throws IOException {
// String fileName = "4958813_1";
String fileName = "4848970_1";
String inFileType = ".PNG";
String outFileType = ".TIFF";
ImageIO.scanForPlugins();
File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType);
InputStream fis = new BufferedInputStream(new FileInputStream(
fInputFile));
PNGImageReaderSpi spi = new PNGImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
//Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("TIFF");
//ImageWriter writer = iter.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW");
param.setCompressionQuality(0.5f);
File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType);
ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile);
writer.setOutput(ios);
writer.write(bi);
}
</code></pre>
|
[
{
"answer_id": 281612,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>I don't know Java IO, but generally you want to look at a few things</p>\n\n<ol>\n<li>Can you use JPEG compression instead of LZW?</li>\n<li>See how to set the TIFF strip size -- if small size is what you want, set it to the height of the image.</li>\n</ol>\n\n<p>Edit: Looks like a TiffWriteParam has the following methods</p>\n\n<pre><code>tiffWriteParam.setTilingMode(ImageWriteParam.MODE_EXPLICIT);\ntiffWriteParam.setTiling(imageWidth, imageHeight, 0, 0);\n</code></pre>\n\n<p>set the imageWidth and imageHeight vars to your image's size. The downside is that it will be slower to read out regions of the image.</p>\n"
},
{
"answer_id": 281619,
"author": "Alnitak",
"author_id": 6782,
"author_profile": "https://Stackoverflow.com/users/6782",
"pm_score": 5,
"selected": true,
"text": "<p><code>Writer.getDefaultWriteParam()</code> only creates an <code>ImageWriteParam</code> object, it doesn't link it back to anything else.</p>\n\n<p>I don't see any mechanism in your code for your modified <code>param</code> object to be subsequently used in the <code>ImageWriter</code>.</p>\n\n<p>I believe that instead of:</p>\n\n<pre><code>writer.write(bi);\n</code></pre>\n\n<p>you need to use:</p>\n\n<pre><code>writer.write(null, new IIOImage(bi, null, null), param);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36641/"
] |
I am having issues converting a png to tiff. The conversion goes fine, but the image is huge. I think the issue is that I am not doing the compression correctly? Anyone have any suggestions??
Here is the code sample
```
public static void test() throws IOException {
// String fileName = "4958813_1";
String fileName = "4848970_1";
String inFileType = ".PNG";
String outFileType = ".TIFF";
ImageIO.scanForPlugins();
File fInputFile = new File("I:/HPF/UU/" + fileName + inFileType);
InputStream fis = new BufferedInputStream(new FileInputStream(
fInputFile));
PNGImageReaderSpi spi = new PNGImageReaderSpi();
ImageReader reader = spi.createReaderInstance();
ImageInputStream iis = ImageIO.createImageInputStream(fis);
reader.setInput(iis, true);
BufferedImage bi = reader.read(0);
TIFFImageWriterSpi tiffspi = new TIFFImageWriterSpi();
ImageWriter writer = tiffspi.createWriterInstance();
//Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("TIFF");
//ImageWriter writer = iter.next();
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionType("LZW");
param.setCompressionQuality(0.5f);
File fOutputFile = new File("I:\\HPF\\UU\\" + fileName + outFileType);
ImageOutputStream ios = ImageIO.createImageOutputStream(fOutputFile);
writer.setOutput(ios);
writer.write(bi);
}
```
|
`Writer.getDefaultWriteParam()` only creates an `ImageWriteParam` object, it doesn't link it back to anything else.
I don't see any mechanism in your code for your modified `param` object to be subsequently used in the `ImageWriter`.
I believe that instead of:
```
writer.write(bi);
```
you need to use:
```
writer.write(null, new IIOImage(bi, null, null), param);
```
|
281,526 |
<p>I have a delete statement that's going against one of my core application tables. The delete statement is using the table's primary key but is still taking around 30 seconds. As far as I can tell the execution plan needs to do about 12 checks in other tables where this table is a FK prior to doing the delete. I need help reading and understanding this execution plan to truly know what I can do to fix the slowness. I'm guessing some of the index seeks or clustered index scans need to be tweaked.</p>
<pre>
StmtText
---------------------------------------------
delete from Clean where CleanId = 17526195
(1 row(s) affected)
StmtText
--------
|--Assert(WHERE:(CASE WHEN NOT [Expr1042] IS NULL THEN (0) ELSE CASE WHEN NOT [Expr1043] IS NULL THEN (1) ELSE CASE WHEN NOT [Expr1044] IS NULL THEN (2) ELSE CASE WHEN NOT [Expr1045] IS NULL THEN (3) ELSE CASE WHEN NOT [Expr1046] IS NULL THEN (4) ELSE CA
|--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1053] = [PROBE VALUE]))
|--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1052] = [PROBE VALUE]))
| |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1051] = [PROBE VALUE]))
| | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1050] = [PROBE VALUE]))
| | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1049] = [PROBE VALUE]))
| | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1048] = [PROBE VALUE]))
| | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1047] = [PROBE VALUE]))
| | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1046] = [PROBE VALUE]))
| | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1045] = [PROBE VALUE]))
| | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1044] = [PROBE VALUE]))
| | | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1043] = [PROBE VALUE]))
| | | | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1042] = [PROBE VALUE]))
| | | | | | | | | | | |--Clustered Index Delete(OBJECT:([TcaNetMigrated].[dbo].[Clean].[PK_Clean]), OBJECT:([TcaNetMigrated].[dbo].[Clean].[_IX_Clean_CustomerID_CleanID]), OBJECT:([TcaNetMigrated].[dbo].[Clean].
| | | | | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Breakage].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Breakage].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Cancellation].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Cancellation].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | | | |--Clustered Index Seek(OBJECT:([TcaNetMigrated].[dbo].[CleanEmployee].[PK_CleanEmployee]), SEEK:([TcaNetMigrated].[dbo].[CleanEmployee].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FO
| | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[CleanTransaction].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[CleanTransaction].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Complaint].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Complaint].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Complaint].[IX_Complaint_RedoCleanId]), SEEK:([TcaNetMigrated].[dbo].[Complaint].[RedoCleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[GreatJob].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[GreatJob].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Inspection].[IX_Inspection_CleanId_InspectionId]), SEEK:([TcaNetMigrated].[dbo].[Inspection].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | |--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[FranchiseCall].[PK_FranchiseCalls]), WHERE:([TcaNetMigrated].[dbo].[FranchiseCall].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
| | |--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[IVRLog].[PK_IVRLog]), WHERE:([TcaNetMigrated].[dbo].[IVRLog].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
| |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Lockout].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Lockout].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
|--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[ManualUpdateTime].[PK_ManualUpdateTimes]), WHERE:([TcaNetMigrated].[dbo].[ManualUpdateTime].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
(26 row(s) affected)
</pre>
|
[
{
"answer_id": 281566,
"author": "Charles Bretana",
"author_id": 32632,
"author_profile": "https://Stackoverflow.com/users/32632",
"pm_score": 0,
"selected": false,
"text": "<p>In the execution plan, which step is taking the majority pf the time? Also can you reRun the delete with \"Set Statistics IO ON\" and see which table/index has the highest logica reads against it. These two bits of data will be a helpful hint as to where you need to devote some attention.</p>\n"
},
{
"answer_id": 281569,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure there are no triggers on this table, or on one of the other dependent tables?</p>\n"
},
{
"answer_id": 281570,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 4,
"selected": true,
"text": "<p>Make sure you have indexes on the FKs in the other tables. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281526",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1989/"
] |
I have a delete statement that's going against one of my core application tables. The delete statement is using the table's primary key but is still taking around 30 seconds. As far as I can tell the execution plan needs to do about 12 checks in other tables where this table is a FK prior to doing the delete. I need help reading and understanding this execution plan to truly know what I can do to fix the slowness. I'm guessing some of the index seeks or clustered index scans need to be tweaked.
```
StmtText
---------------------------------------------
delete from Clean where CleanId = 17526195
(1 row(s) affected)
StmtText
--------
|--Assert(WHERE:(CASE WHEN NOT [Expr1042] IS NULL THEN (0) ELSE CASE WHEN NOT [Expr1043] IS NULL THEN (1) ELSE CASE WHEN NOT [Expr1044] IS NULL THEN (2) ELSE CASE WHEN NOT [Expr1045] IS NULL THEN (3) ELSE CASE WHEN NOT [Expr1046] IS NULL THEN (4) ELSE CA
|--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1053] = [PROBE VALUE]))
|--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1052] = [PROBE VALUE]))
| |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1051] = [PROBE VALUE]))
| | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1050] = [PROBE VALUE]))
| | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1049] = [PROBE VALUE]))
| | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1048] = [PROBE VALUE]))
| | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1047] = [PROBE VALUE]))
| | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1046] = [PROBE VALUE]))
| | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1045] = [PROBE VALUE]))
| | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1044] = [PROBE VALUE]))
| | | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1043] = [PROBE VALUE]))
| | | | | | | | | | |--Nested Loops(Left Semi Join, OUTER REFERENCES:([TcaNetMigrated].[dbo].[Clean].[CleanId]), DEFINE:([Expr1042] = [PROBE VALUE]))
| | | | | | | | | | | |--Clustered Index Delete(OBJECT:([TcaNetMigrated].[dbo].[Clean].[PK_Clean]), OBJECT:([TcaNetMigrated].[dbo].[Clean].[_IX_Clean_CustomerID_CleanID]), OBJECT:([TcaNetMigrated].[dbo].[Clean].
| | | | | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Breakage].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Breakage].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Cancellation].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Cancellation].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | | | |--Clustered Index Seek(OBJECT:([TcaNetMigrated].[dbo].[CleanEmployee].[PK_CleanEmployee]), SEEK:([TcaNetMigrated].[dbo].[CleanEmployee].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FO
| | | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[CleanTransaction].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[CleanTransaction].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Complaint].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Complaint].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Complaint].[IX_Complaint_RedoCleanId]), SEEK:([TcaNetMigrated].[dbo].[Complaint].[RedoCleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[GreatJob].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[GreatJob].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | | |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Inspection].[IX_Inspection_CleanId_InspectionId]), SEEK:([TcaNetMigrated].[dbo].[Inspection].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
| | | |--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[FranchiseCall].[PK_FranchiseCalls]), WHERE:([TcaNetMigrated].[dbo].[FranchiseCall].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
| | |--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[IVRLog].[PK_IVRLog]), WHERE:([TcaNetMigrated].[dbo].[IVRLog].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
| |--Index Seek(OBJECT:([TcaNetMigrated].[dbo].[Lockout].[IX_UniqueCleanId]), SEEK:([TcaNetMigrated].[dbo].[Lockout].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]) ORDERED FORWARD)
|--Clustered Index Scan(OBJECT:([TcaNetMigrated].[dbo].[ManualUpdateTime].[PK_ManualUpdateTimes]), WHERE:([TcaNetMigrated].[dbo].[ManualUpdateTime].[CleanId]=[TcaNetMigrated].[dbo].[Clean].[CleanId]))
(26 row(s) affected)
```
|
Make sure you have indexes on the FKs in the other tables.
|
281,531 |
<p>Most of my PHP apps have an ob_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done.</p>
<pre><code>ob_start()
//Business Logic, etc
header->output();
echo apply_post_filter(ob_get_clean());
footer->output();
</code></pre>
<p>This ensures that PHP errors get displayed within the content part of the website, and that errors don't interfere with <code>header</code> and <code>session_*</code> calls.</p>
<p>My only problem is that with some large pages PHP runs out of memory. How do I stop this from happening?</p>
<p>Some ideas:</p>
<ol>
<li>Write all of the buffered content to a temporary file and output that.</li>
<li>When the buffers reaches a certain size, output it. Although this might interfere with the post filter.</li>
<li>Raise the memory limit (thanx @troelskn).</li>
</ol>
<p>Whats the drawbacks on each of these approaches? Especially raising the memory limit?</p>
|
[
{
"answer_id": 281615,
"author": "troelskn",
"author_id": 18180,
"author_profile": "https://Stackoverflow.com/users/18180",
"pm_score": 4,
"selected": true,
"text": "<p>Can't you raise the memory limit? Sounds like the best solution to me.</p>\n\n<p>Edit: Obviously, raising the memory limit just because a script tops out should raise some red flags, but it sounds to me like this is a legitimate case - eg. the script is actually producing rather large chunks of output. As such, you have to store the output <em>somewhere</em>, and memory seems to be the best pick, for both performance and convenience reasons.</p>\n\n<p>I should note also that the memory limit setting is just that - a limit. Scripts that don't consume much memory, won't consume more just because you raise the limit. The main reason for its existence, is to prevent misbehaving/buggy scripts from taking down the entire server. This is something that is important if you have a lot of amateurs hacking away on a shared host (Something PHP has been used a lot for). So if this is your own server, or at least you generally know what you're doing, there isn't really any benefit from having a low memory-limit.</p>\n"
},
{
"answer_id": 281651,
"author": "I GIVE TERRIBLE ADVICE",
"author_id": 35344,
"author_profile": "https://Stackoverflow.com/users/35344",
"pm_score": 2,
"selected": false,
"text": "<p>You should raise the memory limit before anything, especially if your only other solution is to go through a temporary file.</p>\n\n<p>There's all kinds of downsides to using temporary files (mainly, it's slower), and if you really need a way to store the buffer before outputing it, Go look for <a href=\"http://ca3.php.net/manual/en/book.memcache.php\" rel=\"nofollow noreferrer\">memcached</a> or <a href=\"http://ca3.php.net/manual/en/book.apc.php\" rel=\"nofollow noreferrer\">APC cache</a>. This would let you do roughly the same as a file, except you have the fast access of RAM.</p>\n\n<p>I must say this is a terrible idea overall, though. If the buffer currently doesn't work right, there's likely something you could build differently in order to make your site work better.</p>\n"
},
{
"answer_id": 281745,
"author": "okoman",
"author_id": 35903,
"author_profile": "https://Stackoverflow.com/users/35903",
"pm_score": 2,
"selected": false,
"text": "<p>If the php errors are the only reason for buffering output consider using set_error_handler. With this function you can define a custom callback for errors in your script. Use it to save the messages somewhere and print them later.</p>\n\n<p><a href=\"http://www.php.net/set_error_handler\" rel=\"nofollow noreferrer\">http://www.php.net/set_error_handler</a></p>\n"
},
{
"answer_id": 283413,
"author": "J.D. Fitz.Gerald",
"author_id": 11542,
"author_profile": "https://Stackoverflow.com/users/11542",
"pm_score": 1,
"selected": false,
"text": "<p>For you to run out of memory due to output you must have a huge amount of data going out or very low memory limits. 4 or so years ago a memory limit of 8mb was common enough, and reasonable. But with the switch to using objects and just better coding styles in general the memory usage of scripts that I've come across have increased.</p>\n\n<p>Hrm... where is it that your scripts run out of memory? If it's always in your output filtering functions maybe they just need to be optimised? <a href=\"http://www.php.net/memory_get_usage\" rel=\"nofollow noreferrer\">memory_get_usage()</a> will return the amount of memory in use by your script at that point.</p>\n\n<p>What's the current memory limit you're running at? Are you running in a shared environment?\nAt the moment I've got memory limits between 64 and 128 depending on the server. </p>\n\n<p>If it's only a specific subset of scripts you want to increase the limit for then you can do it per script:</p>\n\n<pre><code>ini_set('memory_limit','64M');\n</code></pre>\n\n<p>If you want no limit for the script you can set this to -1</p>\n"
},
{
"answer_id": 15505603,
"author": "Haravikk",
"author_id": 2187548,
"author_profile": "https://Stackoverflow.com/users/2187548",
"pm_score": 2,
"selected": false,
"text": "<p>My recommendation would be to try to load the file in stages, or break it apart into smaller pieces for inclusion. How you do this would heavily depend on what the file is, but it would allow you to load it in say… 2mb chunks, if it doesn't generate any errors then you use <code>ob_flush()</code> to send it before loading the next chunk.</p>\n\n<p>For example, you mention it being a PHP template; I'm not sure what that would be exactly, if you're talking about a mixed PHP/HTML file that when executed produces output, then you could try adding into the template some form of block-marker to separate distinct pieces of the template. This way you only need to read up to the end of the current block, then output it and continue. This gets more difficult if you have looping or such, but there is generally always a way to work around it. For example, by adding PHP to your templates that triggers a method/function in your main script that can handle loop output in stages.</p>\n\n<p>You may also want to look at a mechanism for pre-validating the template before you load it, so you don't need to worry about errors creeping into pages at all.</p>\n\n<p>While changing the memory limit will \"solve\" the problem in the short-term it isn't a long-term solution, as that kind of memory usage is definitely to be avoided if possible. In general you don't want to load anything large into memory at all if you can avoid it, or spit it out at the earliest opportunity, as it means that data is at least on its way to the user which reduces the time to first byte for the page.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281531",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6681/"
] |
Most of my PHP apps have an ob\_start at the beginning, runs through all the code, and then outputs the content, sometimes with some modifications, after everything is done.
```
ob_start()
//Business Logic, etc
header->output();
echo apply_post_filter(ob_get_clean());
footer->output();
```
This ensures that PHP errors get displayed within the content part of the website, and that errors don't interfere with `header` and `session_*` calls.
My only problem is that with some large pages PHP runs out of memory. How do I stop this from happening?
Some ideas:
1. Write all of the buffered content to a temporary file and output that.
2. When the buffers reaches a certain size, output it. Although this might interfere with the post filter.
3. Raise the memory limit (thanx @troelskn).
Whats the drawbacks on each of these approaches? Especially raising the memory limit?
|
Can't you raise the memory limit? Sounds like the best solution to me.
Edit: Obviously, raising the memory limit just because a script tops out should raise some red flags, but it sounds to me like this is a legitimate case - eg. the script is actually producing rather large chunks of output. As such, you have to store the output *somewhere*, and memory seems to be the best pick, for both performance and convenience reasons.
I should note also that the memory limit setting is just that - a limit. Scripts that don't consume much memory, won't consume more just because you raise the limit. The main reason for its existence, is to prevent misbehaving/buggy scripts from taking down the entire server. This is something that is important if you have a lot of amateurs hacking away on a shared host (Something PHP has been used a lot for). So if this is your own server, or at least you generally know what you're doing, there isn't really any benefit from having a low memory-limit.
|
281,534 |
<p>Grasping at straws here... I work with a VB6 desktop system using several 2003-style Access databases (.MDB). Recently, I changed the first function from VB6 to VB.NET, still using an Access database. This is more than a conversion, but a rewrite with additional functionality. It is still fairly simple functionality, with a low-volume database. We have 1400 customers, small businesses with varying machine qualities. Most customers are happy with the new screen and functionality. A very few of those customers have experienced EXTREME slowness loading the datagridview. Customer Service tells us that 1) the machines have at least 1 GB of RAM, and 2) rebooting always solves the problem. </p>
<p>I wrote an app to severely slow down my machine, and it STILL runs better for me than it does for those few customers. Also, my Access database has never been trashed by this application. </p>
<p>Any suggestions?</p>
<p>Thanks!!</p>
|
[
{
"answer_id": 281539,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>No, VB.Net works great with Access. SHARED environments will trash access.</p>\n\n<p>Since rebooting solves the problem I would check that you are closing your connections properly.</p>\n"
},
{
"answer_id": 281546,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": -1,
"selected": false,
"text": "<p>Sounds like a big memory leak to me. </p>\n\n<p>Some customers will leave your application running for longer than others, and will be harder hit.</p>\n\n<p>Using Access where there are more than a few concurrent users inevitably results in pain.</p>\n"
},
{
"answer_id": 281553,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>We have similar experience, the most cases are causes by antivirus. They check the file VERY often ( some antivures every access to file ).</p>\n"
},
{
"answer_id": 281773,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 3,
"selected": true,
"text": "<p>Rebooting while updating an access database can trash it.</p>\n\n<p>You need some more info so that you have a better understanding of what is going on. They need to collect some information for you on a workstation that is having the problem. Using task manager you can have them get the following info:</p>\n\n<ul>\n<li>CPU utilization</li>\n<li>What task is consuming the most cpu</li>\n<li>Peak (committed) memory on XP - no equiv on Vista</li>\n<li>Total (committed) memory on XP - no equiv on Vista</li>\n<li>Available (physical) memory on XP - Free on Vista (made worthless by Superfetch)</li>\n</ul>\n\n<p>It's also possible to use the command line tool \"SYSTEMINFO\" on both XP and Vista to get Total and Available memory. If you have very little available and on XP if your Total committed is larger than your Total Physical then you are most likely swapping and lack of memory (or a memory leak) is causing your slow down.</p>\n\n<p>Bottom line is you need more information. It may be another app on the workstation is causing the problem. We had a situation where Notes 5.0 had a problem where if most of the window is covered up by another window and you received a new mail message the cpu utilization on Notes went to 100%. This caused apps to run slow and unless you are on the workstation looking at task monitor you would never guess it was Notes causing the problem. The problem was always called in on a different program (the one in the foreground). Access can also use 100% cpu in different modes even though it doesn't seem like it's doing anything.</p>\n\n<p>Gather as much info as you can. You might want to write a vbscript or program that will will gather some info for you so that whomever is having the problem can run it to gather the info before rebooting.</p>\n\n<p>A batch file that does the following will give you quite a bit of info:</p>\n\n<pre><code>\n@echo off\nSystemInfo >c:\\systeminfo.log\ntasklist /v >>c:\\systeminfo.log\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12897/"
] |
Grasping at straws here... I work with a VB6 desktop system using several 2003-style Access databases (.MDB). Recently, I changed the first function from VB6 to VB.NET, still using an Access database. This is more than a conversion, but a rewrite with additional functionality. It is still fairly simple functionality, with a low-volume database. We have 1400 customers, small businesses with varying machine qualities. Most customers are happy with the new screen and functionality. A very few of those customers have experienced EXTREME slowness loading the datagridview. Customer Service tells us that 1) the machines have at least 1 GB of RAM, and 2) rebooting always solves the problem.
I wrote an app to severely slow down my machine, and it STILL runs better for me than it does for those few customers. Also, my Access database has never been trashed by this application.
Any suggestions?
Thanks!!
|
Rebooting while updating an access database can trash it.
You need some more info so that you have a better understanding of what is going on. They need to collect some information for you on a workstation that is having the problem. Using task manager you can have them get the following info:
* CPU utilization
* What task is consuming the most cpu
* Peak (committed) memory on XP - no equiv on Vista
* Total (committed) memory on XP - no equiv on Vista
* Available (physical) memory on XP - Free on Vista (made worthless by Superfetch)
It's also possible to use the command line tool "SYSTEMINFO" on both XP and Vista to get Total and Available memory. If you have very little available and on XP if your Total committed is larger than your Total Physical then you are most likely swapping and lack of memory (or a memory leak) is causing your slow down.
Bottom line is you need more information. It may be another app on the workstation is causing the problem. We had a situation where Notes 5.0 had a problem where if most of the window is covered up by another window and you received a new mail message the cpu utilization on Notes went to 100%. This caused apps to run slow and unless you are on the workstation looking at task monitor you would never guess it was Notes causing the problem. The problem was always called in on a different program (the one in the foreground). Access can also use 100% cpu in different modes even though it doesn't seem like it's doing anything.
Gather as much info as you can. You might want to write a vbscript or program that will will gather some info for you so that whomever is having the problem can run it to gather the info before rebooting.
A batch file that does the following will give you quite a bit of info:
```
@echo off
SystemInfo >c:\systeminfo.log
tasklist /v >>c:\systeminfo.log
```
|
281,538 |
<p>Are there major advantages to <a href="https://web.archive.org/web/20090207080811/http://www.innodb.com:80/hot-backup/features/" rel="nofollow noreferrer">InnoDB hot backup</a> vs ZRM <a href="https://www.zmanda.com/zrm-enterprise/" rel="nofollow noreferrer">snapshots</a> in terms of disruption to the running site, the size of compressed backup files, and speed of backup/restore on a medium-sized to largish all-InnoDB database?</p>
<p>My understanding is that InnoDB's approach is more reliable, faster, does not cause a significant outage when running, etc.</p>
|
[
{
"answer_id": 281539,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>No, VB.Net works great with Access. SHARED environments will trash access.</p>\n\n<p>Since rebooting solves the problem I would check that you are closing your connections properly.</p>\n"
},
{
"answer_id": 281546,
"author": "Galwegian",
"author_id": 3201,
"author_profile": "https://Stackoverflow.com/users/3201",
"pm_score": -1,
"selected": false,
"text": "<p>Sounds like a big memory leak to me. </p>\n\n<p>Some customers will leave your application running for longer than others, and will be harder hit.</p>\n\n<p>Using Access where there are more than a few concurrent users inevitably results in pain.</p>\n"
},
{
"answer_id": 281553,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 2,
"selected": false,
"text": "<p>We have similar experience, the most cases are causes by antivirus. They check the file VERY often ( some antivures every access to file ).</p>\n"
},
{
"answer_id": 281773,
"author": "bruceatk",
"author_id": 791,
"author_profile": "https://Stackoverflow.com/users/791",
"pm_score": 3,
"selected": true,
"text": "<p>Rebooting while updating an access database can trash it.</p>\n\n<p>You need some more info so that you have a better understanding of what is going on. They need to collect some information for you on a workstation that is having the problem. Using task manager you can have them get the following info:</p>\n\n<ul>\n<li>CPU utilization</li>\n<li>What task is consuming the most cpu</li>\n<li>Peak (committed) memory on XP - no equiv on Vista</li>\n<li>Total (committed) memory on XP - no equiv on Vista</li>\n<li>Available (physical) memory on XP - Free on Vista (made worthless by Superfetch)</li>\n</ul>\n\n<p>It's also possible to use the command line tool \"SYSTEMINFO\" on both XP and Vista to get Total and Available memory. If you have very little available and on XP if your Total committed is larger than your Total Physical then you are most likely swapping and lack of memory (or a memory leak) is causing your slow down.</p>\n\n<p>Bottom line is you need more information. It may be another app on the workstation is causing the problem. We had a situation where Notes 5.0 had a problem where if most of the window is covered up by another window and you received a new mail message the cpu utilization on Notes went to 100%. This caused apps to run slow and unless you are on the workstation looking at task monitor you would never guess it was Notes causing the problem. The problem was always called in on a different program (the one in the foreground). Access can also use 100% cpu in different modes even though it doesn't seem like it's doing anything.</p>\n\n<p>Gather as much info as you can. You might want to write a vbscript or program that will will gather some info for you so that whomever is having the problem can run it to gather the info before rebooting.</p>\n\n<p>A batch file that does the following will give you quite a bit of info:</p>\n\n<pre><code>\n@echo off\nSystemInfo >c:\\systeminfo.log\ntasklist /v >>c:\\systeminfo.log\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/556/"
] |
Are there major advantages to [InnoDB hot backup](https://web.archive.org/web/20090207080811/http://www.innodb.com:80/hot-backup/features/) vs ZRM [snapshots](https://www.zmanda.com/zrm-enterprise/) in terms of disruption to the running site, the size of compressed backup files, and speed of backup/restore on a medium-sized to largish all-InnoDB database?
My understanding is that InnoDB's approach is more reliable, faster, does not cause a significant outage when running, etc.
|
Rebooting while updating an access database can trash it.
You need some more info so that you have a better understanding of what is going on. They need to collect some information for you on a workstation that is having the problem. Using task manager you can have them get the following info:
* CPU utilization
* What task is consuming the most cpu
* Peak (committed) memory on XP - no equiv on Vista
* Total (committed) memory on XP - no equiv on Vista
* Available (physical) memory on XP - Free on Vista (made worthless by Superfetch)
It's also possible to use the command line tool "SYSTEMINFO" on both XP and Vista to get Total and Available memory. If you have very little available and on XP if your Total committed is larger than your Total Physical then you are most likely swapping and lack of memory (or a memory leak) is causing your slow down.
Bottom line is you need more information. It may be another app on the workstation is causing the problem. We had a situation where Notes 5.0 had a problem where if most of the window is covered up by another window and you received a new mail message the cpu utilization on Notes went to 100%. This caused apps to run slow and unless you are on the workstation looking at task monitor you would never guess it was Notes causing the problem. The problem was always called in on a different program (the one in the foreground). Access can also use 100% cpu in different modes even though it doesn't seem like it's doing anything.
Gather as much info as you can. You might want to write a vbscript or program that will will gather some info for you so that whomever is having the problem can run it to gather the info before rebooting.
A batch file that does the following will give you quite a bit of info:
```
@echo off
SystemInfo >c:\systeminfo.log
tasklist /v >>c:\systeminfo.log
```
|
281,548 |
<p>I have the very same delphi version, bpls, components, everything. And yet in three machines the resulting executables are different in size.
What else can influence in the size of the exe?</p>
<p>In my machine I get this size (Vista 6.0.6001):</p>
<pre><code>4.547.584 bytes
</code></pre>
<p>In my colleague's machine, he gets (XP 5.1.2600 SP3):</p>
<pre><code>4.530.688 bytes
</code></pre>
<p>In a third colleage, he gets: (XP 5.1.2600 SP2)</p>
<pre><code>4.527.104 bytes
</code></pre>
<p>Does the OS version influence in the compiled exe size?</p>
|
[
{
"answer_id": 281577,
"author": "QAZ",
"author_id": 14260,
"author_profile": "https://Stackoverflow.com/users/14260",
"pm_score": 2,
"selected": false,
"text": "<p>With Delphi/BCB these are a few factors that can influence size:</p>\n\n<p><strong>Your Build Configuration</strong>: Release Mode does not link in the debug section into the EXE (by default) so is smaller. also you may get a boost from code optimization.</p>\n\n<p><strong>Linking with Dynamic RTL</strong>: If enabled you EXE will be smaller but you will require the external libraries to be available.</p>\n\n<p><strong>Building with Runtime Packages</strong>: If enabled, you dynamically link to the runtime packages you use instead of linking them directly into your EXE. This can result in the largest size differences.</p>\n\n<p>Their are other factors but the above tends to be the main ones I come across.</p>\n"
},
{
"answer_id": 281723,
"author": "Nick Hodges",
"author_id": 2044,
"author_profile": "https://Stackoverflow.com/users/2044",
"pm_score": 3,
"selected": false,
"text": "<p>The differences almost certainly come from different compiler settings between the machines. For instance, turning Range Checking on or off will slightly alter the resulting size of the executable.</p>\n\n<p>One of the nice things about the more recent versions of Delphi is the use of MSBuild, which can easily ensure that the settings for any given build are the same.</p>\n"
},
{
"answer_id": 281926,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 4,
"selected": true,
"text": "<p>It would seem that it is configuration differences, or if maybe you have different versions of components installed between the three machines. I would suggest creating a blank form and trying it on all 3 after you verify that the build settings are the same. If that is the same then add some 3rd party components until you find the one that is different.</p>\n\n<p>Additionally you may have a different version of Delphi (major or minor/update version). </p>\n"
},
{
"answer_id": 379498,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 1,
"selected": false,
"text": "<p>IIRC, re-compiles after making minor changes may also leave cruft laying around - one fo the side effects of the smart compiler, I guess :}</p>\n"
},
{
"answer_id": 643835,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>Actually it's much more interesting than than. </p>\n\n<p>Even re-building the same application on the same machine, several times in succession, making absolutely NO changes to the configuration whatsoever in between compiles, produces executables of slightly different sizes. I built a particular project 10 times and obtained 10 (!) different executable sizes - a different size every time!</p>\n\n<p>I've noticed that the phenomenon only occurs on projects of sufficient size/complexity, though. </p>\n\n<p>If you do this on a relatively simple project, the executable will be the same size, even though there will still be internal differences (if you do a binary compare). I don't have the time to investigate this right now, but I am mildly curious.</p>\n\n<p>Notice that merely doing a compile, i.e. effectively just re-linking the application, does not change the size of the resulting executable, but it does change its content (binary files generated are not identical).</p>\n"
},
{
"answer_id": 643878,
"author": "Ken White",
"author_id": 62576,
"author_profile": "https://Stackoverflow.com/users/62576",
"pm_score": 1,
"selected": false,
"text": "<p>Actually, it's a issue that's been around for quite some time. See</p>\n\n<p><a href=\"http://qc.codegear.com/wc/qcmain.aspx?d=29538\" rel=\"nofollow noreferrer\">CodeGear Quality Control</a></p>\n\n<p><a href=\"http://groups.google.dk/group/borland.public.delphi.winapi/browse_thread/thread/cd3b52072ea9edc9\" rel=\"nofollow noreferrer\">Borland Delphi newsgroups</a></p>\n\n<p>Recent discussion of this on <a href=\"https://forums.codegear.com/thread.jspa?threadID=13609&tstart=0\" rel=\"nofollow noreferrer\">Delphi newsgroups</a> (http view).</p>\n\n<p>It has absolutely nothing to do with differences in component installs or anything like that; in fact, the last reference mentions something to do with timestamps that are inserted into the application on each compile/build. Also, if you're doing a build and are including version info, and have the build number set to autoincrement, this will cause binary differences as well.</p>\n"
},
{
"answer_id": 973800,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>Hmmm...</p>\n\n<p>SizeOf(XPSP2.exe) < SizeOf(XPSP3.exe) < SizeOf(Vista.exe)</p>\n\n<p>Conclusion:</p>\n\n<p>The later the version of Windows, the more \"filler\" is randomly inserted to add credibility. If it takes more space then it must be more powerful, and it was probably coded by the best engineers in the world! :-) (sorry - I've been working at Microsoft for too long!)</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281548",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19224/"
] |
I have the very same delphi version, bpls, components, everything. And yet in three machines the resulting executables are different in size.
What else can influence in the size of the exe?
In my machine I get this size (Vista 6.0.6001):
```
4.547.584 bytes
```
In my colleague's machine, he gets (XP 5.1.2600 SP3):
```
4.530.688 bytes
```
In a third colleage, he gets: (XP 5.1.2600 SP2)
```
4.527.104 bytes
```
Does the OS version influence in the compiled exe size?
|
It would seem that it is configuration differences, or if maybe you have different versions of components installed between the three machines. I would suggest creating a blank form and trying it on all 3 after you verify that the build settings are the same. If that is the same then add some 3rd party components until you find the one that is different.
Additionally you may have a different version of Delphi (major or minor/update version).
|
281,563 |
<p>I'm currently using AntLR to parse some files with a proprietary language.
I have a need of highlighting sections of it on an editor (think of highlighting a method in a Java class, for instance).</p>
<p>Does anyone has a hint on how to get them?
Say I have this code:</p>
<pre><code>function test(param1, param2) {
}
</code></pre>
<p>as function is a keyword, the first position I get in the parser is the one of the identifier "test". How can I get the positions from there up to the ending curly brace? The parameters list is dynamic, as one would expect, so you don't know in advance its length.</p>
<p>Thank you!</p>
|
[
{
"answer_id": 281571,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 0,
"selected": false,
"text": "<p>Not quite following why the first position you are getting is the position of test. You should easily be able to get the character offset of the \"function\" token if you designed the pattern specification correctly. Can you list the relevant parts of the specification?</p>\n"
},
{
"answer_id": 905885,
"author": "fglez",
"author_id": 33622,
"author_profile": "https://Stackoverflow.com/users/33622",
"pm_score": 2,
"selected": true,
"text": "<p>If I understand your question, I think you can use attribute 'pos' on each token</p>\n\n<pre><code>func: FUNCTION ID '(' ID (',' ID)* ')' {\n System.out.println(\"Position = \" + $FUNCTION.pos);\n}\n</code></pre>\n\n<p>which refers to the character position within the line counting from zero.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281563",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7277/"
] |
I'm currently using AntLR to parse some files with a proprietary language.
I have a need of highlighting sections of it on an editor (think of highlighting a method in a Java class, for instance).
Does anyone has a hint on how to get them?
Say I have this code:
```
function test(param1, param2) {
}
```
as function is a keyword, the first position I get in the parser is the one of the identifier "test". How can I get the positions from there up to the ending curly brace? The parameters list is dynamic, as one would expect, so you don't know in advance its length.
Thank you!
|
If I understand your question, I think you can use attribute 'pos' on each token
```
func: FUNCTION ID '(' ID (',' ID)* ')' {
System.out.println("Position = " + $FUNCTION.pos);
}
```
which refers to the character position within the line counting from zero.
|
281,579 |
<p>I'm trying to do Ruby password input with the <a href="http://highline.rubyforge.org/" rel="noreferrer">Highline gem</a> and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:</p>
<pre><code>new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false }
verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false }
</code></pre>
<p>And what I'd like to change it to is something like this:</p>
<pre><code>foo = Proc.new { |prompt| prompt.echo = false }
new_pass = ask("Enter your new password: ") foo
verify_pass = ask("Enter again to verify: ") foo
</code></pre>
<p>Which unfortunately doesn't work. What's the correct way to do this?</p>
|
[
{
"answer_id": 281620,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think the language supports a construct like this. The only way I can see to generalize this in any way is:</p>\n\n<pre><code>def foo(prompt)\n prompt.echo = false\nend\nnew_pass = ask(\"Enter your new password: \") { |prompt| foo(prompt) }\nverify_pass = ask(\"Enter again to verify: \") { |prompt| foo(prompt) }\n</code></pre>\n\n<p>It doesn't really shorten the code, though it does remove some duplication--if you wanted to do more than set <code>prompt.echo</code> to <code>false</code>, you'd only have to add code in one place.</p>\n"
},
{
"answer_id": 281625,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<pre><code>foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \") {|x| foo.call(x)}\nverify_pass = ask(\"Enter again to verify: \") {|x| foo.call(x)}\n</code></pre>\n"
},
{
"answer_id": 281681,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 7,
"selected": true,
"text": "<p>The code by David will work fine, but this is an easier and shorter solution:</p>\n\n<pre><code>foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \", &foo)\nverify_pass = ask(\"Enter again to verify: \", &foo)\n</code></pre>\n\n<p>You can also use an ampersand to assign a block to a variable when defining a method:</p>\n\n<pre><code>def ask(msg, &block)\n puts block.inspect\nend\n</code></pre>\n"
},
{
"answer_id": 281931,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 4,
"selected": false,
"text": "<p>This is how you should do it, clean and simple:</p>\n\n<pre><code>def ask(question)\n yield(question)\nend\n\nproc = Proc.new { |question| puts question }\nnew_pass = ask(\"Enter your new password: \", &proc)\nverify_pass = ask(\"Enter again to verify: \", &proc)\n</code></pre>\n"
},
{
"answer_id": 2884319,
"author": "jspooner",
"author_id": 68751,
"author_profile": "https://Stackoverflow.com/users/68751",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example that will prefix the index with the yield method and append the index with the call method.</p>\n\n<pre><code>class Array\n def alter_each!\n self.each_with_index do |n, i|\n self[i] = yield(n,i)\n end\n end\n def modify_each!(add_one = true, &block)\n self.each_with_index do |n, i|\n j = (add_one) ? (i + 1) : i\n self[i] = block.call(n,j)\n end\n end\nend\n\na = [\"dog\", \"cat\", \"cow\"]\n\na.alter_each! do |n, i|\n \"#{i}_#{n}\"\nend\n\na.modify_each! false do |n,i|\n \"#{n}_#{i}\"\nend\n\nputs a\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/422/"
] |
I'm trying to do Ruby password input with the [Highline gem](http://highline.rubyforge.org/) and since I have the user input the password twice, I'd like to eliminate the duplication on the blocks I'm passing in. For example, a simple version of what I'm doing right now is:
```
new_pass = ask("Enter your new password: ") { |prompt| prompt.echo = false }
verify_pass = ask("Enter again to verify: ") { |prompt| prompt.echo = false }
```
And what I'd like to change it to is something like this:
```
foo = Proc.new { |prompt| prompt.echo = false }
new_pass = ask("Enter your new password: ") foo
verify_pass = ask("Enter again to verify: ") foo
```
Which unfortunately doesn't work. What's the correct way to do this?
|
The code by David will work fine, but this is an easier and shorter solution:
```
foo = Proc.new { |prompt| prompt.echo = false }
new_pass = ask("Enter your new password: ", &foo)
verify_pass = ask("Enter again to verify: ", &foo)
```
You can also use an ampersand to assign a block to a variable when defining a method:
```
def ask(msg, &block)
puts block.inspect
end
```
|
281,584 |
<p>Using an ORM approach in applications can often lead to the scenario where you have a collection of objects you've retrieved and would like to display them in a tabular view using a DataGridView.</p>
<p>In my (limited) experience, binding collections of objects using a custom BindingList to a DataGridView results in poor performance and unsatisfactory sorting. I'm looking for a generic solution to this problem such that it's straightforward to populate a DataGridView and also extract the underlying objects later.</p>
<p>I will describe a good solution I've found, but I'm looking for alternatives.</p>
|
[
{
"answer_id": 281620,
"author": "Lucas Oman",
"author_id": 6726,
"author_profile": "https://Stackoverflow.com/users/6726",
"pm_score": -1,
"selected": false,
"text": "<p>I don't think the language supports a construct like this. The only way I can see to generalize this in any way is:</p>\n\n<pre><code>def foo(prompt)\n prompt.echo = false\nend\nnew_pass = ask(\"Enter your new password: \") { |prompt| foo(prompt) }\nverify_pass = ask(\"Enter again to verify: \") { |prompt| foo(prompt) }\n</code></pre>\n\n<p>It doesn't really shorten the code, though it does remove some duplication--if you wanted to do more than set <code>prompt.echo</code> to <code>false</code>, you'd only have to add code in one place.</p>\n"
},
{
"answer_id": 281625,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<pre><code>foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \") {|x| foo.call(x)}\nverify_pass = ask(\"Enter again to verify: \") {|x| foo.call(x)}\n</code></pre>\n"
},
{
"answer_id": 281681,
"author": "Adam Byrtek",
"author_id": 36656,
"author_profile": "https://Stackoverflow.com/users/36656",
"pm_score": 7,
"selected": true,
"text": "<p>The code by David will work fine, but this is an easier and shorter solution:</p>\n\n<pre><code>foo = Proc.new { |prompt| prompt.echo = false }\nnew_pass = ask(\"Enter your new password: \", &foo)\nverify_pass = ask(\"Enter again to verify: \", &foo)\n</code></pre>\n\n<p>You can also use an ampersand to assign a block to a variable when defining a method:</p>\n\n<pre><code>def ask(msg, &block)\n puts block.inspect\nend\n</code></pre>\n"
},
{
"answer_id": 281931,
"author": "Honza",
"author_id": 8621,
"author_profile": "https://Stackoverflow.com/users/8621",
"pm_score": 4,
"selected": false,
"text": "<p>This is how you should do it, clean and simple:</p>\n\n<pre><code>def ask(question)\n yield(question)\nend\n\nproc = Proc.new { |question| puts question }\nnew_pass = ask(\"Enter your new password: \", &proc)\nverify_pass = ask(\"Enter again to verify: \", &proc)\n</code></pre>\n"
},
{
"answer_id": 2884319,
"author": "jspooner",
"author_id": 68751,
"author_profile": "https://Stackoverflow.com/users/68751",
"pm_score": 2,
"selected": false,
"text": "<p>Here is an example that will prefix the index with the yield method and append the index with the call method.</p>\n\n<pre><code>class Array\n def alter_each!\n self.each_with_index do |n, i|\n self[i] = yield(n,i)\n end\n end\n def modify_each!(add_one = true, &block)\n self.each_with_index do |n, i|\n j = (add_one) ? (i + 1) : i\n self[i] = block.call(n,j)\n end\n end\nend\n\na = [\"dog\", \"cat\", \"cow\"]\n\na.alter_each! do |n, i|\n \"#{i}_#{n}\"\nend\n\na.modify_each! false do |n,i|\n \"#{n}_#{i}\"\nend\n\nputs a\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281584",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3406/"
] |
Using an ORM approach in applications can often lead to the scenario where you have a collection of objects you've retrieved and would like to display them in a tabular view using a DataGridView.
In my (limited) experience, binding collections of objects using a custom BindingList to a DataGridView results in poor performance and unsatisfactory sorting. I'm looking for a generic solution to this problem such that it's straightforward to populate a DataGridView and also extract the underlying objects later.
I will describe a good solution I've found, but I'm looking for alternatives.
|
The code by David will work fine, but this is an easier and shorter solution:
```
foo = Proc.new { |prompt| prompt.echo = false }
new_pass = ask("Enter your new password: ", &foo)
verify_pass = ask("Enter again to verify: ", &foo)
```
You can also use an ampersand to assign a block to a variable when defining a method:
```
def ask(msg, &block)
puts block.inspect
end
```
|
281,605 |
<p>I am developing a touch screen application that has to display a possibly large amount of text. The problem I am having is that the default scroll bar attached to text boxes is just too small to be practically used in a touch screen application. I have tried adding a separate scroll bar control and using it to control the scrolling of the text box. So far I have only come up with two ways of doing this.</p>
<p>The first way I came up with was to use the ScrollToCaret() subroutine. However I do not like this approach because it feels as if there should be a better way to tie in a scroll bar to a text box without changing the text selection</p>
<p>Here is an example:</p>
<pre><code>Dim oSelectionStart As Integer = CInt((TextBox1.Text.Length \ (VScrollBar1.Maximum - VScrollBar1.LargeChange - 1)) * VScrollBar1.Value)
If oSelectionStart >= TextBox1.Text.Length - 10 Then
oSelectionStart = TextBox1.Text.Length
End If
If oSelectionStart <= 10 Or VScrollBar1.Value < 2 Then
oSelectionStart = 0
End If
If Not TextBox1.SelectionStart = oSelectionStart Then
TextBox1.SelectionStart = oSelectionStart
TextBox1.ScrollToCaret()
End If
</code></pre>
<p>The second method I came up with uses windows API calls to set the scroll bars position and to get its current position. There are however some flaws to this approach as well. I am unable to get the large change value from the textboxes scrolling info. Most of the time this doesn't matter but when the default scroll bar on the textbox gets bigger it means that my scroll bar does not scale properly with it, giving my scroll bar the effect of scrolling to the bottom of the text while only being half way down the bar. Another problem with this approach that I found is that the default scroll bar for the textbox must be visible in order for me to be able to retrieve and set the current scrolling info. The last problem I have is one that plagues both methods I have discovered. I am unable to find an appropriate event to fire for when the user scrolls the text with anything other than my scroll bar, this means that I cannot update the position of my scroll bar even though the text has changed its scrolled position.</p>
<p>Heres the example code:</p>
<pre><code>Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs)
Dim minPos As Integer = 0
Dim maxPos As Integer = 0
Dim newPos As Integer = 0
GetScrollRange(TextBox1.Handle, SBS_VERT, minPos, maxPos)
Dim vScrollPerc As Double = ((100 / (VScrollBar1.Maximum - (VScrollBar1.LargeChange - 1))) * VScrollBar1.Value) * 0.01
newPos = CInt(((maxPos - minPos) * vScrollPerc) + minPos)
SetScrollPos(TextBox1.Handle, SBS_VERT, newPos, True)
PostMessageA(TextBox1.Handle, WM_VSCROLL, SB_THUMBPOSITION + &H10000 * newPos, Nothing)
End Sub
'Scrollbar direction
Const SBS_HORZ = 0
Const SBS_VERT = 1
'Windows Messages
Const WM_VSCROLL = &H115
Const WM_HSCROLL = &H114
Const SB_THUMBPOSITION = 4
<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> Private Structure SCROLLINFO
Public cbSize As Integer
Public fMask As Integer
Public nMin As Integer
Public nMax As Integer
Public nPage As Integer
Public nPos As Integer
Public nTrackPos As Integer
End Structure
Private Enum ScrollBarDirection
SB_HORZ = 0
SB_VERT = 1
SB_CTL = 2
SB_BOTH = 3
End Enum
Private Enum ScrollInfoMask
SIF_RANGE = &H1
SIF_PAGE = &H2
SIF_POS = &H4
SIF_DISABLENOSCROLL = &H8
SIF_TRACKPOS = &H10
SIF_ALL = (SIF_RANGE Or SIF_PAGE Or SIF_POS Or SIF_TRACKPOS)
End Enum
Private Declare Function GetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer) As Integer
Private Declare Function SetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByVal nPos As Integer, ByVal bRedraw As Boolean) As Integer
Private Declare Function PostMessageA Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Boolean
Private Declare Function GetScrollRange Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByRef lpMinPos As Integer, ByRef lpMaxPos As Integer) As Integer
Private Declare Function GetScrollInfo Lib "user32" (ByVal hWnd As IntPtr, ByVal fnBar As ScrollBarDirection, ByRef lpsi As SCROLLINFO) As Integer
</code></pre>
<p>I know there must be a better way out there to do this, but so far I have not been able to come up with anything that would be an appropriate solution to my problem. Any help would be appreciated.</p>
|
[
{
"answer_id": 281656,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 1,
"selected": false,
"text": "<p>I think, there is way how to change size of scrollbar wint Win32API.\nLook at:\n<a href=\"http://pinvoke.net/search.aspx?search=scrollbar&namespace=[All]\" rel=\"nofollow noreferrer\">http://pinvoke.net/search.aspx?search=scrollbar&namespace=[All]</a>\n<a href=\"http://pinvoke.net/default.aspx/user32/FindWindowEx.html\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/user32/FindWindowEx.html</a>\n<a href=\"http://pinvoke.net/default.aspx/user32/GetScrollBarInfo.html\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/user32/GetScrollBarInfo.html</a>\n<a href=\"http://pinvoke.net/default.aspx/user32/ShowScrollBar.html\" rel=\"nofollow noreferrer\">http://pinvoke.net/default.aspx/user32/ShowScrollBar.html</a></p>\n\n<p>You should be able change size of scroll bar with Win32API and scrollbar's handle.</p>\n"
},
{
"answer_id": 293267,
"author": "GregUzelac",
"author_id": 27068,
"author_profile": "https://Stackoverflow.com/users/27068",
"pm_score": 0,
"selected": false,
"text": "<p>We have been using WPF in our most recent project. Is WPF an option for you? If yes, it appears as if everything UI can be altered in WPF apps. We use 2 UI artists. One works in in Adope Photoshop, then converts the output to XAML. The second works in Expression Blend, which natively produces XAML.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25511/"
] |
I am developing a touch screen application that has to display a possibly large amount of text. The problem I am having is that the default scroll bar attached to text boxes is just too small to be practically used in a touch screen application. I have tried adding a separate scroll bar control and using it to control the scrolling of the text box. So far I have only come up with two ways of doing this.
The first way I came up with was to use the ScrollToCaret() subroutine. However I do not like this approach because it feels as if there should be a better way to tie in a scroll bar to a text box without changing the text selection
Here is an example:
```
Dim oSelectionStart As Integer = CInt((TextBox1.Text.Length \ (VScrollBar1.Maximum - VScrollBar1.LargeChange - 1)) * VScrollBar1.Value)
If oSelectionStart >= TextBox1.Text.Length - 10 Then
oSelectionStart = TextBox1.Text.Length
End If
If oSelectionStart <= 10 Or VScrollBar1.Value < 2 Then
oSelectionStart = 0
End If
If Not TextBox1.SelectionStart = oSelectionStart Then
TextBox1.SelectionStart = oSelectionStart
TextBox1.ScrollToCaret()
End If
```
The second method I came up with uses windows API calls to set the scroll bars position and to get its current position. There are however some flaws to this approach as well. I am unable to get the large change value from the textboxes scrolling info. Most of the time this doesn't matter but when the default scroll bar on the textbox gets bigger it means that my scroll bar does not scale properly with it, giving my scroll bar the effect of scrolling to the bottom of the text while only being half way down the bar. Another problem with this approach that I found is that the default scroll bar for the textbox must be visible in order for me to be able to retrieve and set the current scrolling info. The last problem I have is one that plagues both methods I have discovered. I am unable to find an appropriate event to fire for when the user scrolls the text with anything other than my scroll bar, this means that I cannot update the position of my scroll bar even though the text has changed its scrolled position.
Heres the example code:
```
Private Sub VScrollBar1_Scroll(ByVal sender As System.Object, ByVal e As System.Windows.Forms.ScrollEventArgs)
Dim minPos As Integer = 0
Dim maxPos As Integer = 0
Dim newPos As Integer = 0
GetScrollRange(TextBox1.Handle, SBS_VERT, minPos, maxPos)
Dim vScrollPerc As Double = ((100 / (VScrollBar1.Maximum - (VScrollBar1.LargeChange - 1))) * VScrollBar1.Value) * 0.01
newPos = CInt(((maxPos - minPos) * vScrollPerc) + minPos)
SetScrollPos(TextBox1.Handle, SBS_VERT, newPos, True)
PostMessageA(TextBox1.Handle, WM_VSCROLL, SB_THUMBPOSITION + &H10000 * newPos, Nothing)
End Sub
'Scrollbar direction
Const SBS_HORZ = 0
Const SBS_VERT = 1
'Windows Messages
Const WM_VSCROLL = &H115
Const WM_HSCROLL = &H114
Const SB_THUMBPOSITION = 4
<Runtime.InteropServices.StructLayout(Runtime.InteropServices.LayoutKind.Sequential)> Private Structure SCROLLINFO
Public cbSize As Integer
Public fMask As Integer
Public nMin As Integer
Public nMax As Integer
Public nPage As Integer
Public nPos As Integer
Public nTrackPos As Integer
End Structure
Private Enum ScrollBarDirection
SB_HORZ = 0
SB_VERT = 1
SB_CTL = 2
SB_BOTH = 3
End Enum
Private Enum ScrollInfoMask
SIF_RANGE = &H1
SIF_PAGE = &H2
SIF_POS = &H4
SIF_DISABLENOSCROLL = &H8
SIF_TRACKPOS = &H10
SIF_ALL = (SIF_RANGE Or SIF_PAGE Or SIF_POS Or SIF_TRACKPOS)
End Enum
Private Declare Function GetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer) As Integer
Private Declare Function SetScrollPos Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByVal nPos As Integer, ByVal bRedraw As Boolean) As Integer
Private Declare Function PostMessageA Lib "user32.dll" (ByVal hwnd As IntPtr, ByVal wMsg As Integer, ByVal wParam As Integer, ByVal lParam As Integer) As Boolean
Private Declare Function GetScrollRange Lib "user32.dll" (ByVal hWnd As IntPtr, ByVal nBar As Integer, ByRef lpMinPos As Integer, ByRef lpMaxPos As Integer) As Integer
Private Declare Function GetScrollInfo Lib "user32" (ByVal hWnd As IntPtr, ByVal fnBar As ScrollBarDirection, ByRef lpsi As SCROLLINFO) As Integer
```
I know there must be a better way out there to do this, but so far I have not been able to come up with anything that would be an appropriate solution to my problem. Any help would be appreciated.
|
I think, there is way how to change size of scrollbar wint Win32API.
Look at:
<http://pinvoke.net/search.aspx?search=scrollbar&namespace=[All]>
<http://pinvoke.net/default.aspx/user32/FindWindowEx.html>
<http://pinvoke.net/default.aspx/user32/GetScrollBarInfo.html>
<http://pinvoke.net/default.aspx/user32/ShowScrollBar.html>
You should be able change size of scroll bar with Win32API and scrollbar's handle.
|
281,640 |
<p>How do I get a human-readable file size in bytes abbreviation using .NET?</p>
<p><strong>Example</strong>:
Take input 7,326,629 and display 6.98 MB</p>
|
[
{
"answer_id": 281665,
"author": "TcKs",
"author_id": 20382,
"author_profile": "https://Stackoverflow.com/users/20382",
"pm_score": 4,
"selected": false,
"text": "<pre><code>int size = new FileInfo( filePath ).Length / 1024;\nstring humanKBSize = string.Format( \"{0} KB\", size );\nstring humanMBSize = string.Format( \"{0} MB\", size / 1024 );\nstring humanGBSize = string.Format( \"{0} GB\", size / 1024 / 1024 );\n</code></pre>\n"
},
{
"answer_id": 281672,
"author": "Peter Crabtree",
"author_id": 36283,
"author_profile": "https://Stackoverflow.com/users/36283",
"pm_score": 2,
"selected": false,
"text": "<p>I assume you're looking for \"1.4 MB\" instead of \"1468006 bytes\"?</p>\n\n<p>I don't think there is a built-in way to do that in .NET. You'll need to just figure out which unit is appropriate, and format it.</p>\n\n<p>Edit: Here's some sample code to do just that:</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cpp/formatsize.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cpp/formatsize.aspx</a></p>\n"
},
{
"answer_id": 281679,
"author": "David Thibault",
"author_id": 5903,
"author_profile": "https://Stackoverflow.com/users/5903",
"pm_score": 10,
"selected": true,
"text": "<p>This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.</p>\n<pre><code>string[] sizes = { "B", "KB", "MB", "GB", "TB" };\ndouble len = new FileInfo(filename).Length;\nint order = 0;\nwhile (len >= 1024 && order < sizes.Length - 1) {\n order++;\n len = len/1024;\n}\n\n// Adjust the format string to your preferences. For example "{0:0.#}{1}" would\n// show a single decimal place, and no space.\nstring result = String.Format("{0:0.##} {1}", len, sizes[order]);\n</code></pre>\n"
},
{
"answer_id": 281684,
"author": "bobwienholt",
"author_id": 24257,
"author_profile": "https://Stackoverflow.com/users/24257",
"pm_score": 3,
"selected": false,
"text": "<pre><code>string[] suffixes = { \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\" };\nint s = 0;\nlong size = fileInfo.Length;\n\nwhile (size >= 1024)\n{\n s++;\n size /= 1024;\n}\n\nstring humanReadable = String.Format(\"{0} {1}\", size, suffixes[s]);\n</code></pre>\n"
},
{
"answer_id": 281716,
"author": "Bob",
"author_id": 45,
"author_profile": "https://Stackoverflow.com/users/45",
"pm_score": 6,
"selected": false,
"text": "<pre><code>[DllImport ( \"Shlwapi.dll\", CharSet = CharSet.Auto )]\npublic static extern long StrFormatByteSize ( \n long fileSize\n , [MarshalAs ( UnmanagedType.LPTStr )] StringBuilder buffer\n , int bufferSize );\n\n\n/// <summary>\n/// Converts a numeric value into a string that represents the number expressed as a size value in bytes, kilobytes, megabytes, or gigabytes, depending on the size.\n/// </summary>\n/// <param name=\"filelength\">The numeric value to be converted.</param>\n/// <returns>the converted string</returns>\npublic static string StrFormatByteSize (long filesize) {\n StringBuilder sb = new StringBuilder( 11 );\n StrFormatByteSize( filesize, sb, sb.Capacity );\n return sb.ToString();\n}\n</code></pre>\n\n<p>From: <a href=\"http://www.pinvoke.net/default.aspx/shlwapi/StrFormatByteSize.html\" rel=\"noreferrer\">http://www.pinvoke.net/default.aspx/shlwapi/StrFormatByteSize.html</a></p>\n"
},
{
"answer_id": 4967106,
"author": "Constantin",
"author_id": 20310,
"author_profile": "https://Stackoverflow.com/users/20310",
"pm_score": 5,
"selected": false,
"text": "<p>One more way to skin it, without any kind of loops and with negative size support (makes sense for things like file size deltas):</p>\n\n<pre><code>public static class Format\n{\n static string[] sizeSuffixes = {\n \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\" };\n\n public static string ByteSize(long size)\n {\n Debug.Assert(sizeSuffixes.Length > 0);\n\n const string formatTemplate = \"{0}{1:0.#} {2}\";\n\n if (size == 0)\n {\n return string.Format(formatTemplate, null, 0, sizeSuffixes[0]);\n }\n\n var absSize = Math.Abs((double)size);\n var fpPower = Math.Log(absSize, 1000);\n var intPower = (int)fpPower;\n var iUnit = intPower >= sizeSuffixes.Length\n ? sizeSuffixes.Length - 1\n : intPower;\n var normSize = absSize / Math.Pow(1000, iUnit);\n\n return string.Format(\n formatTemplate,\n size < 0 ? \"-\" : null, normSize, sizeSuffixes[iUnit]);\n }\n}\n</code></pre>\n\n<p>And here is the test suite:</p>\n\n<pre><code>[TestFixture] public class ByteSize\n{\n [TestCase(0, Result=\"0 B\")]\n [TestCase(1, Result = \"1 B\")]\n [TestCase(1000, Result = \"1 KB\")]\n [TestCase(1500000, Result = \"1.5 MB\")]\n [TestCase(-1000, Result = \"-1 KB\")]\n [TestCase(int.MaxValue, Result = \"2.1 GB\")]\n [TestCase(int.MinValue, Result = \"-2.1 GB\")]\n [TestCase(long.MaxValue, Result = \"9.2 EB\")]\n [TestCase(long.MinValue, Result = \"-9.2 EB\")]\n public string Format_byte_size(long size)\n {\n return Format.ByteSize(size);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 4975942,
"author": "deepee1",
"author_id": 483179,
"author_profile": "https://Stackoverflow.com/users/483179",
"pm_score": 9,
"selected": false,
"text": "<p>using <strong>Log</strong> to solve the problem....</p>\n<pre><code>static String BytesToString(long byteCount)\n{\n string[] suf = { "B", "KB", "MB", "GB", "TB", "PB", "EB" }; //Longs run out around EB\n if (byteCount == 0)\n return "0" + suf[0];\n long bytes = Math.Abs(byteCount);\n int place = Convert.ToInt32(Math.Floor(Math.Log(bytes, 1024)));\n double num = Math.Round(bytes / Math.Pow(1024, place), 1);\n return (Math.Sign(byteCount) * num).ToString() + suf[place];\n}\n</code></pre>\n<p>Also in C#, but should be a snap to convert. Also I rounded to 1 decimal place for readability.</p>\n<p>Basically determine the number of decimal places in Base 1024 and then divide by <code>1024^decimalplaces</code>.</p>\n<p>And some samples of use and output:</p>\n<pre><code>Console.WriteLine(BytesToString(9223372036854775807)); //Results in 8EB\nConsole.WriteLine(BytesToString(0)); //Results in 0B\nConsole.WriteLine(BytesToString(1024)); //Results in 1KB\nConsole.WriteLine(BytesToString(2000000)); //Results in 1.9MB\nConsole.WriteLine(BytesToString(-9023372036854775807)); //Results in -7.8EB\n</code></pre>\n<p>Edit:<br />\nWas pointed out that I missed a <code>Math.Floor</code>, so I incorporated it. (<code>Convert.ToInt32</code> uses rounding, not truncating and that's why <code>Floor</code> is necessary.) Thanks for the catch.</p>\n<p>Edit2:<br />\nThere were a couple of comments about negative sizes and 0 byte sizes, so I updated to handle those cases.</p>\n"
},
{
"answer_id": 10567672,
"author": "NET3",
"author_id": 1289709,
"author_profile": "https://Stackoverflow.com/users/1289709",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Mixture of all solutions :-)</strong></p>\n\n<pre><code> /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,\n /// kilobytes, megabytes, or gigabytes, depending on the size.\n /// </summary>\n /// <param name=\"fileSize\">The numeric value to be converted.</param>\n /// <returns>The converted string.</returns>\n public static string FormatByteSize(double fileSize)\n {\n FileSizeUnit unit = FileSizeUnit.B;\n while (fileSize >= 1024 && unit < FileSizeUnit.YB)\n {\n fileSize = fileSize / 1024;\n unit++;\n }\n return string.Format(\"{0:0.##} {1}\", fileSize, unit);\n }\n\n /// <summary>\n /// Converts a numeric value into a string that represents the number expressed as a size value in bytes,\n /// kilobytes, megabytes, or gigabytes, depending on the size.\n /// </summary>\n /// <param name=\"fileInfo\"></param>\n /// <returns>The converted string.</returns>\n public static string FormatByteSize(FileInfo fileInfo)\n {\n return FormatByteSize(fileInfo.Length);\n }\n}\n\npublic enum FileSizeUnit : byte\n{\n B,\n KB,\n MB,\n GB,\n TB,\n PB,\n EB,\n ZB,\n YB\n}\n</code></pre>\n"
},
{
"answer_id": 11124118,
"author": "humbads",
"author_id": 553396,
"author_profile": "https://Stackoverflow.com/users/553396",
"pm_score": 7,
"selected": false,
"text": "<p>A tested and significantly optimized version of the requested function is posted here:</p>\n\n<p><a href=\"http://www.somacon.com/p576.php\">C# Human Readable File Size - Optimized Function</a></p>\n\n<p>Source code:</p>\n\n<pre><code>// Returns the human-readable file size for an arbitrary, 64-bit file size \n// The default format is \"0.### XB\", e.g. \"4.2 KB\" or \"1.434 GB\"\npublic string GetBytesReadable(long i)\n{\n // Get absolute value\n long absolute_i = (i < 0 ? -i : i);\n // Determine the suffix and readable value\n string suffix;\n double readable;\n if (absolute_i >= 0x1000000000000000) // Exabyte\n {\n suffix = \"EB\";\n readable = (i >> 50);\n }\n else if (absolute_i >= 0x4000000000000) // Petabyte\n {\n suffix = \"PB\";\n readable = (i >> 40);\n }\n else if (absolute_i >= 0x10000000000) // Terabyte\n {\n suffix = \"TB\";\n readable = (i >> 30);\n }\n else if (absolute_i >= 0x40000000) // Gigabyte\n {\n suffix = \"GB\";\n readable = (i >> 20);\n }\n else if (absolute_i >= 0x100000) // Megabyte\n {\n suffix = \"MB\";\n readable = (i >> 10);\n }\n else if (absolute_i >= 0x400) // Kilobyte\n {\n suffix = \"KB\";\n readable = i;\n }\n else\n {\n return i.ToString(\"0 B\"); // Byte\n }\n // Divide by 1024 to get fractional value\n readable = (readable / 1024);\n // Return formatted number with suffix\n return readable.ToString(\"0.### \") + suffix;\n}\n</code></pre>\n"
},
{
"answer_id": 12409014,
"author": "Berend",
"author_id": 1669001,
"author_profile": "https://Stackoverflow.com/users/1669001",
"pm_score": 1,
"selected": false,
"text": "<p>My 2 cents:</p>\n\n<ul>\n<li>The prefix for kilobyte is kB (lowercase K)</li>\n<li>Since these functions are for presentation purposes, one should supply a culture, for example: <code>string.Format(CultureInfo.CurrentCulture, \"{0:0.##} {1}\", fileSize, unit);</code></li>\n<li>Depending on the context a kilobyte can be either <a href=\"http://en.wikipedia.org/wiki/Kilobyte\" rel=\"nofollow\">1000 or 1024 bytes</a>. The same goes for MB, GB, etc.</li>\n</ul>\n"
},
{
"answer_id": 15065986,
"author": "Giles",
"author_id": 594006,
"author_profile": "https://Stackoverflow.com/users/594006",
"pm_score": 2,
"selected": false,
"text": "<p>One more approach, for what it's worth. I liked @humbads optimized solution referenced above, so have copied the principle, but I've implemented it a little differently.</p>\n\n<p>I suppose it's debatable as to whether it should be an extension method (since not all longs are necessarily byte sizes), but I like them, and it's somewhere I can find the method when I next need it!</p>\n\n<p>Regarding the units, I don't think I've ever said 'Kibibyte' or 'Mebibyte' in my life, and while I'm skeptical of such enforced rather than evolved standards, I suppose it'll avoid confusion in the long term.</p>\n\n<pre><code>public static class LongExtensions\n{\n private static readonly long[] numberOfBytesInUnit;\n private static readonly Func<long, string>[] bytesToUnitConverters;\n\n static LongExtensions()\n {\n numberOfBytesInUnit = new long[6] \n {\n 1L << 10, // Bytes in a Kibibyte\n 1L << 20, // Bytes in a Mebibyte\n 1L << 30, // Bytes in a Gibibyte\n 1L << 40, // Bytes in a Tebibyte\n 1L << 50, // Bytes in a Pebibyte\n 1L << 60 // Bytes in a Exbibyte\n };\n\n // Shift the long (integer) down to 1024 times its number of units, convert to a double (real number), \n // then divide to get the final number of units (units will be in the range 1 to 1023.999)\n Func<long, int, string> FormatAsProportionOfUnit = (bytes, shift) => (((double)(bytes >> shift)) / 1024).ToString(\"0.###\");\n\n bytesToUnitConverters = new Func<long,string>[7]\n {\n bytes => bytes.ToString() + \" B\",\n bytes => FormatAsProportionOfUnit(bytes, 0) + \" KiB\",\n bytes => FormatAsProportionOfUnit(bytes, 10) + \" MiB\",\n bytes => FormatAsProportionOfUnit(bytes, 20) + \" GiB\",\n bytes => FormatAsProportionOfUnit(bytes, 30) + \" TiB\",\n bytes => FormatAsProportionOfUnit(bytes, 40) + \" PiB\",\n bytes => FormatAsProportionOfUnit(bytes, 50) + \" EiB\",\n };\n }\n\n public static string ToReadableByteSizeString(this long bytes)\n {\n if (bytes < 0)\n return \"-\" + Math.Abs(bytes).ToReadableByteSizeString();\n\n int counter = 0;\n while (counter < numberOfBytesInUnit.Length)\n {\n if (bytes < numberOfBytesInUnit[counter])\n return bytesToUnitConverters[counter](bytes);\n counter++;\n }\n return bytesToUnitConverters[counter](bytes);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 22366441,
"author": "Omar",
"author_id": 160823,
"author_profile": "https://Stackoverflow.com/users/160823",
"pm_score": 5,
"selected": false,
"text": "<p>Check out my <a href=\"https://github.com/omar/ByteSize\" rel=\"nofollow noreferrer\">ByteSize</a> library. It's the <code>System.TimeSpan</code> for bytes!</p>\n<p>It handles the conversion and formatting for you.</p>\n<pre><code>var maxFileSize = ByteSize.FromKiloBytes(10);\nmaxFileSize.Bytes;\nmaxFileSize.MegaBytes;\nmaxFileSize.GigaBytes;\n</code></pre>\n<p>It also does string representation and parsing.</p>\n<pre><code>// ToString\nByteSize.FromKiloBytes(1024).ToString(); // 1 MB\nByteSize.FromGigabytes(.5).ToString(); // 512 MB\nByteSize.FromGigabytes(1024).ToString(); // 1 TB\n\n// Parsing\nByteSize.Parse("5b");\nByteSize.Parse("1.55B");\n</code></pre>\n"
},
{
"answer_id": 23053777,
"author": "Jernej Novak",
"author_id": 1063571,
"author_profile": "https://Stackoverflow.com/users/1063571",
"pm_score": 3,
"selected": false,
"text": "<p>There is one open source project which can do that and much more. </p>\n\n<pre><code>7.Bits().ToString(); // 7 b\n8.Bits().ToString(); // 1 B\n(.5).Kilobytes().Humanize(); // 512 B\n(1000).Kilobytes().ToString(); // 1000 KB\n(1024).Kilobytes().Humanize(); // 1 MB\n(.5).Gigabytes().Humanize(); // 512 MB\n(1024).Gigabytes().ToString(); // 1 TB\n</code></pre>\n\n<p><a href=\"http://humanizr.net/#bytesize\" rel=\"noreferrer\">http://humanizr.net/#bytesize</a></p>\n\n<p><a href=\"https://github.com/MehdiK/Humanizer\" rel=\"noreferrer\">https://github.com/MehdiK/Humanizer</a></p>\n"
},
{
"answer_id": 31833405,
"author": "Mark",
"author_id": 1463355,
"author_profile": "https://Stackoverflow.com/users/1463355",
"pm_score": 4,
"selected": false,
"text": "<p>I like to use the following method (it supports up to terabytes, which is enough for most cases, but it can easily be extended):</p>\n\n<pre><code>private string GetSizeString(long length)\n{\n long B = 0, KB = 1024, MB = KB * 1024, GB = MB * 1024, TB = GB * 1024;\n double size = length;\n string suffix = nameof(B);\n\n if (length >= TB) {\n size = Math.Round((double)length / TB, 2);\n suffix = nameof(TB);\n }\n else if (length >= GB) {\n size = Math.Round((double)length / GB, 2);\n suffix = nameof(GB);\n }\n else if (length >= MB) {\n size = Math.Round((double)length / MB, 2);\n suffix = nameof(MB);\n }\n else if (length >= KB) {\n size = Math.Round((double)length / KB, 2);\n suffix = nameof(KB);\n }\n\n return $\"{size} {suffix}\";\n}\n</code></pre>\n\n<p>Please keep in mind that this is written for C# 6.0 (2015), so it might need a little editing for earlier versions.</p>\n"
},
{
"answer_id": 35854271,
"author": "Metalogic",
"author_id": 487051,
"author_profile": "https://Stackoverflow.com/users/487051",
"pm_score": 3,
"selected": false,
"text": "<p>If you are trying to match the size as shown in Windows Explorer's detail view, this is the code you want:</p>\n\n<pre><code>[DllImport(\"shlwapi.dll\", CharSet = CharSet.Unicode)]\nprivate static extern long StrFormatKBSize(\n long qdw,\n [MarshalAs(UnmanagedType.LPTStr)] StringBuilder pszBuf,\n int cchBuf);\n\npublic static string BytesToString(long byteCount)\n{\n var sb = new StringBuilder(32);\n StrFormatKBSize(byteCount, sb, sb.Capacity);\n return sb.ToString();\n}\n</code></pre>\n\n<p>This will not only match Explorer exactly but will also provide the strings translated for you and match differences in Windows versions (for example in Win10, K = 1000 vs. previous versions K = 1024).</p>\n"
},
{
"answer_id": 44407234,
"author": "alvinsay",
"author_id": 1448446,
"author_profile": "https://Stackoverflow.com/users/1448446",
"pm_score": 3,
"selected": false,
"text": "<p>Like @NET3's solution. Use shift instead of division to test the range of <code>bytes</code>, because division takes more CPU cost.</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>private static readonly string[] UNITS = new string[] { \"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\" };\n\npublic static string FormatSize(ulong bytes)\n{\n int c = 0;\n for (c = 0; c < UNITS.Length; c++)\n {\n ulong m = (ulong)1 << ((c + 1) * 10);\n if (bytes < m)\n break;\n }\n\n double n = bytes / (double)((ulong)1 << (c * 10));\n return string.Format(\"{0:0.##} {1}\", n, UNITS[c]);\n}\n</code></pre>\n"
},
{
"answer_id": 46805502,
"author": "RooiWillie",
"author_id": 1715044,
"author_profile": "https://Stackoverflow.com/users/1715044",
"pm_score": 2,
"selected": false,
"text": "<p>How about some recursion:</p>\n\n<pre><code>private static string ReturnSize(double size, string sizeLabel)\n{\n if (size > 1024)\n {\n if (sizeLabel.Length == 0)\n return ReturnSize(size / 1024, \"KB\");\n else if (sizeLabel == \"KB\")\n return ReturnSize(size / 1024, \"MB\");\n else if (sizeLabel == \"MB\")\n return ReturnSize(size / 1024, \"GB\");\n else if (sizeLabel == \"GB\")\n return ReturnSize(size / 1024, \"TB\");\n else\n return ReturnSize(size / 1024, \"PB\");\n }\n else\n {\n if (sizeLabel.Length > 0)\n return string.Concat(size.ToString(\"0.00\"), sizeLabel);\n else\n return string.Concat(size.ToString(\"0.00\"), \"Bytes\");\n }\n}\n</code></pre>\n\n<p>Then you call it:</p>\n\n<pre><code>return ReturnSize(size, string.Empty);\n</code></pre>\n"
},
{
"answer_id": 49535675,
"author": "DKH",
"author_id": 5452928,
"author_profile": "https://Stackoverflow.com/users/5452928",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a concise answer that determines the unit automatically.</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string ToBytesCount(this long bytes)\n{\n int unit = 1024;\n string unitStr = "B";\n if (bytes < unit)\n {\n return string.Format("{0} {1}", bytes, unitStr);\n }\n int exp = (int)(Math.Log(bytes) / Math.Log(unit));\n return string.Format("{0:##.##} {1}{2}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], unitStr);\n}\n</code></pre>\n<p><em>"b" is for bit, "B" is for Byte and "KMGTPEZY" are respectively for kilo, mega, giga, tera, peta, exa, zetta and yotta</em></p>\n<p>One can expand it to take <a href=\"https://en.wikipedia.org/wiki/ISO/IEC_80000\" rel=\"nofollow noreferrer\">ISO/IEC80000</a> into account:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>public static string ToBytesCount(this long bytes, bool isISO = true)\n{\n int unit = isISO ? 1024 : 1000;\n string unitStr = "B";\n if (bytes < unit)\n {\n return string.Format("{0} {1}", bytes, unitStr);\n }\n int exp = (int)(Math.Log(bytes) / Math.Log(unit));\n return string.Format("{0:##.##} {1}{2}{3}", bytes / Math.Pow(unit, exp), "KMGTPEZY"[exp - 1], isISO ? "i" : "", unitStr);\n}\n</code></pre>\n"
},
{
"answer_id": 53406079,
"author": "masterwok",
"author_id": 563509,
"author_profile": "https://Stackoverflow.com/users/563509",
"pm_score": 2,
"selected": false,
"text": "<p>I use the <em>Long</em> extension method below to convert to a human readable size string. This method is the C# implementation of the Java solution of this same question posted on Stack Overflow, <a href=\"https://stackoverflow.com/a/3758880/563509\">here</a>.</p>\n\n<pre><code>/// <summary>\n/// Convert a byte count into a human readable size string.\n/// </summary>\n/// <param name=\"bytes\">The byte count.</param>\n/// <param name=\"si\">Whether or not to use SI units.</param>\n/// <returns>A human readable size string.</returns>\npublic static string ToHumanReadableByteCount(\n this long bytes\n , bool si\n)\n{\n var unit = si\n ? 1000\n : 1024;\n\n if (bytes < unit)\n {\n return $\"{bytes} B\";\n }\n\n var exp = (int) (Math.Log(bytes) / Math.Log(unit));\n\n return $\"{bytes / Math.Pow(unit, exp):F2} \" +\n $\"{(si ? \"kMGTPE\" : \"KMGTPE\")[exp - 1] + (si ? string.Empty : \"i\")}B\";\n}\n</code></pre>\n"
},
{
"answer_id": 64881832,
"author": "Zombo",
"author_id": 1002260,
"author_profile": "https://Stackoverflow.com/users/1002260",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a method with <code>Log10</code>:</p>\n<pre><code>using System;\n\nclass Program {\n static string NumberFormat(double n) {\n var n2 = (int)Math.Log10(n) / 3;\n var n3 = n / Math.Pow(1e3, n2);\n return String.Format("{0:f3}", n3) + new[]{"", " k", " M", " G"}[n2];\n }\n\n static void Main() {\n var s = NumberFormat(9012345678);\n Console.WriteLine(s == "9.012 G");\n }\n}\n</code></pre>\n<p><a href=\"https://learn.microsoft.com/dotnet/api/system.math.log10\" rel=\"nofollow noreferrer\">https://learn.microsoft.com/dotnet/api/system.math.log10</a></p>\n"
},
{
"answer_id": 65996342,
"author": "Kim Homann",
"author_id": 5773733,
"author_profile": "https://Stackoverflow.com/users/5773733",
"pm_score": 2,
"selected": false,
"text": "<p>In order to get the human-readable string exactly as the user's used to in his Windows environment, you should use <code>StrFormatByteSize()</code>:</p>\n<pre><code>using System.Runtime.InteropServices;\n</code></pre>\n<p>...</p>\n<pre><code>private long mFileSize;\n\n[DllImport("Shlwapi.dll", CharSet = CharSet.Auto)]\npublic static extern int StrFormatByteSize(\n long fileSize,\n [MarshalAs(UnmanagedType.LPTStr)] StringBuilder buffer,\n int bufferSize);\n \npublic string HumanReadableFileSize\n{\n get\n {\n var sb = new StringBuilder(20);\n StrFormatByteSize(mFileSize, sb, 20);\n return sb.ToString();\n }\n}\n</code></pre>\n<p>I found this here:\n<a href=\"http://csharphelper.com/blog/2014/07/format-file-sizes-in-kb-mb-gb-and-so-forth-in-c/\" rel=\"nofollow noreferrer\">http://csharphelper.com/blog/2014/07/format-file-sizes-in-kb-mb-gb-and-so-forth-in-c/</a></p>\n"
},
{
"answer_id": 69075216,
"author": "dkackman",
"author_id": 155537,
"author_profile": "https://Stackoverflow.com/users/155537",
"pm_score": 0,
"selected": false,
"text": "<p>Here is a <a href=\"https://learn.microsoft.com/en-us/dotnet/api/system.numerics.biginteger?view=net-5.0\" rel=\"nofollow noreferrer\">BigInteger</a> version of <a href=\"https://stackoverflow.com/a/4975942/155537\">@deepee1's answer</a> that gets around the size limitation of longs (so therefore supports yottabyte and theoretically whatever comes after that):</p>\n<pre><code>public static string ToBytesString(this BigInteger byteCount, string format = "N3")\n{\n string[] suf = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "YiB" };\n if (byteCount.IsZero)\n {\n return $"{0.0.ToString(format)} {suf[0]}";\n }\n\n var abs = BigInteger.Abs(byteCount);\n var place = Convert.ToInt32(Math.Floor(BigInteger.Log(abs, 1024)));\n var pow = Math.Pow(1024, place);\n\n // since we need to do this with integer math, get the quotient and remainder\n var quotient = BigInteger.DivRem(abs, new BigInteger(pow), out var remainder);\n // convert the remainder to a ratio and add both back together as doubles\n var num = byteCount.Sign * (Math.Floor((double)quotient) + ((double)remainder / pow));\n\n return $"{num.ToString(format)} {suf[place]}";\n}\n</code></pre>\n"
},
{
"answer_id": 71561573,
"author": "David V McKay",
"author_id": 250988,
"author_profile": "https://Stackoverflow.com/users/250988",
"pm_score": -1,
"selected": false,
"text": "<p>1-liner (plus the prefixes constant)</p>\n<pre class=\"lang-cs prettyprint-override\"><code>const String prefixes = " KMGTPEY";\n/// <summary> Returns the human-readable file size for an arbitrary, 64-bit file size. </summary>\npublic static String HumanSize(UInt64 bytes)\n => Enumerable\n .Range(0, prefixes.Length)\n .Where(i => bytes < 1024U<<(i*10))\n .Select(i => $"{(bytes>>(10*i-10))/1024:0.###} {prefixes[i]}B")\n .First();\n</code></pre>\n<p>Or, if you want to reduce LINQ object allocations, use for-loop variation of the same:</p>\n<pre class=\"lang-cs prettyprint-override\"><code>/// <summary>\n/// Returns the human-readable file size for an arbitrary, 64-bit file size.\n/// </summary>\npublic static String HumanSize(UInt64 bytes)\n{\n const String prefixes = " KMGTPEY";\n for (var i = 0; i < prefixes.Length; i++)\n if (bytes < 1024U<<(i*10))\n return $"{(bytes>>(10*i-10))/1024:0.###} {prefixes[i]}B";\n\n throw new ArgumentOutOfRangeException(nameof(bytes));\n}\n</code></pre>\n"
},
{
"answer_id": 71621946,
"author": "SN74H74N",
"author_id": 2896816,
"author_profile": "https://Stackoverflow.com/users/2896816",
"pm_score": -1,
"selected": false,
"text": "<p>This question is old, but a very fast C# function could be:</p>\n<pre><code>public static string PrettyPrintBytes(long numBytes)\n{\n if (numBytes < 1024)\n return $"{numBytes} B";\n \n if (numBytes < 1048576)\n return $"{numBytes / 1024d:0.##} KB";\n\n if (numBytes < 1073741824)\n return $"{numBytes / 1048576d:0.##} MB";\n\n if (numBytes < 1099511627776)\n return $"{numBytes / 1073741824d:0.##} GB";\n\n if (numBytes < 1125899906842624)\n return $"{numBytes / 1099511627776d:0.##} TB";\n \n if (numBytes < 1152921504606846976)\n return $"{numBytes / 1125899906842624d:0.##} PB";\n\n return $"{numBytes / 1152921504606846976d:0.##} EB";\n}\n</code></pre>\n<p>This has only one cast and one divide per call and only up to 6 compares. When benchmarking, I found that string interpolation is much faster than using String.Format().</p>\n"
},
{
"answer_id": 73842309,
"author": "kellybs1",
"author_id": 20081009,
"author_profile": "https://Stackoverflow.com/users/20081009",
"pm_score": 0,
"selected": false,
"text": "<p>Nothing here did exactly what I needed, and I made my own based on this thread, so here's my long extension that allows you to choose the formatting requirement depending on standard.</p>\n<p>Definitely not the fastest but flexible. Supports up to EB/EiB.</p>\n<pre><code>// <summary>\n/// <paramref name="byteCount"/> The original size in bytes ( 8 bits )\n/// <paramref name="notationFormat"/> is supported in the following ways:\n/// [ 'B' / 'b' : Binary : Kilobyte (KB) is 1024 bytes, Megabyte (MB) is 1048576 bytes, etc ]\n/// [ 'I' / 'i' : IEC: Kibibyte (KiB) is 1024 bytes, Mebibyte (MiB) is 1048576 bytes, etc ]\n/// [ 'D' / 'd' : Decimal : Kilobyte (KB) is 1000 bytes, Megabyte (MB) is 1000000 bytes, etc ]\n/// </summary>\n\npublic static string ToDataSizeString( this long byteCount, char notationFormat = 'b' )\n{\n char[] supportedFormatChars = { 'b', 'i', 'd' };\n\n var lowerCaseNotationFormat = char.ToLowerInvariant( notationFormat );\n\n // Stop shooting holes in my ship!\n if ( !supportedFormatChars.Contains( lowerCaseNotationFormat ) )\n {\n throw new ArgumentException( $"notationFormat argument '{notationFormat}' not supported" );\n }\n\n long ebLimit = 1152921504606846976;\n long pbLimit = 1125899906842624;\n long tbLimit = 1099511627776;\n long gbLimit = 1073741824;\n long mbLimit = 1048576;\n long kbLimit = 1024;\n\n var ebSuffix = "EB";\n var pbSuffix = "PB";\n var tbSuffix = "TB";\n var gbSuffix = "GB";\n var mbSuffix = "MB";\n var kbSuffix = "KB";\n var bSuffix = " B";\n\n switch ( lowerCaseNotationFormat )\n {\n case 'b':\n // Sweet as\n break;\n\n case 'i':\n // Limits stay the same, suffixes need changed\n ebSuffix = "EiB";\n pbSuffix = "PiB";\n tbSuffix = "TiB";\n gbSuffix = "GiB";\n mbSuffix = "MiB";\n kbSuffix = "KiB";\n bSuffix = " B";\n break;\n\n case 'd':\n // Suffixes stay the same, limits need changed\n ebLimit = 1000000000000000000;\n pbLimit = 1000000000000000;\n tbLimit = 1000000000000;\n gbLimit = 1000000000;\n mbLimit = 1000000;\n kbLimit = 1000;\n break;\n\n default:\n // Should have already Excepted, but hey whatever\n throw new ArgumentException( $"notationFormat argument '{notationFormat}' not supported" );\n\n }\n\n string fileSizeText;\n\n // Exa/Exbi sized\n if ( byteCount >= ebLimit )\n {\n fileSizeText = $"{( (double)byteCount / ebLimit ):N1} {ebSuffix}";\n }\n // Peta/Pebi sized\n else if ( byteCount >= pbLimit )\n {\n fileSizeText = $"{( (double)byteCount / pbLimit ):N1} {pbSuffix}";\n }\n // Tera/Tebi sized\n else if ( byteCount >= tbLimit )\n {\n fileSizeText = $"{( (double)byteCount / tbLimit ):N1} {tbSuffix}";\n }\n // Giga/Gibi sized\n else if ( byteCount >= gbLimit )\n {\n fileSizeText = $"{( (double)byteCount / gbLimit ):N1} {gbSuffix}";\n }\n // Mega/Mibi sized\n else if ( byteCount >= mbLimit )\n {\n fileSizeText = $"{( (double)byteCount / mbLimit ):N1} {mbSuffix}";\n }\n // Kilo/Kibi sized\n else if ( byteCount >= kbLimit )\n {\n fileSizeText = $"{( (double)byteCount / kbLimit ):N1} {kbSuffix}";\n }\n // Byte sized\n else\n {\n fileSizeText = $"{byteCount} {bSuffix}";\n }\n\n return fileSizeText;\n}\n</code></pre>\n"
},
{
"answer_id": 74586340,
"author": "Stanislav Vladev",
"author_id": 9575469,
"author_profile": "https://Stackoverflow.com/users/9575469",
"pm_score": 0,
"selected": false,
"text": "<p>I made up this and it works just fine.</p>\n<pre><code>public string[] DetermineDigitalSize(string filename)\n {\n string[] result = new string[2];\n string[] sizes = { "B", "KB", "MB", "GB", "GB" };\n double len = new FileInfo(filename).Length;\n double adjustedSize = len;\n double testSize = 0;\n int order = 0;\n while (order< sizes.Length-1)\n {\n testSize = adjustedSize / 1024;\n if (testSize >= 1) { adjustedSize = testSize; order++; }\n else { break; }\n }\n result[0] = $"{adjustedSize:f2}";\n result[1] = sizes[order];\n return result;\n }\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281640",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/337/"
] |
How do I get a human-readable file size in bytes abbreviation using .NET?
**Example**:
Take input 7,326,629 and display 6.98 MB
|
This may not the most efficient or optimized way to do it, but it's easier to read if you are not familiar with log maths, and should be fast enough for most scenarios.
```
string[] sizes = { "B", "KB", "MB", "GB", "TB" };
double len = new FileInfo(filename).Length;
int order = 0;
while (len >= 1024 && order < sizes.Length - 1) {
order++;
len = len/1024;
}
// Adjust the format string to your preferences. For example "{0:0.#}{1}" would
// show a single decimal place, and no space.
string result = String.Format("{0:0.##} {1}", len, sizes[order]);
```
|
281,664 |
<p>Imagine the following scenario - we have Page1 which contains controls Control A and Control B.</p>
<p>Say Control A has a button, and on the click of this button we want Control B to react.
But we want to do this in an abstract fashion, i.e. we can't have Control B knowing anything about Control A, and vice versa.</p>
<p>That way we can develop these controls in isolation, and drive them by unit-testing.</p>
<p>Now, I thought I had the solution, just want to know what you guys think of it.</p>
<p>On Control A's button click, I put a 'message' on the Session, i.e. Session["MESSAGES"] = "ControlA_Click".</p>
<p>In Page1, on the Page_LoadComplete(), I put a call to ProcessMessages, which looks like this:</p>
<pre><code> List<Message> messages = SessionMessages.GetMessageList(Page);
foreach(Message m in messages)
{
//Get Controls
ControlA controlA = FindControl("controlA") as ControlA;
controlA .ProcessMessage(m);
ControlB controlB = FindControl("controlB") as ControlB;
controlB.ProcessMessage(m);
}
</code></pre>
<p>in ControlB's ProcessMessage() method, we can react to the messages that ControlB is interested in, like so:</p>
<pre><code> if (m.MessageName == SessionMessages.C_MESSAGE_SEARCH)
{
this.Visible = true;
}
</code></pre>
<p>To me, this seems to work. It allows us to develop these controls completely separately from eachother, while still allowing for inter-control-communication at an abstract level.</p>
<p>The only thing I can think of that might bring this crashing down is <em>perhaps</em> the ASP.NET life-cycle in relation to Pages and User Controls. The way I figure it though is that ALL events should have been processed on the controls before Page_LoadComplete() is called on the owning Page.</p>
<p>Thoughts?</p>
|
[
{
"answer_id": 281678,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>an interesting abuse of the session...</p>\n\n<p>you could also have the message queue belong to the hosting page instead</p>\n\n<p>i would recommend that instead you have the hosting page do something to the control in response to the message, rather than making the control be 'smart' - there is really no need for a button to be 'smart'</p>\n"
},
{
"answer_id": 281695,
"author": "Briggie Smalls",
"author_id": 9559,
"author_profile": "https://Stackoverflow.com/users/9559",
"pm_score": 3,
"selected": false,
"text": "<ol>\n<li>Control A should raise an event</li>\n<li>The page housing the controls subscribes to the event & then calls the appropriate method in the other control</li>\n<li>Control B should process the message()</li>\n</ol>\n"
},
{
"answer_id": 281720,
"author": "Bruno Shine",
"author_id": 28294,
"author_profile": "https://Stackoverflow.com/users/28294",
"pm_score": 0,
"selected": false,
"text": "<p>Check out the <a href=\"http://www.codeplex.com/MEFContrib\" rel=\"nofollow noreferrer\">Managed Extensibility Framework</a> Contrib project. They have just a sample website that is just what you want.</p>\n"
},
{
"answer_id": 281728,
"author": "user7375",
"author_id": 7375,
"author_profile": "https://Stackoverflow.com/users/7375",
"pm_score": 1,
"selected": false,
"text": "<p>Isn't this what databinding is for? Control A responds to an event that updates the model and then calls databind on its dependencies. </p>\n\n<p>If you want to make a messaging system, design it to the publisher and subscriber do not need to know about each other, only the message itself. Create an interface something like:</p>\n\n<pre><code>public interface IHandle<T> where T:IMessage\n{\n void Process(T message)\n}\n</code></pre>\n\n<p>You will need a method of discovering which controls implement it and build a map of messagetype->handlers, have a look at the way the main DI frameworks handle property injection to ASP .NET controls to see how you can achieve this. You can then use a single SendMessage method which is responsible for dispatching the message to all controls that can handle that message. It's more common see this sort of pattern in forms UI.</p>\n"
},
{
"answer_id": 281729,
"author": "Aleris",
"author_id": 20417,
"author_profile": "https://Stackoverflow.com/users/20417",
"pm_score": 0,
"selected": false,
"text": "<p>There are some problems with this approach like:<br>\n - The 'events' are not verified at compile (you can easily mistype an event name and find out about this at runtime or worst)<br>\n - Filling session with communication stuff<br>\n - You need to put control names as\n strings\n - If there are more than one control that is a subscriber to these event can become difficult to control<br>\n - When parameters will need to be send between controls the solution will become more difficult to manage </p>\n\n<p>A better approach is to use the build in event mechanism by declaring events on the controls:</p>\n\n<pre><code>public event EventHandler SpecialClick;\n</code></pre>\n\n<p>Each control that needs to do something will subscribe to this event </p>\n\n<pre><code>controlA.SpecialClick += new EventHandler(controlA_SpecialClick)\n</code></pre>\n\n<p>using the normal dot.net events.</p>\n"
},
{
"answer_id": 281766,
"author": "Cory Foy",
"author_id": 4083,
"author_profile": "https://Stackoverflow.com/users/4083",
"pm_score": 2,
"selected": false,
"text": "<p>As Briggie alludes to - this is exactly what Model-View Presenter is all about. Here's <a href=\"http://www.cornetdesign.com/2007/10/tdd-of-winform-app-part-2-presenting.html\" rel=\"nofollow noreferrer\">an article</a> around MVP in .NET, if you want to roll your own.</p>\n\n<p>Ideally you want to look at the MVC framework as an example of what you can do when you separate out everything.</p>\n\n<p>What I normally do is have the button click event raise a domain-specific event, something like:</p>\n\n<pre><code>\nprivate void ControlA_OnClick(..)\n{\n if(LoginRequested != null)\n LoginRequested(this, loginObj);\n}\n</code></pre>\n\n<p>That way it makes it clear why someone would click the button and drives home the separation.</p>\n"
},
{
"answer_id": 282131,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 2,
"selected": true,
"text": "<p>What you have is pretty much an <a href=\"http://msforge.net/blogs/paki/archive/2007/11/20/EventBroker-implementation-in-C_2300_-full-source-code.aspx\" rel=\"nofollow noreferrer\">EventBroker</a>. I don't think Session is the appropiate place for this, as it's not necessary to live across requests. <a href=\"http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx\" rel=\"nofollow noreferrer\">HttpContext</a> might work, but unless I wanted the message bus to be shared between IHttpModules and IHttpHandlers, I'd probably just either use a base Page class that custom controls can cast their Page instance to:</p>\n\n<pre><code>interface IEventBroker {\n void Send(Message m);\n}\n\nclass ControlA {\n void MyButton_Click(object sender, EventArgs e) {\n var eb = this.Page as IEventBroker;\n if (eb != null) eb.Send(new Message());\n }\n}\n</code></pre>\n\n<p>or give the controls a reference to the EventBroker - in which case I'd probably make the EventBroker itself a control and give the ID to each control so that they could use Page.FindControl.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281664",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7140/"
] |
Imagine the following scenario - we have Page1 which contains controls Control A and Control B.
Say Control A has a button, and on the click of this button we want Control B to react.
But we want to do this in an abstract fashion, i.e. we can't have Control B knowing anything about Control A, and vice versa.
That way we can develop these controls in isolation, and drive them by unit-testing.
Now, I thought I had the solution, just want to know what you guys think of it.
On Control A's button click, I put a 'message' on the Session, i.e. Session["MESSAGES"] = "ControlA\_Click".
In Page1, on the Page\_LoadComplete(), I put a call to ProcessMessages, which looks like this:
```
List<Message> messages = SessionMessages.GetMessageList(Page);
foreach(Message m in messages)
{
//Get Controls
ControlA controlA = FindControl("controlA") as ControlA;
controlA .ProcessMessage(m);
ControlB controlB = FindControl("controlB") as ControlB;
controlB.ProcessMessage(m);
}
```
in ControlB's ProcessMessage() method, we can react to the messages that ControlB is interested in, like so:
```
if (m.MessageName == SessionMessages.C_MESSAGE_SEARCH)
{
this.Visible = true;
}
```
To me, this seems to work. It allows us to develop these controls completely separately from eachother, while still allowing for inter-control-communication at an abstract level.
The only thing I can think of that might bring this crashing down is *perhaps* the ASP.NET life-cycle in relation to Pages and User Controls. The way I figure it though is that ALL events should have been processed on the controls before Page\_LoadComplete() is called on the owning Page.
Thoughts?
|
What you have is pretty much an [EventBroker](http://msforge.net/blogs/paki/archive/2007/11/20/EventBroker-implementation-in-C_2300_-full-source-code.aspx). I don't think Session is the appropiate place for this, as it's not necessary to live across requests. [HttpContext](http://msdn.microsoft.com/en-us/library/system.web.httpcontext.items.aspx) might work, but unless I wanted the message bus to be shared between IHttpModules and IHttpHandlers, I'd probably just either use a base Page class that custom controls can cast their Page instance to:
```
interface IEventBroker {
void Send(Message m);
}
class ControlA {
void MyButton_Click(object sender, EventArgs e) {
var eb = this.Page as IEventBroker;
if (eb != null) eb.Send(new Message());
}
}
```
or give the controls a reference to the EventBroker - in which case I'd probably make the EventBroker itself a control and give the ID to each control so that they could use Page.FindControl.
|
281,682 |
<p>I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity</p>
<pre><code>XmlDocument xmldoc = new XmlDocument();
string text = "Hello, I am text &alpha; &nbsp; &ndash; &mdash;"
xmldoc.InnerXml = "<p>" + text + "</p>";
</code></pre>
<p>This throws the exception: </p>
<blockquote>
<p>Reference to undeclared entity 'alpha'. Line 2, position 2.. </p>
</blockquote>
<p>How would I go about solving this problem?</p>
|
[
{
"answer_id": 281686,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>Try replacing &Alpha with </p>\n\n<pre><code> &#913;\n</code></pre>\n"
},
{
"answer_id": 281703,
"author": "Stephan Leclercq",
"author_id": 34838,
"author_profile": "https://Stackoverflow.com/users/34838",
"pm_score": 6,
"selected": true,
"text": "<p>XML, unlike HTML does not define entities (ie named references to UNICODE characters) so &alpha; &mdash; etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use &lt; and &amp; in XML</p>\n\n<p>If you want to create HTML, use an HtmlDocument instead.</p>\n"
},
{
"answer_id": 281739,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 3,
"selected": false,
"text": "<p>The preceding answer is right. Another alternative is to link your html document to the DTD where those character entities are defined, and that is standard XHTML DTD definition. Your xml file should include the following declaration:</p>\n\n<pre><code> <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n</code></pre>\n"
},
{
"answer_id": 281751,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "<p>You could also set the InnerText to <code>\"Hello, I am text α – —\"</code>, making the XmlDocument escape them automatically. I think.</p>\n"
},
{
"answer_id": 842836,
"author": "LandedGently",
"author_id": 103965,
"author_profile": "https://Stackoverflow.com/users/103965",
"pm_score": 4,
"selected": false,
"text": "<p>In .Net, you can use the <code>System.Xml.XmlConvert</code> class:</p>\n\n<pre><code>string text = XmlConvert.EncodeName(\"Hello &alpha;\");\n</code></pre>\n\n<p>Alternatively, you can declare the entities locally by putting the declarations between square brackets in a DOCTYPE declaration. Add the following header to your xml:</p>\n\n<pre><code><!DOCTYPE documentElement[\n<!ENTITY Alpha \"&#913;\">\n<!ENTITY ndash \"&#8211;\">\n<!ENTITY mdash \"&#8212;\">\n]>\n</code></pre>\n\n<p>Do a google on \"html character entities\" for the entity definitions.</p>\n"
},
{
"answer_id": 2285004,
"author": "Nick Josevski",
"author_id": 75963,
"author_profile": "https://Stackoverflow.com/users/75963",
"pm_score": 0,
"selected": false,
"text": "<p>The use of a HtmlDocument wasn't suitable in my situation, our system had a custom XmlUrlResolver which we made use of for loading the xml.</p>\n\n<pre><code>//setup\npublic class CustomXmlResolver : XmlUrlResolver { /* ... */ }\nString originalXml; //fetched xml with html entities in it\n\nvar doc = new XmlDocument();\ndoc.XmlResolver = new AdCastXmlResolver();\n\n//making use of a transitional dtd\ndoc.LoadXml(\"<!DOCTYPE html SYSTEM \\\"xhtml1-transitional.dtd\\\" > \" + originalXml);\n</code></pre>\n"
},
{
"answer_id": 22090784,
"author": "verbedr",
"author_id": 1077228,
"author_profile": "https://Stackoverflow.com/users/1077228",
"pm_score": 2,
"selected": false,
"text": "<p>Use string System.Net.WebUtility.HtmlDecode(string) which will decode all HTML entity encoded characters to its Unicode variant. It is available from dot.net framework 4</p>\n"
},
{
"answer_id": 34587281,
"author": "dret",
"author_id": 5705032,
"author_profile": "https://Stackoverflow.com/users/5705032",
"pm_score": 0,
"selected": false,
"text": "<p>If you do want to use the HTML entity names you are used to, the W3C has got you covered and has produced \"XML Entity Definitions for Characters\" <a href=\"http://www.w3.org/TR/xml-entity-names/\" rel=\"nofollow\">http://www.w3.org/TR/xml-entity-names/</a>, which essentially is a list of named entities very similar to the ones that HTML has. But as mentioned above, this is not built into XML, and needs to be explicitly supported by XML applications that want to use these named entities.</p>\n"
},
{
"answer_id": 66313035,
"author": "Felix Sasaki",
"author_id": 15178054,
"author_profile": "https://Stackoverflow.com/users/15178054",
"pm_score": 1,
"selected": false,
"text": "<p>A variant of the solution described at\n<a href=\"https://stackoverflow.com/a/842836/15178054\">https://stackoverflow.com/a/842836/15178054</a>\nis: Declare the entities in a separate file, and then reference that file from the XML declaration subset. Here is an example for how to use HTML entities in an XSLT stylesheet.</p>\n<pre><code><!DOCTYPE xsl:stylesheet\n[\n<!ENTITY % htmlentities SYSTEM "html-entity-list.ent">\n%htmlentities;\n]>\n<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"...>\n</code></pre>\n<p>The external file with entities is "html-entitiy-list.ent". I have generated it from <a href=\"https://html.spec.whatwg.org/entities.json\" rel=\"nofollow noreferrer\">https://html.spec.whatwg.org/entities.json</a> . An example entry in the generated file is this one:</p>\n<pre><code><!ENTITY Auml "Ä">\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281682",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6201/"
] |
I am trying to set the innerxml of a xmldoc but get the exception: Reference to undeclared entity
```
XmlDocument xmldoc = new XmlDocument();
string text = "Hello, I am text α – —"
xmldoc.InnerXml = "<p>" + text + "</p>";
```
This throws the exception:
>
> Reference to undeclared entity 'alpha'. Line 2, position 2..
>
>
>
How would I go about solving this problem?
|
XML, unlike HTML does not define entities (ie named references to UNICODE characters) so α — etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use < and & in XML
If you want to create HTML, use an HtmlDocument instead.
|
281,694 |
<p>I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:</p>
<pre><code><rp:do-something runat="server" id="doSomething1" /></code></pre>
<p>I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the <a href="http://msdn.microsoft.com/en-us/library/ms164641.aspx" rel="nofollow noreferrer" title="tagMapping Element">tagMapping element</a> doesn't quite match up for what I'd like to do.</p>
|
[
{
"answer_id": 281686,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": false,
"text": "<p>Try replacing &Alpha with </p>\n\n<pre><code> &#913;\n</code></pre>\n"
},
{
"answer_id": 281703,
"author": "Stephan Leclercq",
"author_id": 34838,
"author_profile": "https://Stackoverflow.com/users/34838",
"pm_score": 6,
"selected": true,
"text": "<p>XML, unlike HTML does not define entities (ie named references to UNICODE characters) so &alpha; &mdash; etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use &lt; and &amp; in XML</p>\n\n<p>If you want to create HTML, use an HtmlDocument instead.</p>\n"
},
{
"answer_id": 281739,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 3,
"selected": false,
"text": "<p>The preceding answer is right. Another alternative is to link your html document to the DTD where those character entities are defined, and that is standard XHTML DTD definition. Your xml file should include the following declaration:</p>\n\n<pre><code> <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\n \"http://www.w3.org/TR/html4/strict.dtd\">\n</code></pre>\n"
},
{
"answer_id": 281751,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 0,
"selected": false,
"text": "<p>You could also set the InnerText to <code>\"Hello, I am text α – —\"</code>, making the XmlDocument escape them automatically. I think.</p>\n"
},
{
"answer_id": 842836,
"author": "LandedGently",
"author_id": 103965,
"author_profile": "https://Stackoverflow.com/users/103965",
"pm_score": 4,
"selected": false,
"text": "<p>In .Net, you can use the <code>System.Xml.XmlConvert</code> class:</p>\n\n<pre><code>string text = XmlConvert.EncodeName(\"Hello &alpha;\");\n</code></pre>\n\n<p>Alternatively, you can declare the entities locally by putting the declarations between square brackets in a DOCTYPE declaration. Add the following header to your xml:</p>\n\n<pre><code><!DOCTYPE documentElement[\n<!ENTITY Alpha \"&#913;\">\n<!ENTITY ndash \"&#8211;\">\n<!ENTITY mdash \"&#8212;\">\n]>\n</code></pre>\n\n<p>Do a google on \"html character entities\" for the entity definitions.</p>\n"
},
{
"answer_id": 2285004,
"author": "Nick Josevski",
"author_id": 75963,
"author_profile": "https://Stackoverflow.com/users/75963",
"pm_score": 0,
"selected": false,
"text": "<p>The use of a HtmlDocument wasn't suitable in my situation, our system had a custom XmlUrlResolver which we made use of for loading the xml.</p>\n\n<pre><code>//setup\npublic class CustomXmlResolver : XmlUrlResolver { /* ... */ }\nString originalXml; //fetched xml with html entities in it\n\nvar doc = new XmlDocument();\ndoc.XmlResolver = new AdCastXmlResolver();\n\n//making use of a transitional dtd\ndoc.LoadXml(\"<!DOCTYPE html SYSTEM \\\"xhtml1-transitional.dtd\\\" > \" + originalXml);\n</code></pre>\n"
},
{
"answer_id": 22090784,
"author": "verbedr",
"author_id": 1077228,
"author_profile": "https://Stackoverflow.com/users/1077228",
"pm_score": 2,
"selected": false,
"text": "<p>Use string System.Net.WebUtility.HtmlDecode(string) which will decode all HTML entity encoded characters to its Unicode variant. It is available from dot.net framework 4</p>\n"
},
{
"answer_id": 34587281,
"author": "dret",
"author_id": 5705032,
"author_profile": "https://Stackoverflow.com/users/5705032",
"pm_score": 0,
"selected": false,
"text": "<p>If you do want to use the HTML entity names you are used to, the W3C has got you covered and has produced \"XML Entity Definitions for Characters\" <a href=\"http://www.w3.org/TR/xml-entity-names/\" rel=\"nofollow\">http://www.w3.org/TR/xml-entity-names/</a>, which essentially is a list of named entities very similar to the ones that HTML has. But as mentioned above, this is not built into XML, and needs to be explicitly supported by XML applications that want to use these named entities.</p>\n"
},
{
"answer_id": 66313035,
"author": "Felix Sasaki",
"author_id": 15178054,
"author_profile": "https://Stackoverflow.com/users/15178054",
"pm_score": 1,
"selected": false,
"text": "<p>A variant of the solution described at\n<a href=\"https://stackoverflow.com/a/842836/15178054\">https://stackoverflow.com/a/842836/15178054</a>\nis: Declare the entities in a separate file, and then reference that file from the XML declaration subset. Here is an example for how to use HTML entities in an XSLT stylesheet.</p>\n<pre><code><!DOCTYPE xsl:stylesheet\n[\n<!ENTITY % htmlentities SYSTEM "html-entity-list.ent">\n%htmlentities;\n]>\n<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"...>\n</code></pre>\n<p>The external file with entities is "html-entitiy-list.ent". I have generated it from <a href=\"https://html.spec.whatwg.org/entities.json\" rel=\"nofollow noreferrer\">https://html.spec.whatwg.org/entities.json</a> . An example entry in the generated file is this one:</p>\n<pre><code><!ENTITY Auml "Ä">\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34224/"
] |
I want to set up an ASP.NET custom control such that it has a custom name, specifically, with a hyphen within it, so it might look like this in markup:
```
<rp:do-something runat="server" id="doSomething1" />
```
I don't mind if this syntax requires setting up a tag mapping in web.config or something to that effect, but the [tagMapping element](http://msdn.microsoft.com/en-us/library/ms164641.aspx "tagMapping Element") doesn't quite match up for what I'd like to do.
|
XML, unlike HTML does not define entities (ie named references to UNICODE characters) so α — etc. are not translated to their corresponding character. You must use the numerical value instead. You can only use < and & in XML
If you want to create HTML, use an HtmlDocument instead.
|
281,697 |
<p>I used code like this to find the remote user name:</p>
<pre><code>banner_label.Text = "Welcome, <B>" + User.Identity.Name + "</B>!"
</code></pre>
<p>I'd also like to find the remote host name.
My production environment will be a corporate intranet with active directory.</p>
|
[
{
"answer_id": 281732,
"author": "John Boker",
"author_id": 2847,
"author_profile": "https://Stackoverflow.com/users/2847",
"pm_score": 0,
"selected": false,
"text": "<p>maybe this would work for you</p>\n\n<pre><code>Request.UserHostName\n</code></pre>\n\n<p>edit:</p>\n\n<p>i think what you're trying to do will not working over the internet, what you're trying to get is the name of the computer, which will not be transmitted with the request to the server.</p>\n"
},
{
"answer_id": 281742,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 1,
"selected": false,
"text": "<p>I believe you can use <code>HttpContext.Current.Request.ServerVariables[\"REMOTE_HOST\"]</code>, but be warned that the information is pretty unreliable. Anything being sent to you can be spoofed.</p>\n\n<p>Also, I don't think this will work over the internet.</p>\n"
},
{
"answer_id": 281746,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I googled around and found Request.UserHostName, but this only returned 127.0.0.1 in my development environment.</p>\n\n<p>I tried this</p>\n\n<pre><code>System.Net.DNS.GetHostName\n</code></pre>\n\n<p>And that returned my hostname successfully. However since I'm still in dev, with my client and server on the same machine, I still need to test to make sure its actually giving me the remote host name instead of the server's name.</p>\n"
},
{
"answer_id": 282073,
"author": "sliderhouserules",
"author_id": 31385,
"author_profile": "https://Stackoverflow.com/users/31385",
"pm_score": 2,
"selected": false,
"text": "<p>You're on an Intranet, so Request.UserHostName should work well for you. If you have a complex network, some of the routers may not let that info through, but...</p>\n\n<p>Here's something similar I did in an app at a previous job, to record the IP and host name:</p>\n\n<pre><code>// NAT'ed addresses are sometimes still shown in HTTP_X_FORWARDED_FOR\nstring userHost = Request.ServerVariables[\"HTTP_X_FORWARDED_FOR\"];\n\nif (String.IsNullOrEmpty(userHost) || String.Compare(userHost, \"unknown\", true) == 0)\n userHost = Request.UserHostAddress;\n\nif (String.Compare(userHost, Request.UserHostName) != 0)\n userHost += \" (\" + Request.UserHostName + \")\";\n</code></pre>\n\n<p>I then record this string in the database with every login attempt.</p>\n\n<hr>\n\n<p>Edit: Skimmed over your reply above... thought this code did what you're asking for, let me go test it and see.</p>\n\n<hr>\n\n<p>Not sure why that code above worked at my previous job. It wasn't reliable, which is why I put that if statement around it, but I thought it returned the host name semi-reliably... Posts online say it has something to do with anonymous access.</p>\n\n<p>Anyway, this gets you what you want, and should work reliably since you're on an Intranet:</p>\n\n<pre><code>System.Net.Dns.GetHostEntry(userHost).HostName\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281697",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I used code like this to find the remote user name:
```
banner_label.Text = "Welcome, <B>" + User.Identity.Name + "</B>!"
```
I'd also like to find the remote host name.
My production environment will be a corporate intranet with active directory.
|
You're on an Intranet, so Request.UserHostName should work well for you. If you have a complex network, some of the routers may not let that info through, but...
Here's something similar I did in an app at a previous job, to record the IP and host name:
```
// NAT'ed addresses are sometimes still shown in HTTP_X_FORWARDED_FOR
string userHost = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (String.IsNullOrEmpty(userHost) || String.Compare(userHost, "unknown", true) == 0)
userHost = Request.UserHostAddress;
if (String.Compare(userHost, Request.UserHostName) != 0)
userHost += " (" + Request.UserHostName + ")";
```
I then record this string in the database with every login attempt.
---
Edit: Skimmed over your reply above... thought this code did what you're asking for, let me go test it and see.
---
Not sure why that code above worked at my previous job. It wasn't reliable, which is why I put that if statement around it, but I thought it returned the host name semi-reliably... Posts online say it has something to do with anonymous access.
Anyway, this gets you what you want, and should work reliably since you're on an Intranet:
```
System.Net.Dns.GetHostEntry(userHost).HostName
```
|
281,698 |
<p>I just don't get it. Tried on VC++ 2008 and G++ 4.3.2</p>
<pre><code>#include <map>
class A : public std::multimap<int, bool>
{
public:
size_type erase(int k, bool v)
{
return erase(k); // <- this fails; had to change to __super::erase(k)
}
};
int main()
{
A a;
a.erase(0, false);
a.erase(0); // <- fails. can't find base class' function?!
return 0;
}
</code></pre>
|
[
{
"answer_id": 281707,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 6,
"selected": true,
"text": "<p>When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should <em>stop looking</em> for the function you are trying to call once it finds the first match. After finding the function by name, <em>then</em> it applies the overload resolution rules.</p>\n\n<p>So what is happening is the compiler finds your implementation of <code>erase(int, bool)</code> when you call <code>erase(0)</code>, and then decides that the arguments don't match.</p>\n"
},
{
"answer_id": 281708,
"author": "Marcin",
"author_id": 22724,
"author_profile": "https://Stackoverflow.com/users/22724",
"pm_score": 3,
"selected": false,
"text": "<p>First of all, you should never derive from STL containers, because no STL containers define a virtual destructor.<br>\nSecond of all, see Greg's answer about inheritance.</p>\n"
},
{
"answer_id": 281734,
"author": "J Francis",
"author_id": 19169,
"author_profile": "https://Stackoverflow.com/users/19169",
"pm_score": 3,
"selected": false,
"text": "<p>You've hidden the base class's erase member function by defining a function in the derived class with the same name but different arguments.</p>\n\n<p><a href=\"http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9\" rel=\"nofollow noreferrer\">http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.9</a></p>\n"
},
{
"answer_id": 281738,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 4,
"selected": false,
"text": "<p>1: You need to be <em>extremely</em> careful when deriving from C++ standard library containers. It can be done, but because they don't have virtual destructors and other such niceties, it is usually the wrong approach.</p>\n\n<p>2: Overload rules are a bit quirky here. The compiler first looks in the derived class, and if it finds <em>any</em> overload with the same name, it stops looking there. It only looks in the base class if no overloads were found in the derived class.</p>\n\n<p>A simple solution to that is to introduce the functions you need from the base class into the derived class' namespace:</p>\n\n<pre><code>class A : public std::multimap<int, bool>\n{\npublic:\n using std::multimap<int, bool>::erase; // Any erase function found in the base class should be injected into the derived class namespace as well\n size_type erase(int k, bool v)\n {\n return erase(k);\n }\n};\n</code></pre>\n\n<p>Alternatively, of course, you could simply write a small helper function in the derived class redirecting to the base class function</p>\n"
},
{
"answer_id": 281904,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 0,
"selected": false,
"text": "<p>To replace __super in a portable way, define a typedef at the top of your class like this:</p>\n\n<pre><code>typedef std::multimap<int, bool> parent;\npublic:\n size_type erase(int k, bool v)\n {\n return parent::erase(k);\n }\n</code></pre>\n\n<p>It does not need to be \"parent\" of course. It could be any name you like, as long as it is used consistently throughout your project.</p>\n"
},
{
"answer_id": 281927,
"author": "Enno",
"author_id": 30404,
"author_profile": "https://Stackoverflow.com/users/30404",
"pm_score": 3,
"selected": false,
"text": "<p>Think whether you really want to inherit from std::map. In all the time I've written code, and that's longer than STL exists, I've never seen an instance where inheriting from a std::container was the best solution.</p>\n\n<p>Specifically, ask yourself whether your class <strong>IS</strong> a multimap or <strong>HAS</strong> a multimap.</p>\n"
},
{
"answer_id": 281948,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 2,
"selected": false,
"text": "<p>Others have answered how to resolve the syntax problem and why it can be dangerous to derive from standard classes, but it's also worth pointing out:</p>\n\n<p><strong>Prefer composition to inheritance.</strong></p>\n\n<p>I doubt you mean for 'A' to explicitly have the \"is-a\" relationship to multimap< int, bool >. <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321113586\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">C++ Coding Standards</a> by Sutter/Alexandrescu has entire chapter on this (#34), and <a href=\"http://www.google.com/search?q=Prefer+composition+to+inheritance\" rel=\"nofollow noreferrer\">Google points to many good references</a> on the subject.</p>\n\n<p>It appears there is a <a href=\"https://stackoverflow.com/questions/49002/prefer-composition-over-inheritance\">SO thread on the topic as well</a>.</p>\n"
},
{
"answer_id": 281982,
"author": "bradtgmurray",
"author_id": 1546,
"author_profile": "https://Stackoverflow.com/users/1546",
"pm_score": 1,
"selected": false,
"text": "<p>For those that use <a href=\"https://rads.stackoverflow.com/amzn/click/com/0321334876\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Effective C++</a> as a C++ programming reference, this issue is covered in Item 33 (Avoid hiding inherited names.) in the book.</p>\n"
},
{
"answer_id": 286759,
"author": "Andy Balaam",
"author_id": 22610,
"author_profile": "https://Stackoverflow.com/users/22610",
"pm_score": 1,
"selected": false,
"text": "<p>I agree with others' comments that you need to be very careful inheriting from STL classes, and it should almost always be avoided.</p>\n\n<p>However, this problem could arise with some other base class from which it's perfectly sensible to inherit.</p>\n\n<p>My question is: why not give your 2-argument function a different name? If it takes different arguments, presumably it has a slightly different meaning? E.g. erase_if_true or erase_and_delete or whatever the bool means.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281698",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21704/"
] |
I just don't get it. Tried on VC++ 2008 and G++ 4.3.2
```
#include <map>
class A : public std::multimap<int, bool>
{
public:
size_type erase(int k, bool v)
{
return erase(k); // <- this fails; had to change to __super::erase(k)
}
};
int main()
{
A a;
a.erase(0, false);
a.erase(0); // <- fails. can't find base class' function?!
return 0;
}
```
|
When you declare a function in a class with the same name but different signature from a superclass, then the name resolution rules state that the compiler should *stop looking* for the function you are trying to call once it finds the first match. After finding the function by name, *then* it applies the overload resolution rules.
So what is happening is the compiler finds your implementation of `erase(int, bool)` when you call `erase(0)`, and then decides that the arguments don't match.
|
281,706 |
<p>I'm having an issue dragging a file from Windows Explorer on to a Windows Forms application. </p>
<p>It works fine when I drag text, but for some reason it is not recognizing the file. Here is my test code:</p>
<pre><code>namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}
</code></pre>
<p>AllowDrop is set to true on Form1, and as I mentioned, it works if I drag text on to the form, just not an actual file.</p>
<p>I'm using Vista 64-bit ... not sure if that is part of the problem.</p>
|
[
{
"answer_id": 281770,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 0,
"selected": false,
"text": "<p>The code you posted <em>should</em> work.</p>\n\n<p>Try putting this at the beginning of the DragEnter method</p>\n\n<pre><code>string formats = string.Join( \"\\n\", e.Data.GetFormats(false) );\nMessageBox.Show( formats );\n</code></pre>\n\n<p>which will dump data formats associated with the d'n'd operation. Might help us narrowing down where the problem lies.</p>\n"
},
{
"answer_id": 282279,
"author": "mattruma",
"author_id": 1768,
"author_profile": "https://Stackoverflow.com/users/1768",
"pm_score": 0,
"selected": false,
"text": "<p>I added the code that <a href=\"https://stackoverflow.com/questions/281706/drag-and-drop-from-windows-file-explorer-onto-a-windows-form-is-not-working#281770\">arul</a> mentioned and things still didn't work, but it got me thinking. </p>\n\n<p>I started thinking it might be a Vista issue so I sent it to a friend that had Windows XP and it worked great! I then tried running it outside of the Release folder in the bin directory and what do you know it worked! </p>\n\n<p>The only time it does not work is when I am running it inside the Visual Studio 2008 IDE ... that's just weird.</p>\n"
},
{
"answer_id": 288146,
"author": "Gene",
"author_id": 16662,
"author_profile": "https://Stackoverflow.com/users/16662",
"pm_score": 5,
"selected": true,
"text": "<p>The problem comes from Vista's <a href=\"http://en.wikipedia.org/wiki/User_Account_Control\" rel=\"noreferrer\">UAC</a>. DevStudio is running as administrator, but explorer is running as a regular user. When you drag a file from explorer and drop it on your DevStudio hosted application, that is the same as a non-privileged user trying to communicate with a privileged user. It's not allowed.</p>\n\n<p>This will probably not show up when you run the app outside of the debugger. Unless you run it as an administrator there (or if Vista auto-detects that it's an installer/setup app). </p>\n\n<p>You could also <a href=\"http://www.neowin.net/forum/lofiversion/index.php/t575104.html\" rel=\"noreferrer\">run explorer as an admin</a>, at least for testing. Or disable UAC (which I would not recommend, since you really want to catch these issues during development, not during deployment!)</p>\n"
},
{
"answer_id": 12625720,
"author": "k3b",
"author_id": 519334,
"author_profile": "https://Stackoverflow.com/users/519334",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try to add the <code>STAThread</code> attribute to the main method?</p>\n\n<pre><code> [STAThread]\n static void Main(string[] args)\n {\n }\n</code></pre>\n\n<p>I had the same problem as @mattruma meaning i got not Drag&Drop events.\nAfter adding the <code>STAThread</code> attribute to the main method it worked as expected.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1768/"
] |
I'm having an issue dragging a file from Windows Explorer on to a Windows Forms application.
It works fine when I drag text, but for some reason it is not recognizing the file. Here is my test code:
```
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_DragDrop(object sender, DragEventArgs e)
{
}
private void Form1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effect = DragDropEffects.Copy;
}
else if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
e.Effect = DragDropEffects.Copy;
}
else
{
e.Effect = DragDropEffects.None;
}
}
}
}
```
AllowDrop is set to true on Form1, and as I mentioned, it works if I drag text on to the form, just not an actual file.
I'm using Vista 64-bit ... not sure if that is part of the problem.
|
The problem comes from Vista's [UAC](http://en.wikipedia.org/wiki/User_Account_Control). DevStudio is running as administrator, but explorer is running as a regular user. When you drag a file from explorer and drop it on your DevStudio hosted application, that is the same as a non-privileged user trying to communicate with a privileged user. It's not allowed.
This will probably not show up when you run the app outside of the debugger. Unless you run it as an administrator there (or if Vista auto-detects that it's an installer/setup app).
You could also [run explorer as an admin](http://www.neowin.net/forum/lofiversion/index.php/t575104.html), at least for testing. Or disable UAC (which I would not recommend, since you really want to catch these issues during development, not during deployment!)
|
281,719 |
<p>I am quantitatively studying various metrics associated with automated tests. Chrome seems to have a reasonable set, so I wanted to add it to my data set. I downloaded the Chrome source code and tried to build it with VisualStudio but got several hundred errors--types not defined, identifiers not defined, etc. Has anyone out there succeeded in building Chrome under Windows? Are there tricks I need to know?</p>
|
[
{
"answer_id": 281736,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 3,
"selected": true,
"text": "<p>From the Chromium dev page:</p>\n<h1>Compilation failures</h1>\n<p>Some common things to think about when you have weird compilation failures:</p>\n<ul>\n<li>Make sure you have SP1 for Visual Studio 2005. It's required. Really.</li>\n<li>Sometimes Visual Studio does the wrong thing when building Chromium and gets stuck on a bogus error. A good indication of this is if it is only failing for one person but others (including the Buildbots) are not complaining. To resolve this, try the following steps:\n<ul>\n<li>Close Visual Studio.</li>\n<li>Sync to the tip of tree and ensure there are no conflicts ("svn st" should not show any "C"s in front of files that you've changed).</li>\n<li>If there were conflicts, sync again after resolving them.</li>\n<li>Manually erase the output directory (chrome\\Debug and chrome\\Release. Using the command line, you can use "erase /S /Q Debug Release" from the chrome directory to do this, or "rm -rf Debug Release" if you have Unix-like tools installed.</li>\n<li>Restart Visual Studio and open the Chromium solution.</li>\n<li>Rebuild the solution.</li>\n</ul>\n</li>\n</ul>\n<p>If it still doesn't work, repeating this process probably won't help.</p>\n<h1>chrome_kjs.sln tempfile problems</h1>\n<p>If, while building JavaScriptCore, you see errors like:</p>\n<pre><code>3>Error in tempfile() using /tmp/dftables-XXXXXXXX.in: Parent directory (/tmp/) is not writable\n3> at /cygdrive/c/b/slave/WEBKIT~1/build/webkit/third_party/JavaScriptCore/pcre/dftables line 236\n3>make: *** [chartables.c] Error 255\n</code></pre>\n<p>...it's because the Cygwin installation included in the Chromium source is having trouble mapping the NT ACL to POSIX permissions. This seems to happen when Chromium is checked out into a directory for which Cygwin can't figure out the permissions in the first place, possibly when the directory is created from within a Cygwin environment before running mkpasswd. Cygwin then imposes its own access control, which is incorrectly restrictive. As a workaround, do one of the following:</p>\n<ul>\n<li><p>Edit the NT permissions on third_party\\cygwin\\tmp to allow Modify and Write actions for Everyone and machine\\Users. Cygwin is able to figure this out. Or,</p>\n</li>\n<li><p>Figure out what went wrong with your checkout and try again - try doing the checkout from cmd instead of from a Cygwin shell, then verify that the permissions aren't completely blank in your Cygwin installation. Or,</p>\n</li>\n<li><p>Bypass Cygwin's access control (NT's will still be in effect) by editing webkit\\build\\JavaScriptCore\\prebuild.bat and webkit\\build\\WebCore\\prebuild.bat to include the following line before invoking anything that uses Cygwin:</p>\n<pre><code> set CYGWIN=nontsec\n</code></pre>\n</li>\n</ul>\n<p>Only one of these solutions should be needed.</p>\n"
},
{
"answer_id": 3210772,
"author": "UmairP",
"author_id": 387497,
"author_profile": "https://Stackoverflow.com/users/387497",
"pm_score": 0,
"selected": false,
"text": "<p>I have been able to build Chrome many times. I have comprehensive material if you want to see \n<a href=\"http://blog.umairp.com/index.php/2010/07/building-chrome-in-windows-7-using-visual-studio-net-2008/\" rel=\"nofollow noreferrer\">Building Chrome in Windows 7 using Visual Studio.NET 2008</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13842/"
] |
I am quantitatively studying various metrics associated with automated tests. Chrome seems to have a reasonable set, so I wanted to add it to my data set. I downloaded the Chrome source code and tried to build it with VisualStudio but got several hundred errors--types not defined, identifiers not defined, etc. Has anyone out there succeeded in building Chrome under Windows? Are there tricks I need to know?
|
From the Chromium dev page:
Compilation failures
====================
Some common things to think about when you have weird compilation failures:
* Make sure you have SP1 for Visual Studio 2005. It's required. Really.
* Sometimes Visual Studio does the wrong thing when building Chromium and gets stuck on a bogus error. A good indication of this is if it is only failing for one person but others (including the Buildbots) are not complaining. To resolve this, try the following steps:
+ Close Visual Studio.
+ Sync to the tip of tree and ensure there are no conflicts ("svn st" should not show any "C"s in front of files that you've changed).
+ If there were conflicts, sync again after resolving them.
+ Manually erase the output directory (chrome\Debug and chrome\Release. Using the command line, you can use "erase /S /Q Debug Release" from the chrome directory to do this, or "rm -rf Debug Release" if you have Unix-like tools installed.
+ Restart Visual Studio and open the Chromium solution.
+ Rebuild the solution.
If it still doesn't work, repeating this process probably won't help.
chrome\_kjs.sln tempfile problems
=================================
If, while building JavaScriptCore, you see errors like:
```
3>Error in tempfile() using /tmp/dftables-XXXXXXXX.in: Parent directory (/tmp/) is not writable
3> at /cygdrive/c/b/slave/WEBKIT~1/build/webkit/third_party/JavaScriptCore/pcre/dftables line 236
3>make: *** [chartables.c] Error 255
```
...it's because the Cygwin installation included in the Chromium source is having trouble mapping the NT ACL to POSIX permissions. This seems to happen when Chromium is checked out into a directory for which Cygwin can't figure out the permissions in the first place, possibly when the directory is created from within a Cygwin environment before running mkpasswd. Cygwin then imposes its own access control, which is incorrectly restrictive. As a workaround, do one of the following:
* Edit the NT permissions on third\_party\cygwin\tmp to allow Modify and Write actions for Everyone and machine\Users. Cygwin is able to figure this out. Or,
* Figure out what went wrong with your checkout and try again - try doing the checkout from cmd instead of from a Cygwin shell, then verify that the permissions aren't completely blank in your Cygwin installation. Or,
* Bypass Cygwin's access control (NT's will still be in effect) by editing webkit\build\JavaScriptCore\prebuild.bat and webkit\build\WebCore\prebuild.bat to include the following line before invoking anything that uses Cygwin:
```
set CYGWIN=nontsec
```
Only one of these solutions should be needed.
|
281,725 |
<p>I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.</p>
<p>-edit-</p>
<p>I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.</p>
<pre><code>class SomeTag {};
class InheritSomeTag : public SomeTag {};
template <class T, class Tag=T>
struct MyClass
{
};
template <class T>
struct MyClass<T, SomeTag>
{
typedef int isSpecialized;
};
int main()
{
MyClass<SomeTag>::isSpecialized test1; //ok
MyClass<InheritSomeTag>::isSpecialized test2; //how do i make this specialized w/o changing main()
return 0;
}
</code></pre>
|
[
{
"answer_id": 281795,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>In your case, the only way that I see would be to explicitly specialize <code>MyClass</code> for <code>InheritSomeTag</code>. However, the <a href=\"http://www.biomedcentral.com/1471-2105/9/11/abstract\" rel=\"nofollow noreferrer\">SeqAn paper</a> proposes a mechanism called “template sublassing” that does what you want – albeit with a different inheritance syntax, so the code isn't compatible with your current <code>main</code> function.</p>\n\n<pre><code>// Base class\ntemplate <typename TSpec = void>\nclass SomeTag { };\n\n// Type tag, NOT part of the inheritance chain\ntemplate <typename TSpec = void>\nstruct InheritSomeTag { };\n\n// Derived class, uses type tag\ntemplate <typename TSpec>\nclass SomeTag<InheritSomeTag<TSpec> > : public SomeTag<void> { };\n\ntemplate <class T, class Tag=T>\nstruct MyClass { };\n\ntemplate <class T, typename TSpec>\nstruct MyClass<T, SomeTag<TSpec> >\n{\n typedef int isSpecialized;\n};\n\nint main()\n{\n MyClass<SomeTag<> >::isSpecialized test1; //ok\n MyClass<SomeTag<InheritSomeTag<> > >::isSpecialized test2; //ok\n}\n</code></pre>\n\n<p>This certainly looks strange and is very cumbersome but it allows a true inheritance mechanism with polymorphic functions that is executed at compile time. If you want to see this in action, have a look at some <a href=\"http://www.seqan.de/dddoc/html/INDEXPAGE_Demo.html\" rel=\"nofollow noreferrer\">SeqAn examples</a>.</p>\n\n<p>That being said, I believe that SeqAn is a special case and not many applications would profit from this extremely difficult syntax (deciphering SeqAn-related compiler errors is a real pain in the *ss!)</p>\n"
},
{
"answer_id": 281830,
"author": "Jesse Beder",
"author_id": 112,
"author_profile": "https://Stackoverflow.com/users/112",
"pm_score": 6,
"selected": true,
"text": "<p>This article describes a neat trick: <a href=\"http://www.gotw.ca/publications/mxc++-item-4.htm\" rel=\"noreferrer\">http://www.gotw.ca/publications/mxc++-item-4.htm</a></p>\n\n<p>Here's the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking):</p>\n\n<pre><code>template<typename D, typename B>\nclass IsDerivedFrom\n{\n class No { };\n class Yes { No no[3]; }; \n\n static Yes Test( B* ); // not defined\n static No Test( ... ); // not defined \n\n static void Constraints(D* p) { B* pb = p; pb = p; } \n\npublic:\n enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) }; \n\n IsDerivedFrom() { void(*p)(D*) = Constraints; }\n};\n</code></pre>\n\n<p>Then your MyClass needs an implementation that's potentially specialized:</p>\n\n<pre><code>template<typename T, int>\nclass MyClassImpl\n{\n // general case: T is not derived from SomeTag\n}; \n\ntemplate<typename T>\nclass MyClassImpl<T, 1>\n{\n // T is derived from SomeTag\n public:\n typedef int isSpecialized;\n}; \n</code></pre>\n\n<p>and MyClass actually looks like:</p>\n\n<pre><code>template<typename T>\nclass MyClass: public MyClassImpl<T, IsDerivedFrom<T, SomeTag>::Is>\n{\n};\n</code></pre>\n\n<p>Then your main will be fine the way it is:</p>\n\n<pre><code>int main()\n{\n MyClass<SomeTag>::isSpecialized test1; //ok\n MyClass<InheritSomeTag>::isSpecialized test2; //ok also\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 282006,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "<p>Well, the article in the answer above appeared in February 2002. While it works, today we know there are better ways. Alternatively, you can use <code>enable_if</code>:</p>\n\n<pre><code>template<bool C, typename T = void>\nstruct enable_if {\n typedef T type;\n};\n\ntemplate<typename T>\nstruct enable_if<false, T> { };\n\ntemplate<typename, typename>\nstruct is_same {\n static bool const value = false;\n};\n\ntemplate<typename A>\nstruct is_same<A, A> {\n static bool const value = true;\n};\n\ntemplate<typename B, typename D> \nstruct is_base_of { \n static D * create_d(); \n static char (& chk(B *))[1]; \n static char (& chk(...))[2]; \n static bool const value = sizeof chk(create_d()) == 1 && \n !is_same<B volatile const, \n void volatile const>::value;\n};\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T, typename = void>\nstruct MyClass { /* T not derived from SomeTag */ };\n\ntemplate<typename T>\nstruct MyClass<T, typename enable_if<is_base_of<SomeTag, T>::value>::type> {\n typedef int isSpecialized;\n};\n\nint main() {\n MyClass<SomeTag>::isSpecialized test1; /* ok */\n MyClass<InheritSomeTag>::isSpecialized test2; /* ok */\n}\n</code></pre>\n"
},
{
"answer_id": 25934222,
"author": "Carlo Wood",
"author_id": 1487069,
"author_profile": "https://Stackoverflow.com/users/1487069",
"pm_score": 5,
"selected": false,
"text": "<p>And the short version now, 2014, using C++-11:</p>\n\n<pre><code>#include <type_traits>\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T, bool = std::is_base_of<SomeTag, T>::value>\nstruct MyClass { };\n\ntemplate<typename T>\nstruct MyClass<T, true> {\n typedef int isSpecialized;\n};\n\nint main() {\n MyClass<SomeTag>::isSpecialized test1; /* ok */\n MyClass<InheritSomeTag>::isSpecialized test2; /* ok */\n}\n</code></pre>\n"
},
{
"answer_id": 73214685,
"author": "bonkt",
"author_id": 16036714,
"author_profile": "https://Stackoverflow.com/users/16036714",
"pm_score": 1,
"selected": false,
"text": "<p>Using concepts and the requires keyword from C++20 is an even simpler and more expressive way to do this without having to introduce a redundant boolean non-type template parameter like in C++11:</p>\n<pre><code>// C++20:\n#include <concepts>\n#include <iostream>\n\nstruct SomeTag { };\nstruct InheritSomeTag : SomeTag { };\n\ntemplate<typename T>\nstruct MyClass \n{ \n void Print()\n {\n std::cout << "Not derived from someTag\\n";\n }\n};\n\n// std::derived_from is a predefined concept already included in the STL\ntemplate<typename T>\n requires std::derived_from<T, SomeTag> \nstruct MyClass<T> \n{\n void Print()\n {\n std::cout << "derived from someTag\\n";\n }\n};\n\nint main() \n{\n MyClass<InheritSomeTag> test1;\n test1.Print(); // derived from someTag\n MyClass<int> test2; \n test2.Print(); // Not derived from someTag\n\n // Note how even the base tag itself returns true from std::derived_from:\n MyClass<SomeTag> test3; \n test3.Print(); // derived from someTag \n\n}\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I want to make this specialized w/o changing main. Is it possible to specialize something based on its base class? I hope so.
-edit-
I'll have several classes that inherit from SomeTag. I don't want to write the same specialization for each of them.
```
class SomeTag {};
class InheritSomeTag : public SomeTag {};
template <class T, class Tag=T>
struct MyClass
{
};
template <class T>
struct MyClass<T, SomeTag>
{
typedef int isSpecialized;
};
int main()
{
MyClass<SomeTag>::isSpecialized test1; //ok
MyClass<InheritSomeTag>::isSpecialized test2; //how do i make this specialized w/o changing main()
return 0;
}
```
|
This article describes a neat trick: <http://www.gotw.ca/publications/mxc++-item-4.htm>
Here's the basic idea. You first need an IsDerivedFrom class (this provides runtime and compile-time checking):
```
template<typename D, typename B>
class IsDerivedFrom
{
class No { };
class Yes { No no[3]; };
static Yes Test( B* ); // not defined
static No Test( ... ); // not defined
static void Constraints(D* p) { B* pb = p; pb = p; }
public:
enum { Is = sizeof(Test(static_cast<D*>(0))) == sizeof(Yes) };
IsDerivedFrom() { void(*p)(D*) = Constraints; }
};
```
Then your MyClass needs an implementation that's potentially specialized:
```
template<typename T, int>
class MyClassImpl
{
// general case: T is not derived from SomeTag
};
template<typename T>
class MyClassImpl<T, 1>
{
// T is derived from SomeTag
public:
typedef int isSpecialized;
};
```
and MyClass actually looks like:
```
template<typename T>
class MyClass: public MyClassImpl<T, IsDerivedFrom<T, SomeTag>::Is>
{
};
```
Then your main will be fine the way it is:
```
int main()
{
MyClass<SomeTag>::isSpecialized test1; //ok
MyClass<InheritSomeTag>::isSpecialized test2; //ok also
return 0;
}
```
|
281,743 |
<p>I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).</p>
<p>I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.</p>
|
[
{
"answer_id": 281753,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 3,
"selected": true,
"text": "<p>This should get you started. Test to see if the Address field matches this regex.</p>\n\n<pre><code>\"^P\\.?\\s?O\\.?\\sB[Oo][Xx].\"\n</code></pre>\n\n<p>Translation to English: That's a P at the beginning of the line, followed by an optional period and space, followed by an O, followed by an optional period, followed by a space, followed by \"Box\", followed by anything else.</p>\n"
},
{
"answer_id": 281756,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 3,
"selected": false,
"text": "<p>UPS also has tools that you can integrate to do this... that way you can verify an address exactly as to whether or not they will ship, what the cost would be, schedules, etc. I suggest visiting the UPS IT Solutions page for more information.</p>\n"
},
{
"answer_id": 281760,
"author": "John",
"author_id": 30006,
"author_profile": "https://Stackoverflow.com/users/30006",
"pm_score": 2,
"selected": false,
"text": "<p>You might be better off putting a disclaimer on the page warning that you can not ship to post office boxes, opposed to validating the input.</p>\n\n<p>More than likely if you do create a regex that catches most of the P.O. Box scenarios, there's a good chance it'll also catch things you weren't intending (i.e. a customer with a street name containing the letters 'p' 'o' and 'box')</p>\n"
},
{
"answer_id": 281808,
"author": "dkretz",
"author_id": 31641,
"author_profile": "https://Stackoverflow.com/users/31641",
"pm_score": 0,
"selected": false,
"text": "<p>I'd start with a regex ala Lizard (but use the \"ignore case\" flag :)), test on historical data, then iterate as you see what invalid inclusions and exclusions you see in testing.</p>\n"
},
{
"answer_id": 283158,
"author": "TAG",
"author_id": 36400,
"author_profile": "https://Stackoverflow.com/users/36400",
"pm_score": 0,
"selected": false,
"text": "<p>Most shipping providers (for example FedEx) will validate the shipping address. For example, with FedEx web services, there is a call to validate a shipping address and get the estimated cost. This not only ensures that the address is not a PO Box, but also makes sure that the rest of the address is valid.</p>\n"
},
{
"answer_id": 284572,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 0,
"selected": false,
"text": "<p>Regarding the OP's comment to Jason Coco's answer:</p>\n\n<p>Since you're in a position to add regex validation to the shipping address, I assume that you have control of the application (i.e., you have the source and can modify it). If that's the case, then you should have the ability to, on reciept of the submitted data, check whether it is to be shipped via USPS, FedEx, or UPS and submit a request to the appropriate shipper-specific address validator, gaining all the benefits suggested in Jason's answer.</p>\n\n<p>By making it shipper-specific, this would also allow you to avoid implementing one-size-fits-all rules, such as \"no PO boxes because UPS doesn't deliver to them\", even though the user can select non-UPS shippers who do deliver to PO boxes.</p>\n"
},
{
"answer_id": 1835159,
"author": "Evan Smith",
"author_id": 223166,
"author_profile": "https://Stackoverflow.com/users/223166",
"pm_score": 0,
"selected": false,
"text": "<p>What if it doesn't start with \"PO Box..\" or \"P.O. Box\" ?</p>\n\n<p>Example:</p>\n\n<p>John Schmidt |\nSilver Valley PO Box 3901 |\nWhereswaldoville, SI. 78946 </p>\n\n<p>I used an onblur event for the address field to use a javascript function, indexOf, to recognize the input.toUpperCase \"PO BOX\" || \"P.O\" that is >= 0.</p>\n\n<p>If either of these two searches are not found, the return is -1, otherwise, it will return the string's start position which will always be 0 or more.</p>\n\n<p>This will ensure that lazy typing, 'po box,' 'p.o box,' and as well as 'p.o. box' will be recognized. I suppose you could add 'po. box' as well.</p>\n\n<p>Anyway, the condition triggers an unobtrusive message to show that 'We can't ship to a PO Box address.\" It's a feature to not see it if it doesn't apply to you. Otherwise, for users who don't have js or css enabled, they'll just see the message. The only fail on this graceful degradation is if a user has css, but not js enabled (where they just won't see the message at all). I only came up with the solution today, but if I think of a better way, I'll come back to post it here.</p>\n"
},
{
"answer_id": 7588307,
"author": "bluescrubbie",
"author_id": 367902,
"author_profile": "https://Stackoverflow.com/users/367902",
"pm_score": 1,
"selected": false,
"text": "<p>Unfortunately, UPS's online software allows P.O. Boxes to go through, but will choke on them once they're in the shipping channel.\nIn our case, our cart abandonment rate went up when we tried to gracefully prevent P.O. Boxes. We found it much more cost effective to leave it alone, accept the sale, bring it to the attention of customer service, and let them resolve it.\nOf course, if you get a high incidence of P.O Boxes, this may not be the case for you. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281743",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13583/"
] |
I have a client which is shipping via UPS, and therefore cannot deliver to Post Office boxes. I would like to be able to validate customer address fields in order to prevent them from entering addresses which include a PO box. It would be best if this were implemented as a regex so that I could use a client-side regex validation control (ASP.NET).
I realize there's probably no way to get a 100% detection rate, I'm just looking for something that will work most of the time.
|
This should get you started. Test to see if the Address field matches this regex.
```
"^P\.?\s?O\.?\sB[Oo][Xx]."
```
Translation to English: That's a P at the beginning of the line, followed by an optional period and space, followed by an O, followed by an optional period, followed by a space, followed by "Box", followed by anything else.
|
281,744 |
<p>Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory.
But how should the specific prepared statements be defined after that?
Right now I'm only using a PoolingDataSource to get connections from the pool. How do I use the prepared statements from the pool?</p>
|
[
{
"answer_id": 282135,
"author": "Georgy Bolyuba",
"author_id": 4052,
"author_profile": "https://Stackoverflow.com/users/4052",
"pm_score": 4,
"selected": true,
"text": "<p>Well talking about getting connection from the pool vs getting \"not-pooled\" connection, do you have any change in your code :)? I bet you do not. Same way with prepared statements. Your code should not change. So, there is no useful code example to this.</p>\n\n<p>You should read docs for your JDBC Datasource implementation and see what developers have to say about pooling. There is no other source of reliable info on this.</p>\n\n<p>From <a href=\"http://commons.apache.org/dbcp/configuration.html\" rel=\"noreferrer\">here</a>:\nThis component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:</p>\n\n<pre><code>* public PreparedStatement prepareStatement(String sql)\n* public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)\n</code></pre>\n\n<p>So, you just keep using prepareStatement() call and your dbcp will in theory take care of pooling (i.e. if you are trying to create \"select * from users u where u.name like :id\", it will try to find this statement in the pool first)</p>\n"
},
{
"answer_id": 6016142,
"author": "sproketboy",
"author_id": 53069,
"author_profile": "https://Stackoverflow.com/users/53069",
"pm_score": 0,
"selected": false,
"text": "<p>Here's basic code I use.</p>\n\n<pre><code> GenericObjectPool connectionPool = new GenericObjectPool(null);\n connectionPool.setMinEvictableIdleTimeMillis(1000 * 60 * 30);\n connectionPool.setTimeBetweenEvictionRunsMillis(1000 * 60 * 30);\n connectionPool.setNumTestsPerEvictionRun(3);\n connectionPool.setTestOnBorrow(true);\n connectionPool.setTestWhileIdle(false);\n connectionPool.setTestOnReturn(false);\n\n props = new Properties();\n props.put(\"user\", username);\n props.put(\"password\", password);\n ConnectionFactory connectionFactory = new DriverManagerConnectionFactory(url, props);\n\n PoolableConnectionFactory poolableConnectionFactory = new PoolableConnectionFactory(connectionFactory, connectionPool, null, \"SELECT 1\", false, true);\n PoolingDataSource dataSource = new PoolingDataSource(connectionPool);\n</code></pre>\n"
},
{
"answer_id": 7038489,
"author": "Stanislav Bashkyrtsev",
"author_id": 886697,
"author_profile": "https://Stackoverflow.com/users/886697",
"pm_score": 0,
"selected": false,
"text": "<p>The thing is if you use a single <code>Connection</code>, it will cache <code>PreparedStatement</code>s whether you want this or not, the only possible way to impact on this is to use <code>DataSource</code> properties or to use vendor-specific API. But these statements are not visible by other connections and if you prepare the same statement using another connection, it will recreate it again. So Connection Pools like DBCP under the hood allow reusing of <code>PreparedStatement</code>s betwixt different connections (it uses <code>PooledConnection</code> interface instead of simple <code>Connection</code>), they keep track of all the statements prepared by all connections.</p>\n\n<p><strong>UPDATE:</strong> it seems I was wrong on this info, at least I couldn't find this functionality in C3P0. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12649/"
] |
Can someone explain how exactly prepared connection pooling using dbcp can be used? (with some example code if possible). I've figured out how to turn it on - passing a KeyedObjectPoolFactory to the PoolableConnectionFactory.
But how should the specific prepared statements be defined after that?
Right now I'm only using a PoolingDataSource to get connections from the pool. How do I use the prepared statements from the pool?
|
Well talking about getting connection from the pool vs getting "not-pooled" connection, do you have any change in your code :)? I bet you do not. Same way with prepared statements. Your code should not change. So, there is no useful code example to this.
You should read docs for your JDBC Datasource implementation and see what developers have to say about pooling. There is no other source of reliable info on this.
From [here](http://commons.apache.org/dbcp/configuration.html):
This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:
```
* public PreparedStatement prepareStatement(String sql)
* public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
```
So, you just keep using prepareStatement() call and your dbcp will in theory take care of pooling (i.e. if you are trying to create "select \* from users u where u.name like :id", it will try to find this statement in the pool first)
|
281,758 |
<p>I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree.</p>
<p>For example, if I have a controller <code>HomeController</code>, which needs to have a <code>LoginService</code> injected into it, then in my unit test <code>HomeControllerTest</code> I simply instantiate the object as normal (outside of Spring) and inject the property:</p>
<pre><code>protected void setUp() throws Exception {
super.setUp();
//...
controller = new HomeController();
controller.setLoginService( new SimpleLoginService() );
//...
}
</code></pre>
<p>This works great for testing each component as an isolated unit - except now that I have a few dozen classes in the project, after writing a class and writing a successful unit test for it, I keep forgetting to update my Spring MVC context file that does the actual wiring-up in the deployed application. I find out that I forgot to update the context file when I deploy the project to Tomcat and find a bunch of NullPointers from non-wired-up beans.</p>
<p>So, here are my questions:</p>
<ol>
<li><p>This is my first Spring project - is it normal to create unit tests for the individual beans, as I have done, and then create a second suite of tests (integration tests) to test that everything works as expected with the actual application context? Is there an established best practice for this?</p></li>
<li><p>In addition, how do you separate the unit tests from the integration tests? I have all of the source code in <code>src</code>, the unit tests in <code>test</code> - should there be a 2nd test folder (such as <code>test-integration</code>) for integration test cases?</p></li>
</ol>
<p>Since this is my first Spring project, I'm curious how others usually go about doing this sort of thing - and rather than re-invent the wheel I rather ask the rest of the community.</p>
|
[
{
"answer_id": 281841,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 6,
"selected": true,
"text": "<p>I can't speak to being a best practice, but here's what I've done in the past.</p>\n\n<p><strong>Unit tests:</strong></p>\n\n<ul>\n<li>Create unit tests for non-trivial beans (ie, most of your Spring related beans) </li>\n<li>Use Mocks for injected services where practical (ie, most if not all the time).</li>\n<li>Use a standard naming convention for these tests in the project <code>test</code> directory. Using <code>Test</code> or <code>TestCase</code> as a prefix or suffix to the classname seems to be widely practiced.</li>\n</ul>\n\n<p><strong>Integration Tests:</strong></p>\n\n<ul>\n<li>Create an <code>AbstractIntegrationTestCase</code> that sets up a <code>Spring</code> <code>WebApplicationContext</code> for use in intetgration test clases.</li>\n<li>Use a naming convention for integration tests in the <code>test</code> directory. I've used <code>IntTest</code> or <code>IntegrationTest</code> as a prefix or suffix for these tests.</li>\n</ul>\n\n<p>Set up three Ant <code>test</code> targets: </p>\n\n<ol>\n<li>test-all (or whatever you want to name it): Run Unit and Integration Tests</li>\n<li>test: Run Unit tests (just because <code>test</code> seems to be the most common usage for unit testing</li>\n<li>test-integration: run the integration tests.</li>\n</ol>\n\n<p>As noted, you can use the naming conventions that make sense for your project.</p>\n\n<p>As to separating unit from integration tests into a separate directory, I don't think it matters as long as the developers <em>and their tools</em> can find and execute them easily.</p>\n\n<p>As an example, the last Java project I worked on with Spring used exactly what is described above, with integration tests and unit tests living in the same <code>test</code> directory. Grails projects, on the other hand, explicitly separate unit and integration test directories under a general test directory.</p>\n"
},
{
"answer_id": 281869,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 2,
"selected": false,
"text": "<p>A lot of the tedious double-book-keeping with spring goes away if you also switch to a purely annotated regime, where you annotate all your beans with @Component, @Controller, @Service and @Repository. Just add @Autowired to the attributes you need to get injected. </p>\n\n<p>See section 3.11 of the spring reference manual. <a href=\"http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config\" rel=\"nofollow noreferrer\">http://static.springframework.org/spring/docs/2.5.x/reference/beans.html#beans-annotation-config</a></p>\n\n<p>On a related note, we have been using the division Unit/Integratrion tests that KenG describe. In my most recent regime we have also introduced a third \"class\" of tests, \"ComponentTests\". These run with full spring wiring, but with wired stub implementations (using component-scan filters and annotations in spring).</p>\n\n<p>The reason we did this was because for some of the \"service\" layer you end up with an horrendous amount of hand-coded wiring logic to manually wire up the bean, and sometimes ridiculous amounts of mock-objects. 100 lines of wiring for 5 lines of test is not uncommon. The component tests alleviate this problem.</p>\n"
},
{
"answer_id": 281882,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>When I've created integration tests for web applications, I've put them in a separate directory. They are built using jUnit or TestNG and interact with the system under test using something like <a href=\"http://selenium.openqa.org/\" rel=\"nofollow noreferrer\">Selenium</a> that hits the web pages as if they were users. The cycle would go like this: compile, run unit tests, build the web app, deploy it to a running server, execute the tests, undeploy the app, and report results. The idea is to test the whole system. </p>\n"
},
{
"answer_id": 282041,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 2,
"selected": false,
"text": "<p>Use the InitializingBean interface (implements a method \"afterPropertiesSet\") or specify an init-method for your beans. InitializingBean is typically easier because you don't need to remember to add the init method to your beans.</p>\n\n<p>Use afterPropertiesSet to ensure everything is injected as non-null, if it is null, throw an Exception.</p>\n"
},
{
"answer_id": 1432768,
"author": "Paul McKenzie",
"author_id": 135624,
"author_profile": "https://Stackoverflow.com/users/135624",
"pm_score": 0,
"selected": false,
"text": "<p>With regard to running unit tests separately from integration tests, I put all the latter into an integration-test directory and run them using IDE/Ant using an approach like <a href=\"https://stackoverflow.com/questions/1293880/run-all-tests-in-a-source-tree-not-a-package\">this</a>. Works for me.</p>\n"
},
{
"answer_id": 3486627,
"author": "Benjamin Wootton",
"author_id": 247573,
"author_profile": "https://Stackoverflow.com/users/247573",
"pm_score": 3,
"selected": false,
"text": "<p>A few isolated points:</p>\n\n<p>Yes, it's a common approach to Spring testing - seperate unit tests and integration tests where the former doesn't load any Spring context. </p>\n\n<p>For your unit tests, maybe consider mocking to ensure that your tests are focussed on one isolated module. </p>\n\n<p>If you're tests are wiring in a ton of dependencies then they aren't really unit tests. They're integration tests where you are wiring of dependencies using new rather than dependency injection. A waste of time and duplicated effort when your production application uses Spring!</p>\n\n<p>Basic integration tests to bring up your Spring contexts are useful.</p>\n\n<p>The @required annotation may help you to ensure you catch required dependencies in your Spring wiring.</p>\n\n<p>Maybe look into Maven which will give you explicit phases to bind your unit and integration tests on to. Maven is quite widely used in the Spring community.</p>\n"
},
{
"answer_id": 15464302,
"author": "Ali",
"author_id": 747661,
"author_profile": "https://Stackoverflow.com/users/747661",
"pm_score": 0,
"selected": false,
"text": "<p>the difference between unit test and integration test is , unit test does not necessarily load your context, you are focusing on the code which you have written - it works fails fast , that is with and without exceptions, by mocking any depends calls in it.\nBut in case of integration tests , you load context and perform end to end test like actual scenarios.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4249/"
] |
I'm working on a Spring MVC project, and I have unit tests for all of the various components in the source tree.
For example, if I have a controller `HomeController`, which needs to have a `LoginService` injected into it, then in my unit test `HomeControllerTest` I simply instantiate the object as normal (outside of Spring) and inject the property:
```
protected void setUp() throws Exception {
super.setUp();
//...
controller = new HomeController();
controller.setLoginService( new SimpleLoginService() );
//...
}
```
This works great for testing each component as an isolated unit - except now that I have a few dozen classes in the project, after writing a class and writing a successful unit test for it, I keep forgetting to update my Spring MVC context file that does the actual wiring-up in the deployed application. I find out that I forgot to update the context file when I deploy the project to Tomcat and find a bunch of NullPointers from non-wired-up beans.
So, here are my questions:
1. This is my first Spring project - is it normal to create unit tests for the individual beans, as I have done, and then create a second suite of tests (integration tests) to test that everything works as expected with the actual application context? Is there an established best practice for this?
2. In addition, how do you separate the unit tests from the integration tests? I have all of the source code in `src`, the unit tests in `test` - should there be a 2nd test folder (such as `test-integration`) for integration test cases?
Since this is my first Spring project, I'm curious how others usually go about doing this sort of thing - and rather than re-invent the wheel I rather ask the rest of the community.
|
I can't speak to being a best practice, but here's what I've done in the past.
**Unit tests:**
* Create unit tests for non-trivial beans (ie, most of your Spring related beans)
* Use Mocks for injected services where practical (ie, most if not all the time).
* Use a standard naming convention for these tests in the project `test` directory. Using `Test` or `TestCase` as a prefix or suffix to the classname seems to be widely practiced.
**Integration Tests:**
* Create an `AbstractIntegrationTestCase` that sets up a `Spring` `WebApplicationContext` for use in intetgration test clases.
* Use a naming convention for integration tests in the `test` directory. I've used `IntTest` or `IntegrationTest` as a prefix or suffix for these tests.
Set up three Ant `test` targets:
1. test-all (or whatever you want to name it): Run Unit and Integration Tests
2. test: Run Unit tests (just because `test` seems to be the most common usage for unit testing
3. test-integration: run the integration tests.
As noted, you can use the naming conventions that make sense for your project.
As to separating unit from integration tests into a separate directory, I don't think it matters as long as the developers *and their tools* can find and execute them easily.
As an example, the last Java project I worked on with Spring used exactly what is described above, with integration tests and unit tests living in the same `test` directory. Grails projects, on the other hand, explicitly separate unit and integration test directories under a general test directory.
|
281,787 |
<p>What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?</p>
<p>Contrived example: </p>
<pre><code>class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
</code></pre>
<p>I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container, </p>
<pre><code>class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;</code></pre>
<p>This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"</p>
<p>Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.</p>
|
[
{
"answer_id": 281807,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 2,
"selected": true,
"text": "<p>Take a look at <a href=\"http://s11n.net\" rel=\"nofollow noreferrer\">this library</a> .</p>\n"
},
{
"answer_id": 281816,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 1,
"selected": false,
"text": "<p>What you need is object serialization or object marshalling. A <a href=\"https://stackoverflow.com/questions/154185/what-is-object-marshalling\">recurrent thema</a> in stackoverflow.</p>\n"
},
{
"answer_id": 281820,
"author": "Peter Crabtree",
"author_id": 36283,
"author_profile": "https://Stackoverflow.com/users/36283",
"pm_score": 2,
"selected": false,
"text": "<p>What you're looking for is \"[reflection](<a href=\"http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Reflection_(computer_science)#C.2B.2B)</a>\".</p>\n\n<p>I found two promising links with a Google search for \"C++ reflection\":</p>\n\n<p><a href=\"http://www.garret.ru/cppreflection/docs/reflect.html\" rel=\"nofollow noreferrer\">http://www.garret.ru/cppreflection/docs/reflect.html</a></p>\n\n<p><a href=\"http://seal-reflex.web.cern.ch/seal-reflex/index.html\" rel=\"nofollow noreferrer\">http://seal-reflex.web.cern.ch/seal-reflex/index.html</a></p>\n"
},
{
"answer_id": 281832,
"author": "ReaperUnreal",
"author_id": 4218,
"author_profile": "https://Stackoverflow.com/users/4218",
"pm_score": 0,
"selected": false,
"text": "<p>There's unfortunately no macro that can do this for you. What you're looking for is a reflective type library. These can vary from fairly simple to home-rolled monstrosities that have no place in a work environment.</p>\n\n<p>There's no real simple way of doing this, and though you may be tempted to simply dump the memory at an address like so:</p>\n\n<pre><code>char *buffer = new char[sizeof(Container)];\nmemcpy(buffer, containerInstance, sizeof(Container));\n</code></pre>\n\n<p>I'd really suggest against it unless all you have are simple types.</p>\n\n<p>If you want something really simple but not complete, I'd suggest writing your own\n<code>printOn(ostream &)</code> member method.</p>\n"
},
{
"answer_id": 281836,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 1,
"selected": false,
"text": "<p>I'd highly recommend taking a look at Google's <a href=\"http://code.google.com/p/protobuf/\" rel=\"nofollow noreferrer\">Protocol Buffers</a>.</p>\n"
},
{
"answer_id": 281929,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>Boost has a serialization library that can serialize into text files. You will, however, not be able to get around with now knowing what members the class contains. You would need reflection, which C++ does not have.</p>\n"
},
{
"answer_id": 282373,
"author": "INS",
"author_id": 13136,
"author_profile": "https://Stackoverflow.com/users/13136",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/External_Data_Representation\" rel=\"nofollow noreferrer\">XDR</a> is one way to do this in a platform independent way.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281787",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22724/"
] |
What's the best way to output the public contents of an object to a human-readable file? I'm looking for a way to do this that would not require me to know of all the members of the class, but rather use the compiler to tell me what members exist, and what their names are. There have to be macros or something like that, right?
Contrived example:
```
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
int otherStuff;
};
Container myCollection;
```
I would like to be able to do something to see output along the lines of "myCollection: stuff = value, otherStuff = value".
But then if another member is added to Container,
```
class Container
{
public:
Container::Container() {/*initialize members*/};
int stuff;
string evenMoreStuff;
int otherStuff;
};
Container myCollection;
```
This time, the output of this snapshot would be "myCollection: stuff = value, evenMoreStuff=value, otherStuff = value"
Is there a macro that would help me accomplish this? Is this even possible? (Also, I can't modify the Container class.)
Another note: I'm most interested about a potential macros in VS, but other solutions are welcome too.
|
Take a look at [this library](http://s11n.net) .
|
281,811 |
<p>How do I test if two dates are within a certain tolerance in NUnit?</p>
|
[
{
"answer_id": 281853,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 1,
"selected": false,
"text": "<p>Convert your tolerance to Ticks and then use an And constraint. Something like;</p>\n\n<pre><code>long ticks = mydate.Ticks;\nlong tolerance = 1000;\nAssert.That( ticks, Is.LessThan( ticks + tolerance ) & Is.GreaterThan( ticks - tolerance ) );\n</code></pre>\n\n<p>I would create an extension method or your own Assert to do this though.</p>\n"
},
{
"answer_id": 281857,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>Subtract one from the other, which gives you a TimeSpan value, use the TotalXYZ properties (like TotalMilliseconds) to get a value, use Math.Abs on it to convert it to a always-positive value, and check against your tolerance value.</p>\n\n<p>For instance, if they need to be within 10 milliseconds of each other:</p>\n\n<pre><code>if (Math.Abs((dt1 - dt2).TotalMilliseconds) <= 10)\n{\n CloseEnough();\n}\n</code></pre>\n"
},
{
"answer_id": 282053,
"author": "CubanX",
"author_id": 27555,
"author_profile": "https://Stackoverflow.com/users/27555",
"pm_score": 3,
"selected": true,
"text": "<p>You may want to look at the \"Within\" method that lives off of the Constraint object.</p>\n\n<p>For example:</p>\n\n<pre><code>Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));\n</code></pre>\n\n<p>It's usually used to give a tolerance to doubles and floats, but since in the end a DateTime is a double, it might suit your needs.</p>\n"
},
{
"answer_id": 6680959,
"author": "Howard",
"author_id": 842938,
"author_profile": "https://Stackoverflow.com/users/842938",
"pm_score": 2,
"selected": false,
"text": "<pre><code>TimeSpan tolerance = new TimeSpan(0,1,0); // e.g. 1 minute\n\nAssert.IsTrue((firstDateTime-SecondDateTime).Duration() > tolerance);\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281811",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/549/"
] |
How do I test if two dates are within a certain tolerance in NUnit?
|
You may want to look at the "Within" method that lives off of the Constraint object.
For example:
```
Assert.That(DateTime.Now, Is.EqualTo(DateTime.Now.AddMilliseconds(1000)).Within(101));
```
It's usually used to give a tolerance to doubles and floats, but since in the end a DateTime is a double, it might suit your needs.
|
281,818 |
<p>I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a <code>type_info</code> class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. <code>typeid(std::vector<int>).name()</code> returns <code>St6vectorIiSaIiEE</code>.</p>
<p>Is there a way to produce something useful from this? Like <code>std::vector<int></code> for the above example. If it only works for non-template classes, that's fine too.</p>
<p>The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.</p>
|
[
{
"answer_id": 281834,
"author": "Eclipse",
"author_id": 8701,
"author_profile": "https://Stackoverflow.com/users/8701",
"pm_score": 3,
"selected": false,
"text": "<p>It's implementation defined, so it's not something that's going to be portable. In MSVC++, name() is the undecorated name, and you have to look at raw_name() to get the decorated one.<br>\nJust a stab in the dark here, but under gcc, you might want to look at <a href=\"http://hte.sourceforge.net/doxygenized-0.8.0pre1/demangle_8h.html\" rel=\"noreferrer\">demangle.h</a></p>\n"
},
{
"answer_id": 281840,
"author": "quamrana",
"author_id": 4834,
"author_profile": "https://Stackoverflow.com/users/4834",
"pm_score": 0,
"selected": false,
"text": "<p>I've always wanted to use type_info, but I'm sure that the result of the name() member function is non-standard and won't necessarily return anything that can be converted to a meaningful result.<br>\nIf you are sticking to one compiler, there maybe a compiler specific function that will do what you want. Check the documentation.</p>\n"
},
{
"answer_id": 281860,
"author": "CesarB",
"author_id": 28258,
"author_profile": "https://Stackoverflow.com/users/28258",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at <code>__cxa_demangle</code> which you can find at <code>cxxabi.h</code>.</p>\n"
},
{
"answer_id": 281876,
"author": "KeithB",
"author_id": 2298,
"author_profile": "https://Stackoverflow.com/users/2298",
"pm_score": 4,
"selected": false,
"text": "<p>This is what we use. HAVE_CXA_DEMANGLE is only set if available (recent versions of GCC only).</p>\n\n<pre><code>#ifdef HAVE_CXA_DEMANGLE\nconst char* demangle(const char* name)\n{\n char buf[1024];\n unsigned int size=1024;\n int status;\n char* res = abi::__cxa_demangle (name,\n buf,\n &size,\n &status);\n return res;\n }\n#else\nconst char* demangle(const char* name)\n{\n return name;\n}\n#endif \n</code></pre>\n"
},
{
"answer_id": 281880,
"author": "luke",
"author_id": 16434,
"author_profile": "https://Stackoverflow.com/users/16434",
"pm_score": 2,
"selected": false,
"text": "<p>Not a complete solution, but you may want to look at what some of the standard (or widely supported) macro's define. It's common in logging code to see the use of the macros:</p>\n\n<pre><code>__FUNCTION__\n__FILE__\n__LINE__\n\ne.g.:\n\nlog(__FILE__, __LINE__, __FUNCTION__, mymessage);\n</code></pre>\n"
},
{
"answer_id": 281905,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 3,
"selected": false,
"text": "<p>Here, take a look at <a href=\"https://github.com/Eelis/geordi/blob/master/prelude/type_strings.hpp\" rel=\"nofollow noreferrer\">type_strings.hpp</a> it contains a function that does what you want.</p>\n\n<p>If you just look for a demangling tool, which you e.g. could use to mangle stuff shown in a log file, take a look at <code>c++filt</code>, which comes with binutils. It can demangle C++ and Java symbol names.</p>\n"
},
{
"answer_id": 282009,
"author": "terminus",
"author_id": 9232,
"author_profile": "https://Stackoverflow.com/users/9232",
"pm_score": 2,
"selected": false,
"text": "<p>I also found a macro called <code>__PRETTY_FUNCTION__</code>, which does the trick. It gives a pretty function name (figures :)). This is what I needed.</p>\n\n<p>I.e. it gives me the following:</p>\n\n<pre><code>virtual bool mutex::do_unlock()\n</code></pre>\n\n<p>But I don't think it works on other compilers.</p>\n"
},
{
"answer_id": 2624567,
"author": "Dan Dare",
"author_id": 314786,
"author_profile": "https://Stackoverflow.com/users/314786",
"pm_score": 1,
"selected": false,
"text": "<pre><code>// KeithB's solution is good, but has one serious flaw in that unless buf is static\n// it'll get trashed from the stack before it is returned in res - and will point who-knows-where\n// Here's that problem fixed, but the code is still non-re-entrant and not thread-safe.\n// Anyone care to improve it?\n\n#include <cxxabi.h>\n\n// todo: javadoc this properly\nconst char* demangle(const char* name)\n{\n static char buf[1024];\n size_t size = sizeof(buf);\n int status;\n // todo:\n char* res = abi::__cxa_demangle (name,\n buf,\n &size,\n &status);\n buf[sizeof(buf) - 1] = 0; // I'd hope __cxa_demangle does this when the name is huge, but just in case.\n return res;\n }\n</code></pre>\n"
},
{
"answer_id": 4541470,
"author": "Ali",
"author_id": 341970,
"author_profile": "https://Stackoverflow.com/users/341970",
"pm_score": 8,
"selected": true,
"text": "<p>Given the attention this question / answer receives, and the valuable feedback from <a href=\"https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname/4541470#comment26629807_4541470\">GManNickG</a>, I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.</p>\n\n<p>In file <strong>type.hpp</strong></p>\n\n\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#ifndef TYPE_HPP\n#define TYPE_HPP\n\n#include <string>\n#include <typeinfo>\n\nstd::string demangle(const char* name);\n\ntemplate <class T>\nstd::string type(const T& t) {\n\n return demangle(typeid(t).name());\n}\n\n#endif\n</code></pre>\n\n<p>In file <strong>type.cpp</strong> (requires C++11)</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include \"type.hpp\"\n#ifdef __GNUG__\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\nstd::string demangle(const char* name) {\n\n int status = -4; // some arbitrary value to eliminate the compiler warning\n\n // enable c++11 by passing the flag -std=c++11 to g++\n std::unique_ptr<char, void(*)(void*)> res {\n abi::__cxa_demangle(name, NULL, NULL, &status),\n std::free\n };\n\n return (status==0) ? res.get() : name ;\n}\n\n#else\n\n// does nothing if not g++\nstd::string demangle(const char* name) {\n return name;\n}\n\n#endif\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include \"type.hpp\"\n\nstruct Base { virtual ~Base() {} };\n\nstruct Derived : public Base { };\n\nint main() {\n\n Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code!\n\n std::cout << \"Type of ptr_base: \" << type(ptr_base) << std::endl;\n\n std::cout << \"Type of pointee: \" << type(*ptr_base) << std::endl;\n\n delete ptr_base;\n}\n</code></pre>\n\n<p>It prints:</p>\n\n<p>Type of ptr_base: <code>Base*</code><br>\nType of pointee: <code>Derived</code></p>\n\n<p>Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2).</p>\n\n<p>If you cannot use C++11 features, here is how it can be done in C++98, the file <strong>type.cpp</strong> is now:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include \"type.hpp\"\n#ifdef __GNUG__\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\nstruct handle {\n char* p;\n handle(char* ptr) : p(ptr) { }\n ~handle() { std::free(p); }\n};\n\nstd::string demangle(const char* name) {\n\n int status = -4; // some arbitrary value to eliminate the compiler warning\n\n handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );\n\n return (status==0) ? result.p : name ;\n}\n\n#else\n\n// does nothing if not g++\nstd::string demangle(const char* name) {\n return name;\n}\n\n#endif\n</code></pre>\n\n<hr>\n\n<hr>\n\n<p><em>(Update from Sep 8, 2013)</em></p>\n\n<p><a href=\"https://stackoverflow.com/a/281876/341970\">The accepted answer (as of Sep 7, 2013)</a>, when the call to <code>abi::__cxa_demangle()</code> is successful, <strong>returns a pointer to a local, stack allocated array</strong>... ouch!<br>\nAlso note that if you provide a buffer, <code>abi::__cxa_demangle()</code> assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): <em>\"If <code>output_buffer</code> is not long enough, it is expanded using <code>realloc</code>.\"</em> <strong>Calling <code>realloc()</code> on a pointer to the stack</strong>... ouch! (See also <a href=\"https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname#comment16312718_4541470\">Igor Skochinsky</a>'s kind comment.) </p>\n\n<p>You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name <em>not</em> longer than 15 (so <code>realloc()</code> is <em>not</em> called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash.<br>\nTo verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call <code>realloc()</code> with a pointer to the stack.</p>\n\n<hr>\n\n<p><em>(The old answer from Dec 27, 2010)</em></p>\n\n<p>Important changes made to <a href=\"https://stackoverflow.com/a/281876/341970\">KeithB's code</a>: <strong>the buffer has to be either allocated by malloc or specified as NULL.</strong> Do NOT allocate it on the stack.</p>\n\n<p>It's wise to check that status as well.</p>\n\n<p>I failed to find <code>HAVE_CXA_DEMANGLE</code>. I check <code>__GNUG__</code> although that does not guarantee that the code will even compile. Anyone has a better idea?</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <cxxabi.h>\n\nconst string demangle(const char* name) {\n\n int status = -4;\n\n char* res = abi::__cxa_demangle(name, NULL, NULL, &status);\n\n const char* const demangled_name = (status==0)?res:name;\n\n string ret_val(demangled_name);\n\n free(res);\n\n return ret_val;\n}\n</code></pre>\n"
},
{
"answer_id": 29606760,
"author": "matzzz",
"author_id": 4783138,
"author_profile": "https://Stackoverflow.com/users/4783138",
"pm_score": 2,
"selected": false,
"text": "<p>A slight variation on Ali's solution. If you want the code to still be very similar to </p>\n\n<p><code>typeid(bla).name()</code>, </p>\n\n<p>writing this instead </p>\n\n<p><code>Typeid(bla).name()</code> (differing only in capital first letter)</p>\n\n<p>then you may be interested in this:</p>\n\n<p>In file <strong>type.hpp</strong></p>\n\n<pre><code>#ifndef TYPE_HPP\n#define TYPE_HPP\n\n#include <string>\n#include <typeinfo>\n\nstd::string demangle(const char* name);\n\n/*\ntemplate <class T>\nstd::string type(const T& t) {\n\n return demangle(typeid(t).name());\n}\n*/\n\nclass Typeid {\n public:\n\n template <class T>\n Typeid(const T& t) : typ(typeid(t)) {}\n\n std::string name() { return demangle(typ.name()); }\n\n private:\n const std::type_info& typ;\n};\n\n\n#endif\n</code></pre>\n\n<p><strong>type.cpp</strong> stays same as in Ali's solution</p>\n"
},
{
"answer_id": 34916852,
"author": "moof2k",
"author_id": 4343378,
"author_profile": "https://Stackoverflow.com/users/4343378",
"pm_score": 5,
"selected": false,
"text": "<p>Boost core contains a demangler. Checkout <a href=\"http://www.boost.org/doc/libs/master/libs/core/doc/html/core/demangle.html#core.demangle.header_boost_core_demangle_hpp\" rel=\"noreferrer\">core/demangle.hpp</a>:</p>\n\n<pre><code>#include <boost/core/demangle.hpp>\n#include <typeinfo>\n#include <iostream>\n\ntemplate<class T> struct X\n{\n};\n\nint main()\n{\n char const * name = typeid( X<int> ).name();\n\n std::cout << name << std::endl; // prints 1XIiE\n std::cout << boost::core::demangle( name ) << std::endl; // prints X<int>\n}\n</code></pre>\n\n<p>It's basically just a wrapper for <code>abi::__cxa_demangle</code>, as has been suggested previously.</p>\n"
},
{
"answer_id": 53865723,
"author": "sancho.s ReinstateMonicaCellio",
"author_id": 2707864,
"author_profile": "https://Stackoverflow.com/users/2707864",
"pm_score": 2,
"selected": false,
"text": "<p>The <a href=\"https://stackoverflow.com/a/4541470/2707864\">accepted solution</a> [1] works mostly well.\nI found at least one case (and I wouldn't call it a corner case) where it does not report what I expected... with references.</p>\n\n<p>For those cases, I found another solution, posted at the bottom.</p>\n\n<p><strong>Problematic case</strong> (using <code>type</code> as defined in [1]):</p>\n\n<pre><code>int i = 1;\ncout << \"Type of \" << \"i\" << \" is \" << type(i) << endl;\nint & ri = i;\ncout << \"Type of \" << \"ri\" << \" is \" << type(ri) << endl;\n</code></pre>\n\n<p>produces</p>\n\n<pre><code>Type of i is int\nType of ri is int\n</code></pre>\n\n<p><strong>Solution</strong> (using <code>type_name<decltype(obj)>()</code>, see code below):</p>\n\n<pre><code>cout << \"Type of \" << \"i\" << \" is \" << type_name<decltype(i)>() << endl;\ncout << \"Type of \" << \"ri\" << \" is \" << type_name<decltype(ri)>() << endl;\n</code></pre>\n\n<p>produces</p>\n\n<pre><code>Type of i is int\nType of ri is int&\n</code></pre>\n\n<p>as desired (at least by me)</p>\n\n<p><strong>Code</strong>\n.\nIt has to be in an included header, not in a separately compiled source, due to specialization issues. See <a href=\"https://stackoverflow.com/questions/10632251/undefined-reference-to-template-function\">undefined reference to template function</a> for instance.</p>\n\n<pre><code>#ifndef _MSC_VER\n# include <cxxabi.h>\n#endif\n#include <memory>\n#include <string>\n#include <cstdlib>\n\ntemplate <class T>\nstd::string\ntype_name()\n{\n typedef typename std::remove_reference<T>::type TR;\n std::unique_ptr<char, void(*)(void*)> own\n (\n#ifndef _MSC_VER\n abi::__cxa_demangle(typeid(TR).name(), nullptr,\n nullptr, nullptr),\n#else\n nullptr,\n#endif\n std::free\n );\n std::string r = own != nullptr ? own.get() : typeid(TR).name();\n if (std::is_const<TR>::value)\n r += \" const\";\n if (std::is_volatile<TR>::value)\n r += \" volatile\";\n if (std::is_lvalue_reference<T>::value)\n r += \"&\";\n else if (std::is_rvalue_reference<T>::value)\n r += \"&&\";\n return r;\n}\n</code></pre>\n"
},
{
"answer_id": 62465912,
"author": "Alexis Paques",
"author_id": 3540247,
"author_profile": "https://Stackoverflow.com/users/3540247",
"pm_score": 1,
"selected": false,
"text": "<p>Following Ali's solution, here is the <strong>C++11</strong> templated alternative which worked best for my usage.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// type.h\n#include <cstdlib>\n#include <memory>\n#include <cxxabi.h>\n\ntemplate <typename T>\nstd::string demangle() {\n int status = -4;\n\n std::unique_ptr<char, void (*)(void*)> res{\n abi::__cxa_demangle(typeid(T).name(), NULL, NULL, &status), std::free};\n return (status == 0) ? res.get() : typeid(T).name();\n}\n</code></pre>\n\n<p>Usage:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>// main.cpp\n#include <iostream>\n\nnamespace test {\n struct SomeStruct {};\n}\n\nint main()\n{\n std::cout << demangle<double>() << std::endl;\n std::cout << demangle<const int&>() << std::endl;\n std::cout << demangle<test::SomeStruct>() << std::endl;\n\n return 0;\n}\n</code></pre>\n\n<p>Will print:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>double \nint \ntest::SomeStruct\n</code></pre>\n"
},
{
"answer_id": 66551751,
"author": "Human-Compiler",
"author_id": 1678770,
"author_profile": "https://Stackoverflow.com/users/1678770",
"pm_score": 4,
"selected": false,
"text": "<p>If all we want is the unmangled type name for the purpose of logging, we can actually do this without using <code>std::type_info</code> or even RTTI at all.</p>\n<p>A slightly portable solution that works for the big 3 main compiler front-ends (<a href=\"/questions/tagged/gcc\" class=\"post-tag\" title=\"show questions tagged 'gcc'\" rel=\"tag\" aria-labelledby=\"gcc-container\">gcc</a>, <a href=\"/questions/tagged/clang\" class=\"post-tag\" title=\"show questions tagged 'clang'\" rel=\"tag\" aria-labelledby=\"clang-container\">clang</a>, and <a href=\"/questions/tagged/msvc\" class=\"post-tag\" title=\"show questions tagged 'msvc'\" rel=\"tag\" aria-labelledby=\"msvc-container\">msvc</a>) would be to use a function <code>template</code> and extract the type name from the function name.</p>\n<p><code>gcc</code> and <code>clang</code> both offer <code>__PRETTY_FUNCTION__</code> which is the name of a current function or function template with all type-argument in the string. Similarly MSVC has <code>__FUNCSIG__</code> which is equivalent. Each of these are formatted a little differently, for example, for a call of <code>void foo<int></code>, the compilers will output something different:</p>\n<ul>\n<li><code>gcc</code> is formatted <code>void foo() [with T = int; ]</code></li>\n<li><code>clang</code> is formatted <code>void foo() [T = int]</code></li>\n<li><code>msvc</code> is formatted <code>void foo<int>()</code></li>\n</ul>\n<p>Knowing this, it's just a matter of parsing out a prefix and suffix and wrapping this into a function in order to extract out the type name.</p>\n<p>We can even use <a href=\"/questions/tagged/c%2b%2b17\" class=\"post-tag\" title=\"show questions tagged 'c++17'\" rel=\"tag\" aria-labelledby=\"c++17-container\">c++17</a>'s <code>std::string_view</code> and extended <code>constexpr</code> to get string names at <strong>compile-time</strong>, just by parsing the name of a template function. This could also be done in any earlier C++ version, but this will still require some form of string parsing.</p>\n<p>For example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <string_view>\n\ntemplate <typename T>\nconstexpr auto get_type_name() -> std::string_view\n{\n#if defined(__clang__)\n constexpr auto prefix = std::string_view{"[T = "};\n constexpr auto suffix = "]";\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(__GNUC__)\n constexpr auto prefix = std::string_view{"with T = "};\n constexpr auto suffix = "; ";\n constexpr auto function = std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n constexpr auto prefix = std::string_view{"get_type_name<"};\n constexpr auto suffix = ">(void)";\n constexpr auto function = std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n\n const auto start = function.find(prefix) + prefix.size();\n const auto end = function.find(suffix);\n const auto size = end - start;\n\n return function.substr(start, size);\n}\n</code></pre>\n<p>With this, you can call <code>get_type_name<T>()</code> to get a <code>std::string_view</code> at compile-time indicating the unmangled type name.</p>\n<p>For example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>std::cout << get_type_name<std::string>() << std::endl;\n</code></pre>\n<p>on GCC will output:</p>\n<pre><code>std::__cxx11::basic_string<char>\n</code></pre>\n<p>and on clang will output:</p>\n<pre><code>std::basic_string<char>\n</code></pre>\n<p><kbd><a href=\"https://gcc.godbolt.org/z/qo146d\" rel=\"nofollow noreferrer\">Live Example</a></kbd></p>\n<hr />\n<p>A similar augmentation to this approach which avoids a <code>prefix</code> and <code>suffix</code> is to assume that the function name is the same for all types, and search for a sentinel type to parse out the offset to the sentinel from each end. This ensures that the string searching only happens once, and the offset is assumed to find the string name each time. For example, using <code>double</code> as a simple sentinel:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>template <typename T>\nconstexpr auto full_function_name() -> std::string_view\n{\n#if defined(__clang__) || defined(__GNUC__)\n return std::string_view{__PRETTY_FUNCTION__};\n#elif defined(_MSC_VER)\n return std::string_view{__FUNCSIG__};\n#else\n# error Unsupported compiler\n#endif\n}\n\n// Outside of the template so its computed once\nstruct type_name_info {\n static constexpr auto sentinel_function = full_function_name<double>();\n static constexpr auto prefix_offset = sentinel_function.find("double");\n static constexpr auto suffix_offset = sentinel_function.size() - prefix_offset - /* strlen("double") */ 6;\n};\n\ntemplate <typename T>\nconstexpr auto get_type_name() -> std::string_view\n{\n constexpr auto function = full_function_name<T>();\n\n const auto start = type_name_info::prefix_offset;\n const auto end = function.size() - type_name_info::suffix_offset;\n const auto size = end - start;\n\n return function.substr(start, size);\n}\n</code></pre>\n<p><kbd><a href=\"https://gcc.godbolt.org/z/33MG9fP5h\" rel=\"nofollow noreferrer\">Live Example</a></kbd></p>\n<hr />\n<p>This isn't portable to <em>all</em> compilers, but can be modified for any compiler that offers a <code>__FUNCSIG__</code>/<code>__PRETTY_FUNCTION__</code> equivalent; it just requires a bit of parsing.</p>\n<p><strong>note:</strong> This hasn't been <em>fully</em> tested, so there may be some bugs; but the primary idea is to parse any output that contains the name in totality -- which is often a side-effect of <code>__func__</code>-like outputs on compilers.</p>\n"
},
{
"answer_id": 71820656,
"author": "GKxx",
"author_id": 8395081,
"author_profile": "https://Stackoverflow.com/users/8395081",
"pm_score": 0,
"selected": false,
"text": "<p><code>boost::typeindex</code> provides something helpful.</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <boost/type_index.hpp>\n#include <iostream>\n#include <vector>\n\nclass Widget {};\n\nint main() {\n using boost::typeindex::type_id_with_cvr;\n const std::vector<Widget> vw;\n std::cout << type_id_with_cvr<decltype(vw)>().pretty_name() << std::endl;\n std::cout << type_id_with_cvr<decltype(vw[0])>().pretty_name() << std::endl;\n return 0;\n}\n</code></pre>\n<p>The output is</p>\n<pre><code>std::vector<Widget, std::allocator<Widget> > const\nWidget const&\n</code></pre>\n<p>What is worthy of notice is that <code>type_id_with_cvr</code> preserves reference and c/v qualifiers, while <code>typeid</code> doesn't. See the following example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n#include <boost/type_index.hpp>\n#include <typeindex>\n#include <vector>\n#include <typeinfo>\n\nclass Widget {};\n\ntemplate <typename T>\nvoid f(const T &param) {\n std::cout << typeid(param).name() << std::endl;\n std::cout\n << boost::typeindex::type_id_with_cvr<decltype(param)>().pretty_name()\n << std::endl;\n}\n\nint main() {\n const std::vector<Widget> vw(1);\n f(&vw[0]);\n return 0;\n}\n</code></pre>\n<p>The output is</p>\n<pre><code>PK6Widget\nWidget const* const&\n</code></pre>\n<p>Here, <code>typeid</code> produces <code>PK6Widget</code>, which means <strong>P</strong>ointer to <strong>K</strong>onst Widget. The number '6' is the length of the name 'Widget'. This is not the correct type of <code>param</code>, in which the reference and const qualifier are dropped.</p>\n<p>The <code>type_id_with_cvr</code> actually uses the demangling functions in <code>boost::core</code>, as has been mentioned in <a href=\"https://stackoverflow.com/a/34916852/8395081\">this answer</a>. To preserve the cv qualifiers or reference, it just defines an empty template named <code>cvr_saver</code> and then passes <code>cvr_saver<type></code> to <code>typeid</code>.</p>\n<p><em>Effective Modern C++</em> Item 4 talks about this.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9232/"
] |
I'm currently working on some logging code that supposed to - among other things - print information about the calling function. This should be relatively easy, standard C++ has a `type_info` class. This contains the name of the typeid'd class/function/etc. but it's mangled. It's not very useful. I.e. `typeid(std::vector<int>).name()` returns `St6vectorIiSaIiEE`.
Is there a way to produce something useful from this? Like `std::vector<int>` for the above example. If it only works for non-template classes, that's fine too.
The solution should work for gcc, but it would be better if I could port it. It's for logging so it's not so important that it can't be turned off, but it should be helpful for debugging.
|
Given the attention this question / answer receives, and the valuable feedback from [GManNickG](https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname/4541470#comment26629807_4541470), I have cleaned up the code a little bit. Two versions are given: one with C++11 features and another one with only C++98 features.
In file **type.hpp**
```cpp
#ifndef TYPE_HPP
#define TYPE_HPP
#include <string>
#include <typeinfo>
std::string demangle(const char* name);
template <class T>
std::string type(const T& t) {
return demangle(typeid(t).name());
}
#endif
```
In file **type.cpp** (requires C++11)
```cpp
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
// enable c++11 by passing the flag -std=c++11 to g++
std::unique_ptr<char, void(*)(void*)> res {
abi::__cxa_demangle(name, NULL, NULL, &status),
std::free
};
return (status==0) ? res.get() : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
```
Usage:
```cpp
#include <iostream>
#include "type.hpp"
struct Base { virtual ~Base() {} };
struct Derived : public Base { };
int main() {
Base* ptr_base = new Derived(); // Please use smart pointers in YOUR code!
std::cout << "Type of ptr_base: " << type(ptr_base) << std::endl;
std::cout << "Type of pointee: " << type(*ptr_base) << std::endl;
delete ptr_base;
}
```
It prints:
Type of ptr\_base: `Base*`
Type of pointee: `Derived`
Tested with g++ 4.7.2, g++ 4.9.0 20140302 (experimental), clang++ 3.4 (trunk 184647), clang 3.5 (trunk 202594) on Linux 64 bit and g++ 4.7.2 (Mingw32, Win32 XP SP2).
If you cannot use C++11 features, here is how it can be done in C++98, the file **type.cpp** is now:
```cpp
#include "type.hpp"
#ifdef __GNUG__
#include <cstdlib>
#include <memory>
#include <cxxabi.h>
struct handle {
char* p;
handle(char* ptr) : p(ptr) { }
~handle() { std::free(p); }
};
std::string demangle(const char* name) {
int status = -4; // some arbitrary value to eliminate the compiler warning
handle result( abi::__cxa_demangle(name, NULL, NULL, &status) );
return (status==0) ? result.p : name ;
}
#else
// does nothing if not g++
std::string demangle(const char* name) {
return name;
}
#endif
```
---
---
*(Update from Sep 8, 2013)*
[The accepted answer (as of Sep 7, 2013)](https://stackoverflow.com/a/281876/341970), when the call to `abi::__cxa_demangle()` is successful, **returns a pointer to a local, stack allocated array**... ouch!
Also note that if you provide a buffer, `abi::__cxa_demangle()` assumes it to be allocated on the heap. Allocating the buffer on the stack is a bug (from the gnu doc): *"If `output_buffer` is not long enough, it is expanded using `realloc`."* **Calling `realloc()` on a pointer to the stack**... ouch! (See also [Igor Skochinsky](https://stackoverflow.com/questions/281818/unmangling-the-result-of-stdtype-infoname#comment16312718_4541470)'s kind comment.)
You can easily verify both of these bugs: just reduce the buffer size in the accepted answer (as of Sep 7, 2013) from 1024 to something smaller, for example 16, and give it something with a name *not* longer than 15 (so `realloc()` is *not* called). Still, depending on your system and the compiler optimizations, the output will be: garbage / nothing / program crash.
To verify the second bug: set the buffer size to 1 and call it with something whose name is longer than 1 character. When you run it, the program almost assuredly crashes as it attempts to call `realloc()` with a pointer to the stack.
---
*(The old answer from Dec 27, 2010)*
Important changes made to [KeithB's code](https://stackoverflow.com/a/281876/341970): **the buffer has to be either allocated by malloc or specified as NULL.** Do NOT allocate it on the stack.
It's wise to check that status as well.
I failed to find `HAVE_CXA_DEMANGLE`. I check `__GNUG__` although that does not guarantee that the code will even compile. Anyone has a better idea?
```cpp
#include <cxxabi.h>
const string demangle(const char* name) {
int status = -4;
char* res = abi::__cxa_demangle(name, NULL, NULL, &status);
const char* const demangled_name = (status==0)?res:name;
string ret_val(demangled_name);
free(res);
return ret_val;
}
```
|
281,831 |
<p>I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble.</p>
<p>I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus.</p>
<p>In MFC, we show the new context menu by calling <strong>TrackPopupMenuEx</strong> with the <strong>TPM_RECURSE</strong> flag.</p>
<p><strong>ContextMenu</strong> and the newer <strong>ContextMenuStrip</strong> classes in .NET only have a <em>Show</em> method. Does anyone know how to do this in .NET?</p>
<p><strong>EDIT</strong></p>
<p>I have tried using <strong>TrackPopupMenuEx</strong> through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new <strong>MenuStrip</strong> and <strong>ContextMenuStrip</strong>.</p>
<p>I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for <strong>MenuStrip</strong>, but <strong>ContextMenuStrip</strong> still allows the right click events to pass through as clicks.</p>
|
[
{
"answer_id": 281883,
"author": "Jason Diller",
"author_id": 2187,
"author_profile": "https://Stackoverflow.com/users/2187",
"pm_score": 2,
"selected": false,
"text": "<p>You'll probably have to p/invoke the method. </p>\n\n<pre><code>[DllImport(\"user32.dll\")]\nstatic extern bool TrackPopupMenuEx(IntPtr hmenu, uint fuFlags, int x, int y,\nIntPtr hwnd, IntPtr lptpm);\n\nconst int TPM_RECURSE = 0x0001; \n</code></pre>\n"
},
{
"answer_id": 282202,
"author": "Eren Aygunes",
"author_id": 27980,
"author_profile": "https://Stackoverflow.com/users/27980",
"pm_score": 5,
"selected": true,
"text": "<p>Edit, due to a comment:</p>\n\n<p>In:</p>\n\n<pre><code>protected override void OnClick(EventArgs e)\n{\n if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)\n {\n base.OnClick(e);\n }\n}\n</code></pre>\n\n<p>this part </p>\n\n<pre><code> MouseButtons != MouseButtons.Right\n</code></pre>\n\n<p>should and does compile as it is a call to Control.MouseButtons. Since the Form inherits Control class, it is sufficient to call MouseButtons property directly.</p>\n\n<p>Hope this helps: </p>\n\n<pre><code>public partial class Form1 : Form\n{\n class CustomToolStripMenuItem : ToolStripMenuItem\n {\n private ContextMenuStrip secondaryContextMenu;\n\n public ContextMenuStrip SecondaryContextMenu\n {\n get\n {\n return secondaryContextMenu;\n }\n set\n {\n secondaryContextMenu = value;\n }\n }\n\n public CustomToolStripMenuItem(string text)\n : base(text)\n { }\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n if (secondaryContextMenu != null)\n {\n secondaryContextMenu.Dispose();\n secondaryContextMenu = null;\n }\n }\n\n base.Dispose(disposing);\n }\n\n protected override void OnClick(EventArgs e)\n {\n if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)\n {\n base.OnClick(e);\n }\n }\n }\n\n class CustomContextMenuStrip : ContextMenuStrip\n {\n private bool secondaryContextMenuActive = false;\n private ContextMenuStrip lastShownSecondaryContextMenu = null;\n\n protected override void Dispose(bool disposing)\n {\n if (disposing)\n {\n if (lastShownSecondaryContextMenu != null)\n {\n lastShownSecondaryContextMenu.Close();\n lastShownSecondaryContextMenu = null;\n }\n }\n base.Dispose(disposing);\n }\n\n protected override void OnControlAdded(ControlEventArgs e)\n {\n e.Control.MouseClick += new MouseEventHandler(Control_MouseClick);\n base.OnControlAdded(e);\n }\n\n protected override void OnControlRemoved(ControlEventArgs e)\n {\n e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick);\n base.OnControlRemoved(e);\n }\n\n private void Control_MouseClick(object sender, MouseEventArgs e)\n {\n ShowSecondaryContextMenu(e);\n }\n\n protected override void OnMouseClick(MouseEventArgs e)\n {\n ShowSecondaryContextMenu(e);\n base.OnMouseClick(e);\n }\n\n private bool ShowSecondaryContextMenu(MouseEventArgs e)\n {\n CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem;\n\n if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right)\n {\n return false;\n }\n\n lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu;\n secondaryContextMenuActive = true;\n ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);\n ctsm.SecondaryContextMenu.Show(Cursor.Position);\n return true;\n }\n\n void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)\n {\n ((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);\n lastShownSecondaryContextMenu = null;\n secondaryContextMenuActive = false;\n Focus();\n }\n\n protected override void OnClosing(ToolStripDropDownClosingEventArgs e)\n {\n if (secondaryContextMenuActive)\n {\n e.Cancel = true;\n }\n\n base.OnClosing(e);\n }\n }\n\n public Form1()\n {\n InitializeComponent();\n\n\n CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem(\"item primary 1\");\n itemPrimary1.SecondaryContextMenu = new ContextMenuStrip();\n itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { \n new ToolStripMenuItem(\"item primary 1.1\"),\n new ToolStripMenuItem(\"item primary 1.2\"),\n });\n\n CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem(\"item primary 2\");\n itemPrimary2.DropDownItems.Add(\"item primary 2, sub 1\");\n itemPrimary2.DropDownItems.Add(\"item primary 2, sub 2\");\n itemPrimary2.SecondaryContextMenu = new ContextMenuStrip();\n itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] { \n new ToolStripMenuItem(\"item primary 2.1\"),\n new ToolStripMenuItem(\"item primary 2.2\"),\n });\n\n CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip();\n primaryContextMenu.Items.AddRange(new ToolStripItem[]{\n itemPrimary1,\n itemPrimary2\n });\n\n this.ContextMenuStrip = primaryContextMenu;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 398421,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>This shows how to use multiple ContextMenus as well as different ones with any combination of mouse clicks.</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/11
|
[
"https://Stackoverflow.com/questions/281831",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30827/"
] |
I am porting an MFC application to .NET WinForms. In the MFC application, you can right click on a menu or on a context menu item and we show another context menu with diagnostic and configuration items. I am trying to port this functionality to .NET, but I am having trouble.
I have been able to capture the right click, disable the click of the underlying menu and pop up a context menu at the right location, but the original menu disappears as soon as it loses focus.
In MFC, we show the new context menu by calling **TrackPopupMenuEx** with the **TPM\_RECURSE** flag.
**ContextMenu** and the newer **ContextMenuStrip** classes in .NET only have a *Show* method. Does anyone know how to do this in .NET?
**EDIT**
I have tried using **TrackPopupMenuEx** through a p/invoke, but that limits you to using a ContextMenu instead of a ContextMenuStrip which looks out of place in our application. It also still does not work correctly. It doesn't work with the new **MenuStrip** and **ContextMenuStrip**.
I have also tried subclassing ToolStripMenuItem to see if I can add a context menu to it. That is working for **MenuStrip**, but **ContextMenuStrip** still allows the right click events to pass through as clicks.
|
Edit, due to a comment:
In:
```
protected override void OnClick(EventArgs e)
{
if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)
{
base.OnClick(e);
}
}
```
this part
```
MouseButtons != MouseButtons.Right
```
should and does compile as it is a call to Control.MouseButtons. Since the Form inherits Control class, it is sufficient to call MouseButtons property directly.
Hope this helps:
```
public partial class Form1 : Form
{
class CustomToolStripMenuItem : ToolStripMenuItem
{
private ContextMenuStrip secondaryContextMenu;
public ContextMenuStrip SecondaryContextMenu
{
get
{
return secondaryContextMenu;
}
set
{
secondaryContextMenu = value;
}
}
public CustomToolStripMenuItem(string text)
: base(text)
{ }
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (secondaryContextMenu != null)
{
secondaryContextMenu.Dispose();
secondaryContextMenu = null;
}
}
base.Dispose(disposing);
}
protected override void OnClick(EventArgs e)
{
if (SecondaryContextMenu == null || MouseButtons != MouseButtons.Right)
{
base.OnClick(e);
}
}
}
class CustomContextMenuStrip : ContextMenuStrip
{
private bool secondaryContextMenuActive = false;
private ContextMenuStrip lastShownSecondaryContextMenu = null;
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (lastShownSecondaryContextMenu != null)
{
lastShownSecondaryContextMenu.Close();
lastShownSecondaryContextMenu = null;
}
}
base.Dispose(disposing);
}
protected override void OnControlAdded(ControlEventArgs e)
{
e.Control.MouseClick += new MouseEventHandler(Control_MouseClick);
base.OnControlAdded(e);
}
protected override void OnControlRemoved(ControlEventArgs e)
{
e.Control.MouseClick -= new MouseEventHandler(Control_MouseClick);
base.OnControlRemoved(e);
}
private void Control_MouseClick(object sender, MouseEventArgs e)
{
ShowSecondaryContextMenu(e);
}
protected override void OnMouseClick(MouseEventArgs e)
{
ShowSecondaryContextMenu(e);
base.OnMouseClick(e);
}
private bool ShowSecondaryContextMenu(MouseEventArgs e)
{
CustomToolStripMenuItem ctsm = this.GetItemAt(e.Location) as CustomToolStripMenuItem;
if (ctsm == null || ctsm.SecondaryContextMenu == null || e.Button != MouseButtons.Right)
{
return false;
}
lastShownSecondaryContextMenu = ctsm.SecondaryContextMenu;
secondaryContextMenuActive = true;
ctsm.SecondaryContextMenu.Closed += new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);
ctsm.SecondaryContextMenu.Show(Cursor.Position);
return true;
}
void SecondaryContextMenu_Closed(object sender, ToolStripDropDownClosedEventArgs e)
{
((ContextMenuStrip)sender).Closed -= new ToolStripDropDownClosedEventHandler(SecondaryContextMenu_Closed);
lastShownSecondaryContextMenu = null;
secondaryContextMenuActive = false;
Focus();
}
protected override void OnClosing(ToolStripDropDownClosingEventArgs e)
{
if (secondaryContextMenuActive)
{
e.Cancel = true;
}
base.OnClosing(e);
}
}
public Form1()
{
InitializeComponent();
CustomToolStripMenuItem itemPrimary1 = new CustomToolStripMenuItem("item primary 1");
itemPrimary1.SecondaryContextMenu = new ContextMenuStrip();
itemPrimary1.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] {
new ToolStripMenuItem("item primary 1.1"),
new ToolStripMenuItem("item primary 1.2"),
});
CustomToolStripMenuItem itemPrimary2 = new CustomToolStripMenuItem("item primary 2");
itemPrimary2.DropDownItems.Add("item primary 2, sub 1");
itemPrimary2.DropDownItems.Add("item primary 2, sub 2");
itemPrimary2.SecondaryContextMenu = new ContextMenuStrip();
itemPrimary2.SecondaryContextMenu.Items.AddRange(new ToolStripMenuItem[] {
new ToolStripMenuItem("item primary 2.1"),
new ToolStripMenuItem("item primary 2.2"),
});
CustomContextMenuStrip primaryContextMenu = new CustomContextMenuStrip();
primaryContextMenu.Items.AddRange(new ToolStripItem[]{
itemPrimary1,
itemPrimary2
});
this.ContextMenuStrip = primaryContextMenu;
}
}
```
|
281,837 |
<p>I would like to parse HTML document and replace action attribute of all the forms and add some hidden fields with XSL. Can someone show some examples of XSL that can do this?</p>
|
[
{
"answer_id": 281848,
"author": "andy.gurin",
"author_id": 22388,
"author_profile": "https://Stackoverflow.com/users/22388",
"pm_score": 0,
"selected": false,
"text": "<p>You can start from <a href=\"http://www.w3schools.com/xsl/\" rel=\"nofollow noreferrer\">this tutorial</a></p>\n\n<p>But be aware that generally <code>XSLT</code> requires well-formed <code>XML</code> as input and <code>HTML</code> isn't always well-formed</p>\n"
},
{
"answer_id": 281932,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 2,
"selected": false,
"text": "<p>What you need first is well formed HTML (at least transitional), although best recommended XHTML. Some XSLT processors could accept malformed HTML but it is not the rule.</p>\n\n<p>To try the example below you can download <a href=\"http://www.microsoft.com/downloads/details.aspx?FamilyId=2FB55371-C94E-4373-B0E9-DB4816552E41&displaylang=en\" rel=\"nofollow noreferrer\">this small Microsoft command line app</a>.</p>\n\n<p>Quick and dirty XSLT example for what you need (example-xslt.xsl):</p>\n\n<pre><code><xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:template match=\"*\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\"/>\n <xsl:apply-templates/>\n </xsl:copy>\n </xsl:template>\n\n <xsl:template match=\"form[@action='foo']\">\n <xsl:copy>\n <xsl:copy-of select=\"@*\"/>\n <xsl:attribute name=\"action\">non-foo</xsl:attribute>\n <input type=\"hidden\" name=\"my-hidden-prop\" value=\"hide-foo-here\"/>\n <xsl:apply-templates select=\"*\"/>\n </xsl:copy>\n </xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>And the corresponding XML example (example.xml).</p>\n\n<pre><code><?xml version =\"1.0\"?>\n<?xml-stylesheet type=\"text/xsl\" href=\"example-xslt.xsl\"?>\n<html>\n <head></head>\n <body>\n <form action=\"foo\">\n </form>\n <form action=\"other\">\n </form>\n </body>\n</html>\n</code></pre>\n"
},
{
"answer_id": 281943,
"author": "ChuckB",
"author_id": 28605,
"author_profile": "https://Stackoverflow.com/users/28605",
"pm_score": 0,
"selected": false,
"text": "<p>Thinking of gurin's answer: one possible XSLT-based pathway for HTML is to use tidy to convert it to XHTML, apply XSLT to the XHTML, but use <code>xsl:output[@method=\"html\"]</code> to get HTML back out. The <code>@doctype-system</code> and <code>@doctype-public</code> attributes let you provide a doctype declaration in the output file as well.</p>\n\n<p>I don't have any sample files for shahbhat, but the general approach is straightforward from an XSLT point of view: start with an identity transform and add in templates for the action attributes to override them in the way you want. To add hidden fields, I suspect the easiest way would be to create a template explicitly for the <code>form</code> element as an identity transform, but with additional elements inside it that are output as well. I think Fernando Miguélez has just posted an example.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281837",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I would like to parse HTML document and replace action attribute of all the forms and add some hidden fields with XSL. Can someone show some examples of XSL that can do this?
|
What you need first is well formed HTML (at least transitional), although best recommended XHTML. Some XSLT processors could accept malformed HTML but it is not the rule.
To try the example below you can download [this small Microsoft command line app](http://www.microsoft.com/downloads/details.aspx?FamilyId=2FB55371-C94E-4373-B0E9-DB4816552E41&displaylang=en).
Quick and dirty XSLT example for what you need (example-xslt.xsl):
```
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="*">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:apply-templates/>
</xsl:copy>
</xsl:template>
<xsl:template match="form[@action='foo']">
<xsl:copy>
<xsl:copy-of select="@*"/>
<xsl:attribute name="action">non-foo</xsl:attribute>
<input type="hidden" name="my-hidden-prop" value="hide-foo-here"/>
<xsl:apply-templates select="*"/>
</xsl:copy>
</xsl:template>
</xsl:stylesheet>
```
And the corresponding XML example (example.xml).
```
<?xml version ="1.0"?>
<?xml-stylesheet type="text/xsl" href="example-xslt.xsl"?>
<html>
<head></head>
<body>
<form action="foo">
</form>
<form action="other">
</form>
</body>
</html>
```
|
281,843 |
<p>I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.</p>
<pre><code>public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
public override IPermission CreatePermission()
{
MySecurityPermission permission = new MySecurityPermission();
//set its properties
permission.Name = this.Name;
permission.Unrestricted = this.Unrestricted;
return permission;
}
}
public class MySecurityPermission : IPermission, IUnrestrictedPermission
{
public MySecurityPermission(PermissionState state)
{
// what method was the attribute decorating that
// created this MySecurityPermission?
}
public void Demand()
{
// Or here?
}
}
</code></pre>
|
[
{
"answer_id": 343463,
"author": "Miral",
"author_id": 43534,
"author_profile": "https://Stackoverflow.com/users/43534",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I guess you could use reflection to scan through all the loaded assemblies, looking for any class/member that has <code>this</code> as an attribute. It'd be quite slow, though, so it's not something you'd want to do often, or in a large project.</p>\n"
},
{
"answer_id": 876371,
"author": "blowdart",
"author_id": 2525,
"author_profile": "https://Stackoverflow.com/users/2525",
"pm_score": 1,
"selected": false,
"text": "<p>What about walking the call stack? At least that would narrow down what you need to reflect over. Grab <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx\" rel=\"nofollow noreferrer\">System.Diagnostics.StackTrace</a> and use <a href=\"http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx\" rel=\"nofollow noreferrer\">GetFrame</a> to get the stack frame one step up from where you are.</p>\n\n<p>It's rather nasty though - CAS attributes really, in my opinion, shouldn't be conditional on what was decorated, rather they should depend on the conditions set in their parameters.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281843",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36668/"
] |
I realize you can't get the target entity in the Attribute itself, but what about in an associated Permission object when using a CodeAccessSecurityAttribute? The Permission object gets called at runtime so it seems there should be a way but I'm at a loss.
```
public sealed class MySecurityAttribute : CodeAccessSecurityAttribute
{
public override IPermission CreatePermission()
{
MySecurityPermission permission = new MySecurityPermission();
//set its properties
permission.Name = this.Name;
permission.Unrestricted = this.Unrestricted;
return permission;
}
}
public class MySecurityPermission : IPermission, IUnrestrictedPermission
{
public MySecurityPermission(PermissionState state)
{
// what method was the attribute decorating that
// created this MySecurityPermission?
}
public void Demand()
{
// Or here?
}
}
```
|
What about walking the call stack? At least that would narrow down what you need to reflect over. Grab [System.Diagnostics.StackTrace](http://msdn.microsoft.com/en-us/library/system.diagnostics.stacktrace.aspx) and use [GetFrame](http://msdn.microsoft.com/en-us/library/system.diagnostics.stackframe.getmethod.aspx) to get the stack frame one step up from where you are.
It's rather nasty though - CAS attributes really, in my opinion, shouldn't be conditional on what was decorated, rather they should depend on the conditions set in their parameters.
|
281,847 |
<p>I understand that there's no universal answer to the attribute vs. element debate (and I read through the other questions I saw on this), but any insight into this particular circumstance would be greatly appreciated. </p>
<p>In our case we're going to be receiving very large amounts of master and transactional data from a system of record to be merged into our own database (upwards of a gig, nightly). The information we receive is essentially a one-for-one with the records in our tables, so for example a list of customers would be (in our old version):</p>
<pre><code><Custs>
<Cust ID="101" LongName="Large customer" ShortName="LgCust" Loc="SE"/>
<Cust ID="102" LongName="Small customer" ShortName="SmCust" Loc="NE"/>
....
</Custs>
</code></pre>
<p>However we've been discussing the merits of moving to a structure that's more element based, for example:</p>
<pre><code><Custs>
<Cust ID="101">
<LongName>Large Customer</LongName>
<ShortName>LgCust</ShortName>
<Loc>SE</Loc>
</Cust>
<Cust ID="102">
<LongName>Small Customer</LongName>
<ShortName>SmCust</ShortName>
<Loc>NE</Loc>
</Cust>
....
</Custs>
</code></pre>
<p>Because the files are so large I don't think we'll be using a DOM parser to try to load these into memory, nor do we have any need of locating particular items in the files. So my question is: in this case, is one form (elements or attributes) generally preferred over the other when you've got large amounts of data and performance demands to consider?</p>
|
[
{
"answer_id": 281861,
"author": "David Norman",
"author_id": 34502,
"author_profile": "https://Stackoverflow.com/users/34502",
"pm_score": 2,
"selected": true,
"text": "<p>If performance is the only requirement, I think you have to go with the attributes, just because it takes up less space. I don't see any advantage to the elements.</p>\n"
},
{
"answer_id": 281867,
"author": "Werg38",
"author_id": 27569,
"author_profile": "https://Stackoverflow.com/users/27569",
"pm_score": 1,
"selected": false,
"text": "<p>I have used both methods with very large files both with DOM and with a line-by-line reader. Certainly you need to use a line-by-line reader to get good performance for very large files. Beyond this my gut feeling is that attributes are more efficient but I have no hard data to back that opinion up with!</p>\n"
},
{
"answer_id": 282080,
"author": "Robert Rossney",
"author_id": 19403,
"author_profile": "https://Stackoverflow.com/users/19403",
"pm_score": 2,
"selected": false,
"text": "<p>If someone's providing you with 1gb of data at a time and you care about performance at all, you should really re-examine the decision to use XML as your transmission format. You're not parsing the data into a DOM, so you're not really able to make use of the benefits that XML gives you over (say) CSV -- ensuring well-formedness, schema validation, transformation, querying, etc.</p>\n\n<p>And now you're considering moving to a format where half of the data that you're going to be processing is markup. What kind of sense does that make?</p>\n\n<p>I come from the when-the-only-tool-you-have-is-a-hammer-you-tend-to-perceive-all-problems-as-nails school of XML, and even I wouldn't use XML for this.</p>\n"
},
{
"answer_id": 282104,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 1,
"selected": false,
"text": "<p>The \"attribute way\" is more preferable if you plan to validate your xml prior to processing by means of a plain old DTD. There is no rule to validate one element content in DTD language but some basic rules can be applied to attribute values.</p>\n\n<p>If you plan to use XSD or no validation at all then I would choose the most readable form, which IMHO is the \"element way\".</p>\n\n<p>No matter where the XML comes from, XML validation should be the first step to process any XML. It makes your application safer and your code smaller since many checks are made before your code even toches the XML data. XSD should be the preferred choice since its syntax allows to check even data conversions (ie float, date fields inside element or attribute content). The con, it is much more complex than a plain DTD file.</p>\n"
},
{
"answer_id": 285995,
"author": "Mads Hansen",
"author_id": 14419,
"author_profile": "https://Stackoverflow.com/users/14419",
"pm_score": 1,
"selected": false,
"text": "<p>Exchanging the data in XML format isn't <strong><em>necessarily</em></strong> bad just because it is a large data set. </p>\n\n<p>However, if you are exchanging really big XML files you might want to consider compressing them before transmission using zip, GZIP, etc. in order to save time and bandwidth.</p>\n\n<p>If you are exchanging database info, consider formatting the information as SQL statements(and even compressing those SQL files before sending); especially if that is what you wind up converting the XML into anyway.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281847",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3613/"
] |
I understand that there's no universal answer to the attribute vs. element debate (and I read through the other questions I saw on this), but any insight into this particular circumstance would be greatly appreciated.
In our case we're going to be receiving very large amounts of master and transactional data from a system of record to be merged into our own database (upwards of a gig, nightly). The information we receive is essentially a one-for-one with the records in our tables, so for example a list of customers would be (in our old version):
```
<Custs>
<Cust ID="101" LongName="Large customer" ShortName="LgCust" Loc="SE"/>
<Cust ID="102" LongName="Small customer" ShortName="SmCust" Loc="NE"/>
....
</Custs>
```
However we've been discussing the merits of moving to a structure that's more element based, for example:
```
<Custs>
<Cust ID="101">
<LongName>Large Customer</LongName>
<ShortName>LgCust</ShortName>
<Loc>SE</Loc>
</Cust>
<Cust ID="102">
<LongName>Small Customer</LongName>
<ShortName>SmCust</ShortName>
<Loc>NE</Loc>
</Cust>
....
</Custs>
```
Because the files are so large I don't think we'll be using a DOM parser to try to load these into memory, nor do we have any need of locating particular items in the files. So my question is: in this case, is one form (elements or attributes) generally preferred over the other when you've got large amounts of data and performance demands to consider?
|
If performance is the only requirement, I think you have to go with the attributes, just because it takes up less space. I don't see any advantage to the elements.
|
281,864 |
<p>I have a function that checks if a cookie (by name) exists or not:</p>
<pre><code>Private Function cookieExists(ByVal cName As String) As Boolean
For Each c As HttpCookie In Response.Cookies
If c.Name = cName Then Return True
Next
Return False
End Function
</code></pre>
<p>I have a class that handles cookies in an application-specific manner, and I want to consolidate all the cookie-related functions to this class. However, I cannot use this code if I simply move it from the aspx page (where it currently resides) to the aforementioned class because I get the error: <code>'Name' Response is not declared.</code> I modified the class to allow the passing of a reference to the <strong><code>Response</code></strong> object:</p>
<pre><code>Public Function cookieExists(ByVal cName As String, ByRef Response As HttpResponse) As Boolean
For Each c As HttpCookie In Response.Cookies
If c.Name = cName Then Return True
Next
Return False
End Function
</code></pre>
<p>My question is: Is there a better way?</p>
|
[
{
"answer_id": 281872,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 5,
"selected": true,
"text": "<pre><code>HttpContext.Current.Response\nHttpContext.Current.Request\n</code></pre>\n"
},
{
"answer_id": 281879,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 2,
"selected": false,
"text": "<p>HttpContext.Current uses the Ambient Context design pattern, so you should be able to access the Response object from just about anywhere in your code. It is very useful.</p>\n\n<p>For those wondering, the Ambient Context pattern is very cool, and is detailed here:</p>\n\n<p><a href=\"http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/\" rel=\"nofollow noreferrer\">http://aabs.wordpress.com/2007/12/31/the-ambient-context-design-pattern-in-net/</a></p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25515/"
] |
I have a function that checks if a cookie (by name) exists or not:
```
Private Function cookieExists(ByVal cName As String) As Boolean
For Each c As HttpCookie In Response.Cookies
If c.Name = cName Then Return True
Next
Return False
End Function
```
I have a class that handles cookies in an application-specific manner, and I want to consolidate all the cookie-related functions to this class. However, I cannot use this code if I simply move it from the aspx page (where it currently resides) to the aforementioned class because I get the error: `'Name' Response is not declared.` I modified the class to allow the passing of a reference to the **`Response`** object:
```
Public Function cookieExists(ByVal cName As String, ByRef Response As HttpResponse) As Boolean
For Each c As HttpCookie In Response.Cookies
If c.Name = cName Then Return True
Next
Return False
End Function
```
My question is: Is there a better way?
|
```
HttpContext.Current.Response
HttpContext.Current.Request
```
|
281,866 |
<p>Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title.</p>
<p>I have a similar problem but needing multiple aggregates. I'd like to display a list of items in any of 3 formats depending on user options:</p>
<ul>
<li>My item's name (15 total, 13 owned by me)</li>
<li>My item's name (15 total)</li>
<li>My item's name (13 owned by me)</li>
</ul>
<p>My database is:</p>
<ul>
<li><strong>items</strong>: itemId, itemName, ownerId</li>
<li><strong>categories</strong>: catId, catName</li>
<li><strong>map</strong>: mapId, itemId, catId</li>
</ul>
<p>The query below gets: category name, count of item ids per category</p>
<pre><code>SELECT
categories.catName,
COUNT(map.itemId) AS item_count
FROM categories
LEFT JOIN map
ON categories.catId = map.catId
GROUP BY categories.catName
</code></pre>
<p>This one gets: category name, count of item ids per category for this owner_id only</p>
<pre><code>SELECT categories.catName,
COUNT(map.itemId) AS owner_item_count
FROM categories
LEFT JOIN map
ON categories.catId = map.catId
LEFT JOIN items
ON items.itemId = map.itemId
WHERE owner = @ownerId
GROUP BY categories.catId
</code></pre>
<p>But how do i get them at the same time in a single query? I.e.: category name, count of item ids per category, count of item ids per category for this owner_id only</p>
<p>Bonus. How can I optionally only retrieve where catId count != 0 for any of these? In trying "WHERE item_count <> 0" I get:</p>
<pre><code>MySQL said: Documentation
#1054 - Unknown column 'rid_count' in 'where clause'
</code></pre>
|
[
{
"answer_id": 281894,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 4,
"selected": true,
"text": "<p>Here's a trick: calculating a <code>SUM()</code> of values that are known to be either 1 or 0 is equivalent to a <code>COUNT()</code> of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL).</p>\n\n<pre><code>SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n LEFT JOIN map m USING (catid)\n LEFT JOIN items i USING (itemid)\nGROUP BY c.catid;\n</code></pre>\n\n<p>As for the bonus question, you could simply do an inner join instead of an outer join, which would mean only categories with at least one row in <code>map</code> would be returned.</p>\n\n<pre><code>SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n INNER JOIN map m USING (catid)\n INNER JOIN items i USING (itemid)\nGROUP BY c.catid;\n</code></pre>\n\n<p>Here's another solution, which is not as efficient but I'll show it to explain why you got the error:</p>\n\n<pre><code>SELECT c.catname, COUNT(m.catid) AS item_count,\n SUM(i.ownerid = @ownerid) AS owner_item_count\nFROM categories c\n LEFT JOIN map m USING (catid)\n LEFT JOIN items i USING (itemid)\nGROUP BY c.catid\nHAVING item_count > 0;\n</code></pre>\n\n<p>You can't use column aliases in the <code>WHERE</code> clause, because expressions in the <code>WHERE</code> clause are evaluated before the expressions in the select-list. In other words, the values associated with select-list expressions aren't available yet.</p>\n\n<p>You can use column aliases in the <code>GROUP BY</code>, <code>HAVING</code>, and <code>ORDER BY</code> clauses. These clauses are run after all the expressions in the select-list have been evaluated.</p>\n"
},
{
"answer_id": 281908,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 2,
"selected": false,
"text": "<p>You can sneak a CASE statement inside your SUM():</p>\n\n<pre><code>SELECT categories.catName, \n COUNT(map.itemId) AS item_count,\n SUM(CASE WHEN owner= @ownerid THEN 1 ELSE 0 END) AS owner_item_count\nFROM categories\nLEFT JOIN map ON categories.catId = map.catId\nLEFT JOIN items ON items.itemId = map.itemId\nGROUP BY categories.catId\nHAVING COUNT(map.itemId) > 0\n</code></pre>\n"
},
{
"answer_id": 281955,
"author": "eswald",
"author_id": 21229,
"author_profile": "https://Stackoverflow.com/users/21229",
"pm_score": 2,
"selected": false,
"text": "<pre><code>SELECT categories.catName, \n COUNT(map.itemId) AS item_count,\n COUNT(items.itemId) AS owner_item_count\nFROM categories\nINNER JOIN map\n ON categories.catId = map.catId\nLEFT JOIN items\n ON items.itemId = map.itemId\n AND items.owner = @ownerId\nGROUP BY categories.catId\n</code></pre>\n\n<p>Note that you could use a <code>HAVING</code> clause on <code>owner_item_count</code>, but the inner join takes care of item_count for you.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281866",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/356/"
] |
Often you need to show a list of database items and certain aggregate numbers about each item. For instance, when you type the title text on Stack Overflow, the Related Questions list appears. The list shows the titles of related entries and the single aggregated number of quantity of responses for each title.
I have a similar problem but needing multiple aggregates. I'd like to display a list of items in any of 3 formats depending on user options:
* My item's name (15 total, 13 owned by me)
* My item's name (15 total)
* My item's name (13 owned by me)
My database is:
* **items**: itemId, itemName, ownerId
* **categories**: catId, catName
* **map**: mapId, itemId, catId
The query below gets: category name, count of item ids per category
```
SELECT
categories.catName,
COUNT(map.itemId) AS item_count
FROM categories
LEFT JOIN map
ON categories.catId = map.catId
GROUP BY categories.catName
```
This one gets: category name, count of item ids per category for this owner\_id only
```
SELECT categories.catName,
COUNT(map.itemId) AS owner_item_count
FROM categories
LEFT JOIN map
ON categories.catId = map.catId
LEFT JOIN items
ON items.itemId = map.itemId
WHERE owner = @ownerId
GROUP BY categories.catId
```
But how do i get them at the same time in a single query? I.e.: category name, count of item ids per category, count of item ids per category for this owner\_id only
Bonus. How can I optionally only retrieve where catId count != 0 for any of these? In trying "WHERE item\_count <> 0" I get:
```
MySQL said: Documentation
#1054 - Unknown column 'rid_count' in 'where clause'
```
|
Here's a trick: calculating a `SUM()` of values that are known to be either 1 or 0 is equivalent to a `COUNT()` of the rows where the value is 1. And you know that a boolean comparison returns 1 or 0 (or NULL).
```
SELECT c.catname, COUNT(m.catid) AS item_count,
SUM(i.ownerid = @ownerid) AS owner_item_count
FROM categories c
LEFT JOIN map m USING (catid)
LEFT JOIN items i USING (itemid)
GROUP BY c.catid;
```
As for the bonus question, you could simply do an inner join instead of an outer join, which would mean only categories with at least one row in `map` would be returned.
```
SELECT c.catname, COUNT(m.catid) AS item_count,
SUM(i.ownerid = @ownerid) AS owner_item_count
FROM categories c
INNER JOIN map m USING (catid)
INNER JOIN items i USING (itemid)
GROUP BY c.catid;
```
Here's another solution, which is not as efficient but I'll show it to explain why you got the error:
```
SELECT c.catname, COUNT(m.catid) AS item_count,
SUM(i.ownerid = @ownerid) AS owner_item_count
FROM categories c
LEFT JOIN map m USING (catid)
LEFT JOIN items i USING (itemid)
GROUP BY c.catid
HAVING item_count > 0;
```
You can't use column aliases in the `WHERE` clause, because expressions in the `WHERE` clause are evaluated before the expressions in the select-list. In other words, the values associated with select-list expressions aren't available yet.
You can use column aliases in the `GROUP BY`, `HAVING`, and `ORDER BY` clauses. These clauses are run after all the expressions in the select-list have been evaluated.
|
281,881 |
<p>I am trying to keep track of something and using the SessionID as they key to that object</p>
<p>However the SessionID every 2-3 reqiests changes shouldn't it remain the same?</p>
<pre><code>HttpContext.Session.SessionID
</code></pre>
<p>Is the code I am using.</p>
|
[
{
"answer_id": 281917,
"author": "MrJavaGuy",
"author_id": 7138,
"author_profile": "https://Stackoverflow.com/users/7138",
"pm_score": 2,
"selected": false,
"text": "<p>I would look into using TempData to keep track of something.</p>\n"
},
{
"answer_id": 283321,
"author": "Hrvoje Hudo",
"author_id": 1407,
"author_profile": "https://Stackoverflow.com/users/1407",
"pm_score": 0,
"selected": false,
"text": "<p>Try with adding machine key into your web.config:<br>\nOnline key generator: <a href=\"http://aspnetresources.com/tools/keycreator.aspx\" rel=\"nofollow noreferrer\">http://aspnetresources.com/tools/keycreator.aspx</a>\nIt seems that server resets machine key for client and generates new one with new session id, every few minutes, which is much lower than it should. Don't know if that's bug or feature:)<br>\nAlso, you can increase your session state timeout, which is i think 20min by default.</p>\n"
},
{
"answer_id": 283341,
"author": "Maxam",
"author_id": 15310,
"author_profile": "https://Stackoverflow.com/users/15310",
"pm_score": 7,
"selected": true,
"text": "<p>I've seen that happen even without MVC. If I remember correctly, ASP.NET keeps assigning new session ids until you place something into the Session variable.</p>\n"
},
{
"answer_id": 458694,
"author": "robnardo",
"author_id": 56774,
"author_profile": "https://Stackoverflow.com/users/56774",
"pm_score": 3,
"selected": false,
"text": "<p>I am working on a .NET MVC cart application and I added </p>\n\n<pre><code>Session[\"myVar\"] = \"1234\";\n</code></pre>\n\n<p>to the Page_Load method found in the Default.aspx.cs code. I also added </p>\n\n<pre><code><%= this.Session.SessionID %>\n</code></pre>\n\n<p>to the Site.Master footer. I then rebuilt my app and browsed the various pages of my app and the footer displays the same session id for all pages as expected!</p>\n"
},
{
"answer_id": 4047914,
"author": "ScottEg",
"author_id": 490716,
"author_profile": "https://Stackoverflow.com/users/490716",
"pm_score": 2,
"selected": false,
"text": "<p>If you look the seession ID cookie is not even sent to the browser unless it's used on the server.</p>\n\n<p>So when a page roundtrips there is no current session ID cookie, so a new session ID is created, hence it is random.</p>\n\n<p>This is logical, why bother tying up the app to a session if the session is not in use?</p>\n"
},
{
"answer_id": 5835631,
"author": "javierlinked",
"author_id": 65629,
"author_profile": "https://Stackoverflow.com/users/65629",
"pm_score": 5,
"selected": false,
"text": "<p>You should initialize the Session object within <code>Global.asax.cs</code>.</p>\n\n<pre><code>void Session_Start(object sender, EventArgs e)\n{\n HttpContext.Current.Session.Add(\"__MyAppSession\", string.Empty);\n}\n</code></pre>\n\n<p>This way the session will not change unless your browser window is closed.</p>\n"
},
{
"answer_id": 21244428,
"author": "Flea",
"author_id": 256212,
"author_profile": "https://Stackoverflow.com/users/256212",
"pm_score": 0,
"selected": false,
"text": "<p>I was having the same problem using ASP.NET Web Forms. I just had to add a <code>global.asax</code> file to the solution and the fixed it for me.</p>\n"
},
{
"answer_id": 36168332,
"author": "sobelito",
"author_id": 643723,
"author_profile": "https://Stackoverflow.com/users/643723",
"pm_score": 0,
"selected": false,
"text": "<p>Summing up answers from @jrojo and @Maxam above, with what I am using.</p>\n\n<p>I am using AWS DynamoDB as the session store (out of scope of the question a little, but gives sample).</p>\n\n<p>Add package via NUGET:\nInstall-Package AWS.SessionProvider </p>\n\n<p>Update Web.config to have keys in appSettings:</p>\n\n<pre><code><add key=\"AWSAccessKey\" value=\"XXX\" />\n<add key=\"AWSSecretKey\" value=\"YYY\" />\n</code></pre>\n\n<p>And session provider to system.web:</p>\n\n<pre><code><sessionState timeout=\"20\"\n mode=\"Custom\"\n customProvider=\"DynamoDBSessionStoreProvider\">\n <providers>\n <add name=\"DynamoDBSessionStoreProvider\"\n type=\"Amazon.SessionProvider.DynamoDBSessionStateStore, AWS.SessionProvider\"\n AWSProfilesLocation=\".aws/credentials\"\n Table=\"ASP.NET_SessionState\"\n Region=\"us-east-1\"\n />\n </providers>\n</sessionState>\n</code></pre>\n\n<p>Add anything to session in global.asax on session start:</p>\n\n<pre><code>void Session_Start(object sender, EventArgs e) {\n HttpContext.Current.Session.Add(\"somethingToForceSessionIdToStick\", string.Empty);\n}\n</code></pre>\n\n<p>Verify by adding this to razor of any page. Refresh that page, then open an ignito window and see a different session:</p>\n\n<pre><code>@HttpContext.Current.Session.SessionID\n</code></pre>\n\n<h1>BobsYourUncle</h1>\n"
},
{
"answer_id": 70582411,
"author": "AnkitK",
"author_id": 784542,
"author_profile": "https://Stackoverflow.com/users/784542",
"pm_score": 0,
"selected": false,
"text": "<p>please see if you have set the cookie samesite attribute to strict.</p>\n<p>remove cookieSameSite="Strict" and check.\n</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281881",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22093/"
] |
I am trying to keep track of something and using the SessionID as they key to that object
However the SessionID every 2-3 reqiests changes shouldn't it remain the same?
```
HttpContext.Session.SessionID
```
Is the code I am using.
|
I've seen that happen even without MVC. If I remember correctly, ASP.NET keeps assigning new session ids until you place something into the Session variable.
|
281,888 |
<p>In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:</p>
<pre><code>import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')
</code></pre>
<p>but I have no solution for files.</p>
|
[
{
"answer_id": 281911,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 8,
"selected": true,
"text": "<p>From <a href=\"http://www.geoffchappell.com/studies/windows/shell/explorer/cmdline.htm\" rel=\"noreferrer\">Geoff Chappell's <em>The Windows Explorer Command Line</em></a></p>\n\n<pre><code>import subprocess\nsubprocess.Popen(r'explorer /select,\"C:\\path\\of\\folder\\file\"')\n</code></pre>\n"
},
{
"answer_id": 27251095,
"author": "user1767754",
"author_id": 1767754,
"author_profile": "https://Stackoverflow.com/users/1767754",
"pm_score": 4,
"selected": false,
"text": "<p>For some reason, on windows 7 it always opens the users Path, for me following worked out:</p>\n\n<pre><code>import subprocess\nsubprocess.call(\"explorer C:\\\\temp\\\\yourpath\", shell=True)\n</code></pre>\n"
},
{
"answer_id": 49159988,
"author": "Guillaume Lebreton",
"author_id": 5823489,
"author_profile": "https://Stackoverflow.com/users/5823489",
"pm_score": 5,
"selected": false,
"text": "<p>A nicer and safer solution (only in Windows unfortunately) is <a href=\"https://docs.python.org/3.6/library/os.html#os.startfile\" rel=\"noreferrer\">os.startfile()</a>.</p>\n<p>When it's given a folder instead of a file, it will open Explorer.</p>\n<p>Im aware that i do not completely answer the question since its not selecting a file, but using <code>subprocess</code> is always kind of a bad idea (for security reasons) and this solution may help other people.</p>\n"
},
{
"answer_id": 50965628,
"author": "ewerybody",
"author_id": 469322,
"author_profile": "https://Stackoverflow.com/users/469322",
"pm_score": 4,
"selected": false,
"text": "<p>As <code>explorer</code> could be overridden it would be a little safer to point to the executable directly. (just had to be <a href=\"https://bandit.readthedocs.io/en/latest/plugins/b607_start_process_with_partial_path.html#b607-start-process-with-partial-path\" rel=\"noreferrer\">schooled on this</a> too)</p>\n<p>And while you're at it: use Python 3s current subprocess API: <code>run()</code></p>\n<pre><code>import os\nimport subprocess\nFILEBROWSER_PATH = os.path.join(os.getenv('WINDIR'), 'explorer.exe')\n\ndef explore(path):\n # explorer would choke on forward slashes\n path = os.path.normpath(path)\n\n if os.path.isdir(path):\n subprocess.run([FILEBROWSER_PATH, path])\n elif os.path.isfile(path):\n subprocess.run([FILEBROWSER_PATH, '/select,', path])\n</code></pre>\n"
},
{
"answer_id": 52881473,
"author": "MacNutter",
"author_id": 10331178,
"author_profile": "https://Stackoverflow.com/users/10331178",
"pm_score": 4,
"selected": false,
"text": "<p>Alternatively, you could use the fileopenbox module of <a href=\"http://easygui.sourceforge.net/\" rel=\"noreferrer\">EasyGUI</a> to open the file explorer for the user to click through and then select a file (returning the full filepath).</p>\n\n<pre><code>import easygui\nfile = easygui.fileopenbox()\n</code></pre>\n"
},
{
"answer_id": 65309355,
"author": "Stephan Yazvinski",
"author_id": 13457123,
"author_profile": "https://Stackoverflow.com/users/13457123",
"pm_score": 3,
"selected": false,
"text": "<p>For anyone wondering how to use a variable in place of a direct file path. The code below will open explorer and highlight the file specified.</p>\n<pre><code>import subprocess\nsubprocess.Popen(f'explorer /select,{variableHere}')\n</code></pre>\n<p>The code below will just open the specified folder in explorer without highlighting any specific file.</p>\n<pre><code>import subprocess\nsubprocess.Popen(f'explorer "{variableHere}"')\n</code></pre>\n<p>Ive only tested on windows</p>\n"
},
{
"answer_id": 70241584,
"author": "Pixelsuft",
"author_id": 16315296,
"author_profile": "https://Stackoverflow.com/users/16315296",
"pm_score": -1,
"selected": false,
"text": "<p>Code To Open Folder In Explorer:</p>\n<pre class=\"lang-py prettyprint-override\"><code>import os\nimport ctypes\nSW_SHOWDEFAULT = 10\npath_to_open = os.getenv('windir')\nctypes.windll.shell32.ShellExecuteW(0, "open", path_to_open, 0, 0, SW_SHOWDEFAULT)\n</code></pre>\n"
},
{
"answer_id": 72888227,
"author": "RAllenAZ",
"author_id": 19417436,
"author_profile": "https://Stackoverflow.com/users/19417436",
"pm_score": 0,
"selected": false,
"text": "<pre><code>import subprocess\nsubprocess.Popen(r'explorer /open,"C:\\path\\of\\folder\\file"')\n</code></pre>\n<p>I find that the explorer /open command will list the files in the directory.\nWhen I used the /select command (as shown above), explorer opened the parent directory and had my directory highlighted.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25705/"
] |
In Python, how do I jump to a file in the Windows Explorer? I found a solution for jumping to folders:
```
import subprocess
subprocess.Popen('explorer "C:\path\of\folder"')
```
but I have no solution for files.
|
From [Geoff Chappell's *The Windows Explorer Command Line*](http://www.geoffchappell.com/studies/windows/shell/explorer/cmdline.htm)
```
import subprocess
subprocess.Popen(r'explorer /select,"C:\path\of\folder\file"')
```
|
281,890 |
<p>There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.</p>
<p>Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)</p>
|
[
{
"answer_id": 497798,
"author": "Kariem",
"author_id": 12039,
"author_profile": "https://Stackoverflow.com/users/12039",
"pm_score": 3,
"selected": false,
"text": "<p>I'm not sure, whether this is considered a workaround, because you already referred to it in your question. You can use <a href=\"http://tools.hibernate.org/\" rel=\"noreferrer\">Hibernate Tools</a> to generate DDL from JPA annotated classes. You just need hibernate tools and its dependencies on the classpath and should be fine with something like the following:</p>\n\n<pre><code><target name=\"schemaexport\" description=\"Export schema to DDL file\"\n depends=\"compile-jpa\"> <!-- compile model classes before running hibernatetool -->\n\n <!-- task definition; project.class.path contains all necessary libs -->\n <taskdef name=\"hibernatetool\" classname=\"org.hibernate.tool.ant.HibernateToolTask\"\n classpathref=\"project.class.path\" />\n\n <hibernatetool destdir=\"export/db\"> <!-- check that directory exists -->\n <jpaconfiguration persistenceunit=\"myPersistenceUnitName\" />\n <classpath>\n <!--\n compiled model classes and other configuration files don't forget\n to put the parent directory of META-INF/persistence.xml here\n -->\n </classpath>\n <hbm2ddl outputfilename=\"schemaexport.sql\" format=\"true\"\n export=\"false\" drop=\"true\" />\n </hibernatetool>\n</target>\n</code></pre>\n\n<p>On the other hand, if you are using Eclipse with Webtools and have configured the project settings correctly, you can just right click and select <em>Generate DDL</em> from the context menu. More information about that on the <a href=\"http://www.eclipse.org/webtools/dali/\" rel=\"noreferrer\">Eclipse Dali website</a>.</p>\n"
},
{
"answer_id": 1652435,
"author": "Andrew Thompson",
"author_id": 198173,
"author_profile": "https://Stackoverflow.com/users/198173",
"pm_score": 2,
"selected": false,
"text": "<p>Here's an explaination of how to use the hibernate SchemaExport class to do what you want. Similar to the anttask method mentioned before, but not everyone uses ant. You can execute this example code right from the commandline.</p>\n\n<p><a href=\"http://jandrewthompson.blogspot.com/2009/10/how-to-generate-ddl-scripts-from.html\" rel=\"nofollow noreferrer\">http://jandrewthompson.blogspot.com/2009/10/how-to-generate-ddl-scripts-from.html</a></p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281890",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/450527/"
] |
There are Hibernate tools for mapping files to ddl generation; ddl to mapping files and so on, but I can't find any command line tools for simple DDL generation from JPA annotated classes.
Does anyone know an easy way to do this? (Not using Ant or Maven workarounds)
|
I'm not sure, whether this is considered a workaround, because you already referred to it in your question. You can use [Hibernate Tools](http://tools.hibernate.org/) to generate DDL from JPA annotated classes. You just need hibernate tools and its dependencies on the classpath and should be fine with something like the following:
```
<target name="schemaexport" description="Export schema to DDL file"
depends="compile-jpa"> <!-- compile model classes before running hibernatetool -->
<!-- task definition; project.class.path contains all necessary libs -->
<taskdef name="hibernatetool" classname="org.hibernate.tool.ant.HibernateToolTask"
classpathref="project.class.path" />
<hibernatetool destdir="export/db"> <!-- check that directory exists -->
<jpaconfiguration persistenceunit="myPersistenceUnitName" />
<classpath>
<!--
compiled model classes and other configuration files don't forget
to put the parent directory of META-INF/persistence.xml here
-->
</classpath>
<hbm2ddl outputfilename="schemaexport.sql" format="true"
export="false" drop="true" />
</hibernatetool>
</target>
```
On the other hand, if you are using Eclipse with Webtools and have configured the project settings correctly, you can just right click and select *Generate DDL* from the context menu. More information about that on the [Eclipse Dali website](http://www.eclipse.org/webtools/dali/).
|
281,891 |
<p>I'm using ASP.NET Membership and noticed there isn't a method in the <a href="http://msdn.microsoft.com/en-us/library/system.web.security.roles_members.aspx" rel="nofollow noreferrer">Roles class</a> to <em>modify</em> a role (its name for instance), only to create and delete them.</p>
<p>Is it possible or it's not supported?</p>
<p>EDIT: @CheGueVerra: Yes, nice workaround. </p>
<p>Do you know (for extra credit :) ) why it's not possible?</p>
|
[
{
"answer_id": 281907,
"author": "Harper Shelby",
"author_id": 21196,
"author_profile": "https://Stackoverflow.com/users/21196",
"pm_score": 3,
"selected": false,
"text": "<p>Renaming a Role in the ASP.NET Membership model programatically would be a Bad Thing™, because the Role names are used in the configuration file to define permissions. If there were a programmatic way to change the Role name (which persisted the change to the database), you would immediately break any Role-based security configurations in web.config for any web apps using the database, and there'd be no way to guarantee that a single web app could alter the configuration of every web app using that Membership DB.</p>\n"
},
{
"answer_id": 281935,
"author": "CheGueVerra",
"author_id": 17787,
"author_profile": "https://Stackoverflow.com/users/17787",
"pm_score": 5,
"selected": true,
"text": "<p>There is no direct way to change a role name in the Membership provider.</p>\n\n<p>I would get the list of users that are in the role you want to rename, then remove them from the list, delete the role, create the role with the new name and then Add the users found earlier to the role with the new name.</p>\n\n<pre><code>public void RenameRoleAndUsers(string OldRoleName, string NewRoleName)\n{\n string[] users = Roles.GetUsersInRole(OldRoleName);\n Roles.CreateRole(NewRoleName);\n Roles.AddUsersToRole(users, NewRoleName);\n Roles.RemoveUsersFromRole(users, OldRoleName);\n Roles.DeleteRole(OldRoleName);\n}\n</code></pre>\n\n<p>That will change the name of the role for all users in the role.</p>\n\n<p>Follow-up: Roles, are used to ensure a user plays only his part in the system, thus User.IsInRole(ROLE_NAME), will help you enforce the BR securities that apply, for a user and the roles he is in. If you can change the role names on the fly, how are you going to validate that the user is really in that role. Well that's what I understood, when I asked about it.</p>\n\n<p>rtpHarry edit: Converted pseudocode sample to compilable c# method</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1782/"
] |
I'm using ASP.NET Membership and noticed there isn't a method in the [Roles class](http://msdn.microsoft.com/en-us/library/system.web.security.roles_members.aspx) to *modify* a role (its name for instance), only to create and delete them.
Is it possible or it's not supported?
EDIT: @CheGueVerra: Yes, nice workaround.
Do you know (for extra credit :) ) why it's not possible?
|
There is no direct way to change a role name in the Membership provider.
I would get the list of users that are in the role you want to rename, then remove them from the list, delete the role, create the role with the new name and then Add the users found earlier to the role with the new name.
```
public void RenameRoleAndUsers(string OldRoleName, string NewRoleName)
{
string[] users = Roles.GetUsersInRole(OldRoleName);
Roles.CreateRole(NewRoleName);
Roles.AddUsersToRole(users, NewRoleName);
Roles.RemoveUsersFromRole(users, OldRoleName);
Roles.DeleteRole(OldRoleName);
}
```
That will change the name of the role for all users in the role.
Follow-up: Roles, are used to ensure a user plays only his part in the system, thus User.IsInRole(ROLE\_NAME), will help you enforce the BR securities that apply, for a user and the roles he is in. If you can change the role names on the fly, how are you going to validate that the user is really in that role. Well that's what I understood, when I asked about it.
rtpHarry edit: Converted pseudocode sample to compilable c# method
|
281,909 |
<p>let's say I have a excel spread sheet like below:</p>
<pre>
col1 col2
------------
dog1 dog
dog2 dog
dog3 dog
dog4 dog
cat1 cat
cat2 cat
cat3 cat
</pre>
<p>I want to return a range of cells (dog1,dog2,dog3,dog4) or (cat1,cat2,cat3) based on either "dog" or "cat"</p>
<p>I know I can do a loop to check one by one, but is there any other method in VBA so I can "filter" the result in one shot? </p>
<p>maybe the Range.Find(XXX) can help, but I only see examples for just one cell not a range of cells.</p>
<p>Please advice</p>
<p>Regards</p>
|
[
{
"answer_id": 281971,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 1,
"selected": false,
"text": "<p>This guy has a nice FindAll function:</p>\n\n<p><a href=\"http://www.cpearson.com/excel/findall.aspx\" rel=\"nofollow noreferrer\">http://www.cpearson.com/excel/findall.aspx</a></p>\n"
},
{
"answer_id": 282003,
"author": "simon",
"author_id": 36674,
"author_profile": "https://Stackoverflow.com/users/36674",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks DJ.</p>\n\n<p>That FindAll solution still uses a VBA loop to do things.</p>\n\n<p>I'm trying to find a way without using user level loop to filter a range in excel VBA.</p>\n\n<p>Here I found a solution. it takes advantage of excel built-in engine to do the job. </p>\n\n<p>(1) use \n worksheetfunction.CountIf(,\"Cat\") to get the count of \"cat\" cells</p>\n\n<p>(2) use .Find(\"cat\") to get the first row of \"cat\"</p>\n\n<p>with the count of rows and the first row, I can get the \"cat\" range already. </p>\n\n<p>The good part of this solution is: no user-level loop, this might improve the performance if the range is big.</p>\n"
},
{
"answer_id": 282054,
"author": "Eric Ness",
"author_id": 18891,
"author_profile": "https://Stackoverflow.com/users/18891",
"pm_score": 0,
"selected": false,
"text": "<p>Excel supports the ODBC protocol. I know that you can connect to an Excel spreadsheet from an Access database and query it. I haven't done it, but perhaps there is a way to query the spreadsheet using ODBC from inside Excel.</p>\n"
},
{
"answer_id": 282141,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 0,
"selected": false,
"text": "<p>Unless you're using a veeeery old machine, or you have an XL2007 worksheet with a bazillion rows, a loop is going to be fast enough. Honest!</p>\n\n<p>Don't trust me? Look at this. I filled a million-row range with random letters using this:</p>\n\n<pre><code>=CHAR(RANDBETWEEN(65,90))\n</code></pre>\n\n<p>Then I wrote this function and called it from a 26-cell range using Control-Shift-Enter:</p>\n\n<pre><code>=TRANSPOSE(UniqueChars(A1:A1000000))\n</code></pre>\n\n<p>Here's the not-very-optimised VBA function I hacked out in a couple of minutes:</p>\n\n<pre><code>Option Explicit\n\nPublic Function UniqueChars(rng As Range)\n\nDim dict As New Dictionary\nDim vals\nDim row As Long\nDim started As Single\n\n started = Timer\n\n vals = rng.Value2\n\n For row = LBound(vals, 1) To UBound(vals, 1)\n If dict.Exists(vals(row, 1)) Then\n Else\n dict.Add vals(row, 1), vals(row, 1)\n End If\n Next\n\n UniqueChars = dict.Items\n\n Debug.Print Timer - started\n\nEnd Function\n</code></pre>\n\n<p>On my year-old Core 2 Duo T7300 (2GHz) laptop it took 0.58 sec.</p>\n"
},
{
"answer_id": 282170,
"author": "Mike Woodhouse",
"author_id": 1060,
"author_profile": "https://Stackoverflow.com/users/1060",
"pm_score": 1,
"selected": false,
"text": "<p>Forgot another XL2007 feature: advanced filtering. If you want it in VBA, I got this from a recorded macro:</p>\n\n<pre><code>Range(\"A1:A1000000\").AdvancedFilter Action:=xlFilterCopy, CopyToRange:= Range(\"F1\"), Unique:=True\n</code></pre>\n\n<p>I timed it at about 0.35 sec...</p>\n\n<p>Admittedly, not much use if you don't have 2007.</p>\n"
},
{
"answer_id": 282353,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": false,
"text": "<p>Here are some notes on using a recordset to return the range.</p>\n\n<pre><code>Sub GetRange()\nDim cn As Object\nDim rs As Object\nDim strcn, strFile, strPos1, strPos2\n\n Set cn = CreateObject(\"ADODB.Connection\")\n Set rs = CreateObject(\"ADODB.Recordset\")\n\n strFile = ActiveWorkbook.FullName\n\n strcn = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" _\n & strFile & \";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';\"\n\n cn.Open strcn\n\n rs.Open \"SELECT * FROM [Sheet1$]\", cn, 3 'adOpenStatic'\n\n rs.Find \"Col2='cat'\"\n strPos1 = rs.AbsolutePosition + 1\n rs.MoveLast\n If Trim(rs!Col2 & \"\") <> \"cat\" Then\n rs.Find \"Col2='cat'\", , -1 'adSearchBackward'\n strPos2 = rs.AbsolutePosition + 1\n Else\n strPos2 = rs.AbsolutePosition + 1\n End If\n Range(\"A\" & strPos1, \"B\" & strPos2).Select\nEnd Sub\n</code></pre>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281909",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36674/"
] |
let's say I have a excel spread sheet like below:
```
col1 col2
------------
dog1 dog
dog2 dog
dog3 dog
dog4 dog
cat1 cat
cat2 cat
cat3 cat
```
I want to return a range of cells (dog1,dog2,dog3,dog4) or (cat1,cat2,cat3) based on either "dog" or "cat"
I know I can do a loop to check one by one, but is there any other method in VBA so I can "filter" the result in one shot?
maybe the Range.Find(XXX) can help, but I only see examples for just one cell not a range of cells.
Please advice
Regards
|
Here are some notes on using a recordset to return the range.
```
Sub GetRange()
Dim cn As Object
Dim rs As Object
Dim strcn, strFile, strPos1, strPos2
Set cn = CreateObject("ADODB.Connection")
Set rs = CreateObject("ADODB.Recordset")
strFile = ActiveWorkbook.FullName
strcn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" _
& strFile & ";Extended Properties='Excel 8.0;HDR=Yes;IMEX=1';"
cn.Open strcn
rs.Open "SELECT * FROM [Sheet1$]", cn, 3 'adOpenStatic'
rs.Find "Col2='cat'"
strPos1 = rs.AbsolutePosition + 1
rs.MoveLast
If Trim(rs!Col2 & "") <> "cat" Then
rs.Find "Col2='cat'", , -1 'adSearchBackward'
strPos2 = rs.AbsolutePosition + 1
Else
strPos2 = rs.AbsolutePosition + 1
End If
Range("A" & strPos1, "B" & strPos2).Select
End Sub
```
|
281,914 |
<p>This is as much a code maintenance issue as a code issue, but I have a WebForm that no longer checks it CustomValidator. It worked when I last touched the code over a year ago, but it no longer works now that the user has requested some changes ...</p>
<p>The WebForm contains a data-bound drop down with a default " - All -" item with String.Empty as its value. When the user clicks the submit button, the validator should check that the drop down's value is not String.Empty. I've set break points in the client validation code and the server validation code, but neither fire. </p>
<p>Where would you start looking? What are the usual suspects? I have, of course, compared my working copy to what is in source control, but nothing jumps out as being suspicious.</p>
<p>Just in case it matters, here is my code:</p>
<pre><code><asp:DropDownList ID="_AssessmentDropDown" runat="server" DataSourceID="_AssessmentsData" CausesValidation="true" AutoPostBack="false"
DataTextField="AssessmentName" DataValueField="AssessmentName" OnDataBound="_HandleAssessmentsBound">
</asp:DropDownList>
<asp:CustomValidator ID="_AssessmentValidator" runat="server" ClientValidationFunction="_HandleValidateAssessment_Client"
ControlToValidate="_AssessmentDropDown" ErrorMessage="* You must select an Assessment."
OnServerValidate="_HandleValidateAssessment" />
<asp:ObjectDataSource ID="_AssessmentsData" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="DataTableAdapters.GET_GRADE_ASSESSMENTSTableAdapter">
<SelectParameters>
<asp:ControlParameter Name="GRADECODE" ControlID="_GradeCodeDropDown" PropertyName="SelectedValue" />
</SelectParameters>
</asp:ObjectDataSource>
</code></pre>
|
[
{
"answer_id": 281919,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>Some troubleshooting steps:</p>\n\n<ul>\n<li>Is this the only validator on the form? </li>\n<li>Is validation enabled on the page? </li>\n<li>Is validation enabled for the targeted control? </li>\n<li>Is the validator itself enabled?</li>\n</ul>\n"
},
{
"answer_id": 281921,
"author": "Maxime Rouiller",
"author_id": 24975,
"author_profile": "https://Stackoverflow.com/users/24975",
"pm_score": 0,
"selected": false,
"text": "<p>I would take a serious look at the ValidationGroup.</p>\n\n<p>If something has been left out of the group, it wouldn't validate anymore. Otherwise, make sure that you don't have any javascript error (for the client side) and that the method that is \"OnServerValidate\" has a break point inside.</p>\n"
},
{
"answer_id": 281923,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Is the validator in the same validator group as the submit button?</p>\n"
},
{
"answer_id": 281946,
"author": "devio",
"author_id": 21336,
"author_profile": "https://Stackoverflow.com/users/21336",
"pm_score": 4,
"selected": true,
"text": "<p>I notice a couple of issues</p>\n\n<ul>\n<li>I don't think you need a CausesValidation=true if AutoPostBack is set to false</li>\n<li>You do not use validation groups, so that cannot be the cause</li>\n<li>Why not use a RequiredFieldValidator?</li>\n<li>If you want to fire validation on empty fields, set the ValidateEmptyText property to true</li>\n</ul>\n"
},
{
"answer_id": 281966,
"author": "AndreasKnudsen",
"author_id": 36465,
"author_profile": "https://Stackoverflow.com/users/36465",
"pm_score": 1,
"selected": false,
"text": "<p>A CustomValidator doesn't fire if the control it is validating has an empty value, so a CustomValidator should always be accompanied by RequiredFieldValidator</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281914",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/470/"
] |
This is as much a code maintenance issue as a code issue, but I have a WebForm that no longer checks it CustomValidator. It worked when I last touched the code over a year ago, but it no longer works now that the user has requested some changes ...
The WebForm contains a data-bound drop down with a default " - All -" item with String.Empty as its value. When the user clicks the submit button, the validator should check that the drop down's value is not String.Empty. I've set break points in the client validation code and the server validation code, but neither fire.
Where would you start looking? What are the usual suspects? I have, of course, compared my working copy to what is in source control, but nothing jumps out as being suspicious.
Just in case it matters, here is my code:
```
<asp:DropDownList ID="_AssessmentDropDown" runat="server" DataSourceID="_AssessmentsData" CausesValidation="true" AutoPostBack="false"
DataTextField="AssessmentName" DataValueField="AssessmentName" OnDataBound="_HandleAssessmentsBound">
</asp:DropDownList>
<asp:CustomValidator ID="_AssessmentValidator" runat="server" ClientValidationFunction="_HandleValidateAssessment_Client"
ControlToValidate="_AssessmentDropDown" ErrorMessage="* You must select an Assessment."
OnServerValidate="_HandleValidateAssessment" />
<asp:ObjectDataSource ID="_AssessmentsData" runat="server"
OldValuesParameterFormatString="original_{0}" SelectMethod="GetData"
TypeName="DataTableAdapters.GET_GRADE_ASSESSMENTSTableAdapter">
<SelectParameters>
<asp:ControlParameter Name="GRADECODE" ControlID="_GradeCodeDropDown" PropertyName="SelectedValue" />
</SelectParameters>
</asp:ObjectDataSource>
```
|
I notice a couple of issues
* I don't think you need a CausesValidation=true if AutoPostBack is set to false
* You do not use validation groups, so that cannot be the cause
* Why not use a RequiredFieldValidator?
* If you want to fire validation on empty fields, set the ValidateEmptyText property to true
|
281,922 |
<p>I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.</p>
<pre><code>c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
</code></pre>
<p>This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?</p>
<p>(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)</p>
<p>Addendum & Clarification:</p>
<p>I shared a google doc with notes on what I'm doing. <a href="http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz" rel="nofollow noreferrer">http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz</a></p>
<p>I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<a href="http://pyro.sourceforge.net/" rel="nofollow noreferrer">http://pyro.sourceforge.net/</a>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.</p>
<p>I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.</p>
<p><strong>Conclusion:</strong>
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<a href="http://launchpad.net/dstorage" rel="nofollow noreferrer">http://launchpad.net/dstorage</a>).</p>
|
[
{
"answer_id": 281991,
"author": "eswald",
"author_id": 21229,
"author_profile": "https://Stackoverflow.com/users/21229",
"pm_score": 2,
"selected": false,
"text": "<p>For a synchronous client, Twisted probably isn't the right option. Instead, you might want to use the socket module directly.</p>\n\n<pre><code>import socket\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\ns.connect((self.host, self.port))\ns.send(output)\ndata = s.recv(size)\ns.close()\n</code></pre>\n\n<p>The <code>recv()</code> call might need to be repeated until you get an empty string, but this shows the basics.</p>\n\n<p>Alternatively, you can rearrange your entire program to support asynchronous calls...</p>\n"
},
{
"answer_id": 282301,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 1,
"selected": false,
"text": "<p>If you are using Twisted you should probably know that:</p>\n\n<ol>\n<li>You will not be making synchronous calls to any network service</li>\n<li>The reactor can only ever be run once, so do not stop it (by calling <code>reactor.stop()</code>) until your application is ready to exit.</li>\n</ol>\n\n<p>I hope this answers your question. I personally believe that Twisted is <strong>exactly</strong> the correct solution for your use case, but that you need to work around your synchronicity issue.</p>\n\n<p>Addendum & Clarification:</p>\n\n<blockquote>\n <p>Part of what I don't understand is\n that when I call reactor.run() it\n seems to go into a loop that just\n watches for network activity. How do I\n continue running the rest of my\n program while it uses the network? if\n I can get past that, then I can\n probably work through the\n synchronicity issue.</p>\n</blockquote>\n\n<p>That is exactly what reactor.run() does. It runs a main loop which is an event reactor. It will not only wait for entwork events, but anything else you have scheduled to happen. With Twisted you will need to structure the rest of your application in a way to deal with its asynchronous nature. Perhaps if we knew what kind of application it is, we could advise.</p>\n"
},
{
"answer_id": 288650,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 3,
"selected": true,
"text": "<p>If you're even considering Pyro, check out <a href=\"http://rpyc.wikidot.com/\" rel=\"nofollow noreferrer\">RPyC</a> first, and re-consider XML-RPC.</p>\n\n<p>Regarding Twisted: try leaving the reactor up instead of stopping it, and just <code>ClientCreator(...).connectTCP(...)</code> each time.</p>\n\n<p>If you <code>self.transport.loseConnection()</code> in your Protocol you won't be leaving open connections.</p>\n"
},
{
"answer_id": 315881,
"author": "Dustin",
"author_id": 39975,
"author_profile": "https://Stackoverflow.com/users/39975",
"pm_score": 2,
"selected": false,
"text": "<p>Why do you feel that it needs to be synchronous?</p>\n\n<p>If you want to ensure that only one of these is happening at a time, invoke all of the calls through a DeferredSemaphore so you can rate limit the actual invocations (to any arbitrary value).</p>\n\n<p>If you want to be able to run multiple streams of these at different times, but don't care about concurrency limits, then you should at least separate reactor startup and teardown from the invocations (the reactor should run throughout the entire lifetime of the process).</p>\n\n<p>If you just can't figure out how to express your application's logic in a reactor pattern, you can use deferToThread and write a chunk of purely synchronous code -- although I would guess this would not be necessary.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35247/"
] |
I'm building a program that has a class used locally, but I want the same class to be used the same way over the network. This means I need to be able to make synchronous calls to any of its public methods. The class reads and writes files, so I think XML-RPC is too much overhead. I created a basic rpc client/server using the examples from twisted, but I'm having trouble with the client.
```
c = ClientCreator(reactor, Greeter)
c.connectTCP(self.host, self.port).addCallback(request)
reactor.run()
```
This works for a single call, when the data is received I'm calling reactor.stop(), but if I make any more calls the reactor won't restart. Is there something else I should be using for this? maybe a different twisted module or another framework?
(I'm not including the details of how the protocol works, because the main point is that I only get one call out of this.)
Addendum & Clarification:
I shared a google doc with notes on what I'm doing. <http://docs.google.com/Doc?id=ddv9rsfd_37ftshgpgz>
I have a version written that uses fuse and can combine multiple local folders into the fuse mount point. The file access is already handled within a class, so I want to have servers that give me network access to the same class. After continuing to search, I suspect pyro (<http://pyro.sourceforge.net/>) might be what I'm really looking for (simply based on reading their home page right now) but I'm open to any suggestions.
I could achieve similar results by using an nfs mount and combining it with my local folder, but I want all of the peers to have access to the same combined filesystem, so that would require every computer to bee an nfs server with a number of nfs mounts equal to the number of computers in the network.
**Conclusion:**
I have decided to use rpyc as it gave me exactly what I was looking for. A server that keeps an instance of a class that I can manipulate as if it was local. If anyone is interested I put my project up on Launchpad (<http://launchpad.net/dstorage>).
|
If you're even considering Pyro, check out [RPyC](http://rpyc.wikidot.com/) first, and re-consider XML-RPC.
Regarding Twisted: try leaving the reactor up instead of stopping it, and just `ClientCreator(...).connectTCP(...)` each time.
If you `self.transport.loseConnection()` in your Protocol you won't be leaving open connections.
|
281,928 |
<p>I often find myself writing simple for loops to perform an operation to many files, for example:</p>
<pre><code>for i in `find . | grep ".xml$"`; do bzip2 $i; done
</code></pre>
<p>It seems a bit depressing that on my 4-core machine only one core is getting used.. is there an easy way I can add parallelism to my shell scripting?</p>
<p>EDIT: To introduce a bit more context to my problems, sorry I was not more clear to start with!</p>
<p>I often want to run simple(ish) scripts, such as plot a graph, compress or uncompress, or run some program, on reasonable sized datasets (usually between 100 and 10,000). The scripts I use to solve such problems look like the one above, but might have a different command, or even a sequence of commands to execute.</p>
<p>For example, just now I am running:</p>
<pre><code>for i in `find . | grep ".xml.bz2$"`; do find_graph -build_graph $i.graph $i; done
</code></pre>
<p>So my problems are in no way bzip specific! (Although parallel bzip does look cool, I intend to use it in future).</p>
|
[
{
"answer_id": 281952,
"author": "Tom Ritter",
"author_id": 8435,
"author_profile": "https://Stackoverflow.com/users/8435",
"pm_score": 1,
"selected": false,
"text": "<p>I think you could to the following</p>\n\n<blockquote>\n<pre><code>for i in `find . | grep \".xml$\"`; do bzip2 $i&; done\n</code></pre>\n</blockquote>\n\n<p>But that would spin off however many processes as you have files instantly and isn't an optimal as just running four processes at a time.</p>\n"
},
{
"answer_id": 281967,
"author": "Peter Crabtree",
"author_id": 36283,
"author_profile": "https://Stackoverflow.com/users/36283",
"pm_score": 3,
"selected": false,
"text": "<p><a href=\"http://www.perlmonks.org/?node_id=651934\" rel=\"nofollow noreferrer\">This perl program</a> fits your needs fairly well, you would just do this:</p>\n\n<pre><code>runN -n 4 bzip2 `find . | grep \".xml$\"`\n</code></pre>\n"
},
{
"answer_id": 281968,
"author": "Davide",
"author_id": 25891,
"author_profile": "https://Stackoverflow.com/users/25891",
"pm_score": 2,
"selected": false,
"text": "<p>The answer to the general question is difficult, because it depends on the details of the things you are parallelizing. \nOn the other hand, for this specific purpose, you should use pbzip2 instead of plain bzip2 (chances are that pbzip2 is already installed or at least in the repositories or your distro). See here for details: <a href=\"http://compression.ca/pbzip2/\" rel=\"nofollow noreferrer\">http://compression.ca/pbzip2/</a></p>\n"
},
{
"answer_id": 281981,
"author": "Fernando Miguélez",
"author_id": 34880,
"author_profile": "https://Stackoverflow.com/users/34880",
"pm_score": 2,
"selected": false,
"text": "<p>I find this kind of operation counterproductive. The reason is the more processes access the disk at the same time the higher the read/write time goes so the final result ends in a longer time. The bottleneck here won't be a CPU issue, no matter how many cores you have.</p>\n\n<p>Haven't you ever performed a simple two big file copies at the same time on the same HD drive? I is usually faster to copy one and then another.</p>\n\n<p>I know this task involves some CPU power (bzip2 is demanding compression method), but try measuring first CPU load before going the \"challenging\" path we all technicians tend to choose much more often than needed.</p>\n"
},
{
"answer_id": 282101,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 2,
"selected": false,
"text": "<p>gnu make has a nice parallelism feature (eg. -j 5) that would work in your case. Create a Makefile</p>\n\n<pre><code>%.xml.bz2 : %.xml\n\n\nall: $(patsubt %.xml,%xml.bz2,$(shell find . -name '*.xml') ) \n</code></pre>\n\n<p>then do a </p>\n\n<pre><code>nice make -j 5\n</code></pre>\n\n<p>replace '5' with some number, probably 1 more than the number of CPU's. You might want to do 'nice' this just in case someone else wants to use the machine while you are on it.</p>\n"
},
{
"answer_id": 282151,
"author": "Steve Baker",
"author_id": 13566,
"author_profile": "https://Stackoverflow.com/users/13566",
"pm_score": 2,
"selected": false,
"text": "<p>I did something like this for bash. The parallel make trick is probably a lot faster for one-offs, but here is the main code section to implement something like this in bash, you will need to modify it for your purposes though:</p>\n\n<pre><code>#!/bin/bash\n\n# Replace NNN with the number of loops you want to run through\n# and CMD with the command you want to parallel-ize.\n\nset -m\n\nnodes=`grep processor /proc/cpuinfo | wc -l`\njob=($(yes 0 | head -n $nodes | tr '\\n' ' '))\n\nisin()\n{\n local v=$1\n\n shift 1\n while (( $# > 0 ))\n do\n if [ $v = $1 ]; then return 0; fi\n shift 1\n done\n return 1\n}\n\ndowait()\n{\n while true\n do\n nj=( $(jobs -p) )\n if (( ${#nj[@]} < nodes ))\n then\n for (( o=0; o<nodes; o++ ))\n do\n if ! isin ${job[$o]} ${nj[*]}; then let job[o]=0; fi\n done\n return;\n fi\n sleep 1\n done\n}\n\nlet x=0\nwhile (( x < NNN ))\ndo\n for (( o=0; o<nodes; o++ ))\n do\n if (( job[o] == 0 )); then break; fi\n done\n\n if (( o == nodes )); then\n dowait;\n continue;\n fi\n\n CMD &\n let job[o]=$!\n\n let x++\ndone\n\nwait\n</code></pre>\n"
},
{
"answer_id": 282177,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 4,
"selected": false,
"text": "<p><strong>Solution</strong>: Use <code>xargs</code> to run in parallel (don't forget the <code>-n</code> option!)</p>\n\n<pre><code>find -name \\*.xml -print0 | xargs -0 -n 1 -P 3 bzip2\n</code></pre>\n"
},
{
"answer_id": 22211099,
"author": "Ole Tange",
"author_id": 363028,
"author_profile": "https://Stackoverflow.com/users/363028",
"pm_score": 2,
"selected": true,
"text": "<p>If you had to solve the problem today you would probably use a tool like GNU Parallel (unless there is a specialized parallelized tool for your task like <code>pbzip2</code>):</p>\n\n<pre><code>find . | grep \".xml$\" | parallel bzip2\n</code></pre>\n\n<p>To learn more: </p>\n\n<ul>\n<li>Watch the intro video for a quick introduction:\n<a href=\"https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1\" rel=\"nofollow\">https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1</a></li>\n<li>Walk through the tutorial (man parallel_tutorial). You command line\nwith love you for it.</li>\n</ul>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281928",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/27074/"
] |
I often find myself writing simple for loops to perform an operation to many files, for example:
```
for i in `find . | grep ".xml$"`; do bzip2 $i; done
```
It seems a bit depressing that on my 4-core machine only one core is getting used.. is there an easy way I can add parallelism to my shell scripting?
EDIT: To introduce a bit more context to my problems, sorry I was not more clear to start with!
I often want to run simple(ish) scripts, such as plot a graph, compress or uncompress, or run some program, on reasonable sized datasets (usually between 100 and 10,000). The scripts I use to solve such problems look like the one above, but might have a different command, or even a sequence of commands to execute.
For example, just now I am running:
```
for i in `find . | grep ".xml.bz2$"`; do find_graph -build_graph $i.graph $i; done
```
So my problems are in no way bzip specific! (Although parallel bzip does look cool, I intend to use it in future).
|
If you had to solve the problem today you would probably use a tool like GNU Parallel (unless there is a specialized parallelized tool for your task like `pbzip2`):
```
find . | grep ".xml$" | parallel bzip2
```
To learn more:
* Watch the intro video for a quick introduction:
<https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1>
* Walk through the tutorial (man parallel\_tutorial). You command line
with love you for it.
|
281,933 |
<p>Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:</p>
<pre><code>String word = "foobooandfoo";
String converted = "";
converted = word.replaceAll("[ao]", "1");
converted = converted.replaceAll("[df]", "2");
converted = converted.replaceAll("[n]", "3");
</code></pre>
<p>My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?</p>
|
[
{
"answer_id": 281949,
"author": "auramo",
"author_id": 4110,
"author_profile": "https://Stackoverflow.com/users/4110",
"pm_score": 1,
"selected": false,
"text": "<p>I don't know if StringBuilder is the tool for you here. I'd consider looking at <a href=\"http://java.sun.com/j2se/1.4.2/docs/api/java/util/regex/Matcher.html\" rel=\"nofollow noreferrer\">Matcher</a> which is part of the java regex package and might be faster than your example above <em>in case you really need the performance</em>. </p>\n"
},
{
"answer_id": 281956,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": 0,
"selected": false,
"text": "<p>I had a look at the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#replaceAll(java.lang.String)\" rel=\"nofollow noreferrer\"><code>Matcher.replaceAll()</code></a> and I noticed that it returns a <code>String</code>. Therefore, I think that what you've got is going to be plenty fast. Regex's are easy to read and quick.</p>\n\n<p>Remember the first rule of optimization: don't do it!</p>\n"
},
{
"answer_id": 281958,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 2,
"selected": false,
"text": "<p>I'd actually say that the code is pretty OK in most applications although it's theoretically inferior to other methods. If you don't want to use the <code>Matcher</code>, try it like this:</p>\n\n<pre><code>StringBuilder result = new StringBuilder(word.length());\n\nfor (char c : word.toCharArray()) {\n switch (c) {\n case 'a': case 'o': result.append('1'); break;\n case 'd': case 'f': result.append('2'); break;\n case 'n': result.append('3'); break;\n default: result.append(c); break;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 281961,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 1,
"selected": false,
"text": "<p>I don't believe you can. All the regex replace APIs use String instead of StringBuilder.</p>\n\n<p>If you're basically converting each char into a different char, you could just do something like:</p>\n\n<pre><code>public String convert(String text)\n{\n char[] chars = new char[text.length()];\n for (int i=0; i < text.length(); i++)\n {\n char c = text.charAt(i);\n char converted;\n switch (c)\n {\n case 'a': converted = '1'; break;\n case 'o': converted = '1'; break;\n case 'd': converted = '2'; break;\n case 'f': converted = '2'; break;\n case 'n': converted = '3'; break;\n default : converted = c; break;\n }\n chars[i] = converted;\n }\n return new String(chars);\n}\n</code></pre>\n\n<p>However, if you do any complex regular expressions, that obviously won't help much.</p>\n"
},
{
"answer_id": 281977,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 4,
"selected": true,
"text": "<p>I think this is a case where clarity and performance happily coincide. I would use a lookup table to do the \"translation\".</p>\n\n<pre><code> public static void translate(StringBuilder str, char[] table)\n {\n for (int idx = 0; idx < str.length(); ++idx) {\n char ch = str.charAt(idx);\n if (ch < table.length) {\n ch = table[ch];\n str.setCharAt(idx, ch);\n }\n }\n }\n</code></pre>\n\n<p>If you have a large alphabet for the <code>str</code> input, or your mappings are sparse, you could use a real map, like this:</p>\n\n<pre><code> public static void translate(StringBuilder str, Map<Character, Character> table)\n {\n for (int idx = 0; idx < str.length(); ++idx) {\n char ch = str.charAt(idx);\n Character conversion = table.get(ch);\n if (conversion != null) \n str.setCharAt(idx, conversion);\n }\n }\n</code></pre>\n\n<p>While these implementations work in-place, you could create a new <code>StringBuilder</code> instance (or append to one that's passed in).</p>\n"
},
{
"answer_id": 282025,
"author": "Andrea Francia",
"author_id": 36131,
"author_profile": "https://Stackoverflow.com/users/36131",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations.</p>\n</blockquote>\n\n<p>Who say that to you? The best way is those that is more clear to read, to the one that uses StringBuilder. The StringBuilder is some circumnstances but in many does not provide a percetible speed up.</p>\n\n<p>You shouldn't initialize \"converted\" if the value is always replaced.</p>\n\n<p>You can remove some of the boiler plate to improve your code:</p>\n\n<pre><code>String word = \"foobooandfoo\";\nString converted = word.replaceAll(\"[ao]\", \"1\")\n .replaceAll(\"[df]\", \"2\")\n .replaceAll(\"[n]\", \"3\");\n</code></pre>\n\n<p>If you want use StringBuilder you could use this method</p>\n\n<p>java.util.regex.Pattern#matcher(java.lang.CharSequence)</p>\n\n<p>which accept CharSequence (implemented by StringBuilder).\nSee <a href=\"http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#matcher(java.lang.CharSequence)\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/docs/api/java/util/regex/Pattern.html#matcher(java.lang.CharSequence)</a>.</p>\n"
},
{
"answer_id": 282115,
"author": "P Arrayah",
"author_id": 33459,
"author_profile": "https://Stackoverflow.com/users/33459",
"pm_score": -1,
"selected": false,
"text": "<p>I would NOT recommend using any regex for this, those are actually all painfully slow when you're doing simple operations. Instead I'd recommend you start with something like this</p>\n\n<pre><code>// usage:\nMap<String, String> replaceRules = new HashMap<String, String>();\nreplaceRules.put(\"ao\", \"1\");\nreplaceRules.put(\"df\", \"2\");\nreplaceRules.put(\"n\", \"3\");\nString s = replacePartsOf(\"foobooandfoo\", replaceRules);\n\n// actual method\npublic String replacePartsOf(String thisString, Map<String, String> withThese) {\n for(Entry<String, String> rule : withThese.entrySet()) {\n thisString = thisString.replaceAll(rule.getKey(), rule.getValue());\n }\n\n return thisString;\n}\n</code></pre>\n\n<p>and after you've got that working, refactor it to use character arrays instead. While I think what you want to do can be done with StringBuilder it most likely won't be worth the effort.</p>\n"
},
{
"answer_id": 283569,
"author": "Alan Moore",
"author_id": 20938,
"author_profile": "https://Stackoverflow.com/users/20938",
"pm_score": 0,
"selected": false,
"text": "<p>StringBuilder vs. regex is a false dichotomy. The reason String#replaceAll() is the wrong tool is because, each time you call it, you're compiling the regex and processing the whole string. You can avoid all that excess work by combining all the regexes into one and using the lower-level methods in Matcher instead of replaceAll(), like so:</p>\n\n<pre><code>String text = \"foobooandfoo\";\nPattern p = Pattern.compile(\"([ao])|([df])|n\");\nMatcher m = p.matcher(text);\nStringBuffer sb = new StringBuffer();\nwhile (m.find())\n{\n m.appendReplacement(sb, \"\");\n sb.append(m.start(1) != -1 ? '1' :\n m.start(2) != -1 ? '2' :\n '3');\n}\nm.appendTail(sb);\nSystem.out.println(sb.toString());\n</code></pre>\n\n<p>Of course, this is still overkill; for a job as simple as this one, I recommend erickson's approach.</p>\n"
},
{
"answer_id": 7403628,
"author": "MSorah",
"author_id": 942768,
"author_profile": "https://Stackoverflow.com/users/942768",
"pm_score": 1,
"selected": false,
"text": "<p>StringBuilder and StringBuffer can have a big performance difference in some programs. See: <a href=\"http://www.thectoblog.com/2011/01/stringbuilder-vs-stringbuffer-vs.html\" rel=\"nofollow\">http://www.thectoblog.com/2011/01/stringbuilder-vs-stringbuffer-vs.html</a>\nWhich would be a strong reason to want to hold onto it.</p>\n\n<p>The original post asked for multi-character to be replaced with single character. This has a resize impact, which in turn could affect performance. </p>\n\n<p>That said the simplest way to do this is with a String. But to take care of were it is done so as to minimize the gc and other effect if performance is a concern.</p>\n\n<p>I like P Arrayah's approach, but for a more generic answer it should use a LinkedHashMap or something that preserves order in case the replacements have a dependency.</p>\n\n<p>Map replaceRules = new HashMap();</p>\n\n<p>Map replaceRules = new LinkedHashMap();</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33203/"
] |
Given a word, I've to replace some specific alphabets with some specific letters such as 1 for a, 5 for b etc. I'm using regex for this. I understand that StringBuilder is the best way to deal with this problem as I'm doing a lot of string manipulations. Here is what I'm doing:
```
String word = "foobooandfoo";
String converted = "";
converted = word.replaceAll("[ao]", "1");
converted = converted.replaceAll("[df]", "2");
converted = converted.replaceAll("[n]", "3");
```
My problem is how to rewrite this program using StringBuilder. I tried everything but I can't succeed. Or using String is just fine for this?
|
I think this is a case where clarity and performance happily coincide. I would use a lookup table to do the "translation".
```
public static void translate(StringBuilder str, char[] table)
{
for (int idx = 0; idx < str.length(); ++idx) {
char ch = str.charAt(idx);
if (ch < table.length) {
ch = table[ch];
str.setCharAt(idx, ch);
}
}
}
```
If you have a large alphabet for the `str` input, or your mappings are sparse, you could use a real map, like this:
```
public static void translate(StringBuilder str, Map<Character, Character> table)
{
for (int idx = 0; idx < str.length(); ++idx) {
char ch = str.charAt(idx);
Character conversion = table.get(ch);
if (conversion != null)
str.setCharAt(idx, conversion);
}
}
```
While these implementations work in-place, you could create a new `StringBuilder` instance (or append to one that's passed in).
|
281,945 |
<p>Does anyone know of a way to store values as NVARCHAR in a manually created query in ColdFusion using the querynew() function? I have multiple parts of a largish program relying on using a query as an input point to construct an excel worksheet (using Ben's POI) so it's somewhat important I can continue to use it as a query to avoid a relatively large rewrite.</p>
<p>The problem came up when a user tried storing something that is outside of the VARCHAR range, some Japanese characters and such.</p>
<p>Edit: If this is not possible, and you are 100% sure, I'd like to know that too :)</p>
|
[
{
"answer_id": 282260,
"author": "Adam Tuttle",
"author_id": 751,
"author_profile": "https://Stackoverflow.com/users/751",
"pm_score": 1,
"selected": false,
"text": "<p>The only thing I've been able to come up with so far is this:</p>\n\n<pre><code><cfset x = QueryNew(\"foobar\")/>\n<cfset queryAddRow(x) />\n<cfset querySetCell(x, \"foobar\", chr(163)) />\n<cfdump var=\"#x#\">\n</code></pre>\n\n<p>When dumped, this query does contain the British Pound symbol.</p>\n\n<p>I haven't tried this with Ben's POI utility, but hopefully it helps you some.</p>\n"
},
{
"answer_id": 282398,
"author": "Ben Doom",
"author_id": 12267,
"author_profile": "https://Stackoverflow.com/users/12267",
"pm_score": 1,
"selected": false,
"text": "<p>You might try using JavaCast() to set the values, as shown here:\n<a href=\"http://www.bennadel.com/blog/291-QueryNew-JavaCast-And-Notes-About-Data-Type-Translation.htm\" rel=\"nofollow noreferrer\">Kinky Solutions (Ben Nadel) on JavaCast()</a></p>\n"
},
{
"answer_id": 290188,
"author": "Patrick McElhaney",
"author_id": 437,
"author_profile": "https://Stackoverflow.com/users/437",
"pm_score": 1,
"selected": false,
"text": "<p>Make sure you're <a href=\"http://mysecretbase.com/ColdFusion_and_Unicode.cfm\" rel=\"nofollow noreferrer\">using Unicode end-to-end</a>. </p>\n"
},
{
"answer_id": 522748,
"author": "Mike Oliver",
"author_id": 13921,
"author_profile": "https://Stackoverflow.com/users/13921",
"pm_score": 2,
"selected": true,
"text": "<p>When creating a ColdFusion query with queryNew(), you can pass a list of datatypes as a second argument. For example:</p>\n\n<pre><code><cfset x = queryNew(\"foo,bar\",\"integer,varchar\") />\n</code></pre>\n\n<p>Alternatively, you can use cf_sql_varchar (which you would use in queryparam tags). According to the livedocs, nvarchar is accepted for the CF varchar data type.</p>\n\n<p><a href=\"http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=part_cfm.htm\" rel=\"nofollow noreferrer\">QueryParam livedoc (referenced for nvarchar data type)</a></p>\n\n<p><a href=\"http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00000600.htm\" rel=\"nofollow noreferrer\">QueryNew livedoc (referenced for data type definition)</a></p>\n\n<p><a href=\"http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00001270.htm#1182700\" rel=\"nofollow noreferrer\">Managing Data Types livedoc (referenced for using cf_sql_datatype)</a></p>\n"
},
{
"answer_id": 538288,
"author": "Henry",
"author_id": 35634,
"author_profile": "https://Stackoverflow.com/users/35634",
"pm_score": 0,
"selected": false,
"text": "<p>This is pretty much all you need: </p>\n\n<pre><code><cfprocessingdirective pageEncoding=\"utf-8\"> \n</code></pre>\n\n<p>ColdFusion (& java) stores string in UTF-8 by default. All you need is to tell CF that the encoding of the page is UTF8. The alternative way is to save the Byte-order mark (BOM), but Eclipse/CFEclipse doesn't do it.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16631/"
] |
Does anyone know of a way to store values as NVARCHAR in a manually created query in ColdFusion using the querynew() function? I have multiple parts of a largish program relying on using a query as an input point to construct an excel worksheet (using Ben's POI) so it's somewhat important I can continue to use it as a query to avoid a relatively large rewrite.
The problem came up when a user tried storing something that is outside of the VARCHAR range, some Japanese characters and such.
Edit: If this is not possible, and you are 100% sure, I'd like to know that too :)
|
When creating a ColdFusion query with queryNew(), you can pass a list of datatypes as a second argument. For example:
```
<cfset x = queryNew("foo,bar","integer,varchar") />
```
Alternatively, you can use cf\_sql\_varchar (which you would use in queryparam tags). According to the livedocs, nvarchar is accepted for the CF varchar data type.
[QueryParam livedoc (referenced for nvarchar data type)](http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=part_cfm.htm)
[QueryNew livedoc (referenced for data type definition)](http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00000600.htm)
[Managing Data Types livedoc (referenced for using cf\_sql\_datatype)](http://livedocs.adobe.com/coldfusion/7/htmldocs/wwhelp/wwhimpl/common/html/wwhelp.htm?context=ColdFusion_Documentation&file=00001270.htm#1182700)
|
281,951 |
<p>We're using the following command line from within a Windows Service developed with C# .Net Framework 1.1:</p>
<pre><code>net use z: \\myComputer\c$
</code></pre>
<p>The service is running under a domain account that is a local administrator on "myComputer". After debugging the code we can see that it does not return any errors but the "z:" drive is never mapped. We've tried the exact same code from a console application and it works properly. What is it that we need to add to the Service to make this work?</p>
<p>The code we're using is included below.</p>
<p>Regards,<br>
Sergio</p>
<pre><code>startInfo.FileName = "net";
startInfo.Arguments = string.Format(@"use {0}: \\{1}\{2}", driveLetter,
computerName, folder).Trim();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
proc.EnableRaisingEvents = false;
proc.StartInfo = startInfo;
proc.Start();
// If there is an error during the mapping of the drive, it will be read
// from the StandardError property which is a StreamReader object and
// be fed into the error output parameter.
using(StreamReader errorReader = proc.StandardError)
{
string standardError = string.Empty;
while((standardError = errorReader.ReadLine()) != null)
{
error += standardError + " ";
}
}
proc.WaitForExit();
</code></pre>
|
[
{
"answer_id": 281959,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>You probably need to specify the account used for the login. Type <code>net use /?</code> on a command prompt to get help setting that up with the command.</p>\n"
},
{
"answer_id": 281964,
"author": "kenny",
"author_id": 3225,
"author_profile": "https://Stackoverflow.com/users/3225",
"pm_score": 0,
"selected": false,
"text": "<p>I suspect that it is because the service is not running in the context of the local user. As I remember, you can configure a windows service from years-ago to 'interact with the desktop' or something similar. </p>\n"
},
{
"answer_id": 281974,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 4,
"selected": false,
"text": "<p>From <a href=\"http://msdn.microsoft.com/en-us/library/ms685143.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/ms685143.aspx</a>:</p>\n\n<blockquote>\n <p>A service (or any process running in a\n different security context) that must\n access a remote resource should use\n the Universal Naming Convention (UNC)\n name to access the resource. The\n service must have appropriate\n privileges to access the resource. If\n a server-side service uses an RPC\n connection, delegation must be enabled\n on the remote server.</p>\n \n <p>Drive letters are not global to the\n system. Each logon session receives\n its own set of drive letters from A to\n Z. Therefore, redirected drives cannot\n be shared between processes running\n under different user accounts.\n Moreover, a service (or any process\n running within its own logon session)\n cannot access the drive letters that\n were established within a different\n logon session.</p>\n \n <p>A service should not directly access\n local or network resources through\n mapped drive letters, nor should it\n call the net use command to map drive\n letters at run time.</p>\n</blockquote>\n"
},
{
"answer_id": 281998,
"author": "AlanR",
"author_id": 7311,
"author_profile": "https://Stackoverflow.com/users/7311",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot access user properties from a windows service (including the HKEY-CURRENT-USER from the registry) because the service does not run as a logged in user.</p>\n\n<p>Mapped drives are part of user settings, so you cannot use them as a service unless you dig through to find the user properties in the registry manually, map the drives in your service, etc. It's a pain.</p>\n\n<p>What you may want to try and do is ask a question about how to have your Service execute the login sequence (probably some .EXE). That may do it for you.</p>\n\n<p>Hope this helps,\nAlan.</p>\n"
},
{
"answer_id": 11656869,
"author": "Gary",
"author_id": 393004,
"author_profile": "https://Stackoverflow.com/users/393004",
"pm_score": 0,
"selected": false,
"text": "<p>I was doing something similar to log in to a remote server, but without the mapped drive part. I don't like using mapped drives; in programs that is, I use subst for convenience all the time.\nAnyway, I just had to make sure to include</p>\n\n<pre><code>use \\\\server\\c$ /user:admin password\n</code></pre>\n\n<p>or whatever your user/password is that has access to the remote server, then it doesn't matter what the service is logged on as.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
We're using the following command line from within a Windows Service developed with C# .Net Framework 1.1:
```
net use z: \\myComputer\c$
```
The service is running under a domain account that is a local administrator on "myComputer". After debugging the code we can see that it does not return any errors but the "z:" drive is never mapped. We've tried the exact same code from a console application and it works properly. What is it that we need to add to the Service to make this work?
The code we're using is included below.
Regards,
Sergio
```
startInfo.FileName = "net";
startInfo.Arguments = string.Format(@"use {0}: \\{1}\{2}", driveLetter,
computerName, folder).Trim();
startInfo.UseShellExecute = false;
startInfo.RedirectStandardError = true;
proc.EnableRaisingEvents = false;
proc.StartInfo = startInfo;
proc.Start();
// If there is an error during the mapping of the drive, it will be read
// from the StandardError property which is a StreamReader object and
// be fed into the error output parameter.
using(StreamReader errorReader = proc.StandardError)
{
string standardError = string.Empty;
while((standardError = errorReader.ReadLine()) != null)
{
error += standardError + " ";
}
}
proc.WaitForExit();
```
|
From <http://msdn.microsoft.com/en-us/library/ms685143.aspx>:
>
> A service (or any process running in a
> different security context) that must
> access a remote resource should use
> the Universal Naming Convention (UNC)
> name to access the resource. The
> service must have appropriate
> privileges to access the resource. If
> a server-side service uses an RPC
> connection, delegation must be enabled
> on the remote server.
>
>
> Drive letters are not global to the
> system. Each logon session receives
> its own set of drive letters from A to
> Z. Therefore, redirected drives cannot
> be shared between processes running
> under different user accounts.
> Moreover, a service (or any process
> running within its own logon session)
> cannot access the drive letters that
> were established within a different
> logon session.
>
>
> A service should not directly access
> local or network resources through
> mapped drive letters, nor should it
> call the net use command to map drive
> letters at run time.
>
>
>
|
281,960 |
<p>I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.</p>
<pre><code><html>
<body>
<script>
function focusTest(el)
{
el.select();
}
</script>
<input type="text" value="one" OnFocus="focusTest(this); return false;" />
<br/>
<input type="text" value="two" OnFocus="focusTest(this); return false;" />
</body>
</html>
</code></pre>
<p>When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)</p>
|
[
{
"answer_id": 281965,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure about a Safari-specific solution here, but an alternative would be to wrap the input element in a div and set the border properties of it via CSS. Then change border color, etc. when focused and unfocused.</p>\n"
},
{
"answer_id": 282015,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 4,
"selected": true,
"text": "<p>I noticed Safari is actually selecting the text then removing the selection quickly.</p>\n\n<p>So I tried this quick workaround that works in all browsers:</p>\n\n<pre><code>function focusTest(el)\n{\n setTimeout (function () {el.select();} , 50 );\n}\n</code></pre>\n\n<p>Edit :<br>\nUpon further testing it turns out the OnMouseUp event is clearing the selection so it is enough to add</p>\n\n<pre><code>onMouseUp=\"return false;\"\n</code></pre>\n\n<p>to the input element for things to work as they should.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/281960",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2749/"
] |
I would like the value of the input text box to be highlighted when it gains focus, either by clicking it or tabbing to it.
```
<html>
<body>
<script>
function focusTest(el)
{
el.select();
}
</script>
<input type="text" value="one" OnFocus="focusTest(this); return false;" />
<br/>
<input type="text" value="two" OnFocus="focusTest(this); return false;" />
</body>
</html>
```
When either input field is clicked in Firefox or IE, that field is highlighted. However, this doesn't work in Safari. (NOTE: it works when tabbing between fields.)
|
I noticed Safari is actually selecting the text then removing the selection quickly.
So I tried this quick workaround that works in all browsers:
```
function focusTest(el)
{
setTimeout (function () {el.select();} , 50 );
}
```
Edit :
Upon further testing it turns out the OnMouseUp event is clearing the selection so it is enough to add
```
onMouseUp="return false;"
```
to the input element for things to work as they should.
|
282,014 |
<p>I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...</p>
<p>Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's obviously running under the design time vhost process...</p>
<p>The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...</p>
<p>What is the explanation? Is there a reference?</p>
|
[
{
"answer_id": 282031,
"author": "Tigraine",
"author_id": 21699,
"author_profile": "https://Stackoverflow.com/users/21699",
"pm_score": 0,
"selected": false,
"text": "<p>There are some things you shouldn't do with the designer. I don't have any hard evidence, but I found that the Windows Forms designer hates it when you take away the default constructor from it. Just go ahead and create new overloads, but leave the empty constructor in place.</p>\n\n<p>Also try to avoid doing <code>Form_Load</code> events in base classes you inherit from.</p>\n"
},
{
"answer_id": 282277,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>You can check the UsageMode of the LicenseManager, to check if the code is in design time or not.</p>\n<p>System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime</p>\n<p>Here is a quick example:</p>\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace Test\n{\n public class ComponentClass : Component\n {\n public ComponentClass()\n {\n MessageBox.Show("Runtime!");\n }\n }\n}\n</code></pre>\n<p>When this component gets add to your form in the designer, you will immediatly get a message box.</p>\n<p>To prevent this you can add a simple if statement to check if the code is not in design time</p>\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nnamespace Test\n{\n public class ComponentClass : Component\n {\n public ComponentClass()\n {\n if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)\n {\n MessageBox.Show("Runtime!");\n }\n }\n }\n}\n</code></pre>\n<p>After adding the if statement, the messagebox no longer appears when the component is added to the form via the designer.</p>\n"
},
{
"answer_id": 1000153,
"author": "tzup",
"author_id": 121755,
"author_profile": "https://Stackoverflow.com/users/121755",
"pm_score": 2,
"selected": false,
"text": "<p>You could also use this to check if the Visual Studio Designer is running the code: </p>\n\n<pre><code>public static bool DesignMode\n{\n get { return (System.Diagnostics.Process.GetCurrentProcess().ProcessName == \"devenv\"); }\n}\n</code></pre>\n\n<p>Then in Form_Load: </p>\n\n<pre><code>if (!DesignMode)\n{\n // Run code that breaks in Visual Studio Designer (like trying to get a DB connection)\n}\n</code></pre>\n\n<p>However, this is less elegant than using the <code>LicensManager.UsageMode</code>, but it works (until Microsoft changes the name of the process Visual Studio runs under). </p>\n"
},
{
"answer_id": 5046902,
"author": "Rob Parker",
"author_id": 181460,
"author_profile": "https://Stackoverflow.com/users/181460",
"pm_score": 4,
"selected": false,
"text": "<p>The constructor of a control or form does not get executed when editing that class in the designer (nor does OnLoad get called). I've occasionally used this to set one value in the designer (eg. making its child controls all Visible in the designer) but override some of them to a different default value in the constructor (eg. hiding certain child controls which will only show in certain circumstances, such as an indicator on a status bar).</p>\n\n<p>However, the constructor <em>does</em> get executed if the control is placed as a child on another control or form in the designer. OnLoad gets executed as well. This may be how your logging code was getting accidentally triggered in the designer.</p>\n\n<p>For detecting design vs runtime, <a href=\"https://stackoverflow.com/questions/34664/designmode-with-controls/708594#708594\">an answer</a> to <a href=\"https://stackoverflow.com/questions/34664/designmode-with-controls\">another question</a> has screenshots of some emperical tests showing the values returned by some common approaches. It appears that a child control of a child control (two levels down) of the form or control being edited in the designer sees its own DesignMode == false, so the normal property check will fail to protect code (eg. in the OnLoad method) for controls nested within a control added in the designer. If you were checking DesignMode as one would expect, it could be the nesting which caused it to get around that check. It also always sees DesignMode == false within the constructor.</p>\n\n<p>Also, note that the LicenseManager.UsageMode check <em>only</em> sees DesignTime within the constructor; when OnLoad is called it is within a RunTime LicenseContext. The most complete solution seems to be to check LicenseManager.UsageMode in the constructor of the control or form (or component) and save the setting to a member variable or property which you can check later to avoid running code that should never run in the designer even when nested. There's also another approach in <a href=\"https://stackoverflow.com/questions/34664/designmode-with-controls/2693338#2693338\">another answer</a> to that other question which accounts for nesting but only works outside the constructor.</p>\n"
},
{
"answer_id": 5048767,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 2,
"selected": false,
"text": "<p>Well, since this has been resurrected anyway, here's the function I use to determine whether I'm in design mode:</p>\n\n<pre><code>public static bool IsAnyInDesignMode(Control control){\n while(control != null){\n if(control.Site != null && control.Site.DesignMode)\n return true;\n control = control.Parent;\n }\n return false;\n}\n</code></pre>\n\n<p>This handles the case where the control is a child created by another control. The <code>DesignMode</code> property is only set for controls created by the designer itself.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282014",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36693/"
] |
I have an object that starts a thread, opens a file, and waits for input from other classes. As it receives input, it writes it to disk. Basically, it's a thread safe data logging class...
Here's the weird part. When I open a form in the designer (Visual Studio 2008) that uses the object the file gets created. It's obviously running under the design time vhost process...
The odd thing is I've not been able to reproduce the issue in another project. I'm not sure what the rules are for code that gets executed in the designer and code that does not. For example, creating a file in a Windows Forms constructor doesn't actually create the file at design time...
What is the explanation? Is there a reference?
|
You can check the UsageMode of the LicenseManager, to check if the code is in design time or not.
System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime
Here is a quick example:
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public class ComponentClass : Component
{
public ComponentClass()
{
MessageBox.Show("Runtime!");
}
}
}
```
When this component gets add to your form in the designer, you will immediatly get a message box.
To prevent this you can add a simple if statement to check if the code is not in design time
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
namespace Test
{
public class ComponentClass : Component
{
public ComponentClass()
{
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
MessageBox.Show("Runtime!");
}
}
}
}
```
After adding the if statement, the messagebox no longer appears when the component is added to the form via the designer.
|
282,016 |
<p>I need to make a piece of C# code interact through COM with all kinds of implementations.</p>
<p>To make it easeier for users of that integration, I included the interacted interfaces in IDL (as part of a relevant existing DLL, but without coclass or implementation), then got that into my C# code by running Tlbimp to create the types definition.</p>
<p>I implemented my C#, creating COM objects based on Windows registry info and casting the object into the interface I need.</p>
<p>I then created a C# implementation of the interface in a seperate project and registered it.
The main program creates the testing COM object correctly but fails to cast it into the interface (gets a null object when using C# 'as', gets an InvalidCastException of explicit cast).</p>
<p>Can someone suggest why the interface is not identified as implemented by the testing object?</p>
<p>This is the interface defition in IDL (compiled in C++ in VS 2005):</p>
<pre><code> [
object,
uuid(B60C546F-EE91-48a2-A352-CFC36E613CB7),
dual,
nonextensible,
helpstring("IScriptGenerator Interface"),
pointer_default(unique)
]
interface IScriptGenerator : IDispatch{
[helpstring("Init the Script generator")]
HRESULT Init();
[helpstring("General purpose error reporting")]
HRESULT GetLastError([out] BSTR *Error);
};
</code></pre>
<p>This is the stub created for C# by Tlbimp:</p>
<pre><code>[TypeLibType(4288)]
[Guid("B60C546F-EE91-48A2-A352-CFC36E613CB7")]
public interface IScriptGenerator
{
[DispId(1610743813)]
void GetLastError(out string Error);
[DispId(1610743808)]
void Init();
}
</code></pre>
<p>This is part of the main C# code, creating a COM object by its ProgID and casting it to the IScriptGenerator interface:</p>
<pre><code>public ScriptGenerator(string GUID)
{
Type comType = Type.GetTypeFromProgID(GUID);
object comObj = null;
if (comType != null)
{
try
{
comObj = Activator.CreateInstance(comType);
}
catch (Exception ex)
{
Debug.Fail("Cannot create the script generator COM object due to the following exception: " + ex, ex.Message + "\n" + ex.StackTrace);
throw ex;
}
}
else
throw new ArgumentException("The GUID does not match a registetred COM object", "GUID");
m_internalGenerator = comObj as IScriptGenerator;
if (m_internalGenerator == null)
{
Debug.Fail("The script generator doesn't support the required interface - IScriptGenerator");
throw new InvalidCastException("The script generator with the GUID " + GUID + " doesn't support the required interface - IScriptGenerator");
}
}
</code></pre>
<p>And this is the implementing C# code, to test it's working (and it's not):</p>
<pre><code> [Guid("EB46E31F-0961-4179-8A56-3895DDF2884E"),
ProgId("ScriptGeneratorExample.ScriptGenerator"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(SOAAPIOLELib.IScriptGeneratorCallback))]
public class ScriptGenerator : IScriptGenerator
{
public void GetLastError(out string Error)
{
throw new NotImplementedException();
}
public void Init()
{
// nothing to do
}
}
</code></pre>
|
[
{
"answer_id": 282325,
"author": "Juan Zamudio",
"author_id": 15058,
"author_profile": "https://Stackoverflow.com/users/15058",
"pm_score": 0,
"selected": false,
"text": "<p>I think you need this on the interface</p>\n\n<pre><code>[InterfaceType(ComInterfaceType.InterfaceIsDual)]\n</code></pre>\n"
},
{
"answer_id": 282560,
"author": "Inbar Shani",
"author_id": 36694,
"author_profile": "https://Stackoverflow.com/users/36694",
"pm_score": 3,
"selected": true,
"text": "<p>Again - thanks for the suggestions.</p>\n\n<p>I was able to finally resolve the issue on my own. I tried the above suggestions and didn't made any progress. Then I changed the namespace of the interop in the 'testing' code - it varied from the one in the main code because of different argument use when using Tlbimp. This solved the problem.</p>\n\n<p>Here's my guess to why: .Net creates the COM object, but when it detects this is actually a .Net object, it bypass the COM layer and communicates directly. In which case, queryInterface (with the interface GUID) is not used and the interface do differ because of different C# namespaces.</p>\n\n<p>This means that in order to supprot integration with .Net code, I will need to publish my original interop assembly aside the IDL.</p>\n\n<p>Thanks,\nInbar</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282016",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36694/"
] |
I need to make a piece of C# code interact through COM with all kinds of implementations.
To make it easeier for users of that integration, I included the interacted interfaces in IDL (as part of a relevant existing DLL, but without coclass or implementation), then got that into my C# code by running Tlbimp to create the types definition.
I implemented my C#, creating COM objects based on Windows registry info and casting the object into the interface I need.
I then created a C# implementation of the interface in a seperate project and registered it.
The main program creates the testing COM object correctly but fails to cast it into the interface (gets a null object when using C# 'as', gets an InvalidCastException of explicit cast).
Can someone suggest why the interface is not identified as implemented by the testing object?
This is the interface defition in IDL (compiled in C++ in VS 2005):
```
[
object,
uuid(B60C546F-EE91-48a2-A352-CFC36E613CB7),
dual,
nonextensible,
helpstring("IScriptGenerator Interface"),
pointer_default(unique)
]
interface IScriptGenerator : IDispatch{
[helpstring("Init the Script generator")]
HRESULT Init();
[helpstring("General purpose error reporting")]
HRESULT GetLastError([out] BSTR *Error);
};
```
This is the stub created for C# by Tlbimp:
```
[TypeLibType(4288)]
[Guid("B60C546F-EE91-48A2-A352-CFC36E613CB7")]
public interface IScriptGenerator
{
[DispId(1610743813)]
void GetLastError(out string Error);
[DispId(1610743808)]
void Init();
}
```
This is part of the main C# code, creating a COM object by its ProgID and casting it to the IScriptGenerator interface:
```
public ScriptGenerator(string GUID)
{
Type comType = Type.GetTypeFromProgID(GUID);
object comObj = null;
if (comType != null)
{
try
{
comObj = Activator.CreateInstance(comType);
}
catch (Exception ex)
{
Debug.Fail("Cannot create the script generator COM object due to the following exception: " + ex, ex.Message + "\n" + ex.StackTrace);
throw ex;
}
}
else
throw new ArgumentException("The GUID does not match a registetred COM object", "GUID");
m_internalGenerator = comObj as IScriptGenerator;
if (m_internalGenerator == null)
{
Debug.Fail("The script generator doesn't support the required interface - IScriptGenerator");
throw new InvalidCastException("The script generator with the GUID " + GUID + " doesn't support the required interface - IScriptGenerator");
}
}
```
And this is the implementing C# code, to test it's working (and it's not):
```
[Guid("EB46E31F-0961-4179-8A56-3895DDF2884E"),
ProgId("ScriptGeneratorExample.ScriptGenerator"),
ClassInterface(ClassInterfaceType.None),
ComSourceInterfaces(typeof(SOAAPIOLELib.IScriptGeneratorCallback))]
public class ScriptGenerator : IScriptGenerator
{
public void GetLastError(out string Error)
{
throw new NotImplementedException();
}
public void Init()
{
// nothing to do
}
}
```
|
Again - thanks for the suggestions.
I was able to finally resolve the issue on my own. I tried the above suggestions and didn't made any progress. Then I changed the namespace of the interop in the 'testing' code - it varied from the one in the main code because of different argument use when using Tlbimp. This solved the problem.
Here's my guess to why: .Net creates the COM object, but when it detects this is actually a .Net object, it bypass the COM layer and communicates directly. In which case, queryInterface (with the interface GUID) is not used and the interface do differ because of different C# namespaces.
This means that in order to supprot integration with .Net code, I will need to publish my original interop assembly aside the IDL.
Thanks,
Inbar
|
282,018 |
<p>I'm doing some maintenance on a private svn server. Authentication is handled through Apache basic HTTP+mod_authz_svn. I need to have it so every user has read/write access, except for a single read-only user. The read-only user still needs to be authenticated, though. I setup my authz config file like this:</p>
<pre>[/]
* = rw
read-only = r</pre>
<p>But this doesn't work. The user "read-only" can still commit changes. I can make things read-only for everyone, but the * bit seems to override what I'm trying to set for "read-only."</p>
<p>FWIW, relevant piece of the Apache conf is:</p>
<pre> <Location /repos>
DAV svn
SVNPath ...
SVNIndexXSLT "/svnindex.xsl"
AuthzSVNAccessFile ...
AuthType Basic
AuthName ...
AuthUserFile ...
Require valid-user
</Location>
</pre>
|
[
{
"answer_id": 282052,
"author": "Martin v. Löwis",
"author_id": 33006,
"author_profile": "https://Stackoverflow.com/users/33006",
"pm_score": 3,
"selected": false,
"text": "<p>In this case, the read-only user has still write access as it also matches the * group.</p>\n\n<p>A safe way to achieve what you want is to create a group of all users except read-only, e.g.</p>\n\n<pre><code>[groups]\nall-but-ro = harry, sally, ...\n\n[/]\n@all-but-ro = rw\nread-only = r\n</code></pre>\n\n<p>(alternatively, you might just generate many =rw lines out of the passwd file)</p>\n\n<p>It might be that svn matches from top to bottom - this is not documented, and I didn't test. So try</p>\n\n<pre><code>[/]\nread-only = r\n* = rw\n</code></pre>\n"
},
{
"answer_id": 282074,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 0,
"selected": false,
"text": "<p>Hmmm, the previous posts may be correct on the ACL order, but...</p>\n\n<p>My configuration includes</p>\n\n<pre><code>AuthzSVNAccessFile \"<path-to-svn-acl-file>\"\n</code></pre>\n\n<p>Might this also be a problem?</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36683/"
] |
I'm doing some maintenance on a private svn server. Authentication is handled through Apache basic HTTP+mod\_authz\_svn. I need to have it so every user has read/write access, except for a single read-only user. The read-only user still needs to be authenticated, though. I setup my authz config file like this:
```
[/]
* = rw
read-only = r
```
But this doesn't work. The user "read-only" can still commit changes. I can make things read-only for everyone, but the \* bit seems to override what I'm trying to set for "read-only."
FWIW, relevant piece of the Apache conf is:
```
<Location /repos>
DAV svn
SVNPath ...
SVNIndexXSLT "/svnindex.xsl"
AuthzSVNAccessFile ...
AuthType Basic
AuthName ...
AuthUserFile ...
Require valid-user
</Location>
```
|
In this case, the read-only user has still write access as it also matches the \* group.
A safe way to achieve what you want is to create a group of all users except read-only, e.g.
```
[groups]
all-but-ro = harry, sally, ...
[/]
@all-but-ro = rw
read-only = r
```
(alternatively, you might just generate many =rw lines out of the passwd file)
It might be that svn matches from top to bottom - this is not documented, and I didn't test. So try
```
[/]
read-only = r
* = rw
```
|
282,019 |
<p>I would like to declare a record in Delphi that contains the same layout as it has in C.</p>
<p>For those interested : This record is part of a union in the Windows OS's LDT_ENTRY record. (I need to use this record in Delphi because I'm working on an Xbox emulator in Delphi - see project Dxbx on sourceforge).</p>
<p>Anyway, the record in question is defined as:</p>
<pre><code> struct
{
DWORD BaseMid : 8;
DWORD Type : 5;
DWORD Dpl : 2;
DWORD Pres : 1;
DWORD LimitHi : 4;
DWORD Sys : 1;
DWORD Reserved_0 : 1;
DWORD Default_Big : 1;
DWORD Granularity : 1;
DWORD BaseHi : 8;
}
Bits;
</code></pre>
<p>As far as I know, there are no bit-fields possible in Delphi. I did try this:</p>
<pre><code> Bits = record
BaseMid: Byte; // 8 bits
_Type: 0..31; // 5 bits
Dpl: 0..3; // 2 bits
Pres: Boolean; // 1 bit
LimitHi: 0..15; // 4 bits
Sys: Boolean; // 1 bit
Reserved_0: Boolean; // 1 bit
Default_Big: Boolean; // 1 bit
Granularity: Boolean; // 1 bit
BaseHi: Byte; // 8 bits
end;
</code></pre>
<p>But alas: it's size becomes 10 bytes, instead of the expected 4.
I would like to know how I should declare the record, so that I get a record with the same layout, the same size, and the same members. Preferrably without loads of getter/setters.</p>
<p>TIA.</p>
|
[
{
"answer_id": 282048,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 0,
"selected": false,
"text": "<p>Well, you basically need to get down to the dirty with bit-manipulation.</p>\n\n<p>Why, specifically, do you need to retain that structure?</p>\n\n<p>If you only need to talk to a legacy program that either talks in this dialect (TCP/IP or similar), or stores data in this manner (files, etc.), then I would map a normal Delphi structure to a bit-version compatible. In other words, I would use a normally structured Delphi structure in memory, and write code to write and read that structure in a compatible manner.</p>\n\n<p>If you need to save memory, I would make getters and setters that manipulate bits of internal integers or similar. This will have a performance impact, but not much more than what the original C program would have, the only difference is that the bit-manipulation would be added by compiler magic in the C version, whereas you will have to write it yourself.</p>\n\n<p>If you don't have many records in memory, and don't need to talk to another program, I'd use a natural Delphi structure. Trade-off for higher performance will be more memory used.</p>\n\n<p>But it all depends on your criteria.</p>\n\n<p>In any case, you won't be able to talk the Delphi compiler into doing the same job for you as the C compiler.</p>\n\n<p>PACKED RECORD, suggested by another here, doesn't do that, and was never meant to. It will only remove alignment padding to put integers on 32-bit boundaries and similar, but won't pack multiple fields into one byte.</p>\n\n<p>Note that a common way to do this is through Delphi SETS, which are implementing internally using bit-fields. Again, you will have different code than the C variant.</p>\n"
},
{
"answer_id": 282123,
"author": "Mihai Limbășan",
"author_id": 14444,
"author_profile": "https://Stackoverflow.com/users/14444",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://rvelthuis.de/\" rel=\"noreferrer\">Rudy's Delphi Corner</a> is the best resource I know of regarding Delphi and C/C++ interoperability. His <a href=\"http://rvelthuis.de/articles/articles-convert.html\" rel=\"noreferrer\">Pitfalls of conversion</a> is pretty much a must read when using C/C++ APIs in Delphi. The chapter you'll be most interested in is <a href=\"http://rvelthuis.de/articles/articles-convert.html#bitfields\" rel=\"noreferrer\">Records and alignment -> Bitfields</a>, but I urge you to read the entire thing top to bottom, <em>twice</em>. The other articles are definitely worth the time investment, too.</p>\n"
},
{
"answer_id": 282275,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": false,
"text": "<p>Ok, my bit manipulation is a bit rusty, so I could have reversed the bytes. But the code below gives the general idea:</p>\n\n<pre><code>type\n TBits = record\n private\n FBaseMid : Byte;\n FTypeDplPres : Byte;\n FLimitHiSysEa: Byte;\n FBaseHi : Byte;\n\n function GetType: Byte;\n procedure SetType(const AType: Byte);\n function GetDpl: Byte;\n procedure SetDbl(const ADpl: Byte);\n function GetBit1(const AIndex: Integer): Boolean;\n procedure SetBit1(const AIndex: Integer; const AValue: Boolean);\n function GetLimitHi: Byte;\n procedure SetLimitHi(const AValue: Byte);\n function GetBit2(const AIndex: Integer): Boolean;\n procedure SetBit2(const AIndex: Integer; const AValue: Boolean);\n\n public\n property BaseMid: Byte read FBaseMid write FBaseMid;\n property &Type: Byte read GetType write SetType; // 0..31\n property Dpl: Byte read GetDpl write SetDbl; // 0..3\n property Pres: Boolean index 128 read GetBit1 write SetBit1; \n property LimitHi: Byte read GetLimitHi write SetLimitHi; // 0..15\n\n property Sys: Boolean index 16 read GetBit2 write SetBit2; \n property Reserved0: Boolean index 32 read GetBit2 write SetBit2; \n property DefaultBig: Boolean index 64 read GetBit2 write SetBit2; \n property Granularity: Boolean index 128 read GetBit2 write SetBit2; \n property BaseHi: Byte read FBaseHi write FBaseHi;\n end;\n\n function TBits.GetType: Byte;\n begin\n Result := (FTypeDplPres shr 3) and $1F;\n end;\n\n procedure TBits.SetType(const AType: Byte);\n begin\n FTypeDplPres := (FTypeDplPres and $07) + ((AType and $1F) shr 3);\n end;\n\n function TBits.GetDpl: Byte;\n begin\n Result := (FTypeDplPres and $06) shr 1;\n end;\n\n procedure TBits.SetDbl(const ADpl: Byte);\n begin\n FTypeDblPres := (FTypeDblPres and $F9) + ((ADpl and $3) shl 1);\n end;\n\n function TBits.GetBit1(const AIndex: Integer): Boolean;\n begin\n Result := FTypeDplPres and AIndex = AIndex;\n end;\n\n procedure TBits.SetBit1(const AIndex: Integer; const AValue: Boolean);\n begin\n if AValue then\n FTypeDblPres := FTypeDblPres or AIndex\n else\n FTypeDblPres := FTypeDblPres and not AIndex;\n end;\n\n function TBits.GetLimitHi: Byte;\n begin\n Result := (FLimitHiSysEa shr 4) and $0F;\n end;\n\n procedure TBits.SetLimitHi(const AValue: Byte);\n begin\n FLimitHiSysEa := (FLimitHiSysEa and $0F) + ((AValue and $0F) shr 4);\n end;\n\n function TBits.GetBit2(const AIndex: Integer): Boolean;\n begin\n Result := FLimitHiSysEa and AIndex = AIndex;\n end;\n\n procedure TBits.SetBit2(const AIndex: Integer; const AValue: Boolean);\n begin\n if AValue then\n FLimitHiSysEa := FLimitHiSysEa or AIndex\n else\n FLimitHiSysEa := FLimitHiSysEa and not AIndex;\n end;\n</code></pre>\n"
},
{
"answer_id": 282385,
"author": "PatrickvL",
"author_id": 12170,
"author_profile": "https://Stackoverflow.com/users/12170",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks everyone!</p>\n\n<p>Based on this information, I reduced this to :</p>\n\n<pre><code>RBits = record\npublic\n BaseMid: BYTE;\nprivate\n Flags: WORD;\n function GetBits(const aIndex: Integer): Integer;\n procedure SetBits(const aIndex: Integer; const aValue: Integer);\npublic\n BaseHi: BYTE;\n property _Type: Integer index $0005 read GetBits write SetBits; // 5 bits at offset 0\n property Dpl: Integer index $0502 read GetBits write SetBits; // 2 bits at offset 5\n property Pres: Integer index $0701 read GetBits write SetBits; // 1 bit at offset 7\n property LimitHi: Integer index $0804 read GetBits write SetBits; // 4 bits at offset 8\n property Sys: Integer index $0C01 read GetBits write SetBits; // 1 bit at offset 12\n property Reserved_0: Integer index $0D01 read GetBits write SetBits; // 1 bit at offset 13\n property Default_Big: Integer index $0E01 read GetBits write SetBits; // 1 bit at offset 14\n property Granularity: Integer index $0F01 read GetBits write SetBits; // 1 bit at offset 15\nend;\n</code></pre>\n\n<p>The index is encoded as follows : <code>(BitOffset shl 8) + NrBits</code>. Where 1<=NrBits<=32 and 0<=BitOffset<=31</p>\n\n<p>Now, I can get and set these bits as follows :</p>\n\n<pre><code>{$OPTIMIZATION ON}\n{$OVERFLOWCHECKS OFF}\nfunction RBits.GetBits(const aIndex: Integer): Integer;\nvar\n Offset: Integer;\n NrBits: Integer;\n Mask: Integer;\nbegin\n NrBits := aIndex and $FF;\n Offset := aIndex shr 8;\n\n Mask := ((1 shl NrBits) - 1);\n\n Result := (Flags shr Offset) and Mask;\nend;\n\nprocedure RBits.SetBits(const aIndex: Integer; const aValue: Integer);\nvar\n Offset: Integer;\n NrBits: Integer;\n Mask: Integer;\nbegin\n NrBits := aIndex and $FF;\n Offset := aIndex shr 8;\n\n Mask := ((1 shl NrBits) - 1);\n Assert(aValue <= Mask);\n\n Flags := (Flags and (not (Mask shl Offset))) or (aValue shl Offset);\nend;\n</code></pre>\n\n<p>Pretty nifty, don't you think?!?!</p>\n\n<p>PS: Rudy Velthuis now included a revised version of this in his excellent <a href=\"http://praxis-velthuis.de/rdc/articles/articles-convert.html#propertyindex\" rel=\"noreferrer\">\"Pitfalls of converting\"-article</a>. </p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12170/"
] |
I would like to declare a record in Delphi that contains the same layout as it has in C.
For those interested : This record is part of a union in the Windows OS's LDT\_ENTRY record. (I need to use this record in Delphi because I'm working on an Xbox emulator in Delphi - see project Dxbx on sourceforge).
Anyway, the record in question is defined as:
```
struct
{
DWORD BaseMid : 8;
DWORD Type : 5;
DWORD Dpl : 2;
DWORD Pres : 1;
DWORD LimitHi : 4;
DWORD Sys : 1;
DWORD Reserved_0 : 1;
DWORD Default_Big : 1;
DWORD Granularity : 1;
DWORD BaseHi : 8;
}
Bits;
```
As far as I know, there are no bit-fields possible in Delphi. I did try this:
```
Bits = record
BaseMid: Byte; // 8 bits
_Type: 0..31; // 5 bits
Dpl: 0..3; // 2 bits
Pres: Boolean; // 1 bit
LimitHi: 0..15; // 4 bits
Sys: Boolean; // 1 bit
Reserved_0: Boolean; // 1 bit
Default_Big: Boolean; // 1 bit
Granularity: Boolean; // 1 bit
BaseHi: Byte; // 8 bits
end;
```
But alas: it's size becomes 10 bytes, instead of the expected 4.
I would like to know how I should declare the record, so that I get a record with the same layout, the same size, and the same members. Preferrably without loads of getter/setters.
TIA.
|
Thanks everyone!
Based on this information, I reduced this to :
```
RBits = record
public
BaseMid: BYTE;
private
Flags: WORD;
function GetBits(const aIndex: Integer): Integer;
procedure SetBits(const aIndex: Integer; const aValue: Integer);
public
BaseHi: BYTE;
property _Type: Integer index $0005 read GetBits write SetBits; // 5 bits at offset 0
property Dpl: Integer index $0502 read GetBits write SetBits; // 2 bits at offset 5
property Pres: Integer index $0701 read GetBits write SetBits; // 1 bit at offset 7
property LimitHi: Integer index $0804 read GetBits write SetBits; // 4 bits at offset 8
property Sys: Integer index $0C01 read GetBits write SetBits; // 1 bit at offset 12
property Reserved_0: Integer index $0D01 read GetBits write SetBits; // 1 bit at offset 13
property Default_Big: Integer index $0E01 read GetBits write SetBits; // 1 bit at offset 14
property Granularity: Integer index $0F01 read GetBits write SetBits; // 1 bit at offset 15
end;
```
The index is encoded as follows : `(BitOffset shl 8) + NrBits`. Where 1<=NrBits<=32 and 0<=BitOffset<=31
Now, I can get and set these bits as follows :
```
{$OPTIMIZATION ON}
{$OVERFLOWCHECKS OFF}
function RBits.GetBits(const aIndex: Integer): Integer;
var
Offset: Integer;
NrBits: Integer;
Mask: Integer;
begin
NrBits := aIndex and $FF;
Offset := aIndex shr 8;
Mask := ((1 shl NrBits) - 1);
Result := (Flags shr Offset) and Mask;
end;
procedure RBits.SetBits(const aIndex: Integer; const aValue: Integer);
var
Offset: Integer;
NrBits: Integer;
Mask: Integer;
begin
NrBits := aIndex and $FF;
Offset := aIndex shr 8;
Mask := ((1 shl NrBits) - 1);
Assert(aValue <= Mask);
Flags := (Flags and (not (Mask shl Offset))) or (aValue shl Offset);
end;
```
Pretty nifty, don't you think?!?!
PS: Rudy Velthuis now included a revised version of this in his excellent ["Pitfalls of converting"-article](http://praxis-velthuis.de/rdc/articles/articles-convert.html#propertyindex).
|
282,023 |
<p>I am trying to audit the action that the user performed that resulted in changes to corresponding tables. For example if a user were to transfer money between 2 accounts this would generate the following sequence of events:</p>
<ol>
<li>Insert transfer amount into Transfer table</li>
<li>Subtract transfer amount from balance in Balance Table for Account 1.</li>
<li>Add transfer amount to balance in Balance Table for Account 2.</li>
</ol>
<p>The parent audit message for all tables would be: "User generated transfer for amount XXX"</p>
<p>This is achieved with the following schema:
<a href="http://img48.imageshack.us/img48/7460/auditloggingiv6.png" rel="nofollow noreferrer">schema</a></p>
<p><a href="http://img48.imageshack.us/img48/7460/auditloggingiv6.png" rel="nofollow noreferrer">alt text http://img48.imageshack.us/img48/7460/auditloggingiv6.png</a></p>
<p>The question is how do I represent this in hibernate? </p>
<p>I have created the following:</p>
<p>In Balance and Transfer's mapping files</p>
<pre><code><set name="auditRecords" table="TransferAuditRecord" inverse="false" cascade="save-update">
<key>
<column name="AuditRecordID" not-null="true" />
</key>
<one-to-many class="audit.AuditRecord"/>
</set>
</code></pre>
<p>Transfer and Balance classes then implement IAuditable which has methods </p>
<pre><code>public void setAuditRecords(Set<AuditRecord> auditRecord);
public Set<AuditRecord> getAuditRecords();
</code></pre>
<p>In AuditRecord's mapping file I have:</p>
<pre><code><many-to-one name="parentAuditRecord" lazy="false"
column="parent_id"
class="audit.AuditRecord"
cascade="all" />
</code></pre>
<p>Then in Logging class using AOP and Hibernate Interceptors I have:</p>
<pre><code>AuditRecord auditRecord = new AuditRecord();
auditRecord.setUser(userDAO.findById(
org.springframework.security.context.SecurityContextHolder.getContext()
.getAuthentication().getName()));
auditRecord.setParentAuditRecord(getCurrentActiveServiceRecord());
auditable.getAuditRecords().add(auditRecord);
</code></pre>
<p>Then in the Service Class I call the following method, enclosed in a transaction:</p>
<pre><code>save(balance1);
save(balance2);
transfer.setPassed(true);
update(transfer);
</code></pre>
<p>The parentAuditRecord is created using AOP with a thread safe stack, and the AuditRecordType_id is set using annotations on the method.</p>
<p>I left out the "passed" column on the transfer table. Previously I call save(transfer) to insert the transfer amount into the Transfer table with passed set to false. (This action is also audited).</p>
<p>My requirements are slightly more complicated than the example above :P</p>
<p>So the sequence of events for the above should be:</p>
<ol>
<li>Update Transfer Table</li>
<li>Insert into AuditRecord (Parent)</li>
<li>Insert into AuditRecord (Child)</li>
<li>Insert into TransferAuditRecord</li>
<li>Insert into Balance Table</li>
<li>Insert into AuditRecord (Child)</li>
<li>Insert into BalanceAuditRecord</li>
<li>Insert into Balance Table</li>
<li>Insert into AuditRecord (Child)</li>
<li>Insert into BalanceAuditRecord</li>
</ol>
<p>However the cascade options defined above fail at the update statement. Hibernate refuses to insert a record into the many-to-many table (even if unsaved-value="any" on the AuditRecord Mapping). I always want to insert rows into the many-to-many tables so potentially one Transfer has many Audit Records marking the previous events. However, the latest event determines the message the user wants to see. Hibernate either tries to update the many-to-many table and previous AuditRecord entries or it simply refuses to insert into AuditRecord and TransferAuditRecord, throwing a TransientObjectException.</p>
<p>The Audit Message is retrieved something like this:</p>
<pre><code>msg=... + ((AuditRecord) balance.getAuditRecords().toArray()[getAuditRecords().size()-1])
.getParentAuditRecord().getAuditRecordType().getDescription() + ...;
</code></pre>
<p>The message should say something like this:
"Username set transfer to passed at 12:00 11-Oct-2008" </p>
<p><strong>EDIT</strong> I decided to go with explicitly mapping the many-to-many table (with an associated interface), and then in afterTransactionCompletion, calling save on the parent audit record (which cascades the save to the child audit records) then explicitly saving the interface on all child mapping tables. This isn't a true audit history, rather a non-invasive method of recording user action. I will look into Envers if I need more complete audit history at a later point.</p>
|
[
{
"answer_id": 282071,
"author": "zmf",
"author_id": 13285,
"author_profile": "https://Stackoverflow.com/users/13285",
"pm_score": 1,
"selected": false,
"text": "<p>Seems like the relationship between parentAuditRecord and transferauditrecord and balance auditrecord shouldn't be one to many. When I read what you typed I'm seeing it as a table per subclass usage of that audit hierarchy which is a one-to-one relationship.</p>\n\n<p><a href=\"http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html\" rel=\"nofollow noreferrer\">http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html</a></p>\n\n<p>You may also want to check out JBoss's Envers project.</p>\n"
},
{
"answer_id": 304060,
"author": "Loki",
"author_id": 39057,
"author_profile": "https://Stackoverflow.com/users/39057",
"pm_score": 0,
"selected": false,
"text": "<p>At the design level, it seems like a insert only db design would work marvels here.</p>\n\n<p>If you want to keep it the way it is right now (which I'm sure you do), you could look into Hibernate listeners/interceptors/events (well defined in the doc: <a href=\"http://www.hibernate.org/hib_docs/v3/reference/en-US/html_single/\" rel=\"nofollow noreferrer\">http://www.hibernate.org/hib_docs/v3/reference/en-US/html_single/</a>)</p>\n\n<p>Else, I just looked into JBoss Envers and it also seems pretty useful.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36670/"
] |
I am trying to audit the action that the user performed that resulted in changes to corresponding tables. For example if a user were to transfer money between 2 accounts this would generate the following sequence of events:
1. Insert transfer amount into Transfer table
2. Subtract transfer amount from balance in Balance Table for Account 1.
3. Add transfer amount to balance in Balance Table for Account 2.
The parent audit message for all tables would be: "User generated transfer for amount XXX"
This is achieved with the following schema:
[schema](http://img48.imageshack.us/img48/7460/auditloggingiv6.png)
[alt text http://img48.imageshack.us/img48/7460/auditloggingiv6.png](http://img48.imageshack.us/img48/7460/auditloggingiv6.png)
The question is how do I represent this in hibernate?
I have created the following:
In Balance and Transfer's mapping files
```
<set name="auditRecords" table="TransferAuditRecord" inverse="false" cascade="save-update">
<key>
<column name="AuditRecordID" not-null="true" />
</key>
<one-to-many class="audit.AuditRecord"/>
</set>
```
Transfer and Balance classes then implement IAuditable which has methods
```
public void setAuditRecords(Set<AuditRecord> auditRecord);
public Set<AuditRecord> getAuditRecords();
```
In AuditRecord's mapping file I have:
```
<many-to-one name="parentAuditRecord" lazy="false"
column="parent_id"
class="audit.AuditRecord"
cascade="all" />
```
Then in Logging class using AOP and Hibernate Interceptors I have:
```
AuditRecord auditRecord = new AuditRecord();
auditRecord.setUser(userDAO.findById(
org.springframework.security.context.SecurityContextHolder.getContext()
.getAuthentication().getName()));
auditRecord.setParentAuditRecord(getCurrentActiveServiceRecord());
auditable.getAuditRecords().add(auditRecord);
```
Then in the Service Class I call the following method, enclosed in a transaction:
```
save(balance1);
save(balance2);
transfer.setPassed(true);
update(transfer);
```
The parentAuditRecord is created using AOP with a thread safe stack, and the AuditRecordType\_id is set using annotations on the method.
I left out the "passed" column on the transfer table. Previously I call save(transfer) to insert the transfer amount into the Transfer table with passed set to false. (This action is also audited).
My requirements are slightly more complicated than the example above :P
So the sequence of events for the above should be:
1. Update Transfer Table
2. Insert into AuditRecord (Parent)
3. Insert into AuditRecord (Child)
4. Insert into TransferAuditRecord
5. Insert into Balance Table
6. Insert into AuditRecord (Child)
7. Insert into BalanceAuditRecord
8. Insert into Balance Table
9. Insert into AuditRecord (Child)
10. Insert into BalanceAuditRecord
However the cascade options defined above fail at the update statement. Hibernate refuses to insert a record into the many-to-many table (even if unsaved-value="any" on the AuditRecord Mapping). I always want to insert rows into the many-to-many tables so potentially one Transfer has many Audit Records marking the previous events. However, the latest event determines the message the user wants to see. Hibernate either tries to update the many-to-many table and previous AuditRecord entries or it simply refuses to insert into AuditRecord and TransferAuditRecord, throwing a TransientObjectException.
The Audit Message is retrieved something like this:
```
msg=... + ((AuditRecord) balance.getAuditRecords().toArray()[getAuditRecords().size()-1])
.getParentAuditRecord().getAuditRecordType().getDescription() + ...;
```
The message should say something like this:
"Username set transfer to passed at 12:00 11-Oct-2008"
**EDIT** I decided to go with explicitly mapping the many-to-many table (with an associated interface), and then in afterTransactionCompletion, calling save on the parent audit record (which cascades the save to the child audit records) then explicitly saving the interface on all child mapping tables. This isn't a true audit history, rather a non-invasive method of recording user action. I will look into Envers if I need more complete audit history at a later point.
|
Seems like the relationship between parentAuditRecord and transferauditrecord and balance auditrecord shouldn't be one to many. When I read what you typed I'm seeing it as a table per subclass usage of that audit hierarchy which is a one-to-one relationship.
<http://www.hibernate.org/hib_docs/reference/en/html/inheritance.html>
You may also want to check out JBoss's Envers project.
|
282,024 |
<p>So I'm generating a random number using Rnd and Randomize to set a seed that looks like this:</p>
<pre><code>Randomize lSeed
Response.Write Rnd
</code></pre>
<p>I'm noticing that it's returning the same result for two values in a row for lSeed (e.g. 123, 124) but then on say 125 it will return a new value but 126 will be the same as the on for 125. Why would this be?</p>
<p>Edit:</p>
<p>I have tried something like this</p>
<pre><code>Randomize
Randomize lSeed
Response.write Rnd
</code></pre>
<p>And I get the same results I described above.</p>
|
[
{
"answer_id": 282027,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>You should reseed before getting a random value each time. I'd recommend seeding to a timer.</p>\n"
},
{
"answer_id": 282032,
"author": "Josh Mein",
"author_id": 2486,
"author_profile": "https://Stackoverflow.com/users/2486",
"pm_score": 0,
"selected": false,
"text": "<p>you can also seed off of the current time that seems to work pretty well</p>\n"
},
{
"answer_id": 282033,
"author": "Gordon Bell",
"author_id": 16473,
"author_profile": "https://Stackoverflow.com/users/16473",
"pm_score": 0,
"selected": false,
"text": "<pre><code>' For ASP, you can create a function like:\nPublic Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer\n Randomize()\n Return ((Rnd() * (high - low)) + low)\nEnd Function\n\n' For ASP.NET, you can create a function like:\nPrivate _rnd As System.Random()\nPublic Function RandRange(ByVal low As Integer, ByVal high As Integer) As Integer\n ' Purpose: Returns Random Integer between low and high, inclusive\n ' Note: _rnd variable must be defined outside of RandRange function\n If _rnd Is Nothing Then\n _rnd = New System.Random()\n End If\n Return _rnd.Next(low, high)\nEnd Function\n</code></pre>\n"
},
{
"answer_id": 282058,
"author": "Aaron Palmer",
"author_id": 24908,
"author_profile": "https://Stackoverflow.com/users/24908",
"pm_score": 2,
"selected": false,
"text": "<p>That's the problem with random numbers...</p>\n\n<p><a href=\"http://web.archive.org/web/20011027002011/http://dilbert.com/comics/dilbert/archive/images/dilbert2001182781025.gif\" rel=\"nofollow noreferrer\">http://web.archive.org/web/20011027002011/http://dilbert.com/comics/dilbert/archive/images/dilbert2001182781025.gif</a></p>\n"
},
{
"answer_id": 651106,
"author": "Jon",
"author_id": 12261,
"author_profile": "https://Stackoverflow.com/users/12261",
"pm_score": 1,
"selected": true,
"text": "<p>The issue was that the value for the seed was too large in the other environment (an incrementing database value). I ended up doing value Mod 100 to get something semi-random and that was going to be low to always work.</p>\n"
}
] |
2008/11/11
|
[
"https://Stackoverflow.com/questions/282024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12261/"
] |
So I'm generating a random number using Rnd and Randomize to set a seed that looks like this:
```
Randomize lSeed
Response.Write Rnd
```
I'm noticing that it's returning the same result for two values in a row for lSeed (e.g. 123, 124) but then on say 125 it will return a new value but 126 will be the same as the on for 125. Why would this be?
Edit:
I have tried something like this
```
Randomize
Randomize lSeed
Response.write Rnd
```
And I get the same results I described above.
|
The issue was that the value for the seed was too large in the other environment (an incrementing database value). I ended up doing value Mod 100 to get something semi-random and that was going to be low to always work.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.