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
|
---|---|---|---|---|---|---|
267,064 |
<p>Why is the dropdown not showing my blank item first? Here is what I have</p>
<pre><code>drpList.Items.Add(New ListItem("", ""))
With drpList
.DataSource = myController.GetList(userid)
.DataTextField = "Name"
.DataValueField = "ID"
.DataBind()
End With
</code></pre>
<p>Edit ~ I am binding to a Generig List, could this be the culprit?</p>
|
[
{
"answer_id": 267070,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>it looks like you are adding a blank item, and then databinding, which would empty the list; try inserting the blank item after databinding</p>\n"
},
{
"answer_id": 267074,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 5,
"selected": false,
"text": "<p>The databinding takes place after you've added your blank list item, and it replaces what's there already, you need to add the blank item to the beginning of the List from your controller, or add it after databinding.</p>\n\n<p>EDIT:</p>\n\n<p>After googling this quickly as of ASP.Net 2.0 there's an \"AppendDataBoundItems\" true property that you can set to...append the databound items.</p>\n\n<p>for details see</p>\n\n<p><a href=\"http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=281\" rel=\"noreferrer\">http://imar.spaanjaars.com/QuickDocId.aspx?quickdoc=281</a> or </p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.appenddatabounditems.aspx</a></p>\n"
},
{
"answer_id": 267080,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "<p>Do your databinding and then add the following:</p>\n\n<pre><code>Dim liFirst As New ListItem(\"\", \"\")\ndrpList.Items.Insert(0, liFirst)\n</code></pre>\n"
},
{
"answer_id": 267082,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 9,
"selected": true,
"text": "<p>After your databind:</p>\n\n<pre><code>drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));\ndrpList.SelectedIndex = 0;\n</code></pre>\n"
},
{
"answer_id": 659354,
"author": "Andy McCluggage",
"author_id": 3362,
"author_profile": "https://Stackoverflow.com/users/3362",
"pm_score": 4,
"selected": false,
"text": "<p>I think a better way is to insert the blank item first, then bind the data just as you have been doing. However you need to set the <code>AppendDataBoundItems</code> property of the list control.</p>\n\n<p>We use the following method to bind any data source to any list control...</p>\n\n<pre><code>public static void BindList(ListControl list, IEnumerable datasource, string valueName, string textName)\n{\n list.Items.Clear();\n list.Items.Add(\"\", \"\");\n list.AppendDataBoundItems = true;\n list.DataValueField = valueName;\n list.DataTextField = textName;\n list.DataSource = datasource;\n list.DataBind();\n}\n</code></pre>\n"
},
{
"answer_id": 4060487,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>Like \"Whisk\" Said, the trick is in \"AppendDataBoundItems\" property</p>\n\n<pre><code>protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n DropDownList1.AppendDataBoundItems = true;\n DropDownList1.Items.Insert(0, new ListItem(String.Empty, String.Empty));\n DropDownList1.SelectedIndex = 0;\n }\n}\n</code></pre>\n\n<p>Thanks \"Whisk\"</p>\n"
},
{
"answer_id": 10498971,
"author": "Umesh",
"author_id": 1382097,
"author_profile": "https://Stackoverflow.com/users/1382097",
"pm_score": 2,
"selected": false,
"text": "<p>simple </p>\n\n<p>at last </p>\n\n<pre><code>ddlProducer.Items.Insert(0, \"\");\n</code></pre>\n"
},
{
"answer_id": 13597034,
"author": "ayhtut",
"author_id": 1858461,
"author_profile": "https://Stackoverflow.com/users/1858461",
"pm_score": 5,
"selected": false,
"text": "<p>You can use <code>AppendDataBoundItems=true</code> to easily add:</p>\n<pre><code><asp:DropDownList ID="drpList" AppendDataBoundItems="true" runat="server">\n <asp:ListItem Text="" Value="" />\n</asp:DropDownList>\n</code></pre>\n"
},
{
"answer_id": 16186763,
"author": "Chưa biết",
"author_id": 2246088,
"author_profile": "https://Stackoverflow.com/users/2246088",
"pm_score": 1,
"selected": false,
"text": "<p><code>ddlCategory.DataSource = ds;</code><br>\n<code>ddlCategory.DataTextField = \"CatName\";</code><br>\n<code>ddlCategory.DataValueField = \"CatID\";</code><br></p>\n\n<p>Cách 1:</p>\n\n<p><code>ddlCategory.Items.Add(new ListItem(\"--please select--\", \"-1\"));</code><br>\n<code>ddlCategory.AppendDataBoundItems = true;</code><br>\n<code>ddlCategory.SelectedIndex = -1;</code><br></p>\n\n<p><code>ddlCategory.DataBind();</code><br></p>\n\n<p>Cách 2:<br></p>\n\n<p><code>ddlCategory.Items.Insert(0, new ListItem(\"-- please select --\", \"0\"));</code></p>\n\n<p><strong>(Tested OK)</strong></p>\n"
},
{
"answer_id": 28820158,
"author": "BitsAndBytes",
"author_id": 407635,
"author_profile": "https://Stackoverflow.com/users/407635",
"pm_score": 0,
"selected": false,
"text": "<p>You could also have a union of the blank select with the select that has content:</p>\n\n<pre><code>select '' value, '' name\nunion\nselect value, name from mytable\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23667/"
] |
Why is the dropdown not showing my blank item first? Here is what I have
```
drpList.Items.Add(New ListItem("", ""))
With drpList
.DataSource = myController.GetList(userid)
.DataTextField = "Name"
.DataValueField = "ID"
.DataBind()
End With
```
Edit ~ I am binding to a Generig List, could this be the culprit?
|
After your databind:
```
drpList.Items.Insert(0, new ListItem(String.Empty, String.Empty));
drpList.SelectedIndex = 0;
```
|
267,071 |
<p>I'm using the JSP <a href="http://displaytag.sourceforge.net/11/" rel="nofollow noreferrer">displaytag</a> tag lib to create HTML tables. I'd like the user to able to click on a column header in order to sort the data. My JSP code is shown below:</p>
<pre><code><display:table name="tableData" id="stat" sort="page">
<display:column property="name" title="Name" sortable="true"/>
<display:column property="age" title="Age" sortable="true"/>
</display:table>
</code></pre>
<p>I thought this would cause the data to be sorted on the client-side (in JavaScript), but what it actually does is create a broken hyperlink on the column header back to the server.</p>
<p>Is it possible to use displaytag to sort data on the client-side? If so, how?</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 267081,
"author": "Josh",
"author_id": 2204759,
"author_profile": "https://Stackoverflow.com/users/2204759",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at using <a href=\"http://jquery.com\" rel=\"nofollow noreferrer\">jquery</a> and its excellent <a href=\"http://tablesorter.com\" rel=\"nofollow noreferrer\">tablesorter</a> API. This will let you sort the table on the client side using Javascript.</p>\n"
},
{
"answer_id": 267365,
"author": "MetroidFan2002",
"author_id": 8026,
"author_profile": "https://Stackoverflow.com/users/8026",
"pm_score": 3,
"selected": false,
"text": "<p>As far as I know, this is not possible. JQuery's tablesorter may work for the small tables that it uses for its examples, but most tables have to come from an actual database. This hit is far too great to simply retrieve all the data before returning to the client with this information, and then allowing it to be sorted.</p>\n\n<p>Displaytag has a \"requestURI\" element for the tag that allows its requests to go to your configured url-handler. </p>\n\n<p>So, if you use this:</p>\n\n<pre><code><display:table requestURI=\"yourUrlMappedController.yourExtension\" ...>\n</code></pre>\n\n<p>This will allow for the stopgap solution of retrieving the data again from your controller.</p>\n\n<p>Ultimately, though, you'll want to eventually work out a strategy that uses the displaytag sorting parameters to use as options in your \"order by\" clause and page the data from the database instead of pulling it all at once. This is a tricky thing to do, but the upfront effort can be very rewarding in terms of performance.</p>\n\n<p>The displaytag site has three things you should always check for reference, just as an aside. The <a href=\"http://displaytag.sourceforge.net/11/displaytag/tagreference.html\" rel=\"nofollow noreferrer\">Tag Reference</a>, the <a href=\"http://displaytag.sourceforge.net/11/configuration.html\" rel=\"nofollow noreferrer\">Configuration Guide</a> and, of course, their (downloadable) <a href=\"http://displaytag.homeip.net/displaytag-examples-1.1/\" rel=\"nofollow noreferrer\">Live Examples.</a></p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267071",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
I'm using the JSP [displaytag](http://displaytag.sourceforge.net/11/) tag lib to create HTML tables. I'd like the user to able to click on a column header in order to sort the data. My JSP code is shown below:
```
<display:table name="tableData" id="stat" sort="page">
<display:column property="name" title="Name" sortable="true"/>
<display:column property="age" title="Age" sortable="true"/>
</display:table>
```
I thought this would cause the data to be sorted on the client-side (in JavaScript), but what it actually does is create a broken hyperlink on the column header back to the server.
Is it possible to use displaytag to sort data on the client-side? If so, how?
Cheers,
Don
|
As far as I know, this is not possible. JQuery's tablesorter may work for the small tables that it uses for its examples, but most tables have to come from an actual database. This hit is far too great to simply retrieve all the data before returning to the client with this information, and then allowing it to be sorted.
Displaytag has a "requestURI" element for the tag that allows its requests to go to your configured url-handler.
So, if you use this:
```
<display:table requestURI="yourUrlMappedController.yourExtension" ...>
```
This will allow for the stopgap solution of retrieving the data again from your controller.
Ultimately, though, you'll want to eventually work out a strategy that uses the displaytag sorting parameters to use as options in your "order by" clause and page the data from the database instead of pulling it all at once. This is a tricky thing to do, but the upfront effort can be very rewarding in terms of performance.
The displaytag site has three things you should always check for reference, just as an aside. The [Tag Reference](http://displaytag.sourceforge.net/11/displaytag/tagreference.html), the [Configuration Guide](http://displaytag.sourceforge.net/11/configuration.html) and, of course, their (downloadable) [Live Examples.](http://displaytag.homeip.net/displaytag-examples-1.1/)
|
267,076 |
<p>Could someone please tell me which objects types can be tested using Regular Expressions in C#?</p>
|
[
{
"answer_id": 267084,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 4,
"selected": true,
"text": "<p>If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings.</p>\n\n<p>Thus your test would be: </p>\n\n<pre><code>if(obj is string){...}\n</code></pre>\n"
},
{
"answer_id": 267097,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>Regular expressions only apply to strings. What does it even mean to apply a regular expression to (say) a SqlConnection?</p>\n\n<p>If you need some other sort of pattern matching (e.g. being able to match the values of particular properties) you should think about and then explain those requirements in detail.</p>\n"
},
{
"answer_id": 267104,
"author": "Ray",
"author_id": 233,
"author_profile": "https://Stackoverflow.com/users/233",
"pm_score": 1,
"selected": false,
"text": "<p>I suppose you could always use the Regular Expression against Object.ToString(), which could be helpful if you override ToString() to give information about your object that you want to match against.</p>\n"
},
{
"answer_id": 267105,
"author": "ripper234",
"author_id": 11236,
"author_profile": "https://Stackoverflow.com/users/11236",
"pm_score": 0,
"selected": false,
"text": "<pre><code>Regex.IsMatch()\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26327/"
] |
Could someone please tell me which objects types can be tested using Regular Expressions in C#?
|
If I understand you correctly and you are asking which object types can be tested against regular expressions then the answer is: strings and only strings.
Thus your test would be:
```
if(obj is string){...}
```
|
267,085 |
<p>I'm trying to convert the below SQL query to HQL and am having a few issues. A straight line by line conversion doesn't work, I am wondering if I should be using an Inner Join in the HQL?</p>
<pre><code> SELECT (UNIX_TIMESTAMP(cosc1.change_date) - UNIX_TIMESTAMP(cosc2.change_date))
FROM customer_order_state_change cosc1
LEFT JOIN customer_order_state cos1_new on cosc1.new_state_id = cos1_new.customer_order_state_id
LEFT JOIN customer_order_state cos1_old on cosc1.old_state_id = cos1_old.customer_order_state_id
LEFT JOIN customer_order_state_change cosc2 on cosc2.customer_order_id = cosc1.customer_order_id
LEFT JOIN customer_order_state cos2_new on cosc2.new_state_id = cos2_new.customer_order_state_id
LEFT JOIN customer_order_state cos2_old on cosc2.old_state_id = cos2_old.customer_order_state_id
WHERE cos1_new.name = "state1" AND cos2_new.name = "state2" and cosc2.change_date < "2008-11-06 09:00"
AND cosc2.change_date > "2008-11-06 06:00" GROUP BY cosc1.change_date, cosc2.change_date ;
</code></pre>
<p>Query returns time in seconds between state changes for a customer order.</p>
<p>The state names and dates are dynamically inserted into the query.</p>
<p>Edit:
Just tried this</p>
<pre><code>"SELECT (UNIX_TIMESTAMP(cosc1.changeDate) - UNIX_TIMESTAMP(cosc2.changeDate))" +
" FROM" +
" " + CustomerOrderStateChange.class.getName() + " as cosc1" +
" INNER JOIN " + CustomerOrderStateChange.class.getName() + " as cosc2" +
" WHERE cosc1.newState.name = ?" +
" AND cosc1.order.id = cosc2.order.id" +
" AND cosc2.newState.name = ?" +
" AND cosc2.changeDate < ?" +
" AND cosc2.changeDate > ?" +
" GROUP BY cosc1.changeDate, cosc2.changeDate";
</code></pre>
<p>and received exception"<em>outer or full join must be followed by path expression</em>"</p>
|
[
{
"answer_id": 267166,
"author": "Nick",
"author_id": 34558,
"author_profile": "https://Stackoverflow.com/users/34558",
"pm_score": 4,
"selected": true,
"text": "<p>Typically you HQL joins are specified using the property on the object, eg, if class Foo and Bar and Foo.bar is of type Bar, then <code>from Foo f inner join f.bar as b</code> is the join. As far as I know, there's no way of performing a self-join in HQL (I could be wrong here).</p>\n\n<p>That said, Hibernate allows you to write (slightly enhanced) SQL queries with <code>session.createSQLQuery(...)</code>. </p>\n"
},
{
"answer_id": 267504,
"author": "Feet",
"author_id": 18340,
"author_profile": "https://Stackoverflow.com/users/18340",
"pm_score": 0,
"selected": false,
"text": "<p>Ended up changing to use native SQL and a PreparedStatement as it seems that Hibernate's session.createSQLQuery() will only work for Managed Entities.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267085",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18340/"
] |
I'm trying to convert the below SQL query to HQL and am having a few issues. A straight line by line conversion doesn't work, I am wondering if I should be using an Inner Join in the HQL?
```
SELECT (UNIX_TIMESTAMP(cosc1.change_date) - UNIX_TIMESTAMP(cosc2.change_date))
FROM customer_order_state_change cosc1
LEFT JOIN customer_order_state cos1_new on cosc1.new_state_id = cos1_new.customer_order_state_id
LEFT JOIN customer_order_state cos1_old on cosc1.old_state_id = cos1_old.customer_order_state_id
LEFT JOIN customer_order_state_change cosc2 on cosc2.customer_order_id = cosc1.customer_order_id
LEFT JOIN customer_order_state cos2_new on cosc2.new_state_id = cos2_new.customer_order_state_id
LEFT JOIN customer_order_state cos2_old on cosc2.old_state_id = cos2_old.customer_order_state_id
WHERE cos1_new.name = "state1" AND cos2_new.name = "state2" and cosc2.change_date < "2008-11-06 09:00"
AND cosc2.change_date > "2008-11-06 06:00" GROUP BY cosc1.change_date, cosc2.change_date ;
```
Query returns time in seconds between state changes for a customer order.
The state names and dates are dynamically inserted into the query.
Edit:
Just tried this
```
"SELECT (UNIX_TIMESTAMP(cosc1.changeDate) - UNIX_TIMESTAMP(cosc2.changeDate))" +
" FROM" +
" " + CustomerOrderStateChange.class.getName() + " as cosc1" +
" INNER JOIN " + CustomerOrderStateChange.class.getName() + " as cosc2" +
" WHERE cosc1.newState.name = ?" +
" AND cosc1.order.id = cosc2.order.id" +
" AND cosc2.newState.name = ?" +
" AND cosc2.changeDate < ?" +
" AND cosc2.changeDate > ?" +
" GROUP BY cosc1.changeDate, cosc2.changeDate";
```
and received exception"*outer or full join must be followed by path expression*"
|
Typically you HQL joins are specified using the property on the object, eg, if class Foo and Bar and Foo.bar is of type Bar, then `from Foo f inner join f.bar as b` is the join. As far as I know, there's no way of performing a self-join in HQL (I could be wrong here).
That said, Hibernate allows you to write (slightly enhanced) SQL queries with `session.createSQLQuery(...)`.
|
267,091 |
<p>At the risk of being downmodded, I want to ask what the best mechanism (best is obviously subjective for the practice violation inherent here) for viewing data from a table, using C#, with a <em>lot</em> of columns. By a lot, I mean something like 1000.</p>
<p>Now before you get all click happy, or throw out responses like "why the hell would you ever have a table with that many columns" let me say that it's actually part of a design requirement. We are collecting data as fast as we can from 1000 data points. We need to store these as fast as possible, hence the flat table. The data needs to be directly accessible from SQL Server, hence the database (we're using SQL Compact with table-direct).</p>
<p>So let's forget, for now, all that we've learned about proper database design, the rules of normalization, etc. and just focus on the fact that I have a table with 1000 columns and I want to be able to display the data on screen to verify that the data is actually going in there.</p>
<p>I've tried a data grid. It pukes because (not surprisingly) it's not designed to handle that many columns.</p>
<p>I've tried using the viewer in Studio. It pukes after 256, plus the end user won't have Studio installed anyway.</p>
<p>For now the result need not be pretty, it need not be updateable, nor does it need to be sensitive to data changes - just a static snapshot of data in the table at a given point in time.</p>
<p>Relevant (or semi-relevant) info:</p>
<ul>
<li>Table has 1000 columns (read above before getting click happy)</li>
<li>Using SQL Compact version 3.5</li>
<li>Running on the desktop</li>
<li>Looking for a managed-code answer</li>
</ul>
|
[
{
"answer_id": 267107,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 2,
"selected": false,
"text": "<p>try a html table with a <sub>very tiny font</sub></p>\n\n<p>if you're concerned about formatting the table use CSS:</p>\n\n<pre><code>td { font-size: 0.2em; text-align: right; }\n</code></pre>\n\n<p>alternately, if all your numbers are the same size, you could also just generate a \"wall of numbers\" display, e.g. use a fixed-width font and display columns 5 characters wide in a scrolling panel</p>\n"
},
{
"answer_id": 267112,
"author": "Whisk",
"author_id": 908,
"author_profile": "https://Stackoverflow.com/users/908",
"pm_score": 0,
"selected": false,
"text": "<p>I feel dirty even for suggesting this, but you could do something along the lines of:</p>\n\n<pre><code>SELECT Field1 + ' - ' + Field2 + ... AS EvilMegaColumn FROM Table\n</code></pre>\n\n<p>but really I think this falls into the category of \"if you're running into this limitation, you're doing something wrong\". I really can't see any reason, speed or otherwise to need 1000 columns...</p>\n"
},
{
"answer_id": 267130,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": -1,
"selected": false,
"text": "<p>How much of the data is critical for the initial view? I can see doing something like a master/detail type grid where you're putting the critical columns (say like 10) onto the datagrid and when the user clicks to view the details, you can take the remaining columns and display them in a \"properties area\" or something in that regard.</p>\n"
},
{
"answer_id": 267131,
"author": "Manu",
"author_id": 2133,
"author_profile": "https://Stackoverflow.com/users/2133",
"pm_score": 0,
"selected": false,
"text": "<p>Who will read a 1000 column table??? Try to think of way to filter or visualize the data. </p>\n"
},
{
"answer_id": 267132,
"author": "Matthew Watson",
"author_id": 3839,
"author_profile": "https://Stackoverflow.com/users/3839",
"pm_score": 2,
"selected": false,
"text": "<p>do you need to view multiple rows on a single table?</p>\n\n<p>my <em>guess</em> is that this data is numerical, is there any way you could display a single rows data as a 20*50 grid or something like that, then just paginate through the rows?</p>\n\n<p>Eg, row 1, column 1 = colum 1 of the database, row 2, column 1 = column 21 of the database, etc</p>\n\n<pre><code>Id = 1\n 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20\n----|--------------------------------------------------------\n 0 | \n 20 | \n 40 |\n 60 |\n 80 |\n100 |\n120 |\netc |\n</code></pre>\n"
},
{
"answer_id": 267133,
"author": "rmeador",
"author_id": 10861,
"author_profile": "https://Stackoverflow.com/users/10861",
"pm_score": 0,
"selected": false,
"text": "<p>Perhaps you should investigate a different type of database. I've heard column-oriented databases are good for this sort of thing (whereas a typical RDBMS is row-oriented). Also, if you won't be going back to update rows after they're first inserted, maybe a binary flat file would be better than a giant table?</p>\n"
},
{
"answer_id": 267141,
"author": "Ken Paul",
"author_id": 26671,
"author_profile": "https://Stackoverflow.com/users/26671",
"pm_score": 0,
"selected": false,
"text": "<p>I would make this a drill-down. In the first page (or at the top of the page) you would have controls that select the row. In the next page (or at the bottom of the page) you would display the data from the selected row. Depending on the required cell width, you might do this as 100 rows of 10 columns, or 1000 rows of 1 column, for example.</p>\n\n<p>This would be fairly easy to do as dynamic client-side javascript -- you could even make it editable this way. I'm not sure how this would work in C#.</p>\n"
},
{
"answer_id": 267152,
"author": "Jason Down",
"author_id": 9732,
"author_profile": "https://Stackoverflow.com/users/9732",
"pm_score": 3,
"selected": false,
"text": "<p>What about storing the data in a csv file, which would give you options for viewing. If your user has excel or Open Office Calc, they could easily import the data (not sure if there is a column limit on Calc, but excel 2007 can hold 16384 columns) and view it through that program?</p>\n"
},
{
"answer_id": 267153,
"author": "Brody",
"author_id": 17131,
"author_profile": "https://Stackoverflow.com/users/17131",
"pm_score": 0,
"selected": false,
"text": "<p>If you are just after a verification could you not check each field programatically and report that entire row is ok!. Then you need a much simple data grid which lists the rows that are not so good.</p>\n\n<p>They can then be examined by whatever technique you can apply to a single row as you will not need to browse the fields in most cases. I am assuming here that you can view the entire row somehow already and are after a way to browse several rows at the same time looking for missing data (automating this will make it much more reliable).</p>\n"
},
{
"answer_id": 267156,
"author": "Bevan",
"author_id": 30280,
"author_profile": "https://Stackoverflow.com/users/30280",
"pm_score": 0,
"selected": false,
"text": "<p>Coming at it from an oblique angle, I'd ask if the user needs to have all the columns \"loaded\" at one time?</p>\n\n<p>If the users would be happy to have a subset of columns displayed at once (say, 100 at a time, or specfic sets at a time), then I'd use a some kind of data grid (the built in one, or a ListView, or maybe a third party one) to display the subset, with a CheckedListView docked to the side, allowing the subset of interest to be displayed.</p>\n\n<p>Alternatively, could you display some kind of summary data showing the count/average/xxx for groups of 100 columns?</p>\n"
},
{
"answer_id": 267157,
"author": "Jeff Olhoeft",
"author_id": 7909,
"author_profile": "https://Stackoverflow.com/users/7909",
"pm_score": 1,
"selected": false,
"text": "<p>It depends a bit on how pretty it needs to be. If this is just a debug/spot check tool, you could put several DataGrids side by side, each one displaying a selection of columns. Would be kind of ugly, but would be workable.</p>\n\n<p>OTOH, if you need a semi-polished tool, you might want to come up with a custom control to handle it. Basically, you would load the section of the database being viewed, with a bit of buffer, and when the user scrolled off the currently loaded data, run a new query.</p>\n"
},
{
"answer_id": 267161,
"author": "Karl R",
"author_id": 22934,
"author_profile": "https://Stackoverflow.com/users/22934",
"pm_score": -1,
"selected": false,
"text": "<p>If all you need is to make sure the data is being populated then why not have every column with a default value, say, 'void', 'blank', etc.</p>\n\n<p>Then you can iterate through while counting non-default/total to show a percentage.</p>\n\n<p>Now you can visualize the data completeness with a percentage value, maybe even record which columns had the default values (like to a list/array) for further investigation.</p>\n"
},
{
"answer_id": 267202,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 1,
"selected": false,
"text": "<p>A DataGrid (or even a ListView) should be able to handle a table with 32 columns and 32 rows, which would allow you to display an entire DB row's worth of data at once. This would allow you to instantly see whether some cells were missing data or not.</p>\n"
},
{
"answer_id": 267214,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": -1,
"selected": false,
"text": "<p>You might consider checking with your user base and seeing what they really need to see, then set up views for each distinct need, in order to get the column count down.</p>\n\n<p>Another option would be to read the data, and create a whopping big static set of html pages from it. Then you could invoke the browser from within your program to view it.</p>\n"
},
{
"answer_id": 267471,
"author": "configurator",
"author_id": 9536,
"author_profile": "https://Stackoverflow.com/users/9536",
"pm_score": 4,
"selected": false,
"text": "<p>You could format all numbers as n-character strings with spaces and then display them in a fixed width font.</p>\n\n<pre><code>1 2 3 4 6 36 436 6346\n2 3 4 6 36 436 6346 0\n3 4 6 36 436 6346 3 4\n4 6 36 436 6346 333 222 334\n</code></pre>\n"
},
{
"answer_id": 267480,
"author": "Joe Phillips",
"author_id": 20471,
"author_profile": "https://Stackoverflow.com/users/20471",
"pm_score": -1,
"selected": false,
"text": "<p>Have a scrollable pane and show 10 columns at a time (these can be actively loaded or cached or whatever you need). When you are scrolled left, show the first ten. As you scroll right, show the latter sequence of columns. So all in all, only 10 columns are active at any given point. Trying to actually display 1000 columns would be nuts any other way in my opinion. PS: This is nothing more than an ideal guess; I'm not really sure if it's remotely possible.</p>\n"
},
{
"answer_id": 267716,
"author": "MusiGenesis",
"author_id": 14606,
"author_profile": "https://Stackoverflow.com/users/14606",
"pm_score": 4,
"selected": false,
"text": "<p>If you're going to implement your own custom user control, you could do a Fisheye Grid like this:</p>\n\n<blockquote class=\"spoiler\">\n <p> <a href=\"http://img145.imageshack.us/img145/6793/nothingbettertodocd5.jpg\" rel=\"nofollow noreferrer\">Dead image link</a> </p>\n</blockquote>\n\n<p>This example shows a full-size 3x4 panel moving around within a 9x10 table. Since (I assume) you don't need to edit this data, the UI could just be something where the user grabs the panel and drags it around. If you're really masochistic and/or have lots of free time, you can even have multiple fisheye panels on the same grid, allowing you to compare one or more regions of the grid simultaneously.</p>\n\n<p>Update: Silverlight <a href=\"http://objectpeddler.com/feg/FlickrFEGTestTestPage.aspx\" rel=\"nofollow noreferrer\">has one of these</a>, apparently. Sort of.</p>\n"
},
{
"answer_id": 267730,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 0,
"selected": false,
"text": "<p>I would recommend investigating something other than a flat layout. In my experience, databases have restrictions on column counts and row byte sizes.</p>\n\n<ul>\n<li>Your SQL may allow for 1000 columns to be defined.</li>\n<li>A SQL row cannot exceed the row byte limit.</li>\n</ul>\n\n<p>Each database implementation has a page size (4k / 8k), and a single row must fit within this data size. NULLs are typically freebies. This means that 1000 ints 1000 x 4 bytes will <em>just</em> fit within a 4k page size.</p>\n\n<p>If you are talking data with varchars, then the problem is worse. How many characters are in each column? How many columns can be filled in? If you have 10 characters on average, and your page size is 8k, then you lose the data with a SQL error.</p>\n\n<p>Laugh if you must, but this situation did occur with a particularly long winded typist in a flat datatable that I knew was pushing the limits.</p>\n"
},
{
"answer_id": 270576,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 5,
"selected": true,
"text": "<p>Ok, what turned out to be the right answer for me was to use the <a href=\"http://msdn.microsoft.com/en-us/library/ms251671(VS.80).aspx\" rel=\"noreferrer\">ReportViewer control</a>, but not in any manner documented in MSDN. The problem is that I have dynamic data, so I need a dynamic report, and all of the tutorials, etc. seem to assume you have the luxury of knowing everything at design time so you can point and click your way through a Wizard.</p>\n\n<p>The solution ended up requiring a couple pieces. First, I had to create code to dynamically generate the RDLC that the ReportViewer uses to describe the report layout and what data fields map to what. This is what I came up with:</p>\n\n<pre><code>public static Stream BuildRDLCStream(\n DataSet data, string name, string reportXslPath)\n{\n using (MemoryStream schemaStream = new MemoryStream())\n {\n // save the schema to a stream\n data.WriteXmlSchema(schemaStream);\n schemaStream.Seek(0, SeekOrigin.Begin);\n\n // load it into a Document and set the Name variable\n XmlDocument xmlDomSchema = new XmlDocument();\n xmlDomSchema.Load(schemaStream); \n xmlDomSchema.DocumentElement.SetAttribute(\"Name\", data.DataSetName);\n\n // load the report's XSL file (that's the magic)\n XslCompiledTransform xform = new XslCompiledTransform();\n xform.Load(reportXslPath);\n\n // do the transform\n MemoryStream rdlcStream = new MemoryStream();\n XmlWriter writer = XmlWriter.Create(rdlcStream);\n xform.Transform(xmlDomSchema, writer);\n writer.Close();\n rdlcStream.Seek(0, SeekOrigin.Begin);\n\n // send back the RDLC\n return rdlcStream;\n }\n}\n</code></pre>\n\n<p>The second piece is an XSL file that I took right off of <a href=\"http://csharpshooter.blogspot.com/2007/08/revised-dynamic-rdlc-generation.html\" rel=\"noreferrer\">Dan Shipe's blog</a>. The RDLC code there was pretty worthless as it was all intended for Web use, but the XSL is pure gold. I've put it at the bottom of this post for completeness in case that blog ever goes offline.</p>\n\n<p>Once I has those two pieces, it was simply a matter of creating a Form with a ReportViewer control on it, then using this bit of code to set it up:</p>\n\n<pre><code>ds.DataSetName = name;\n\nStream rdlc = RdlcEngine.BuildRDLCStream(\n ds, name, \"c:\\\\temp\\\\rdlc\\\\report.xsl\");\n\nreportView.LocalReport.LoadReportDefinition(rdlc);\nreportView.LocalReport.DataSources.Clear();\nreportView.LocalReport.DataSources.Add(\n new ReportDataSource(ds.DataSetName, ds.Tables[0]));\nreportView.RefreshReport();\n</code></pre>\n\n<p>The key here is that 'ds' is a DataSet object with a single DataTable in it with the data to be displayed.</p>\n\n<p>Again, for completeness, here's the XSL - sorry about the size:</p>\n\n<pre><code> <?xml version=\"1.0\"?>\n <!-- Stylesheet for creating ReportViewer RDLC documents -->\n <xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\"\n xmlns:msxsl=\"urn:schemas-microsoft-com:xslt\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:msdata=\"urn:schemas-microsoft-com:xml-msdata\"\n xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition\"\n >\n\n <xsl:variable name=\"mvarName\" select=\"/xs:schema/@Name\"/>\n <xsl:variable name=\"mvarFontSize\">8pt</xsl:variable>\n <xsl:variable name=\"mvarFontWeight\">500</xsl:variable>\n <xsl:variable name=\"mvarFontWeightBold\">700</xsl:variable>\n\n\n <xsl:template match=\"/\">\n <xsl:apply-templates select=\"/xs:schema/xs:element/xs:complexType/xs:choice/xs:element/xs:complexType/xs:sequence\">\n </xsl:apply-templates>\n </xsl:template>\n\n <xsl:template match=\"xs:sequence\">\n <Report xmlns:rd=\"http://schemas.microsoft.com/SQLServer/reporting/reportdesigner\" xmlns=\"http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition\">\n <BottomMargin>1in</BottomMargin>\n <RightMargin>1in</RightMargin>\n <LeftMargin>1in</LeftMargin>\n <TopMargin>1in</TopMargin>\n <InteractiveHeight>11in</InteractiveHeight>\n <InteractiveWidth>8.5in</InteractiveWidth>\n <Width>6.5in</Width>\n <Language>en-US</Language>\n <rd:DrawGrid>true</rd:DrawGrid>\n <rd:SnapToGrid>true</rd:SnapToGrid>\n <rd:ReportID>7358b654-3ca3-44a0-8677-efe0a55c7c45</rd:ReportID>\n\n <xsl:call-template name=\"BuildDataSource\">\n </xsl:call-template>\n\n <xsl:call-template name=\"BuildDataSet\">\n </xsl:call-template>\n\n <Body>\n <Height>0.50in</Height>\n <ReportItems>\n <Table Name=\"table1\">\n <DataSetName><xsl:value-of select=\"$mvarName\" /></DataSetName>\n <Top>0.5in</Top>\n <Height>0.50in</Height>\n <Header>\n <TableRows>\n <TableRow>\n <Height>0.25in</Height>\n <TableCells>\n\n <xsl:apply-templates select=\"xs:element\" mode=\"HeaderTableCell\">\n </xsl:apply-templates>\n\n </TableCells>\n </TableRow>\n </TableRows>\n </Header>\n <Details>\n <TableRows>\n <TableRow>\n <Height>0.25in</Height>\n <TableCells>\n\n <xsl:apply-templates select=\"xs:element\" mode=\"DetailTableCell\">\n </xsl:apply-templates>\n\n </TableCells>\n </TableRow>\n </TableRows>\n </Details>\n <TableColumns>\n\n <xsl:apply-templates select=\"xs:element\" mode=\"TableColumn\">\n </xsl:apply-templates>\n\n </TableColumns>\n </Table>\n </ReportItems>\n </Body>\n </Report>\n </xsl:template>\n\n <xsl:template name=\"BuildDataSource\">\n <DataSources>\n <DataSource Name=\"DummyDataSource\">\n <ConnectionProperties>\n <ConnectString/>\n <DataProvider>SQL</DataProvider>\n </ConnectionProperties>\n <rd:DataSourceID>84635ff8-d177-4a25-9aa5-5a921652c79c</rd:DataSourceID>\n </DataSource>\n </DataSources>\n </xsl:template>\n\n <xsl:template name=\"BuildDataSet\">\n <DataSets>\n <DataSet Name=\"{$mvarName}\">\n <Query>\n <rd:UseGenericDesigner>true</rd:UseGenericDesigner>\n <CommandText/>\n <DataSourceName>DummyDataSource</DataSourceName>\n </Query>\n <Fields>\n\n <xsl:apply-templates select=\"xs:element\" mode=\"Field\">\n </xsl:apply-templates>\n\n </Fields>\n </DataSet>\n </DataSets>\n </xsl:template>\n\n <xsl:template match=\"xs:element\" mode=\"Field\">\n <xsl:variable name=\"varFieldName\"> \n <xsl:value-of select=\"@name\" />\n </xsl:variable>\n\n <xsl:variable name=\"varDataType\">\n <xsl:choose>\n <xsl:when test=\"@type='xs:int'\">System.Int32</xsl:when>\n <xsl:when test=\"@type='xs:string'\">System.String</xsl:when>\n <xsl:when test=\"@type='xs:dateTime'\">System.DateTime</xsl:when>\n <xsl:when test=\"@type='xs:boolean'\">System.Boolean</xsl:when>\n </xsl:choose>\n </xsl:variable>\n\n <Field Name=\"{$varFieldName}\">\n <rd:TypeName><xsl:value-of select=\"$varDataType\"/></rd:TypeName>\n <DataField><xsl:value-of select=\"$varFieldName\"/></DataField>\n </Field>\n </xsl:template>\n\n <xsl:template match=\"xs:element\" mode=\"HeaderTableCell\">\n <xsl:variable name=\"varFieldName\"> \n <xsl:value-of select=\"@name\" />\n </xsl:variable>\n\n <TableCell>\n <ReportItems>\n <Textbox Name=\"textbox{position()}\">\n <rd:DefaultName>textbox<xsl:value-of select=\"position()\"/>\n </rd:DefaultName>\n <Value><xsl:value-of select=\"$varFieldName\"/></Value>\n <CanGrow>true</CanGrow>\n <ZIndex>7</ZIndex>\n <Style>\n <TextAlign>Center</TextAlign>\n <PaddingLeft>2pt</PaddingLeft>\n <PaddingBottom>2pt</PaddingBottom>\n <PaddingRight>2pt</PaddingRight>\n <PaddingTop>2pt</PaddingTop>\n <FontSize><xsl:value-of select=\"$mvarFontSize\"/></FontSize> \n <FontWeight><xsl:value-of select=\"$mvarFontWeightBold\"/></FontWeight> \n <BackgroundColor>#000000</BackgroundColor> \n <Color>#ffffff</Color>\n <BorderColor>\n <Default>#ffffff</Default>\n </BorderColor>\n <BorderStyle>\n <Default>Solid</Default>\n </BorderStyle>\n </Style>\n </Textbox>\n </ReportItems>\n </TableCell>\n </xsl:template>\n\n <xsl:template match=\"xs:element\" mode=\"DetailTableCell\">\n <xsl:variable name=\"varFieldName\"> \n <xsl:value-of select=\"@name\" />\n </xsl:variable>\n\n <TableCell>\n <ReportItems>\n <Textbox Name=\"{$varFieldName}\">\n <rd:DefaultName><xsl:value-of select=\"$varFieldName\"/></rd:DefaultName>\n <Value>=Fields!<xsl:value-of select=\"$varFieldName\"/>.Value</Value>\n <CanGrow>true</CanGrow>\n <ZIndex>7</ZIndex>\n <Style>\n <TextAlign>Left</TextAlign>\n <PaddingLeft>2pt</PaddingLeft>\n <PaddingBottom>2pt</PaddingBottom>\n <PaddingRight>2pt</PaddingRight>\n <PaddingTop>2pt</PaddingTop>\n <FontSize><xsl:value-of select=\"$mvarFontSize\"/></FontSize> \n <FontWeight><xsl:value-of select=\"$mvarFontWeight\"/></FontWeight> \n <BackgroundColor>#e0e0e0</BackgroundColor> \n <Color>#000000</Color> \n <BorderColor>\n <Default>#ffffff</Default> \n </BorderColor>\n <BorderStyle>\n <Default>Solid</Default>\n </BorderStyle>\n </Style>\n </Textbox>\n </ReportItems>\n </TableCell>\n </xsl:template>\n\n <xsl:template match=\"xs:element\" mode=\"TableColumn\">\n <TableColumn>\n <Width>0.75in</Width>\n </TableColumn>\n </xsl:template>\n\n <xsl:template name=\"replace-string\">\n <xsl:param name=\"text\"/>\n <xsl:param name=\"from\"/>\n <xsl:param name=\"to\"/>\n <xsl:choose>\n <xsl:when test=\"contains($text, $from)\">\n <xsl:variable name=\"before\" select=\"substring-before($text, $from)\"/>\n <xsl:variable name=\"after\" select=\"substring-after($text, $from)\"/>\n <xsl:variable name=\"prefix\" select=\"concat($before, $to)\"/>\n <xsl:value-of select=\"$before\"/>\n <xsl:value-of select=\"$to\"/>\n <xsl:call-template name=\"replace-string\">\n <xsl:with-param name=\"text\" select=\"$after\"/>\n <xsl:with-param name=\"from\" select=\"$from\"/>\n <xsl:with-param name=\"to\" select=\"$to\"/>\n </xsl:call-template>\n </xsl:when>\n <xsl:otherwise>\n <xsl:value-of select=\"$text\"/>\n </xsl:otherwise>\n </xsl:choose>\n </xsl:template>\n </xsl:stylesheet>\n</code></pre>\n"
},
{
"answer_id": 437594,
"author": "Malx",
"author_id": 51086,
"author_profile": "https://Stackoverflow.com/users/51086",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>.. to verify that the data is actually going in there.</p>\n</blockquote>\n\n<p>May be it is outdated, but you could use pixel map where single pixel is representing single cell of table (is screen is more then 1000) or 10 cells for one pixel with zoom region on click.</p>\n\n<p>The color of pixel will be data dependent. It could be black/white for empty/data. Or it could be color to show value grows or decrease with every row. Or red for sudden jumps of data. All anomalies you could catch normally with your eye in data grid.</p>\n\n<p>Then all you need is to catch click coordinates in the area of interest and use small table to show that part of table without any scrolling.</p>\n\n<p>Just click to go back to pixel-map.</p>\n"
},
{
"answer_id": 3099701,
"author": "Gabe",
"author_id": 310574,
"author_profile": "https://Stackoverflow.com/users/310574",
"pm_score": 0,
"selected": false,
"text": "<p>Given that the user will have to scroll horizontally anyway, you could use a regular data grid showing a reasonable number of columns (say, 50). Then you have a horizontal scrollbar positioned under the grid that selects a subset of columns to show. When the scrollbar is at the left you show columns 1-50, when you click the right arrow you go to 2-51, etc.</p>\n\n<p>This gives you the scrolling capability without ever having to overload a grid control with data. While you would lose the ability to freely cursor around in the table or make large rectangular selections, it doesn't sound like that would be an issue for this application.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13154/"
] |
At the risk of being downmodded, I want to ask what the best mechanism (best is obviously subjective for the practice violation inherent here) for viewing data from a table, using C#, with a *lot* of columns. By a lot, I mean something like 1000.
Now before you get all click happy, or throw out responses like "why the hell would you ever have a table with that many columns" let me say that it's actually part of a design requirement. We are collecting data as fast as we can from 1000 data points. We need to store these as fast as possible, hence the flat table. The data needs to be directly accessible from SQL Server, hence the database (we're using SQL Compact with table-direct).
So let's forget, for now, all that we've learned about proper database design, the rules of normalization, etc. and just focus on the fact that I have a table with 1000 columns and I want to be able to display the data on screen to verify that the data is actually going in there.
I've tried a data grid. It pukes because (not surprisingly) it's not designed to handle that many columns.
I've tried using the viewer in Studio. It pukes after 256, plus the end user won't have Studio installed anyway.
For now the result need not be pretty, it need not be updateable, nor does it need to be sensitive to data changes - just a static snapshot of data in the table at a given point in time.
Relevant (or semi-relevant) info:
* Table has 1000 columns (read above before getting click happy)
* Using SQL Compact version 3.5
* Running on the desktop
* Looking for a managed-code answer
|
Ok, what turned out to be the right answer for me was to use the [ReportViewer control](http://msdn.microsoft.com/en-us/library/ms251671(VS.80).aspx), but not in any manner documented in MSDN. The problem is that I have dynamic data, so I need a dynamic report, and all of the tutorials, etc. seem to assume you have the luxury of knowing everything at design time so you can point and click your way through a Wizard.
The solution ended up requiring a couple pieces. First, I had to create code to dynamically generate the RDLC that the ReportViewer uses to describe the report layout and what data fields map to what. This is what I came up with:
```
public static Stream BuildRDLCStream(
DataSet data, string name, string reportXslPath)
{
using (MemoryStream schemaStream = new MemoryStream())
{
// save the schema to a stream
data.WriteXmlSchema(schemaStream);
schemaStream.Seek(0, SeekOrigin.Begin);
// load it into a Document and set the Name variable
XmlDocument xmlDomSchema = new XmlDocument();
xmlDomSchema.Load(schemaStream);
xmlDomSchema.DocumentElement.SetAttribute("Name", data.DataSetName);
// load the report's XSL file (that's the magic)
XslCompiledTransform xform = new XslCompiledTransform();
xform.Load(reportXslPath);
// do the transform
MemoryStream rdlcStream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(rdlcStream);
xform.Transform(xmlDomSchema, writer);
writer.Close();
rdlcStream.Seek(0, SeekOrigin.Begin);
// send back the RDLC
return rdlcStream;
}
}
```
The second piece is an XSL file that I took right off of [Dan Shipe's blog](http://csharpshooter.blogspot.com/2007/08/revised-dynamic-rdlc-generation.html). The RDLC code there was pretty worthless as it was all intended for Web use, but the XSL is pure gold. I've put it at the bottom of this post for completeness in case that blog ever goes offline.
Once I has those two pieces, it was simply a matter of creating a Form with a ReportViewer control on it, then using this bit of code to set it up:
```
ds.DataSetName = name;
Stream rdlc = RdlcEngine.BuildRDLCStream(
ds, name, "c:\\temp\\rdlc\\report.xsl");
reportView.LocalReport.LoadReportDefinition(rdlc);
reportView.LocalReport.DataSources.Clear();
reportView.LocalReport.DataSources.Add(
new ReportDataSource(ds.DataSetName, ds.Tables[0]));
reportView.RefreshReport();
```
The key here is that 'ds' is a DataSet object with a single DataTable in it with the data to be displayed.
Again, for completeness, here's the XSL - sorry about the size:
```
<?xml version="1.0"?>
<!-- Stylesheet for creating ReportViewer RDLC documents -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:msdata="urn:schemas-microsoft-com:xml-msdata"
xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition"
>
<xsl:variable name="mvarName" select="/xs:schema/@Name"/>
<xsl:variable name="mvarFontSize">8pt</xsl:variable>
<xsl:variable name="mvarFontWeight">500</xsl:variable>
<xsl:variable name="mvarFontWeightBold">700</xsl:variable>
<xsl:template match="/">
<xsl:apply-templates select="/xs:schema/xs:element/xs:complexType/xs:choice/xs:element/xs:complexType/xs:sequence">
</xsl:apply-templates>
</xsl:template>
<xsl:template match="xs:sequence">
<Report xmlns:rd="http://schemas.microsoft.com/SQLServer/reporting/reportdesigner" xmlns="http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition">
<BottomMargin>1in</BottomMargin>
<RightMargin>1in</RightMargin>
<LeftMargin>1in</LeftMargin>
<TopMargin>1in</TopMargin>
<InteractiveHeight>11in</InteractiveHeight>
<InteractiveWidth>8.5in</InteractiveWidth>
<Width>6.5in</Width>
<Language>en-US</Language>
<rd:DrawGrid>true</rd:DrawGrid>
<rd:SnapToGrid>true</rd:SnapToGrid>
<rd:ReportID>7358b654-3ca3-44a0-8677-efe0a55c7c45</rd:ReportID>
<xsl:call-template name="BuildDataSource">
</xsl:call-template>
<xsl:call-template name="BuildDataSet">
</xsl:call-template>
<Body>
<Height>0.50in</Height>
<ReportItems>
<Table Name="table1">
<DataSetName><xsl:value-of select="$mvarName" /></DataSetName>
<Top>0.5in</Top>
<Height>0.50in</Height>
<Header>
<TableRows>
<TableRow>
<Height>0.25in</Height>
<TableCells>
<xsl:apply-templates select="xs:element" mode="HeaderTableCell">
</xsl:apply-templates>
</TableCells>
</TableRow>
</TableRows>
</Header>
<Details>
<TableRows>
<TableRow>
<Height>0.25in</Height>
<TableCells>
<xsl:apply-templates select="xs:element" mode="DetailTableCell">
</xsl:apply-templates>
</TableCells>
</TableRow>
</TableRows>
</Details>
<TableColumns>
<xsl:apply-templates select="xs:element" mode="TableColumn">
</xsl:apply-templates>
</TableColumns>
</Table>
</ReportItems>
</Body>
</Report>
</xsl:template>
<xsl:template name="BuildDataSource">
<DataSources>
<DataSource Name="DummyDataSource">
<ConnectionProperties>
<ConnectString/>
<DataProvider>SQL</DataProvider>
</ConnectionProperties>
<rd:DataSourceID>84635ff8-d177-4a25-9aa5-5a921652c79c</rd:DataSourceID>
</DataSource>
</DataSources>
</xsl:template>
<xsl:template name="BuildDataSet">
<DataSets>
<DataSet Name="{$mvarName}">
<Query>
<rd:UseGenericDesigner>true</rd:UseGenericDesigner>
<CommandText/>
<DataSourceName>DummyDataSource</DataSourceName>
</Query>
<Fields>
<xsl:apply-templates select="xs:element" mode="Field">
</xsl:apply-templates>
</Fields>
</DataSet>
</DataSets>
</xsl:template>
<xsl:template match="xs:element" mode="Field">
<xsl:variable name="varFieldName">
<xsl:value-of select="@name" />
</xsl:variable>
<xsl:variable name="varDataType">
<xsl:choose>
<xsl:when test="@type='xs:int'">System.Int32</xsl:when>
<xsl:when test="@type='xs:string'">System.String</xsl:when>
<xsl:when test="@type='xs:dateTime'">System.DateTime</xsl:when>
<xsl:when test="@type='xs:boolean'">System.Boolean</xsl:when>
</xsl:choose>
</xsl:variable>
<Field Name="{$varFieldName}">
<rd:TypeName><xsl:value-of select="$varDataType"/></rd:TypeName>
<DataField><xsl:value-of select="$varFieldName"/></DataField>
</Field>
</xsl:template>
<xsl:template match="xs:element" mode="HeaderTableCell">
<xsl:variable name="varFieldName">
<xsl:value-of select="@name" />
</xsl:variable>
<TableCell>
<ReportItems>
<Textbox Name="textbox{position()}">
<rd:DefaultName>textbox<xsl:value-of select="position()"/>
</rd:DefaultName>
<Value><xsl:value-of select="$varFieldName"/></Value>
<CanGrow>true</CanGrow>
<ZIndex>7</ZIndex>
<Style>
<TextAlign>Center</TextAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingBottom>2pt</PaddingBottom>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<FontSize><xsl:value-of select="$mvarFontSize"/></FontSize>
<FontWeight><xsl:value-of select="$mvarFontWeightBold"/></FontWeight>
<BackgroundColor>#000000</BackgroundColor>
<Color>#ffffff</Color>
<BorderColor>
<Default>#ffffff</Default>
</BorderColor>
<BorderStyle>
<Default>Solid</Default>
</BorderStyle>
</Style>
</Textbox>
</ReportItems>
</TableCell>
</xsl:template>
<xsl:template match="xs:element" mode="DetailTableCell">
<xsl:variable name="varFieldName">
<xsl:value-of select="@name" />
</xsl:variable>
<TableCell>
<ReportItems>
<Textbox Name="{$varFieldName}">
<rd:DefaultName><xsl:value-of select="$varFieldName"/></rd:DefaultName>
<Value>=Fields!<xsl:value-of select="$varFieldName"/>.Value</Value>
<CanGrow>true</CanGrow>
<ZIndex>7</ZIndex>
<Style>
<TextAlign>Left</TextAlign>
<PaddingLeft>2pt</PaddingLeft>
<PaddingBottom>2pt</PaddingBottom>
<PaddingRight>2pt</PaddingRight>
<PaddingTop>2pt</PaddingTop>
<FontSize><xsl:value-of select="$mvarFontSize"/></FontSize>
<FontWeight><xsl:value-of select="$mvarFontWeight"/></FontWeight>
<BackgroundColor>#e0e0e0</BackgroundColor>
<Color>#000000</Color>
<BorderColor>
<Default>#ffffff</Default>
</BorderColor>
<BorderStyle>
<Default>Solid</Default>
</BorderStyle>
</Style>
</Textbox>
</ReportItems>
</TableCell>
</xsl:template>
<xsl:template match="xs:element" mode="TableColumn">
<TableColumn>
<Width>0.75in</Width>
</TableColumn>
</xsl:template>
<xsl:template name="replace-string">
<xsl:param name="text"/>
<xsl:param name="from"/>
<xsl:param name="to"/>
<xsl:choose>
<xsl:when test="contains($text, $from)">
<xsl:variable name="before" select="substring-before($text, $from)"/>
<xsl:variable name="after" select="substring-after($text, $from)"/>
<xsl:variable name="prefix" select="concat($before, $to)"/>
<xsl:value-of select="$before"/>
<xsl:value-of select="$to"/>
<xsl:call-template name="replace-string">
<xsl:with-param name="text" select="$after"/>
<xsl:with-param name="from" select="$from"/>
<xsl:with-param name="to" select="$to"/>
</xsl:call-template>
</xsl:when>
<xsl:otherwise>
<xsl:value-of select="$text"/>
</xsl:otherwise>
</xsl:choose>
</xsl:template>
</xsl:stylesheet>
```
|
267,101 |
<p>once you have a commit that contains a submodule object, you pretty much cannot get git-svn to commit past it.</p>
<p>Any ideas, workarounds, anything that is not "don't use submodules with git-svn"?</p>
<p>So far the answer seems to be a big NO.</p>
<p>Is there any way to at least allow existing git commits containing submodule data to be committed to svn without the submodule data? Even if it means rewriting the tree.</p>
|
[
{
"answer_id": 286185,
"author": "Aupajo",
"author_id": 10407,
"author_profile": "https://Stackoverflow.com/users/10407",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to replace the submodules with the <code>svn:externals</code> property to play nice with Subversion.</p>\n\n<pre><code>svn propset svn:externals [...]\n</code></pre>\n\n<p>I don't think there's any other way round it.</p>\n"
},
{
"answer_id": 10568027,
"author": "Dmitry Pavlenko",
"author_id": 1212681,
"author_profile": "https://Stackoverflow.com/users/1212681",
"pm_score": 0,
"selected": false,
"text": "<p>If you have an access to the SVN server you may install <a href=\"http://subgit.com\" rel=\"nofollow\">SubGit</a> into it. It will create a linked Git repository, such that any push to the Git repository will be translated to the SVN and vice versa. The translation is concurrent-safe, so you may consider this pair of repositories as 2 interfaces (Git and SVN) of the same repository as it is done on GitHub with the difference that the translation is much more transparent (all branches are converted to branches, tags to tags, svn:ignore to .gitginore, svn:eol-style to .gitattributes value and so on).</p>\n\n<p>After that you may add submodules to you resulting Git repository and forget about git-svn.</p>\n\n<p>If you have no access to the server I know no solution, only for svn:externals support from Git (look at SmartGit and .gitsvnextmodules config).</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267101",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13989/"
] |
once you have a commit that contains a submodule object, you pretty much cannot get git-svn to commit past it.
Any ideas, workarounds, anything that is not "don't use submodules with git-svn"?
So far the answer seems to be a big NO.
Is there any way to at least allow existing git commits containing submodule data to be committed to svn without the submodule data? Even if it means rewriting the tree.
|
You'll need to replace the submodules with the `svn:externals` property to play nice with Subversion.
```
svn propset svn:externals [...]
```
I don't think there's any other way round it.
|
267,113 |
<p>I’m trying to implement a dictionary for use with WCF. My requirements are:</p>
<ul>
<li>actual (private variable or base
class) type equivalent to
Dictionary </li>
<li>Comparer
= <code>System.StringComparer.InvariantCultureIgnoreCase</code></li>
<li>Custom (override/new) Add(key,
value) method (to include
validations). </li>
<li>Override ToString()</li>
<li>Use of the same type on both the client and host</li>
</ul>
<p>I’ve attempted using this class in a common project shared by the WCF host and client projects:</p>
<pre><code>[Serializable]
public class MyDictionary : Dictionary<string, object>
{
public MyDictionary()
: base(System.StringComparer.InvariantCultureIgnoreCase)
{ }
public new void Add(string key, object value)
{ /* blah */ }
public override string ToString()
{ /* blah */ }
}
[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ResultClass
{
public object Value{ get; set; }
/* More properties */
}
public class ParmData
{
public object Value{ get; set; }
/* More properties */
}
[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ParameterClass
{
public List<ParmData> Data{ get; set; }
/* More properties */
}
[OperationContract]
ResultClass DoSomething(ParameterClass args);
</code></pre>
<p>Results:</p>
<ul>
<li>When I pass MyDictionary as one of the ParameterClass.Data.Value elements, I get a missing KnownType exception.</li>
<li>I can safely return MyDictionary in the ResultClass, but it is no longer my type. It is just a Dictionary, and is not castable to <code>MyDictionary</code>. Also comparer = <code>System.Collections.Generic.GenericEqualityComparer<string></code>, not the case insensitive comparer I’m looking for.</li>
</ul>
<p>The help I’m asking for is to either fix my failed attempt, or a completely different way to achieve my stated requirements. Any solution should not involve copying one dictionary to another.</p>
<p>Thanks</p>
|
[
{
"answer_id": 267691,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 1,
"selected": false,
"text": "<p>Preamble: note that adding a \"new\" <code>Add</code> doesn't stop people calling the old <code>Add</code> simply by casting. Also, in terms of \"mex\", that is a very vague data-contract - does it need to be so open-ended? (lots of <code>object</code> etc...)</p>\n\n<p>First: haven't you missed a few <code>[DataContract]</code>/<code>[DataMember]</code> markers there? In particular:</p>\n\n<ul>\n<li>ResultClass.Value</li>\n<li>ParamData</li>\n<li>ParamData.Value</li>\n<li>ParameterClass.Data</li>\n</ul>\n\n<p>Can you clarify <em>exactly</em> which version of .NET you are using? <code>DataContractSerializer</code> etc have been tweaked via service packs. With 3.5 SP1 installed (the only thing I have to hand) it does at least serialize and deserialize via <code>DataContractSerializer</code> (no WCF stack), and the correct <code>Add</code> method is called.</p>\n\n<p>Can you check whether the following works with your local version? (it works for me with 3.5 SP1 and with the missing attributes) [output first]:</p>\n\n<pre><code>1\nMyDictionary\nabc=123\ndef=ghi\n</code></pre>\n\n<p>Code:</p>\n\n<pre><code> // or long-hand in C# 2.0\n ParameterClass pc = new ParameterClass {\n Data = new List<ParmData> { new ParmData {\n Value = new MyDictionary {\n {\"abc\",123},\n {\"def\",\"ghi\"}\n }}}};\n DataContractSerializer dcs = new DataContractSerializer(pc.GetType());\n string xml;\n using(StringWriter sw = new StringWriter())\n using(XmlWriter xw = XmlWriter.Create(sw)) {\n dcs.WriteObject(xw, pc);\n xw.Close();\n xml = sw.ToString();\n }\n using(StringReader sr = new StringReader(xml)) {\n ParameterClass clone = (ParameterClass)dcs.ReadObject(XmlReader.Create(sr));\n Console.WriteLine(clone.Data.Count);\n Console.WriteLine(clone.Data[0].Value.GetType().Name);\n MyDictionary d = (MyDictionary)clone.Data[0].Value;\n foreach (KeyValuePair<string, object> pair in d)\n {\n Console.WriteLine(\"{0}={1}\", pair.Key, pair.Value);\n }\n }\n</code></pre>\n\n<p>Obviously this just tests <code>DataContractSerializer</code> (without the entire WCF stack), but it seems to work... so: does the same code work with your local version of .NET? If not, is installing the latest 3.0 service pack an option? (ideally via installing 3.5 SP1).</p>\n\n<p>For info, I get xml:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-16\"?><ParameterClass xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns=\"http://schemas.datacontract.org/2004/07/\"><Data><ParmData><Value xmlns:d4p1=\"http://schemas.microsoft.com/2003/10/Serialization/Arrays\" i:type=\"d4p1:ArrayOfKeyValueOfstringanyType\"><d4p1:KeyValueOfstringanyType><d4p1:Key>abc</d4p1:Key><d4p1:Value xmlns:d6p1=\"http://www.w3.org/2001/XMLSchema\" i:type=\"d6p1:int\">123</d4p1:Value></d4p1:KeyValueOfstringanyType><d4p1:KeyValueOfstringanyType><d4p1:Key>def</d4p1:Key><d4p1:Value xmlns:d6p1=\"http://www.w3.org/2001/XMLSchema\" i:type=\"d6p1:string\">ghi</d4p1:Value></d4p1:KeyValueOfstringanyType></Value></ParmData></Data></ParameterClass>\n</code></pre>\n"
},
{
"answer_id": 268434,
"author": "jezell",
"author_id": 27453,
"author_profile": "https://Stackoverflow.com/users/27453",
"pm_score": 3,
"selected": false,
"text": "<p>Add CollectionDataContract to the Dictionary class:</p>\n\n<p>For more information on using collection data contracts to implement dictionaries, check this link:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa347850.aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/aa347850.aspx</a></p>\n"
},
{
"answer_id": 270580,
"author": "chilltemp",
"author_id": 28736,
"author_profile": "https://Stackoverflow.com/users/28736",
"pm_score": 2,
"selected": true,
"text": "<ul>\n<li>Use the <code>CollectionDataContract</code> attribute as jezell suggested</li>\n<li>Manually generate the reference (proxy) code with SvcUtil, using the /collectionType parameter. This parameter is not supported by the vs2008 service reference GUI.</li>\n</ul>\n\n<p>Source: <a href=\"http://www.codeproject.com/KB/WCF/WCFCollectionTypeSharing.aspx\" rel=\"nofollow noreferrer\">WCF Collection Type Sharing</a></p>\n"
},
{
"answer_id": 562591,
"author": "Shaun Bowe",
"author_id": 1514,
"author_profile": "https://Stackoverflow.com/users/1514",
"pm_score": 1,
"selected": false,
"text": "<p>I finally found a way to do this. I found <a href=\"http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/09eefbbc-bf63-4aa3-a0cb-01a9dbd7f496\" rel=\"nofollow noreferrer\">this link</a> that pointed in the right direction but I will try to summarize.</p>\n\n<ol>\n<li>Make sure you add <code>[CollectionDataContract]</code> to your custom collection</li>\n<li>Add Service Reference through VS like you normally do</li>\n<li>Expand the service reference and look for the Reference.svcmap file</li>\n<li>Under the client options node you will see </li>\n</ol>\n\n<blockquote>\n <p><CollectionMappings/></p>\n</blockquote>\n\n<p>Replace it with the following xml.</p>\n\n<blockquote>\n <p><CollectionMappings><br/>\n <CollectionMapping TypeName=\"Full.Namespace.Here\" Category=\"List\" /><br/> </CollectionMappings></p>\n</blockquote>\n\n<ol start=\"5\">\n<li>Right click on the Service Reference and click update. It should no longer generate that \"proxy\" class and will let you use your shared class.</li>\n</ol>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28736/"
] |
I’m trying to implement a dictionary for use with WCF. My requirements are:
* actual (private variable or base
class) type equivalent to
Dictionary
* Comparer
= `System.StringComparer.InvariantCultureIgnoreCase`
* Custom (override/new) Add(key,
value) method (to include
validations).
* Override ToString()
* Use of the same type on both the client and host
I’ve attempted using this class in a common project shared by the WCF host and client projects:
```
[Serializable]
public class MyDictionary : Dictionary<string, object>
{
public MyDictionary()
: base(System.StringComparer.InvariantCultureIgnoreCase)
{ }
public new void Add(string key, object value)
{ /* blah */ }
public override string ToString()
{ /* blah */ }
}
[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ResultClass
{
public object Value{ get; set; }
/* More properties */
}
public class ParmData
{
public object Value{ get; set; }
/* More properties */
}
[DataContract]
[KnownType(typeof(MyDictionary))]
[KnownType(typeof(object[]))]
[KnownType(typeof(double[]))]
[KnownType(typeof(string[]))]
[KnownType(typeof(DateTime[]))]
public class ParameterClass
{
public List<ParmData> Data{ get; set; }
/* More properties */
}
[OperationContract]
ResultClass DoSomething(ParameterClass args);
```
Results:
* When I pass MyDictionary as one of the ParameterClass.Data.Value elements, I get a missing KnownType exception.
* I can safely return MyDictionary in the ResultClass, but it is no longer my type. It is just a Dictionary, and is not castable to `MyDictionary`. Also comparer = `System.Collections.Generic.GenericEqualityComparer<string>`, not the case insensitive comparer I’m looking for.
The help I’m asking for is to either fix my failed attempt, or a completely different way to achieve my stated requirements. Any solution should not involve copying one dictionary to another.
Thanks
|
* Use the `CollectionDataContract` attribute as jezell suggested
* Manually generate the reference (proxy) code with SvcUtil, using the /collectionType parameter. This parameter is not supported by the vs2008 service reference GUI.
Source: [WCF Collection Type Sharing](http://www.codeproject.com/KB/WCF/WCFCollectionTypeSharing.aspx)
|
267,114 |
<p>I always try to avoid to return string literals, because I fear they aren't defined outside of the function. But I'm not sure if this is the case. Let's take, for example, this function:</p>
<pre><code>
const char *
return_a_string(void)
{
return "blah";
}
</code></pre>
<p>Is this correct code? It does work for me, but maybe it only works for my compiler (gcc). So the question is, do (string) literals have a scope or are they present/defined all the time.</p>
|
[
{
"answer_id": 267134,
"author": "Brian R. Bondy",
"author_id": 3153,
"author_profile": "https://Stackoverflow.com/users/3153",
"pm_score": 7,
"selected": true,
"text": "<p>This code is fine across all platforms. The string gets compiled into the binary as a static string literal. If you are on windows for example you can even open your .exe with notepad and search for the string itself. </p>\n\n<p>Since it is a static string literal scope does not matter.</p>\n\n<p><strong>String pooling:</strong></p>\n\n<p>One thing to look out for is that in some cases, identical string literals can be \"pooled\" to save space in the executable file. In this case each string literal that was the same could have the same memory address. You should never assume that it will or will not be the case though.</p>\n\n<p>In most compilers you can set whether or not to use static string pooling for stirng literals.</p>\n\n<p><strong>Maximum size of string literals:</strong></p>\n\n<p>Several compilers have a maximum size for the string literal. For example with VC++ this is approximately 2,048 bytes.</p>\n\n<p><strong>Modifying a string literal gives undefined behavior:</strong></p>\n\n<p>Modifying a string literal should never be done. It has an undefined behavior.</p>\n\n<pre><code>char * sz = \"this is a test\";\nsz[0] = 'T'; //<--- undefined results\n</code></pre>\n\n<p><strong>Wide string literals:</strong></p>\n\n<p>All of the above applies equally to wide string literals. </p>\n\n<p>Example: L\"this is a wide string literal\";</p>\n\n<p><strong>The C++ standard states:</strong> (section lex.string)</p>\n\n<blockquote>\n <p>1 A string literal is a sequence\n of characters (as defined in\n <em>lex.ccon</em>) surrounded by double quotes, optionally beginning with the\n letter L, as in \"...\" or L\"...\". A string literal that does not begin\n with L is an ordinary string literal, also referred to as a narrow\n string literal. An ordinary string literal has type \"array of n\n const\n char\" and static storage duration (<em>basic.stc</em>), where n is the\n size\n of the string as defined below, and is initialized with the given\n characters. A string literal that begins with L, such as L\"asdf\",\n is\n a wide string literal. A wide string literal has type \"array of \n n\n const wchar_t\" and has static storage duration, where n is the size\n of\n the string as defined below, and is initialized with the given charac-\n ters.</p>\n \n <p>2 Whether all string literals are distinct (that is, are stored in\n nonoverlapping objects) is implementation-defined. The effect \n of\n attempting to modify a string literal is undefined.</p>\n</blockquote>\n"
},
{
"answer_id": 267135,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, that's fine. They live in a global string table.</p>\n"
},
{
"answer_id": 267136,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 2,
"selected": false,
"text": "<p>No, string literals do not have scope, so your code is guaranteed to work across all platforms and compilers. They are stored in your program's binary image, so you can always access them. However, trying to write to them (by casting away the <code>const</code>) will lead to undefined behavior.</p>\n"
},
{
"answer_id": 267139,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>You actually return a pointer to the zero-terminated string stored in the data section of the executable, an area loaded when you load the program. Just avoid to try and change the characters, it might give unpredictable results...</p>\n"
},
{
"answer_id": 267311,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 0,
"selected": false,
"text": "<p>It's really important to make note of the undefined results that Brian mentioned. Since you have declared the function as returning a const char * type, you should be okay, but on many platforms string literals are placed into a read-only segment in the executable (usually the text segment) and modifying them will cause an access violation on most platforms.</p>\n"
},
{
"answer_id": 272158,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 3,
"selected": false,
"text": "<p>This is valid in C (or C++), as others have explained.</p>\n\n<p>The one thing I can think to watch out for is that if you're using dlls, then the pointer will not remain valid if the dll containing this code is unloaded. </p>\n\n<p>The C (or C++) standard doesn't understand or take account of loading and unloading code at runtime, so anything which does that will face implementation-defined consequences: in this case the consequence is that the string literal, which is supposed to have static storage duration, appears from the POV of the calling code not to persist for the full duration of the program.</p>\n"
},
{
"answer_id": 7331474,
"author": "Sumit Trehan",
"author_id": 931458,
"author_profile": "https://Stackoverflow.com/users/931458",
"pm_score": 4,
"selected": false,
"text": "<p>I give you an example so that your confusion becomes somewhat clear</p>\n\n<pre><code>char *f()\n{\nchar a[]=\"SUMIT\";\nreturn a;\n}\n</code></pre>\n\n<p>this won't work.</p>\n\n<p>but </p>\n\n<pre><code>char *f()\n{\nchar *a=\"SUMIT\";\nreturn a;\n}\n</code></pre>\n\n<p>this works.</p>\n\n<p>Reason: <code>\"SUMIT\"</code> is a literal which has a global scope.\nwhile the array which is just a sequence of characters <code>{'S','U','M','I',\"T''\\0'}</code>\nhas a limited scope and it vanishes as soon as the program is returned.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267114",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18687/"
] |
I always try to avoid to return string literals, because I fear they aren't defined outside of the function. But I'm not sure if this is the case. Let's take, for example, this function:
```
const char *
return_a_string(void)
{
return "blah";
}
```
Is this correct code? It does work for me, but maybe it only works for my compiler (gcc). So the question is, do (string) literals have a scope or are they present/defined all the time.
|
This code is fine across all platforms. The string gets compiled into the binary as a static string literal. If you are on windows for example you can even open your .exe with notepad and search for the string itself.
Since it is a static string literal scope does not matter.
**String pooling:**
One thing to look out for is that in some cases, identical string literals can be "pooled" to save space in the executable file. In this case each string literal that was the same could have the same memory address. You should never assume that it will or will not be the case though.
In most compilers you can set whether or not to use static string pooling for stirng literals.
**Maximum size of string literals:**
Several compilers have a maximum size for the string literal. For example with VC++ this is approximately 2,048 bytes.
**Modifying a string literal gives undefined behavior:**
Modifying a string literal should never be done. It has an undefined behavior.
```
char * sz = "this is a test";
sz[0] = 'T'; //<--- undefined results
```
**Wide string literals:**
All of the above applies equally to wide string literals.
Example: L"this is a wide string literal";
**The C++ standard states:** (section lex.string)
>
> 1 A string literal is a sequence
> of characters (as defined in
> *lex.ccon*) surrounded by double quotes, optionally beginning with the
> letter L, as in "..." or L"...". A string literal that does not begin
> with L is an ordinary string literal, also referred to as a narrow
> string literal. An ordinary string literal has type "array of n
> const
> char" and static storage duration (*basic.stc*), where n is the
> size
> of the string as defined below, and is initialized with the given
> characters. A string literal that begins with L, such as L"asdf",
> is
> a wide string literal. A wide string literal has type "array of
> n
> const wchar\_t" and has static storage duration, where n is the size
> of
> the string as defined below, and is initialized with the given charac-
> ters.
>
>
> 2 Whether all string literals are distinct (that is, are stored in
> nonoverlapping objects) is implementation-defined. The effect
> of
> attempting to modify a string literal is undefined.
>
>
>
|
267,124 |
<p>I'm working on an ASP.Net application and working to add some Ajax to it to speed up certain areas. The first area that I am concentrating is the attendance area for the teachers to report attendance (and some other data) about the kids. This needs to be fast.</p>
<p>I've created a dual-control set up where the user clicks on the icon and via Javascript and Jquery I pop up the second control. Then I use a __doPostBack() to refresh the pop up control to load all of the relevant data.</p>
<p>Here's a little video snippet to show how it works: <a href="http://www.screencast.com/users/cyberjared/folders/Jing/media/32ef7c22-fe82-4b60-a74a-9a37ab625f1f" rel="nofollow noreferrer">http://www.screencast.com/users/cyberjared/folders/Jing/media/32ef7c22-fe82-4b60-a74a-9a37ab625f1f</a> (:21 and ignore the audio background).</p>
<p>It's slower than I would like at 2-3 seconds in Firefox and Chrome for each "popping up", but it's entirely unworkable in IE, taking easily 7-8 seconds for each time it pops up and loads. And that disregards any time that is needed to save the data after it's been changed.</p>
<p>Here's the javascript that handles the pop-up:</p>
<pre><code>function showAttendMenu(callingControl, guid) {
var myPnl = $get('" + this.MyPnl.ClientID + @"')
if(myPnl) {
var displayIDFld = $get('" + this.AttendanceFld.ClientID + @"');
var myStyle = myPnl.style;
if(myStyle.display == 'block' && (guid== '' || guid == displayIDFld.value)) {
myStyle.display = 'none';
} else {
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Unblock the form when a partial postback ends.
prm.add_endRequest(function() {
$('#" + this.MyPnl.ClientID + @"').unblock({ fadeOut: 0});
});
var domEl = Sys.UI.DomElement;
//Move it into position
var loc = domEl.getLocation(callingControl);
var width = domEl.getBounds(callingControl).width;
domEl.setLocation(myPnl, loc.x + width, loc.y - 200);
//Show it and block it until we finish loading the data
myStyle.display = 'block';
$('#" + this.MyPnl.ClientID + @"').block({ message: null, overlayCSS: { backgroundColor:'#fff', opacity: '0.7'} });
//Load the data
if(guid != '') { displayIDFld.value = guid; }
__doPostBack('" + UpdatePanel1.ClientID + @"','');
}
}}
</code></pre>
<p>First, I don't understand why the __doPostBack() introduces such a delay in IE. If I take that and the prm.add_endRequest out, it's VERY speedy as no postback is happening.</p>
<p>Second, I need a way to pop up this control and refresh the data so that it is still interactive. I'm not married to an UpdatePanel, but I haven't been able to figure out how to do it with a Web Service/static page method. As you can see this control is loaded many times on the same page so page size and download speed is an issue.</p>
<p>I'd appreciate any ideas?</p>
<p>Edit: It's the same in IE 6 or 7. I'm thinking it has to do with IE's handling of the UpdatePanel, because the same code is much faster in FF and Chrome.</p>
|
[
{
"answer_id": 267159,
"author": "Justin Bozonier",
"author_id": 9401,
"author_profile": "https://Stackoverflow.com/users/9401",
"pm_score": 0,
"selected": false,
"text": "<p>To find out why it's taking so long I would recommend using Fiddler to spy on your IE traffic: <a href=\"http://www.fiddlertool.com/fiddler/\" rel=\"nofollow noreferrer\">http://www.fiddlertool.com/fiddler/</a></p>\n\n<p>You'll be looking at the response of each of the messages to see how large they are. If the messages are >5kb or so then the UpdatePanel is being way too piggy.</p>\n\n<p>It sounds like a fairly simple thing you're trying to do so I'm having a hard time believing the update panel is to blame. Testing it shouldn't be too difficult though. The easiest way to test this without an UpdatePanel would be to use a PageMethod. This page has a great tutorial on it:\n<a href=\"http://weblogs.asp.net/sohailsayed/archive/2008/02/23/calling-methods-in-a-codebehind-function-pagemethods-from-client-side-using-ajax-net.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/sohailsayed/archive/2008/02/23/calling-methods-in-a-codebehind-function-pagemethods-from-client-side-using-ajax-net.aspx</a></p>\n\n<p>Could you also post your UpdatePanel code so we could get more details?</p>\n\n<p>EDIT: Thanks!</p>\n\n<p>What version of IE are you using?</p>\n"
},
{
"answer_id": 267181,
"author": "Jared",
"author_id": 3442,
"author_profile": "https://Stackoverflow.com/users/3442",
"pm_score": 0,
"selected": false,
"text": "<p>Here's the code for the pop up control (there's only one of these on the page that's shared by all of the controls containing the icons):</p>\n\n<pre><code><script type=\"text/javascript\" src=\"<%=Response.ApplyAppPathModifier(\"~/js/jquery-1.2.6.js\") %>\"></script>\n<script type=\"text/javascript\" src=\"<%=Response.ApplyAppPathModifier(\"~/js/jquery.blockUI.js\") %>\"></script>\n<asp:Panel CssClass=\"PopOutBox noPrint\" ID=\"MyPnl\" style=\"display: none; z-index:1000; width:230px; position: absolute;\" runat=\"server\">\n <cmp:Image MyImageType=\"SmallCancel\" CssClass=\"fright\" runat=\"server\" ID=\"CloseImg\" AlternateText=\"Close\" />\n <asp:UpdatePanel ID=\"UpdatePanel1\" runat=\"server\" UpdateMode=\"Conditional\">\n\n <ContentTemplate>\n <asp:HiddenField ID=\"AttendanceFld\" runat=\"server\" />\n <asp:HiddenField ID=\"DatePickerFld\" runat=\"server\" />\n <table width=\"100%\">\n <tr>\n <td valign=\"top\">\n <asp:RadioButtonList EnableViewState=\"false\" ID=\"AttendRBL\" runat=\"server\" RepeatDirection=\"Vertical\">\n <asp:ListItem Selected=\"True\" Text=\"On Time\" Value=\"\" />\n <asp:ListItem Text=\"Late\" Value=\"Late\" />\n <asp:ListItem Text=\"Absent\" Value=\"Absent\" />\n <asp:ListItem Text=\"Cleaning Flunk\" Value=\"Other\" title=\"This is used for things like cubby flunks\" />\n <asp:ListItem Text=\"Major Cleaning Flunk\" Value=\"Major\" title=\"This is used for things like White Glove flunks\" />\n </asp:RadioButtonList>\n </td>\n <td valign=\"top\" style=\"text-align: center; vertical-align: middle;\">\n <asp:CheckBox EnableViewState=\"false\" ID=\"ExcusedCB\" runat=\"server\" />\n <br />\n <asp:Label ID=\"Label1\" EnableViewState=\"false\" AssociatedControlID=\"ExcusedCB\" Text=\"Excused\"\n runat=\"server\" />\n </td>\n </tr>\n\n <tr>\n <td colspan=\"2\">\n <asp:Label EnableViewState=\"false\" ID=\"Label2\" Text=\"Notes\" runat=\"server\" AssociatedControlID=\"DataTB\" />\n <cmp:HelpPopUp EnableViewState=\"false\" runat=\"server\" Text='Must include \"Out Sick\" to be counted as ill on reports and progress reports' />\n <br />\n <asp:TextBox ID=\"DataTB\" EnableViewState=\"false\" runat=\"server\" Columns=\"30\" /><br />\n <div style=\"font-size: 10px; text-align:center;\">\n <a href=\"#\" onclick=\"setAttendVal('<%=this.DataTB.ClientID%>','Out Sick');return false;\">\n (Ill)</a> <a href=\"#\" onclick=\"setAttendVal('<%=this.DataTB.ClientID%>','In Ethics');return false;\">\n (Ethics)</a> <a href=\"#\" onclick=\"setAttendVal('<%=this.DataTB.ClientID %>','Warned');return false;\">\n (Warned)</a>\n </div>\n </td>\n </tr>\n <tr>\n <td colspan=\"2\">\n <cmp:ImageButton ID=\"DeleteBtn\" OnClientClick=\"showAttendMenu(this,'');\" OnClick=\"DeleteAttendance\" ButtonType=\"SmallDelete\"\n CssClass=\"fright\" runat=\"server\" />\n <cmp:ImageButton ID=\"SaveBtn\" OnClientClick=\"showAttendMenu(this,'');\" OnClick=\"SaveAttendance\" ButtonType=\"SmallSave\" runat=\"server\" />\n </td>\n </tr>\n </table>\n </ContentTemplate>\n </asp:UpdatePanel>\n</asp:Panel>\n</code></pre>\n"
},
{
"answer_id": 277176,
"author": "Malfist",
"author_id": 12243,
"author_profile": "https://Stackoverflow.com/users/12243",
"pm_score": 0,
"selected": false,
"text": "<p>Working with the DOM and HTTP Requests are inherently slow, it's the browser. The best way to speed it up is to reduce the number of times there is an HTTP request (AJAX or otherwise), and reduce the number of DOM actions, search, edit, replace, etc.</p>\n"
},
{
"answer_id": 281602,
"author": "AndreasKnudsen",
"author_id": 36465,
"author_profile": "https://Stackoverflow.com/users/36465",
"pm_score": 1,
"selected": false,
"text": "<p>Noticed in a previous project that IE became terribly slow when we had heaps (150+) textboxes on a page, after checking with fiddler we figured it was the rendering engine that was slow. </p>\n\n<p>(btw, before you all shout, the 150+ textboxes was an explicit customer requirement, we basically recreated customized excel on the web)</p>\n"
},
{
"answer_id": 281631,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 4,
"selected": true,
"text": "<p>If speed/performance is a major concern for you, I would strongly suggest against UpdatePanels, as they cause a full page postback that drags the ViewState in the header, among other crap, and forces the page to go through the whole life cycle every time (even though the user doesn't see this).</p>\n\n<p>You should be able to (relatively easily) use PageMethods to accomplish your task.</p>\n\n<pre><code>// In your aspx.cs define the server-side method marked with the \n// WebMethod attribute and it must be public static.\n[WebMethod]\npublic static string HelloWorld(string name)\n{\n return \"Hello World - by \" + name;\n}\n\n// Call the method via javascript\nPageMethods.HelloWorld(\"Jimmy\", callbackMethod, failMethod);\n</code></pre>\n"
},
{
"answer_id": 1809513,
"author": "Alois Reitbauer",
"author_id": 219512,
"author_profile": "https://Stackoverflow.com/users/219512",
"pm_score": 0,
"selected": false,
"text": "<p>I recommend to do perforamnce tracing with <a href=\"http://ajax.dynatrace.com\" rel=\"nofollow noreferrer\" title=\"dynaTrace AJAX Edition\">link text</a>. It is a free tool for AJAX performance analysis in Internet Explorer</p>\n"
},
{
"answer_id": 3382715,
"author": "rick schott",
"author_id": 58856,
"author_profile": "https://Stackoverflow.com/users/58856",
"pm_score": 2,
"selected": false,
"text": "<p>Its a known issue with IE only, see <a href=\"http://support.microsoft.com/kb/2000262\" rel=\"nofollow noreferrer\">KB 2000262</a>. A workaround/fix can be found <a href=\"http://blog.devlpr.net/2009/09/01/updatepanel-async-postsback-slow-in-ie-part-3/\" rel=\"nofollow noreferrer\">here</a>. I worked with them on the script and its a shame they cannot put out a real fix.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3442/"
] |
I'm working on an ASP.Net application and working to add some Ajax to it to speed up certain areas. The first area that I am concentrating is the attendance area for the teachers to report attendance (and some other data) about the kids. This needs to be fast.
I've created a dual-control set up where the user clicks on the icon and via Javascript and Jquery I pop up the second control. Then I use a \_\_doPostBack() to refresh the pop up control to load all of the relevant data.
Here's a little video snippet to show how it works: <http://www.screencast.com/users/cyberjared/folders/Jing/media/32ef7c22-fe82-4b60-a74a-9a37ab625f1f> (:21 and ignore the audio background).
It's slower than I would like at 2-3 seconds in Firefox and Chrome for each "popping up", but it's entirely unworkable in IE, taking easily 7-8 seconds for each time it pops up and loads. And that disregards any time that is needed to save the data after it's been changed.
Here's the javascript that handles the pop-up:
```
function showAttendMenu(callingControl, guid) {
var myPnl = $get('" + this.MyPnl.ClientID + @"')
if(myPnl) {
var displayIDFld = $get('" + this.AttendanceFld.ClientID + @"');
var myStyle = myPnl.style;
if(myStyle.display == 'block' && (guid== '' || guid == displayIDFld.value)) {
myStyle.display = 'none';
} else {
// Get a reference to the PageRequestManager.
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Unblock the form when a partial postback ends.
prm.add_endRequest(function() {
$('#" + this.MyPnl.ClientID + @"').unblock({ fadeOut: 0});
});
var domEl = Sys.UI.DomElement;
//Move it into position
var loc = domEl.getLocation(callingControl);
var width = domEl.getBounds(callingControl).width;
domEl.setLocation(myPnl, loc.x + width, loc.y - 200);
//Show it and block it until we finish loading the data
myStyle.display = 'block';
$('#" + this.MyPnl.ClientID + @"').block({ message: null, overlayCSS: { backgroundColor:'#fff', opacity: '0.7'} });
//Load the data
if(guid != '') { displayIDFld.value = guid; }
__doPostBack('" + UpdatePanel1.ClientID + @"','');
}
}}
```
First, I don't understand why the \_\_doPostBack() introduces such a delay in IE. If I take that and the prm.add\_endRequest out, it's VERY speedy as no postback is happening.
Second, I need a way to pop up this control and refresh the data so that it is still interactive. I'm not married to an UpdatePanel, but I haven't been able to figure out how to do it with a Web Service/static page method. As you can see this control is loaded many times on the same page so page size and download speed is an issue.
I'd appreciate any ideas?
Edit: It's the same in IE 6 or 7. I'm thinking it has to do with IE's handling of the UpdatePanel, because the same code is much faster in FF and Chrome.
|
If speed/performance is a major concern for you, I would strongly suggest against UpdatePanels, as they cause a full page postback that drags the ViewState in the header, among other crap, and forces the page to go through the whole life cycle every time (even though the user doesn't see this).
You should be able to (relatively easily) use PageMethods to accomplish your task.
```
// In your aspx.cs define the server-side method marked with the
// WebMethod attribute and it must be public static.
[WebMethod]
public static string HelloWorld(string name)
{
return "Hello World - by " + name;
}
// Call the method via javascript
PageMethods.HelloWorld("Jimmy", callbackMethod, failMethod);
```
|
267,163 |
<p>I've had significant success with NSURL, NSURL[Mutable]Request, NSURLConnection with my iPhone applications. When trying to compile a stand alone Cocoa application, 10 line program to make a simple HTTP request, there are zero compiler errors or warnings. The program compiles fine, yet the HTTP Request is never made to my web server (I'm running a tcpdump and watching Apache logs in parallel). When I run very similar code in an iPhone app, essentially copy/pasted as evil as that is, all works golden. </p>
<p>I kept the code for the 'obj' declaration in the delegate to NSURLConnection out of this code snippet for the sake of simplicity. I'm also passing the following to gcc:</p>
<p>gcc -o foo foo.m -lobjc -framework cocoa</p>
<p>Thanks for any insight.</p>
<pre><code>#import <Cocoa/Cocoa.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString * urlstr = @"http://tmp/test.php";
[NSApplication sharedApplication];
NSObject *obj = [[NSObject alloc] init];
NSURL *url = [NSURL URLWithString: urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
if([request isKindOfClass:[NSMutableURLRequest class]])
NSLog(@"request is of type NSMutableURLRequest");
[request setHTTPMethod:@"GET"];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:obj
startImmediately:YES];
if(connection)
NSLog(@"We do have a connection.");
[pool release];
return 0;
</code></pre>
<p>} </p>
|
[
{
"answer_id": 267265,
"author": "Mike Abdullah",
"author_id": 28768,
"author_profile": "https://Stackoverflow.com/users/28768",
"pm_score": 2,
"selected": false,
"text": "<p><code>NSURLConnection</code> is an asynchronous API that relies upon <code>NSRunLoop</code>. Your posted code never creates a run loop for the connection to run in. Therefore, I presume Cocoa is unable to create the connection and so returns nil. Things to look into:</p>\n\n<p>1) Anything in the console? Is <code>NSURLConnection</code> throwing an exception or logging an error?</p>\n\n<p>2) What happens if you use the synchronous API instead? +<code>[NSURLConnection sendSynchronousRequest:returningResponse:error:]</code></p>\n\n<p>3) What is the point of this code? Cocoa is not designed for running directly from a main() function yourself. Is there a particular reason why you are not using the Xcode-provided application templates that will take care of setting up run loop, autorelease pool etc.?</p>\n"
},
{
"answer_id": 267392,
"author": "Jason Coco",
"author_id": 34218,
"author_profile": "https://Stackoverflow.com/users/34218",
"pm_score": 4,
"selected": true,
"text": "<p>The other poster pretty much answered this for you, but I thought I would just add a few things.</p>\n\n<p>First, you don't really need to link to Cocoa for this, just linking to the Foundation framework is okay. Also, since you don't need a connection to the Window Server, you can get rid of the [NSApplication sharedApplicaiton] call. If you want just a simple, console test application to start with, use what you have now and add this before your [pool realease] call:</p>\n\n<p>[[NSRunLoop currentRunLoop] run];</p>\n\n<p>Please note, however, that this will block and may actually never return. Before calling this, you can add a timer if you want your code to actually do something in the background :) See the documentation on NSRunLoop for more ways to use this.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I've had significant success with NSURL, NSURL[Mutable]Request, NSURLConnection with my iPhone applications. When trying to compile a stand alone Cocoa application, 10 line program to make a simple HTTP request, there are zero compiler errors or warnings. The program compiles fine, yet the HTTP Request is never made to my web server (I'm running a tcpdump and watching Apache logs in parallel). When I run very similar code in an iPhone app, essentially copy/pasted as evil as that is, all works golden.
I kept the code for the 'obj' declaration in the delegate to NSURLConnection out of this code snippet for the sake of simplicity. I'm also passing the following to gcc:
gcc -o foo foo.m -lobjc -framework cocoa
Thanks for any insight.
```
#import <Cocoa/Cocoa.h>
int main (int argc, char *argv[])
{
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
NSString * urlstr = @"http://tmp/test.php";
[NSApplication sharedApplication];
NSObject *obj = [[NSObject alloc] init];
NSURL *url = [NSURL URLWithString: urlstr];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
if([request isKindOfClass:[NSMutableURLRequest class]])
NSLog(@"request is of type NSMutableURLRequest");
[request setHTTPMethod:@"GET"];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
NSURLConnection *connection = [[NSURLConnection alloc]
initWithRequest:request
delegate:obj
startImmediately:YES];
if(connection)
NSLog(@"We do have a connection.");
[pool release];
return 0;
```
}
|
The other poster pretty much answered this for you, but I thought I would just add a few things.
First, you don't really need to link to Cocoa for this, just linking to the Foundation framework is okay. Also, since you don't need a connection to the Window Server, you can get rid of the [NSApplication sharedApplicaiton] call. If you want just a simple, console test application to start with, use what you have now and add this before your [pool realease] call:
[[NSRunLoop currentRunLoop] run];
Please note, however, that this will block and may actually never return. Before calling this, you can add a timer if you want your code to actually do something in the background :) See the documentation on NSRunLoop for more ways to use this.
|
267,168 |
<p>In Visual Studio, I can select the "Treat warnings as errors" option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings. </p>
<p>There is an option to suppress warnings, but we DO want them to show up as warnings, so that won't work.</p>
<p>It appears that the only way to get the behavior we want is to enter a list of every C# warning number into the "Specific warnings" text box, except for the two we want treated as warnings.</p>
<p>Besides the maintenance headache, the biggest disadvantage to this approach is that a few warnings do not have numbers, so they can't be referenced explicitly. For example, "Could not resolve this reference. Could not locate assembly 'Data....'"</p>
<p>Does anyone know of a better way to do this?</p>
<hr>
<p>Clarifying for those who don't see immediately why this is useful. Think about how most warnings work. They tell you something is a little off in the code you just wrote. It takes about 10 seconds to fix them, and that keeps the code base cleaner.</p>
<p>The "Obsolete" warning is very different from this. Sometimes fixing it means just consuming a new method signature. But if an entire class is obsolete, and you have usage of it scattered through hundreds of thousands of lines of code, it could take weeks or more to fix. You don't want the build to be broken for that long, but you definitely DO want to see a warning about it. This isn't just a hypothetical case--this has happened to us.</p>
<p>Literal "#warning" warnings are also unique. I often <em>want</em> to check it in, but I don't want to break the build.</p>
|
[
{
"answer_id": 267472,
"author": "Tim",
"author_id": 10755,
"author_profile": "https://Stackoverflow.com/users/10755",
"pm_score": 1,
"selected": false,
"text": "<p>Why do you want to keep seeing warnings that you are not treating as errors? I am confused about why this is desirable - either you fix them or you don't. </p>\n\n<p>Would two different build/solution files work - or a script to copy one and then so modify the warnings/warning level be suitable. It seems that perhaps you want some executions of the compiler to squawk, but others you want to keep going. </p>\n\n<p>So different compiler switches seems like a good way to go. You could do this with different targets - one labeled debug or release and the others labeled suitably about the warnings. </p>\n"
},
{
"answer_id": 278706,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": -1,
"selected": false,
"text": "<p>It seems to me the root problem is really a combination of your treating warnings as errors, when they are clearly not, and your apparent policy of permitting check-ins which violate this. As you say, you want to be able to continue working despite a warning. You've only mentioned a few warnings you want to be able to ignore, but what if someone else on the team caused any other type of warning, which would take you equally long to fix? Wouldn't you want to be able to ignore that as well?</p>\n\n<p>The logical solution would be to either 1) Disallow checkins if the code doesn't compile (which means those who created the warnings will have to fix them, since in effect, they broke the build), or 2) treat warnings as warnings. Create two build configurations, one which treats warnings as errors, which can be run regularly to ensure that the code is warning-free, and another, which only treats them as warnings, and allows you to work even if someone else introduced a warning.</p>\n"
},
{
"answer_id": 314882,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>pragma warning (C# Reference)</p>\n\n<p>pragma warning may be used to enable or disable certain warnings.</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/441722ys(VS.80).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/441722ys(VS.80).aspx</a></p>\n"
},
{
"answer_id": 380405,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<p>/warnaserror /warnaserror-:618</p>\n"
},
{
"answer_id": 380416,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>or more specifically, in your case:</p>\n\n<p>/warnaserror /warnaserror-:612,1030,1701,1702</p>\n\n<p>this should treat all warnings as errors except for the ones in your comma separated list</p>\n"
},
{
"answer_id": 468166,
"author": "SvenL",
"author_id": 57790,
"author_profile": "https://Stackoverflow.com/users/57790",
"pm_score": 7,
"selected": false,
"text": "<p>You can add a <code>WarningsNotAsErrors</code>-tag in the project file.</p>\n\n<pre><code><PropertyGroup>\n ...\n ...\n <WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>\n</PropertyGroup>\n</code></pre>\n\n<p>Note: <code>612</code> and <code>618</code> are both warnings about Obsolete, don't know the difference but the project i'm working on is reporting Obsolete with warning 618.</p>\n"
},
{
"answer_id": 468221,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 1,
"selected": false,
"text": "<p>I'm using treat warnings as errors. </p>\n\n<p>In a rare cases, when some acceptable warning shows up (i.e. referencing obsolete member, or missing documentation on XML serialization classes), then it has to be explicitly <strong>suppressed with #pragma disable</strong> (and optionally reason for not having a clean code could be provided as a comment along). </p>\n\n<p>Presence of this directive also allows to find out, <strong>who accepted this warning violation</strong> (by \"blame\" action of version control) in case there are some questions.</p>\n"
},
{
"answer_id": 1499338,
"author": "erikkallen",
"author_id": 47161,
"author_profile": "https://Stackoverflow.com/users/47161",
"pm_score": 0,
"selected": false,
"text": "<p>Why not simply have a rule saying \"Whoever checks in code with any warning inside it other than 612, 1030, 1701 or 1702 in it must go to the whiteboard and write a hundred times 'I will not check in code with disallowed warnings again.'\"</p>\n"
},
{
"answer_id": 67542429,
"author": "Drew Noakes",
"author_id": 24874,
"author_profile": "https://Stackoverflow.com/users/24874",
"pm_score": 4,
"selected": true,
"text": "<p>In Visual Studio 2022 we have a new Project Properties UI which includes an editor for this.</p>\n<p>Under <em>Build | Errors and Warnings</em> if you set <em>Treat warnings as errors</em> to <em>All</em>, then another property appears which allows you to exempt specific warnings from being treated as errors:</p>\n<p><a href=\"https://i.stack.imgur.com/nOUWX.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/nOUWX.png\" alt=\"enter image description here\" /></a></p>\n<p>This will add the following property to your project:</p>\n<pre class=\"lang-xml prettyprint-override\"><code><WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24315/"
] |
In Visual Studio, I can select the "Treat warnings as errors" option to prevent my code from compiling if there are any warnings. Our team uses this option, but there are two warnings we would like to keep as warnings.
There is an option to suppress warnings, but we DO want them to show up as warnings, so that won't work.
It appears that the only way to get the behavior we want is to enter a list of every C# warning number into the "Specific warnings" text box, except for the two we want treated as warnings.
Besides the maintenance headache, the biggest disadvantage to this approach is that a few warnings do not have numbers, so they can't be referenced explicitly. For example, "Could not resolve this reference. Could not locate assembly 'Data....'"
Does anyone know of a better way to do this?
---
Clarifying for those who don't see immediately why this is useful. Think about how most warnings work. They tell you something is a little off in the code you just wrote. It takes about 10 seconds to fix them, and that keeps the code base cleaner.
The "Obsolete" warning is very different from this. Sometimes fixing it means just consuming a new method signature. But if an entire class is obsolete, and you have usage of it scattered through hundreds of thousands of lines of code, it could take weeks or more to fix. You don't want the build to be broken for that long, but you definitely DO want to see a warning about it. This isn't just a hypothetical case--this has happened to us.
Literal "#warning" warnings are also unique. I often *want* to check it in, but I don't want to break the build.
|
In Visual Studio 2022 we have a new Project Properties UI which includes an editor for this.
Under *Build | Errors and Warnings* if you set *Treat warnings as errors* to *All*, then another property appears which allows you to exempt specific warnings from being treated as errors:
[](https://i.stack.imgur.com/nOUWX.png)
This will add the following property to your project:
```xml
<WarningsNotAsErrors>618,1030,1701,1702</WarningsNotAsErrors>
```
|
267,179 |
<p>I'm trying to create a template class to insulate the users from a data type. I would have preferred to use an adapter class, but the function signatures needed to change requiring a template.</p>
<p>In the code sample below(not the actual project just a simplified version to illustrate the problem), while in the main routine I'm able to use the ob_traits interface. But when I attempt to create the templated StructWrapper which uses the ob_traits as a base class, I get errors and gcc doesn't recognize the IntAdapter class created. This compiles on MSVC 8.0 but fails on gcc 4.1.2 20070626 ( Red hat 4.1.2-14)</p>
<p>So two questions first, do you understand why the compile fails with the errors specified below?</p>
<p>Second, any suggestions on how to implement this concept in a more simple manner?</p>
<pre><code> #include <iostream>
template <typename T >
struct ob_traits
{
ob_traits( T& param ) { value = param; };
T value;
};
struct GeneralStructure
{
int a;
GeneralStructure(int param):a(param){}
};
struct DifferentStructure
{
GeneralStructure hidden;
DifferentStructure( int param ):hidden(param){};
}
;
/*template< typename T > struct ob_traits
{
};
*/
template<> struct ob_traits< GeneralStructure >
{
struct IntAdapter
{
IntAdapter( GeneralStructure& valueParam ):value(valueParam){}
GeneralStructure value;
int& getValue() { return value.a; };
};
};
template<> struct ob_traits< DifferentStructure >
{
struct IntAdapter
{
IntAdapter( DifferentStructure& valueParam):value( valueParam ){}
DifferentStructure value;
int& getValue( ){ return value.hidden.a; };
};
void dump()
{
DifferentStructure testLocal(44);
IntAdapter local( testLocal );
std::cout << local.getValue()<<std::endl;
}
};
template <typename T > struct StructWrapper:public ob_traits< T >
{
StructWrapper(){};
/*main.cpp:60: error: 'IntAdapter' was not declared in this scope
main.cpp:60: error: expected `;' before 'inner'
main.cpp:60: error: 'inner' was not declared in this scope
*/
void dumpOuter(const T& tempParam) { IntAdapter inner(tempParam); inner.dump(); };
/*
main.cpp: In member function 'void StructWrapper<T>::dumpOuterFailsAsWell(const T&)':
main.cpp:66: error: expected `;' before 'inner'
main.cpp:66: error: 'inner' was not declared in this scope
*/
void dumpOuterFailsAsWell(const T& tempParam) { ob_traits<T>::IntAdapter inner(tempParam); inner.dump(); };
};
int main(int argc, char* argv[])
{
GeneralStructure dummyGeneral(22);
ob_traits<struct GeneralStructure >::IntAdapter test(dummyGeneral);
DifferentStructure dummyDifferent(33);
ob_traits<struct DifferentStructure >::IntAdapter test2(dummyDifferent);
std::cout << "GeneralStructure: "<<test.getValue()<<std::endl;
std::cout << "DifferentStructure: "<<test2.getValue()<<std::endl;
ob_traits<struct DifferentStructure > test3;
test3.dump();
std::cout << "Test Templated\n";
return 0;
}
</code></pre>
|
[
{
"answer_id": 267254,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "<p><code>StructWrapper</code> is inheriting from the primary class template (ie the least specialized), which does not define IntWrapper, so it cannot be used in this class. I'm not sure if instantiating a <code>StructWrapper</code> with one of the more specialized types will allow it to work, or if it fails on compiling the class definition itself.</p>\n"
},
{
"answer_id": 268044,
"author": "Denes Tarjan",
"author_id": 17617,
"author_profile": "https://Stackoverflow.com/users/17617",
"pm_score": 0,
"selected": false,
"text": "<p>Compile fails because IntAdapter only appears in the specialized template, and therefore it is not visible at the referring point.</p>\n\n<p>Not clear what would you use it for? Please clarify the circumstances.</p>\n"
},
{
"answer_id": 269258,
"author": "Sunlight",
"author_id": 33650,
"author_profile": "https://Stackoverflow.com/users/33650",
"pm_score": 2,
"selected": false,
"text": "<p><code>dumpOuter</code> fails because <code>IntAdapter</code> needs to be qualified (as in the referenced question). <code>dumpOuterFailsAsWell</code> fails because GCC does parsing of this code,even though it's not complete, and so it needs to know it's a type that you mean:</p>\n\n<pre><code>void dumpOuterWorks(const T& tempParam) \n{ \n typename ob_traits<T>::IntAdapter inner(tempParam); \n inner.dump(); \n}\n</code></pre>\n\n<p>Without <code>typename</code> here, GCC will assume that IntAdapter is an identifier, and will expect you to be forming an expression rather than a variable declaration.</p>\n\n<p>Also note that you do not have to put semicolons after method bodies!</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267179",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to create a template class to insulate the users from a data type. I would have preferred to use an adapter class, but the function signatures needed to change requiring a template.
In the code sample below(not the actual project just a simplified version to illustrate the problem), while in the main routine I'm able to use the ob\_traits interface. But when I attempt to create the templated StructWrapper which uses the ob\_traits as a base class, I get errors and gcc doesn't recognize the IntAdapter class created. This compiles on MSVC 8.0 but fails on gcc 4.1.2 20070626 ( Red hat 4.1.2-14)
So two questions first, do you understand why the compile fails with the errors specified below?
Second, any suggestions on how to implement this concept in a more simple manner?
```
#include <iostream>
template <typename T >
struct ob_traits
{
ob_traits( T& param ) { value = param; };
T value;
};
struct GeneralStructure
{
int a;
GeneralStructure(int param):a(param){}
};
struct DifferentStructure
{
GeneralStructure hidden;
DifferentStructure( int param ):hidden(param){};
}
;
/*template< typename T > struct ob_traits
{
};
*/
template<> struct ob_traits< GeneralStructure >
{
struct IntAdapter
{
IntAdapter( GeneralStructure& valueParam ):value(valueParam){}
GeneralStructure value;
int& getValue() { return value.a; };
};
};
template<> struct ob_traits< DifferentStructure >
{
struct IntAdapter
{
IntAdapter( DifferentStructure& valueParam):value( valueParam ){}
DifferentStructure value;
int& getValue( ){ return value.hidden.a; };
};
void dump()
{
DifferentStructure testLocal(44);
IntAdapter local( testLocal );
std::cout << local.getValue()<<std::endl;
}
};
template <typename T > struct StructWrapper:public ob_traits< T >
{
StructWrapper(){};
/*main.cpp:60: error: 'IntAdapter' was not declared in this scope
main.cpp:60: error: expected `;' before 'inner'
main.cpp:60: error: 'inner' was not declared in this scope
*/
void dumpOuter(const T& tempParam) { IntAdapter inner(tempParam); inner.dump(); };
/*
main.cpp: In member function 'void StructWrapper<T>::dumpOuterFailsAsWell(const T&)':
main.cpp:66: error: expected `;' before 'inner'
main.cpp:66: error: 'inner' was not declared in this scope
*/
void dumpOuterFailsAsWell(const T& tempParam) { ob_traits<T>::IntAdapter inner(tempParam); inner.dump(); };
};
int main(int argc, char* argv[])
{
GeneralStructure dummyGeneral(22);
ob_traits<struct GeneralStructure >::IntAdapter test(dummyGeneral);
DifferentStructure dummyDifferent(33);
ob_traits<struct DifferentStructure >::IntAdapter test2(dummyDifferent);
std::cout << "GeneralStructure: "<<test.getValue()<<std::endl;
std::cout << "DifferentStructure: "<<test2.getValue()<<std::endl;
ob_traits<struct DifferentStructure > test3;
test3.dump();
std::cout << "Test Templated\n";
return 0;
}
```
|
`dumpOuter` fails because `IntAdapter` needs to be qualified (as in the referenced question). `dumpOuterFailsAsWell` fails because GCC does parsing of this code,even though it's not complete, and so it needs to know it's a type that you mean:
```
void dumpOuterWorks(const T& tempParam)
{
typename ob_traits<T>::IntAdapter inner(tempParam);
inner.dump();
}
```
Without `typename` here, GCC will assume that IntAdapter is an identifier, and will expect you to be forming an expression rather than a variable declaration.
Also note that you do not have to put semicolons after method bodies!
|
267,186 |
<p>In C++ when can a virtual function use static binding? If it is being accessed through a pointer, accessed directly, or never?</p>
|
[
{
"answer_id": 267231,
"author": "Skizz",
"author_id": 1898,
"author_profile": "https://Stackoverflow.com/users/1898",
"pm_score": 2,
"selected": false,
"text": "<p>Static binding can only be done when the object's type is totally unambiguous at compile time. I can only think of four places where an abstract object's type is unambiguous: in the constructor, in the destructor, when declared locally and within the same scope as a dynamic allocation. I don't know the standard that well so I couldn't say what it says about those four possibilities (I'd say the first two are statically bound, the third possible statically bound and the last not; although it probably says it's undefined or implementation dependent). Other than those points, the object being accessed through a base class pointer could be pointing to a derived class and the current translation unit has no way of knowing, so static binding is not possible. The function could be called with a pointer to the base class in one instance and a pointer to a derived class in another!</p>\n"
},
{
"answer_id": 267238,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": false,
"text": "<p>If you want to call the base class version of a function, you can do that by explicitly naming the base class:</p>\n\n<pre><code>class Base\n{\npublic:\n virtual ~Base() {}\n virtual void DoIt() { printf(\"In Base::DoIt()\\n\"); }\n};\n\nclass Derived : public Base\n{\npublic:\n virtual void DoIt() { printf(\"In Derived::DoIt()\\n\"); }\n};\n\nBase *basePtr = new Derived;\nbasePtr->DoIt(); // Calls Derived::DoIt() through virtual function call\nbasePtr->Base::DoIt(); // Explicitly calls Base::DoIt() using normal function call\ndelete basePtr;</code></pre>\n"
},
{
"answer_id": 267260,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>When a virtual method is called through a pointer or reference, dynamic binding is used. Any other time, compile-time binding is used. Ex:</p>\n\n<pre><code>class C;\n\nvoid Foo(C* a, C& b, C c) {\n a->foo(); // dynamic\n b.foo(); // dynamic\n c.foo(); // static (compile-time)\n}\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267186",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
In C++ when can a virtual function use static binding? If it is being accessed through a pointer, accessed directly, or never?
|
If you want to call the base class version of a function, you can do that by explicitly naming the base class:
```
class Base
{
public:
virtual ~Base() {}
virtual void DoIt() { printf("In Base::DoIt()\n"); }
};
class Derived : public Base
{
public:
virtual void DoIt() { printf("In Derived::DoIt()\n"); }
};
Base *basePtr = new Derived;
basePtr->DoIt(); // Calls Derived::DoIt() through virtual function call
basePtr->Base::DoIt(); // Explicitly calls Base::DoIt() using normal function call
delete basePtr;
```
|
267,191 |
<p>Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:</p>
<pre><code>var theControl = document.getElementById("txtEditBox");
</code></pre>
<p>Then just set the control's Visible property to true/false. It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false. How can I do that? Also, is that the best way to hide/show a ASP.NET control from a Javascript function?</p>
<p>Thanks,
Jeff </p>
|
[
{
"answer_id": 267197,
"author": "Jason Bunting",
"author_id": 1790,
"author_profile": "https://Stackoverflow.com/users/1790",
"pm_score": 6,
"selected": true,
"text": "<p>The \"Visible\" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.</p>\n\n<p>So, you cannot, technically, set that property of the control.</p>\n\n<p>That said, if the control <em>is</em> rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:</p>\n\n<pre><code>var theControl = document.getElementById(\"txtEditBox\");\ntheControl.style.display = \"none\";\n\n// to show it again:\ntheControl.style.display = \"\";\n</code></pre>\n\n<p>That assumes that the control's <code>id</code> attribute really is \"txtEditBox\" on the client and that it is already visible.</p>\n\n<blockquote>\n <p>Also, is that the best way to hide/show a ASP.NET control from a Javascript function?</p>\n</blockquote>\n\n<p>There is not necessarily a \"best\" way, although one better approach is to use CSS class definitions:</p>\n\n<pre><code>.invisible { display: none; }\n</code></pre>\n\n<p>When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose <code>display</code> value starts off as <code>block</code>.</p>\n"
},
{
"answer_id": 267207,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 3,
"selected": false,
"text": "<p>instead of using visible, set its css to display:none</p>\n\n<pre><code>//css:\n.invisible { display:none; }\n\n//C#\ntxtEditBox.CssClass = 'invisible';\ntxtEditBox.CssClass = ''; // visible again\n\n//javascript\ndocument.getElementById('txtEditBox').className = 'invisible'\ndocument.getElementById('txtEditBox').className = ''\n</code></pre>\n"
},
{
"answer_id": 267209,
"author": "gfrizzle",
"author_id": 23935,
"author_profile": "https://Stackoverflow.com/users/23935",
"pm_score": 2,
"selected": false,
"text": "<p>This should hide the control:</p>\n\n<pre><code>theControl.style.display = 'none';\n</code></pre>\n"
},
{
"answer_id": 267211,
"author": "Michael Kniskern",
"author_id": 26327,
"author_profile": "https://Stackoverflow.com/users/26327",
"pm_score": 3,
"selected": false,
"text": "<p>Set the style to \"display: none\".</p>\n\n<pre><code>var theControl = document.getElementById(\"<%= txtEditBox.ClientID %>\");\ntheControl.style.display = \"none\";\n</code></pre>\n"
},
{
"answer_id": 267212,
"author": "C. Dragon 76",
"author_id": 5682,
"author_profile": "https://Stackoverflow.com/users/5682",
"pm_score": 2,
"selected": false,
"text": "<p>You can use the display property for this. But as Jason noted, this is a DHTML DOM (client-side) property that is completely independent from the ASP.NET (server-side) Visible property which controls rendering.</p>\n\n<pre><code>theControl.style.display = \"none\";\n</code></pre>\n\n<p><a href=\"http://www.w3schools.com/css/pr_class_display.asp\" rel=\"nofollow noreferrer\">Display Property</a></p>\n"
},
{
"answer_id": 267216,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 1,
"selected": false,
"text": "<p>You want to set the display style property to 'none' (to hide) or <code>null</code> to show.</p>\n\n<pre><code> var theControl = document.getElementById(\"txtEditBox\");\n\n theControl.style.display = 'none';\n\n theControl.style.display = null;\n</code></pre>\n\n<p>Doing it the jQuery way:</p>\n\n<pre><code> $('#txtEditBox').hide();\n\n $('#txtEditBox').show();\n</code></pre>\n"
},
{
"answer_id": 267245,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 2,
"selected": false,
"text": "<p>You can't hide/ show the <code>ASP.NET</code> version of the control as that only exists in a server context. To use JavaScript you need to play with the controls style/ visibility state.</p>\n\n<p>The only kind-of way to do it would be to wrap the control in an UpdatePanel and have something like this:</p>\n\n<pre><code><asp:UpdatePanel ID=\"panel\" runat=\"server\">\n <ContentTemplate>\n <asp:TextBox ID=\"myTextBox\" runat=\"server\" />\n </ContentTemplate>\n <Triggers>\n <asp:AsynchronousPostbackTrigger ControlID=\"button\" EventName=\"Click\" />\n </Triggers>\n</asp:UpdatePanel>\n<asp:Button ID=\"button\" runat=\"server\" OnClick=\"toggle\" Text=\"Click!\" />\n</code></pre>\n\n<p>Then you need this in your code behind:</p>\n\n<pre><code>protected void toggle(object sender, EventArgs e){\n myTextBox.Visibility = !myTextBox.Visibility;\n}\n</code></pre>\n\n<p>Now when you click the button an async postback occurs and it will refresh the UpdatePanel.</p>\n\n<p><strong>Note:</strong> This is not a <em>good</em> solution, as it'll be a very heavy AJAX request, because you need to submit the ViewState.</p>\n\n<p>Also, it may not be 100% right, I did that from memory.</p>\n"
},
{
"answer_id": 6307429,
"author": "live-love",
"author_id": 436341,
"author_profile": "https://Stackoverflow.com/users/436341",
"pm_score": 1,
"selected": false,
"text": "<p>Or if you don't want to use css:</p>\n\n<pre><code><asp:TextBox ID=\"txtBox\" runat=\"server\" style=\"display:none;\">\n</code></pre>\n"
},
{
"answer_id": 54350083,
"author": "GreatNews",
"author_id": 9290530,
"author_profile": "https://Stackoverflow.com/users/9290530",
"pm_score": 0,
"selected": false,
"text": "<p>I think the best solution is to put your ASP control inside a div and set the property display to the div element.</p>\n\n<pre><code><div id=\"divTest\"> \n <asp:TextBox ID=\"txtTest\" runat=\"server\"></asp:TextBox>\n</div>\n\n<script type=\"text/javascript\">\n SIN JQuery\n document.getElementById('divTest').style.display = \"none\";\n\n CON JQuery\n $('#divTest').hide();\n</script>\n</code></pre>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12172/"
] |
Bascially I want to know the best way to hide/show an ASP.NET control from a Javascript function. I figured I would just access the control in Javascript using:
```
var theControl = document.getElementById("txtEditBox");
```
Then just set the control's Visible property to true/false. It doesn't seem to be working, I can't seem to figure out how to set "Visible" to true/false. How can I do that? Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
Thanks,
Jeff
|
The "Visible" property of an ASP.NET control determines whether or not it will be rendered on the client (i.e. sent to the client). If it is false when the page is rendered, it will never arrive at the client.
So, you cannot, technically, set that property of the control.
That said, if the control *is* rendered on the client because the Visible property is true when the page is rendered, you can then hide it using javascript like this:
```
var theControl = document.getElementById("txtEditBox");
theControl.style.display = "none";
// to show it again:
theControl.style.display = "";
```
That assumes that the control's `id` attribute really is "txtEditBox" on the client and that it is already visible.
>
> Also, is that the best way to hide/show a ASP.NET control from a Javascript function?
>
>
>
There is not necessarily a "best" way, although one better approach is to use CSS class definitions:
```
.invisible { display: none; }
```
When you want to hide something, dynamically apply that class to the element; when you want to show it again, remove it. Note, I believe this will only work for elements whose `display` value starts off as `block`.
|
267,193 |
<p>I have a computer at home which I can't access from work. I'd like to be able to view results from work that my home computer produces. The best idea I've come up with is an automated script running on my home computer that emails myself the results (from a text file or stderr/out) when complete. </p>
<p>I'm decent with bash (I have a <em>linux</em> machine) and java, so an answer using either or both of those would be ideal, but if there's something easier that's fine too.</p>
<p>I typically use gmail, but also have yahoo mail. </p>
<p>My question is this: what would be the basic steps in solving this problem? I can do the nitty gritty stuff, but can't really get the big picture of how something like this would work.</p>
<p>Please help.</p>
<p>jbu</p>
|
[
{
"answer_id": 267220,
"author": "SpoonMeiser",
"author_id": 1577190,
"author_profile": "https://Stackoverflow.com/users/1577190",
"pm_score": 0,
"selected": false,
"text": "<p>Traditionaly, with unix systems like Linux, you'd have an MTA, a mail transfer agent, on the computer that deals with sending e-mail.</p>\n\n<p>This could be a full blown e-mail server like exim, or something simple like ssmtp that just sends messages on to a relaying SMTP server such as would be provided by your ISP.</p>\n\n<p>This isn't neccessarily the case anymore, since mail clients like Thunderbird include their own MTA, much like mail clients on Windows do.</p>\n\n<p>However, it is likely that your distro will install some MTA or other by default, if for no other reason than the fact that other things on your system, like cron, want to be able to send e-mail. Generally there will be a command line tool called sendmail (sendmail being the original MTA [citation needed], other MTAs maintain compatability with its interface and it has sort of become the standard) that can be used from a shell script to send an e-mail.</p>\n"
},
{
"answer_id": 267242,
"author": "digitalsanctum",
"author_id": 22436,
"author_profile": "https://Stackoverflow.com/users/22436",
"pm_score": 0,
"selected": false,
"text": "<p>My solution assumes that you have a SMTP server available which allows you to send an email programmatically. Alternatively, you can use a local install of sendmail which generally is available with most linux distros.</p>\n\n<p>Create a standalone java program which watches the directory your home computer saves the file to. Use the <a href=\"http://java.sun.com/products/javamail/\" rel=\"nofollow noreferrer\">JavaMail API</a> to attach and send the file to any email you wish.</p>\n\n<p>If you're also familiar with the <a href=\"http://www.springframework.org\" rel=\"nofollow noreferrer\">Spring Framework</a>, it has a nice abstraction layer for working with JavaMail and makes this sort of thing trivial.</p>\n"
},
{
"answer_id": 267288,
"author": "rbrayb",
"author_id": 9922,
"author_profile": "https://Stackoverflow.com/users/9922",
"pm_score": 1,
"selected": false,
"text": "<p>You can't access your home computer from work which rules out a \"remote support\" option.</p>\n\n<p>Can you access other computers on the Internet? If so, you could simply set up one of the online storage options and then ftp the results from your home computer. That's a lot simpler then trying to write scripts or code to generate emails with attachments or whatever.</p>\n\n<p>You could then view the external computer from work.</p>\n"
},
{
"answer_id": 267289,
"author": "paavo256",
"author_id": 34911,
"author_profile": "https://Stackoverflow.com/users/34911",
"pm_score": 2,
"selected": false,
"text": "<p>On any Linux I have used the mail sending from command-line is simple:</p>\n\n<pre><code>mail -s \"My subject here\" [email protected] <message_body.txt\n</code></pre>\n\n<p>AFAIK this acts as a front-end to sendmail, and you have to have sendmail configured to forward the messages to your ISP mail server. </p>\n"
},
{
"answer_id": 267301,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "<p>If you have netcat, this command will send you an e-mail:</p>\n\n<p>Given a file in this format (from Wikipedia):</p>\n\n<pre><code>HELO relay.example.org\nMAIL FROM:<[email protected]>\nRCPT TO:<[email protected]>\nRCPT TO:<[email protected]>\nDATA\nFrom: \"Bob Example\" <[email protected]>\nTo: Alice Example <[email protected]>\nCc: [email protected]\nDate: Tue, 15 Jan 2008 16:02:43 -0500\nSubject: Test message\n\nHello Alice.\nThis is a test message with 5 headers and 4 lines in the body.\nYour friend,\nBob\n.\nQUIT\n</code></pre>\n\n<p>Then netcat it to an SMTP server you have access to:</p>\n\n<pre><code>nc mail.somewhere.com 25 < file.txt\n</code></pre>\n\n<p>This will then send the e-mail. You can see how you can create a Java program to do this for you (just execute the commands).</p>\n"
},
{
"answer_id": 341912,
"author": "jpsecher",
"author_id": 13372,
"author_profile": "https://Stackoverflow.com/users/13372",
"pm_score": 2,
"selected": false,
"text": "<h1>Howto set up ssmtp to send through a Gmail account</h1>\n\n<p>Some of the steps here might seem strange at first, but the rationale is put\nin footnotes that should hopefully explain why.</p>\n\n<p>First create a spare account on gmail which you will only use for\nsending email. For instance, if your normal account is <code>[email protected]</code>,\ncreate an account <code>[email protected]</code> with a newly created password\nwhich you only will use for this account [1].</p>\n\n<p>Set up the new account to forward all email to the normal account [2]\nand under account settings you should add all other email adresses you\nuse [3].</p>\n\n<p>Then install ssmtp (On Debian: <code>aptitude install ssmtp</code>) and edit ssmtp's configuration file <code>/etc/ssmtp/ssmtp.conf</code>:</p>\n\n<pre>\[email protected]\nmailhub=smtp.gmail.com:587\nUseSTARTTLS=YES\nAuthUser=user.noreply\nAuthPass=passwdusedonlyforthisaccount\nFromLineOverride=YES\n</pre>\n\n<p>and configure the local mail delivery by editing <code>/etc/ssmtp/revaliases</code>\nassuming that your local login is <code>localuser</code>:</p>\n\n<pre>\nroot:[email protected]:smtp.gmail.com:587\nlocaluser:[email protected]:smtp.gmail.com:587\n</pre>\n\n<p>Make sure the two configuration files are readable to all users who\nshould be able to send email [4].</p>\n\n<p>Test the setup by e.g. <code>mailx</code> (On Debian: <code>aptitude install bsd-mailx</code>):</p>\n\n<pre>\necho 'testing, one, two' | mailx -s 'test 1' [email protected]\n</pre>\n\n<p>Hope this helps.</p>\n\n<hr>\n\n<p>[1] The new gmail user name and password will be visible to everyone who\ncan log onto your machine, so you do not want this account to be\ncritical in any way, meaning you can close it down immediately if\nsomeone should get access to it.</p>\n\n<p>[2] If some email you sent bounces back to you, you might want to know\nabout it, and there actually exists people who will happily reply to an\nemail from <code>johnsmith.noreply</code>.</p>\n\n<p>[3] Gmail will rewrite the <code>From</code> header on the email if it does not recognise the address.</p>\n\n<p>[4] Ssmtp runs as the local user who sends the email, so that user needs\nread access to the configuration files.</p>\n"
},
{
"answer_id": 341914,
"author": "FlySwat",
"author_id": 1965,
"author_profile": "https://Stackoverflow.com/users/1965",
"pm_score": 0,
"selected": false,
"text": "<p>Of course, your home ISP probably has the common SMTP port blocked as well.</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267193",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have a computer at home which I can't access from work. I'd like to be able to view results from work that my home computer produces. The best idea I've come up with is an automated script running on my home computer that emails myself the results (from a text file or stderr/out) when complete.
I'm decent with bash (I have a *linux* machine) and java, so an answer using either or both of those would be ideal, but if there's something easier that's fine too.
I typically use gmail, but also have yahoo mail.
My question is this: what would be the basic steps in solving this problem? I can do the nitty gritty stuff, but can't really get the big picture of how something like this would work.
Please help.
jbu
|
On any Linux I have used the mail sending from command-line is simple:
```
mail -s "My subject here" [email protected] <message_body.txt
```
AFAIK this acts as a front-end to sendmail, and you have to have sendmail configured to forward the messages to your ISP mail server.
|
267,198 |
<p>We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.</p>
<p>This works by handling the PreviewKeyDown event in the form normally. When we add a user control to the form, the event no longer fires.</p>
<p>Am I missing something trivial here? Or do we need to handle the event in the user control first?</p>
<p>Thanks for your help!</p>
<p><p>Thanks Factor. When I get more time :) I'll get it working 'properley'!</p>
|
[
{
"answer_id": 267385,
"author": "BFree",
"author_id": 15861,
"author_profile": "https://Stackoverflow.com/users/15861",
"pm_score": 1,
"selected": false,
"text": "<p>This is probably not the best way of doing it, but the first way that comes to mind. </p>\n\n<p>In your forms constructor, after you call InitializeComponent(); do something like this:</p>\n\n<pre><code> foreach (Control control in this.Controls)\n {\n control.PreviewKeyDown += new PreviewKeyDownEventHandler(HandlePreviewKeyDown);\n }\n</code></pre>\n\n<p>I THINK that should do the trick. In your HandlePreviewKeyDown method you can then do your work and it should trigger regardless of which control has focus.</p>\n"
},
{
"answer_id": 267437,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 1,
"selected": false,
"text": "<p>PreviewKeyDown only works when the control has focus. It sounds like you should look into an application level <strong>hook</strong> for a special shortcut keys. You'll have to do it with a P/Invoke. <a href=\"http://pinvoke.net/default.aspx/user32/SetWindowsHookEx.html\" rel=\"nofollow noreferrer\">SetWindowsHookEx</a> on pinvoke.net is a good place for an example. Here's a <a href=\"http://support.microsoft.com/kb/318804\" rel=\"nofollow noreferrer\">MS KB article about a mouse hook in c#</a>, which appears to be expanded to a keyboard hook <a href=\"http://blogs.msdn.com/toub/archive/2006/05/03/589423.aspx\" rel=\"nofollow noreferrer\">in this article</a>.</p>\n"
},
{
"answer_id": 277907,
"author": "Eric W",
"author_id": 14972,
"author_profile": "https://Stackoverflow.com/users/14972",
"pm_score": 2,
"selected": false,
"text": "<p>The hidden menu you are using works fine for shortcuts that are valid menu item shortcuts, but if you want to use any key as a shortcut (such as Page Up/Page Down), you'll need a different trick.</p>\n\n<p>Another way to do this that doesn't involve P/Invoke is to set the <code>Form.KeyPreview</code> property of your form to true. This will cause all key presses to be sent to the form first, regardless of which control has focus. You can then override OnKeyDown, OnKeyPress, and/or OnKeyUp to handle the key press before any of your controls.</p>\n"
},
{
"answer_id": 2761380,
"author": "Byron Ross",
"author_id": 1811110,
"author_profile": "https://Stackoverflow.com/users/1811110",
"pm_score": 2,
"selected": true,
"text": "<p>We ended up doing this:</p>\n\n<p>I found a workaround for this by setting up a hidden menu item by setting:</p>\n\n<pre><code>ToolStripMenuItem.Visible = false\n</code></pre>\n\n<p>(Thanks to <a href=\"http://blogs.msdn.com/jfoscoding/archive/2005/01/24/359334.aspx\" rel=\"nofollow noreferrer\">this article)</a>.</p>\n\n<p>It appears that the Main Menu of a form always gets searched for your shortcut key combination. This works regardless of whick control has focus</p>\n"
}
] |
2008/11/05
|
[
"https://Stackoverflow.com/questions/267198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1811110/"
] |
We need to handle this event in the base form, regardless of which controls currently have focus. We have a couple of global key commands that need to work regardless of control focus.
This works by handling the PreviewKeyDown event in the form normally. When we add a user control to the form, the event no longer fires.
Am I missing something trivial here? Or do we need to handle the event in the user control first?
Thanks for your help!
Thanks Factor. When I get more time :) I'll get it working 'properley'!
|
We ended up doing this:
I found a workaround for this by setting up a hidden menu item by setting:
```
ToolStripMenuItem.Visible = false
```
(Thanks to [this article)](http://blogs.msdn.com/jfoscoding/archive/2005/01/24/359334.aspx).
It appears that the Main Menu of a form always gets searched for your shortcut key combination. This works regardless of whick control has focus
|
267,219 |
<p>I want to display the current host and database names in a view.</p>
<p>Where can I get these names?</p>
<p>Are there some predefined environment or global variables? </p>
|
[
{
"answer_id": 267251,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 5,
"selected": true,
"text": "<p>You can create a rails configuration object and obtain the necessary information from it:</p>\n\n<pre><code>config = Rails::Configuration.new\nhost = config.database_configuration[RAILS_ENV][\"host\"]\ndatabase = config.database_configuration[RAILS_ENV][\"database\"]\n</code></pre>\n\n<p>See the <a href=\"http://edgedocs.planetargon.org/classes/Rails/Configuration.html\" rel=\"noreferrer\">documentation</a> for Rails::Configuration for details.</p>\n"
},
{
"answer_id": 5385176,
"author": "craic.com",
"author_id": 561807,
"author_profile": "https://Stackoverflow.com/users/561807",
"pm_score": 5,
"selected": false,
"text": "<p>The Rails::configuration.new answer does not work in Rails 3</p>\n\n<pre><code>config = Rails::Configuration.new\nNoMethodError: undefined method `new' for Rails::Configuration:Module\n[...]\n</code></pre>\n\n<p>If you are using MySQL or Postgres then this works</p>\n\n<pre><code>ActiveRecord::Base.connection.current_database\n</code></pre>\n\n<p>But this only works with drivers that have implemented that method. For example, it will not work for SQLite.</p>\n"
},
{
"answer_id": 6953222,
"author": "Ryan Long",
"author_id": 542791,
"author_profile": "https://Stackoverflow.com/users/542791",
"pm_score": 4,
"selected": false,
"text": "<p>On Rails 3, this is most easily accessed via <code>Rails::Application.config</code>, like so:</p>\n\n<pre><code> YourApplicationClassName::Application.config.database_configuration[::Rails.env]\n</code></pre>\n\n<p>If you try to call it directly on <code>Rails</code> instead of <code>YourApplicationClassName</code>, rails will give you a deperecation warning. If you don't know what your application constant is, try <code>Rails.application.class.name</code> in a Rails console for your app.</p>\n"
},
{
"answer_id": 8333129,
"author": "joshmckin",
"author_id": 297561,
"author_profile": "https://Stackoverflow.com/users/297561",
"pm_score": 3,
"selected": false,
"text": "<p>The method below is nice when you are connected to multiple databases. Tested on Sqlite3 and Mysql2</p>\n\n<pre><code>MyModel.connection.instance_variable_get(:@config)[:database]\n</code></pre>\n"
},
{
"answer_id": 17607657,
"author": "Fernando Almeida",
"author_id": 756704,
"author_profile": "https://Stackoverflow.com/users/756704",
"pm_score": 6,
"selected": false,
"text": "<p>With Rails 3 you can use</p>\n\n<pre><code>Rails.configuration.database_configuration[Rails.env]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>Rails.application.config.database_configuration[Rails.env]\n</code></pre>\n\n<p>or</p>\n\n<pre><code>ActiveRecord::Base.connection_config\n</code></pre>\n"
},
{
"answer_id": 19932078,
"author": "mikowiec",
"author_id": 2945404,
"author_profile": "https://Stackoverflow.com/users/2945404",
"pm_score": 3,
"selected": false,
"text": "<p>Tested in Rails console:</p>\n\n<pre><code>ActiveRecord::Base.connection.instance_variable_get(:@config)\n</code></pre>\n\n<p>next info should be out:\nadapter, host, encoding, reconnect, database name, username, pass</p>\n"
},
{
"answer_id": 52583216,
"author": "toomaj",
"author_id": 5638830,
"author_profile": "https://Stackoverflow.com/users/5638830",
"pm_score": 1,
"selected": false,
"text": "<p>Just this should work\n<code>ActiveRecord::Base.connection.database_name</code></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267219",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14755/"
] |
I want to display the current host and database names in a view.
Where can I get these names?
Are there some predefined environment or global variables?
|
You can create a rails configuration object and obtain the necessary information from it:
```
config = Rails::Configuration.new
host = config.database_configuration[RAILS_ENV]["host"]
database = config.database_configuration[RAILS_ENV]["database"]
```
See the [documentation](http://edgedocs.planetargon.org/classes/Rails/Configuration.html) for Rails::Configuration for details.
|
267,221 |
<p>I've got a Perforce server set up, and installed the P4V client. I've created a new depot and a new workspace. Per the documentation, I've mapped the workspace to the depot. So far so good.</p>
<p>I now have a .SQL script that was created by an external application that I wish to check in for the first time. I copied the file into my workspace and can see the file in the client's workspace tree window. Yet when I attempt to mark the file for add, I get a "file(s) not opened on this client" error. I've tried editing a changelist to include the file, but the changelist editor does not "see" the file.</p>
<p>I've read through the documentation (PDF files), but I just do not see what I'm missing. I've worked with other RCS software in a commercial setting, but this is my first stab at trying to set up and administer and RCS system up for personal use.</p>
|
[
{
"answer_id": 267232,
"author": "toolkit",
"author_id": 3295,
"author_profile": "https://Stackoverflow.com/users/3295",
"pm_score": 0,
"selected": false,
"text": "<p>Are you sure your filespec includes the directory you have added your file in?</p>\n\n<p>Perhaps you could post your ClientSpec, and the directory in which your file is located?</p>\n"
},
{
"answer_id": 267435,
"author": "BIll",
"author_id": 34903,
"author_profile": "https://Stackoverflow.com/users/34903",
"pm_score": 0,
"selected": false,
"text": "<p>Workspace root: C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666</p>\n\n<p>File dir under root: C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\\tunnel_files</p>\n\n<p>View mappings:</p>\n\n<p>//tunnel/... //wtansill_localhost_1666/tunnel/...</p>\n\n<p>//tunnel/* //wtansill_localhost_1666/tunnel/*</p>\n\n<p>It's sort of a moot point though. The above workspace was the default set up by Perforce when I installed it. I deleted that workspace and created a new one using the P4V client, retraced my original steps, and now, lo, it works! Go figure.</p>\n"
},
{
"answer_id": 268163,
"author": "Toby Allen",
"author_id": 6244,
"author_profile": "https://Stackoverflow.com/users/6244",
"pm_score": 1,
"selected": false,
"text": "<p>I think your problem is likely to be with the mappings. This is a reasonably common issue.</p>\n\n<p>Taking your details</p>\n\n<pre><code>Workspace root: C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\n\nFile dir under root: C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\\tunnel_files\n\nView mappings:\n\n//tunnel/... //wtansill_localhost_1666/tunnel/...\n\n//tunnel/* //wtansill_localhost_1666/tunnel/*\n</code></pre>\n\n<p>With the details above, the line</p>\n\n<pre><code>//tunnel/... //wtansill_localhost_1666/tunnel/...\n</code></pre>\n\n<p>means that you need to place the files you wish to add into the root of your workspace plus the directory tunnel eg.</p>\n\n<p>C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\\tunnel</p>\n\n<p>rather than</p>\n\n<pre><code>C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\\tunnel_files\n</code></pre>\n\n<p>where you seem to have put them. A way around this is </p>\n\n<ol>\n<li>Create the tunnel folder in the correct place (and any subfolders) </li>\n<li><p>Remove the final folder from your workspace mapping so</p>\n\n<p>//tunnel/... //wtansill_localhost_1666/tunnel/...\nbecomes\n//tunnel/... //wtansill_localhost_1666/...</p></li>\n</ol>\n\n<p>this would mean anything under</p>\n\n<p>C:\\Documents and Settings\\wtansill\\Perforce\\wtansill_localhost_1666\\tunnel_files</p>\n\n<p>would be mapped to //tunnel/tunnel_files which is I think what you want.</p>\n\n<p>Hope this helps.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267221",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34903/"
] |
I've got a Perforce server set up, and installed the P4V client. I've created a new depot and a new workspace. Per the documentation, I've mapped the workspace to the depot. So far so good.
I now have a .SQL script that was created by an external application that I wish to check in for the first time. I copied the file into my workspace and can see the file in the client's workspace tree window. Yet when I attempt to mark the file for add, I get a "file(s) not opened on this client" error. I've tried editing a changelist to include the file, but the changelist editor does not "see" the file.
I've read through the documentation (PDF files), but I just do not see what I'm missing. I've worked with other RCS software in a commercial setting, but this is my first stab at trying to set up and administer and RCS system up for personal use.
|
I think your problem is likely to be with the mappings. This is a reasonably common issue.
Taking your details
```
Workspace root: C:\Documents and Settings\wtansill\Perforce\wtansill_localhost_1666
File dir under root: C:\Documents and Settings\wtansill\Perforce\wtansill_localhost_1666\tunnel_files
View mappings:
//tunnel/... //wtansill_localhost_1666/tunnel/...
//tunnel/* //wtansill_localhost_1666/tunnel/*
```
With the details above, the line
```
//tunnel/... //wtansill_localhost_1666/tunnel/...
```
means that you need to place the files you wish to add into the root of your workspace plus the directory tunnel eg.
C:\Documents and Settings\wtansill\Perforce\wtansill\_localhost\_1666\tunnel
rather than
```
C:\Documents and Settings\wtansill\Perforce\wtansill_localhost_1666\tunnel_files
```
where you seem to have put them. A way around this is
1. Create the tunnel folder in the correct place (and any subfolders)
2. Remove the final folder from your workspace mapping so
//tunnel/... //wtansill\_localhost\_1666/tunnel/...
becomes
//tunnel/... //wtansill\_localhost\_1666/...
this would mean anything under
C:\Documents and Settings\wtansill\Perforce\wtansill\_localhost\_1666\tunnel\_files
would be mapped to //tunnel/tunnel\_files which is I think what you want.
Hope this helps.
|
267,236 |
<p>It seems if I do something like</p>
<pre><code>$file = fopen($filepath, "w");
$CR = curl_init();
curl_setopt($CR, CURLOPT_URL, $source_path);
curl_setopt($CR, CURLOPT_POST, 1);
curl_setopt($CR, CURLOPT_FAILONERROR, true);
curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($CR, CURLOPT_FILE, $file);
$result = curl_exec( $CR );
$error = curl_error( $CR );
print filesize($filepath);
</code></pre>
<p>I get a different result than if I just run</p>
<pre><code>print filesize($filepath);
</code></pre>
<p>a second time. My guess is that curl is still downloading when do a filesize().</p>
|
[
{
"answer_id": 279844,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 3,
"selected": true,
"text": "<p>Note that functions like filesize() cache their result, try adding a call to clearstatcache() above 'print filesize(...);'. Here is an example:</p>\n\n<pre><code>$file = '/tmp/test12345';\nfile_put_contents($file, 'hello');\necho filesize($file), \"\\n\";\nfile_put_contents($file, 'hello world, this is a test');\necho filesize($file), \"\\n\";\nclearstatcache();\necho filesize($file), \"\\n\";\n</code></pre>\n\n<p>See www.php.net/clearstatcache</p>\n"
},
{
"answer_id": 10802130,
"author": "Daniel",
"author_id": 1424080,
"author_profile": "https://Stackoverflow.com/users/1424080",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I have the same problem. curl is supposed to be synchronous, but, depending on how you're using it, it's not synchronous.<br>\nIf you call, after curl, a print, or echo, the content comes void. There's a strange delay.\nBut I'll try this approach - </p>\n\n<pre><code>print_r(curls_getinfo($CR));\n</code></pre>\n\n<p>Doing everything in one step may solve the problem.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10393/"
] |
It seems if I do something like
```
$file = fopen($filepath, "w");
$CR = curl_init();
curl_setopt($CR, CURLOPT_URL, $source_path);
curl_setopt($CR, CURLOPT_POST, 1);
curl_setopt($CR, CURLOPT_FAILONERROR, true);
curl_setopt($CR, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($CR, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($CR, CURLOPT_FILE, $file);
$result = curl_exec( $CR );
$error = curl_error( $CR );
print filesize($filepath);
```
I get a different result than if I just run
```
print filesize($filepath);
```
a second time. My guess is that curl is still downloading when do a filesize().
|
Note that functions like filesize() cache their result, try adding a call to clearstatcache() above 'print filesize(...);'. Here is an example:
```
$file = '/tmp/test12345';
file_put_contents($file, 'hello');
echo filesize($file), "\n";
file_put_contents($file, 'hello world, this is a test');
echo filesize($file), "\n";
clearstatcache();
echo filesize($file), "\n";
```
See www.php.net/clearstatcache
|
267,237 |
<p>What's the best way to unit test protected and private methods in Ruby, using the standard Ruby <code>Test::Unit</code> framework?</p>
<p>I'm sure somebody will pipe up and dogmatically assert that "you should only unit test public methods; if it needs unit testing, it shouldn't be a protected or private method", but I'm not really interested in debating that. I've got several methods that <strong>are</strong> protected or private for good and valid reasons, these private/protected methods are moderately complex, and the public methods in the class depend upon these protected/private methods functioning correctly, therefore I need a way to test the protected/private methods.</p>
<p>One more thing... I generally put all the methods for a given class in one file, and the unit tests for that class in another file. Ideally, I'd like all the magic to implement this "unit test of protected and private methods" functionality into the unit test file, not the main source file, in order to keep the main source file as simple and straightforward as possible.</p>
|
[
{
"answer_id": 267401,
"author": "James Baker",
"author_id": 9365,
"author_profile": "https://Stackoverflow.com/users/9365",
"pm_score": 7,
"selected": false,
"text": "<p>You can bypass encapsulation with the send method:</p>\n\n<pre class=\"lang-ruby prettyprint-override\"><code>myobject.send(:method_name, args)\n</code></pre>\n\n<p>This is a 'feature' of Ruby. :)</p>\n\n<p>There was internal debate during Ruby 1.9 development which considered having <code>send</code> respect privacy and <code>send!</code> ignore it, but in the end nothing changed in Ruby 1.9. Ignore the comments below discussing <code>send!</code> and breaking things.</p>\n"
},
{
"answer_id": 267408,
"author": "rampion",
"author_id": 9859,
"author_profile": "https://Stackoverflow.com/users/9859",
"pm_score": 3,
"selected": false,
"text": "<p><code>instance_eval()</code> might help:</p>\n\n<pre><code>--------------------------------------------------- Object#instance_eval\n obj.instance_eval(string [, filename [, lineno]] ) => obj\n obj.instance_eval {| | block } => obj\n------------------------------------------------------------------------\n Evaluates a string containing Ruby source code, or the given \n block, within the context of the receiver (obj). In order to set \n the context, the variable self is set to obj while the code is \n executing, giving the code access to obj's instance variables. In \n the version of instance_eval that takes a String, the optional \n second and third parameters supply a filename and starting line \n number that are used when reporting compilation errors.\n\n class Klass\n def initialize\n @secret = 99\n end\n end\n k = Klass.new\n k.instance_eval { @secret } #=> 99\n</code></pre>\n\n<p>You can use it to access private methods and instance variables directly.</p>\n\n<p>You could also consider using <code>send()</code>, which will also give you access to private and protected methods (like James Baker suggested)</p>\n\n<p>Alternatively, you could modify the metaclass of your test object to make the private/protected methods public just for that object.</p>\n\n<pre><code> test_obj.a_private_method(...) #=> raises NoMethodError\n test_obj.a_protected_method(...) #=> raises NoMethodError\n class << test_obj\n public :a_private_method, :a_protected_method\n end\n test_obj.a_private_method(...) # executes\n test_obj.a_protected_method(...) # executes\n\n other_test_obj = test.obj.class.new\n other_test_obj.a_private_method(...) #=> raises NoMethodError\n other_test_obj.a_protected_method(...) #=> raises NoMethodError\n</code></pre>\n\n<p>This will let you call these methods without affecting other objects of that class.\nYou could reopen the class within your test directory and make them public for all the \ninstances within your test code, but that might affect your test of the public interface.</p>\n"
},
{
"answer_id": 268953,
"author": "Scott",
"author_id": 7399,
"author_profile": "https://Stackoverflow.com/users/7399",
"pm_score": 3,
"selected": false,
"text": "<p>One way I've done it in the past is:</p>\n\n<pre><code>class foo\n def public_method\n private_method\n end\n\nprivate unless 'test' == Rails.env\n\n def private_method\n 'private'\n end\nend\n</code></pre>\n"
},
{
"answer_id": 268971,
"author": "Mike",
"author_id": 19215,
"author_profile": "https://Stackoverflow.com/users/19215",
"pm_score": 2,
"selected": false,
"text": "<p>I would probably lean toward using instance_eval(). Before I knew about instance_eval(), however, I would create a derived class in my unit test file. I would then set the private method(s) to be public.</p>\n\n<p>In the example below, the build_year_range method is private in the PublicationSearch::ISIQuery class. Deriving a new class just for testing purposes allows me to set a method(s) to be public and, therefore, directly testable. Likewise, the derived class exposes an instance variable called 'result' that was previously not exposed.</p>\n\n<pre><code># A derived class useful for testing.\nclass MockISIQuery < PublicationSearch::ISIQuery\n attr_accessor :result\n public :build_year_range\nend\n</code></pre>\n\n<p>In my unit test I have a test case which instantiates the MockISIQuery class and directly tests the build_year_range() method.</p>\n"
},
{
"answer_id": 269047,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 2,
"selected": false,
"text": "<p>You can \"reopen\" the class and provide a new method that delegates to the private one:</p>\n\n<pre><code>class Foo\n private\n def bar; puts \"Oi! how did you reach me??\"; end\nend\n# and then\nclass Foo\n def ah_hah; bar; end\nend\n# then\nFoo.new.ah_hah\n</code></pre>\n"
},
{
"answer_id": 269452,
"author": "Will Sargent",
"author_id": 5266,
"author_profile": "https://Stackoverflow.com/users/5266",
"pm_score": 6,
"selected": false,
"text": "<p>Here's one easy way if you use RSpec:</p>\n\n<pre><code>before(:each) do\n MyClass.send(:public, *MyClass.protected_instance_methods) \nend\n</code></pre>\n"
},
{
"answer_id": 269771,
"author": "Aaron Hinni",
"author_id": 12086,
"author_profile": "https://Stackoverflow.com/users/12086",
"pm_score": 5,
"selected": false,
"text": "<p>Just reopen the class in your test file, and redefine the method or methods as public. You don't have to redefine the guts of the method itself, just pass the symbol into the <code>public</code> call.</p>\n\n<p>If you original class is defined like this:</p>\n\n<pre><code>class MyClass\n\n private\n\n def foo\n true\n end\nend\n</code></pre>\n\n<p>In you test file, just do something like this:</p>\n\n<pre><code>class MyClass\n public :foo\n\nend\n</code></pre>\n\n<p>You can pass multiple symbols to <code>public</code> if you want to expose more private methods.</p>\n\n<pre><code>public :foo, :bar\n</code></pre>\n"
},
{
"answer_id": 316760,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Here is a general addition to Class which I use. It's a bit more shotgun than only making public the method you are testing, but in most cases it doesn't matter, and it's much more readable.</p>\n\n<pre><code>class Class\n def publicize_methods\n saved_private_instance_methods = self.private_instance_methods\n self.class_eval { public *saved_private_instance_methods }\n begin\n yield\n ensure\n self.class_eval { private *saved_private_instance_methods }\n end\n end\nend\n\nMyClass.publicize_methods do\n assert_equal 10, MyClass.new.secret_private_method\nend\n</code></pre>\n\n<p>Using send to access protected/private methods <em>is</em> broken in 1.9, so is not a recommended solution.</p>\n"
},
{
"answer_id": 1146395,
"author": "user52804",
"author_id": 52804,
"author_profile": "https://Stackoverflow.com/users/52804",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>I'm sure somebody will pipe up and\n dogmatically assert that \"you should\n only unit test public methods; if it\n needs unit testing, it shouldn't be a\n protected or private method\", but I'm\n not really interested in debating\n that.</p>\n</blockquote>\n\n<p>You could also refactor those into a new object in which those methods are public, and delegate to them privately in the original class. This will allow you to test the methods without magic metaruby in your specs while yet keeping them private.</p>\n\n<blockquote>\n <p>I've got several methods that are\n protected or private for good and\n valid reasons</p>\n</blockquote>\n\n<p>What are those valid reasons? Other OOP languages can get away without private methods at all (smalltalk comes to mind - where private methods only exist as a convention).</p>\n"
},
{
"answer_id": 2011241,
"author": "Franz Hinkel",
"author_id": 244496,
"author_profile": "https://Stackoverflow.com/users/244496",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of obj.send you can use a singleton method. It’s 3 more lines of code in your \ntest class and requires no changes in the actual code to be tested.</p>\n\n<pre><code>def obj.my_private_method_publicly (*args)\n my_private_method(*args)\nend\n</code></pre>\n\n<p>In the test cases you then use <code>my_private_method_publicly</code> whenever you want to test <code>my_private_method</code>.</p>\n\n<p><a href=\"http://mathandprogramming.blogspot.com/2010/01/ruby-testing-private-methods.html\" rel=\"nofollow noreferrer\">http://mathandprogramming.blogspot.com/2010/01/ruby-testing-private-methods.html</a></p>\n\n<p><code>obj.send</code> for private methods was replaced by <code>send!</code> in 1.9, but later <code>send!</code> was removed again. So <code>obj.send</code> works perfectly well. </p>\n"
},
{
"answer_id": 2359538,
"author": "Victor K.",
"author_id": 283960,
"author_profile": "https://Stackoverflow.com/users/283960",
"pm_score": 1,
"selected": false,
"text": "<p>To correct the top answer above: in Ruby 1.9.1, it's Object#send that sends all the messages, and Object#public_send that respects privacy.</p>\n"
},
{
"answer_id": 13551935,
"author": "Sean Tan",
"author_id": 191040,
"author_profile": "https://Stackoverflow.com/users/191040",
"pm_score": 3,
"selected": false,
"text": "<p>To make public all protected and private method for the described class, you can add the following to your spec_helper.rb and not having to touch any of your spec files.</p>\n\n<pre><code>RSpec.configure do |config|\n config.before(:each) do\n described_class.send(:public, *described_class.protected_instance_methods)\n described_class.send(:public, *described_class.private_instance_methods)\n end\nend\n</code></pre>\n"
},
{
"answer_id": 14916370,
"author": "Binary Logic",
"author_id": 851181,
"author_profile": "https://Stackoverflow.com/users/851181",
"pm_score": 0,
"selected": false,
"text": "<p>I know I'm late to the party, but don't test private methods....I can't think of a reason to do this. A publicly accessible method is using that private method somewhere, test the public method and the variety of scenarios that would cause that private method to be used. Something goes in, something comes out. Testing private methods is a big no-no, and it makes it much harder to refactor your code later. They are private for a reason.</p>\n"
},
{
"answer_id": 29390223,
"author": "Knut Stenmark",
"author_id": 4269216,
"author_profile": "https://Stackoverflow.com/users/4269216",
"pm_score": 1,
"selected": false,
"text": "<p>In order to do this:</p>\n\n<pre><code>disrespect_privacy @object do |p|\n assert p.private_method\nend\n</code></pre>\n\n<p>You can implement this in your test_helper file:</p>\n\n<pre><code>class ActiveSupport::TestCase\n def disrespect_privacy(object_or_class, &block) # access private methods in a block\n raise ArgumentError, 'Block must be specified' unless block_given?\n yield Disrespect.new(object_or_class)\n end\n\n class Disrespect\n def initialize(object_or_class)\n @object = object_or_class\n end\n def method_missing(method, *args)\n @object.send(method, *args)\n end\n end\nend\n</code></pre>\n"
},
{
"answer_id": 30244377,
"author": "rahul patil",
"author_id": 1298176,
"author_profile": "https://Stackoverflow.com/users/1298176",
"pm_score": 2,
"selected": false,
"text": "<p>In Test::Unit framework can write,</p>\n\n<pre><code>MyClass.send(:public, :method_name)\n</code></pre>\n\n<p>Here \"method_name\" is private method. </p>\n\n<p>& while calling this method can write,</p>\n\n<pre><code>assert_equal expected, MyClass.instance.method_name(params)\n</code></pre>\n"
},
{
"answer_id": 35783607,
"author": "qix",
"author_id": 954643,
"author_profile": "https://Stackoverflow.com/users/954643",
"pm_score": 3,
"selected": false,
"text": "<p>Similar to @WillSargent's response, here's what I've used in a <code>describe</code> block for the special case of testing some protected validators without needing to go through the heavyweight process of creating/updating them with FactoryGirl (and you could use <code>private_instance_methods</code> similarly):</p>\n\n<pre><code> describe \"protected custom `validates` methods\" do\n # Test these methods directly to avoid needing FactoryGirl.create\n # to trigger before_create, etc.\n before(:all) do\n @protected_methods = MyClass.protected_instance_methods\n MyClass.send(:public, *@protected_methods)\n end\n after(:all) do\n MyClass.send(:protected, *@protected_methods)\n @protected_methods = nil\n end\n\n # ...do some tests...\n end\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13157/"
] |
What's the best way to unit test protected and private methods in Ruby, using the standard Ruby `Test::Unit` framework?
I'm sure somebody will pipe up and dogmatically assert that "you should only unit test public methods; if it needs unit testing, it shouldn't be a protected or private method", but I'm not really interested in debating that. I've got several methods that **are** protected or private for good and valid reasons, these private/protected methods are moderately complex, and the public methods in the class depend upon these protected/private methods functioning correctly, therefore I need a way to test the protected/private methods.
One more thing... I generally put all the methods for a given class in one file, and the unit tests for that class in another file. Ideally, I'd like all the magic to implement this "unit test of protected and private methods" functionality into the unit test file, not the main source file, in order to keep the main source file as simple and straightforward as possible.
|
You can bypass encapsulation with the send method:
```ruby
myobject.send(:method_name, args)
```
This is a 'feature' of Ruby. :)
There was internal debate during Ruby 1.9 development which considered having `send` respect privacy and `send!` ignore it, but in the end nothing changed in Ruby 1.9. Ignore the comments below discussing `send!` and breaking things.
|
267,248 |
<p>I have some code that looks like:</p>
<pre><code>template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << x;
}
bar(v);
}
</code></pre>
<p>gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. What's the best way around this? I know I can cast <code>x</code> to be <code>unsigned int</code> but that will cause warnings about <code>x</code> being larger than the width of <code>v</code> (since it is casting a negative number to be positive). I know there is a work-around that involves creating a new templatized <code>shift</code> function, but I'd like to avoid that if possible.</p>
|
[
{
"answer_id": 267255,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "<p>Would this work?</p>\n\n<pre><code>const short unsigned int x = A - B;\n</code></pre>\n\n<p>It's cutting off a lot more bits than need to be cut off, but if your values of A - B are small enough...</p>\n"
},
{
"answer_id": 267257,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 1,
"selected": false,
"text": "<p>why not make x an unsigned char type and cast it? surely you don't need to shift more than 255 bits?</p>\n\n<pre><code>const unsigned char x = static_cast<unsigned char>(A - B);\n</code></pre>\n\n<p>or perhaps use masking to ensure that the shift is in bounds like this:</p>\n\n<pre><code>const unsigned int x = static_cast<unsigned int>(A - B) & 0x1f; // limit A-B to have a range of (0 - 31)\n</code></pre>\n\n<p>EDIT:</p>\n\n<p>in response to the comment here's an idea:</p>\n\n<pre><code>template<unsigned int A, unsigned int B>\nint foo() {\n int v = 1;\n const int x = A - B;\n if (x > 0) {\n v = v << (static_cast<unsigned int>(x) & 0x1f);\n }\n bar(v);\n}\n</code></pre>\n\n<p>NOTE: you can replace 0x1f with something like: (CHAR_BIT * sizeof(T) - 1)</p>\n\n<p>EDIT: in response to the latest comment, this code does not issue any warning compiling with: g++ -W -Wall -ansi -pedantic test.cc -o test</p>\n\n<pre><code>#include <iostream>\n\ntemplate<unsigned int A, unsigned int B>\nint foo() {\n int v = 1;\n const int x = A - B;\n if (x > 0) {\n v = v << (static_cast<unsigned int>(x) & 0x1f);\n }\n return v;\n}\n\nint main() {\n std::cout << foo<1, 3>() << std::endl;\n std::cout << foo<3, 1>() << std::endl;\n std::cout << foo<300, 1>() << std::endl;\n std::cout << foo<25, 31>() << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 267415,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 3,
"selected": true,
"text": "<p>Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime <code>if</code>, without any casts, like this:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\ntemplate< unsigned int A, unsigned int B >\nstruct my\n{\n template< bool P >\n static void shift_if( int & );\n\n template<>\n static void shift_if< false >( int & ) {}\n\n template<>\n static void shift_if< true >( int & v ) { v <<= A - B; }\n\n static void op( int & v ) { shift_if< (A > B) >( v ); }\n};\n\ntemplate< unsigned int A, unsigned int B >\nint foo()\n{\n int v = 1;\n my< A, B >::op( v );\n return v;\n}\n\nint main() {\n cout << foo< 1, 3 >() << endl;\n cout << foo< 3, 1 >() << endl;\n cout << foo< 300, 1 >() << endl;\n cout << foo< 25, 31 >() << endl;\n return 0;\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267248",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have some code that looks like:
```
template<unsigned int A, unsigned int B>
int foo() {
int v = 1;
const int x = A - B;
if (x > 0) {
v = v << x;
}
bar(v);
}
```
gcc will complain about x being negative for certain instantiations of A, B; however, I do perform a check to make sure it is non-negative. What's the best way around this? I know I can cast `x` to be `unsigned int` but that will cause warnings about `x` being larger than the width of `v` (since it is casting a negative number to be positive). I know there is a work-around that involves creating a new templatized `shift` function, but I'd like to avoid that if possible.
|
Since A and B are known at compile time, not only can you get rid of your warning, but you can also get rid of a runtime `if`, without any casts, like this:
```
#include <iostream>
using namespace std;
template< unsigned int A, unsigned int B >
struct my
{
template< bool P >
static void shift_if( int & );
template<>
static void shift_if< false >( int & ) {}
template<>
static void shift_if< true >( int & v ) { v <<= A - B; }
static void op( int & v ) { shift_if< (A > B) >( v ); }
};
template< unsigned int A, unsigned int B >
int foo()
{
int v = 1;
my< A, B >::op( v );
return v;
}
int main() {
cout << foo< 1, 3 >() << endl;
cout << foo< 3, 1 >() << endl;
cout << foo< 300, 1 >() << endl;
cout << foo< 25, 31 >() << endl;
return 0;
}
```
|
267,250 |
<p>I am using <code>getch()</code> and my app crashes instantly. Including when doing:</p>
<pre><code>int main()
{
getch();
}
</code></pre>
<p>I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want <code>cout</code> to work along with cross platform code.</p>
<p>I was told to use <code>std::cin.get()</code>, but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.</p>
<p>Is there any function for this? The code must work under Mac (my os) and Windows.</p>
<hr>
<p>Linking/compiling is not an <a href="https://stackoverflow.com/questions/267250/equivalent-to-getch-mac-linux-crash#comment14636199_267281">issue</a>; I include <code><curses.h></code> and link with <code>-lcurses</code> in XCode, while Windows uses <code><conio.h></code>.</p>
|
[
{
"answer_id": 267281,
"author": "dmckee --- ex-moderator kitten",
"author_id": 2509,
"author_profile": "https://Stackoverflow.com/users/2509",
"pm_score": 2,
"selected": false,
"text": "<p>You have not exhibited a</p>\n\n<pre><code>#include <stdio.h>\n</code></pre>\n\n<p>or</p>\n\n<pre><code>#include <curses.h>\n</code></pre>\n\n<p>or similar line. Are you sure that you are linking against a library that <em>includes</em> <code>getch()</code>?</p>\n"
},
{
"answer_id": 267371,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 5,
"selected": true,
"text": "<p>Have you looked in <code><curses.h></code> to see what the <code>getch()</code> function does?</p>\n\n<p>Hint: OSX and Linux are not the same as Windows.</p>\n\n<p>Specifically, as a macro in <code><curses.h></code>, we find:</p>\n\n<pre><code>#define getch() wgetch(stdscr)\n</code></pre>\n\n<p>Now, there appears, on your system, to be an actual function <code>getch()</code> in the curses library, but it expects <code>stdscr</code> to be set up, and that is done by the curses initialization functions (<code>initscr()</code> and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.</p>\n\n<p>(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)</p>\n\n<p>To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an <code>atexit()</code> function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just <code>read(0, &c, 1)</code>), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.</p>\n\n<p>One book that might help is <a href=\"https://rads.stackoverflow.com/amzn/click/com/0131411543\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">Advanced Unix Programming, 2nd Edn</a> by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use <code><curses.h></code> properly - that will be simpler than a roll-your-own solution, and probably more reliable.</p>\n"
},
{
"answer_id": 17354184,
"author": "Jose Munoz",
"author_id": 2529905,
"author_profile": "https://Stackoverflow.com/users/2529905",
"pm_score": -1,
"selected": false,
"text": "<p>The <code>getch</code> function is not available on Unix-like systems, but you can replace it with console commands through your compiler with the <code>system</code> function.</p>\n\n<p>Usage: </p>\n\n<p>In Windows you can use <code>system(\"pause\");</code></p>\n\n<p>In Unix-like systems (such as OSX) you can use <code>system(\"read -n1 -p ' ' key\");</code></p>\n\n<p>Note: <code>system</code> is declared in <code><stdlib.h></code>.</p>\n"
},
{
"answer_id": 44687705,
"author": "Benjamin",
"author_id": 8196881,
"author_profile": "https://Stackoverflow.com/users/8196881",
"pm_score": 1,
"selected": false,
"text": "<p>Use the cin.get() function for example:</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>#include <iostream>\n\nusing namespace std;\n\nint main()\n{\n char input = cin.get();\n\n cout << \"You Pressed: \" << input;\n}\n</code></pre>\n\n<p>The program would then wait for you to press a key.</p>\n\n<p>Once you have, the key you pressed would be printed to the screen.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267250",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I am using `getch()` and my app crashes instantly. Including when doing:
```
int main()
{
getch();
}
```
I can't find the link but supposedly the problem is that it needs to turn off buffering or something strange along those lines, and I still want `cout` to work along with cross platform code.
I was told to use `std::cin.get()`, but I'd like the app to quit when a key is pressed, not when the user typed in a letter or number then press enter to quit.
Is there any function for this? The code must work under Mac (my os) and Windows.
---
Linking/compiling is not an [issue](https://stackoverflow.com/questions/267250/equivalent-to-getch-mac-linux-crash#comment14636199_267281); I include `<curses.h>` and link with `-lcurses` in XCode, while Windows uses `<conio.h>`.
|
Have you looked in `<curses.h>` to see what the `getch()` function does?
Hint: OSX and Linux are not the same as Windows.
Specifically, as a macro in `<curses.h>`, we find:
```
#define getch() wgetch(stdscr)
```
Now, there appears, on your system, to be an actual function `getch()` in the curses library, but it expects `stdscr` to be set up, and that is done by the curses initialization functions (`initscr()` and relatives), and that is signally not done by your code. So, your code is invoking undefined behaviour by calling curses routines before the correct initialization is done, leading to the crash.
(Good hint from dmckee - it helped get the link line out of acidzombie24, which was important.)
To get to a point where a single key-stroke can be read and the program terminated cleanly, you have to do a good deal of work on Unix (OSX, Linux). You would have to trap the initial state of the terminal, arrange for an `atexit()` function - or some similar mechanism - to restore the state of the terminal, change the terminal from cooked mode into raw mode, then invoke a function to read a character (possibly just `read(0, &c, 1)`), and do your exit. There might be other ways to do it - but it certainly will involve some setup and teardown operations.
One book that might help is [Advanced Unix Programming, 2nd Edn](https://rads.stackoverflow.com/amzn/click/com/0131411543) by Mark Rochkind; it covers terminal handling at the level needed. Alternatively, you can use `<curses.h>` properly - that will be simpler than a roll-your-own solution, and probably more reliable.
|
267,256 |
<p>After considering the answers to my previous question (<a href="https://stackoverflow.com/questions/252459/one-svn-repository-or-many">One SVN Repository or many?</a>), I've decided to take the 4 or so repositories I have and consolidate them into one. This of course leads to the question, <strong>what's the best way to do this?</strong></p>
<p>Is there a way to combine two or more repositories maintaining the version history for both?</p>
<p>Edit: <em>I should also point out that I'm using Assembla.com, which does not provide access to the svnadmin command, AFAIK</em></p>
<p>Another edit: <em>Does this even matter? If svnadmin works on URLs, then it's no problem then.</em></p>
|
[
{
"answer_id": 267284,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, using <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svnadmin.c.dump.html\" rel=\"noreferrer\">svnadmin dump</a> and <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svnadmin.c.load.html\" rel=\"noreferrer\">svnadmin load</a>.</p>\n\n<p>Let's assume that you have to repositories, one with HEAD revision 100 and the other with HEAD revision 150.</p>\n\n<p>You dump the first repository and load it in the new one: you end up with the full story of the first repository, from revision 0 to revision 150.</p>\n\n<p>Then you dump the second repository and load it in the new one: it gets loaded with its full history, the only things that change are the actual revision numbers. The history of the second repository will be represented in the new repository from revision 151 to revision 250.</p>\n\n<p>The full history of both repositories is preserver, only the revision numbers change for the repository that is imported for second.</p>\n\n<p>The same of course applies for more than two repositories.</p>\n\n<p>EDIT: I posted while you were editing, so I didn't see your note...</p>\n"
},
{
"answer_id": 267307,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 7,
"selected": true,
"text": "<p>Edit: Oh well, the question edit was made while I was typing. This is an answer to</p>\n\n<blockquote>\n <p>Is there a way to combine two or more\n repositories maintaining the version\n history for both?</p>\n</blockquote>\n\n<hr>\n\n<p>Assuming that </p>\n\n<p>The existing repositories have a structure like:</p>\n\n<ul>\n<li>repository root\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n</ul>\n\n<p>and you want a structure something like:</p>\n\n<ul>\n<li>repository root\n\n<ul>\n<li>projectA\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n<li>projectB\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>Then for each of your project repositories:</p>\n\n<pre><code>svnadmin dump > project<n>.dmp\n</code></pre>\n\n<p>Then for each of the dump files:</p>\n\n<pre><code>svn mkdir \"<repo url>/project<n>\"\nsvnadmin load --parent-dir \"project<n>\" <filesystem path to repos>\n</code></pre>\n\n<p>More complex manipulations are possible, but this is the simplest, most straightforward. Changing the source repository structure during a dump/load is hazardous, but doable through a combination of <code>svnadmin dump</code>, <code>svndumpfilter</code>, hand-editing or additional text filters and <code>svnadmin load</code></p>\n\n<hr>\n\n<p><strong>Dealing with a third party provider</strong></p>\n\n<ul>\n<li>Request <code>svnadmin dump</code> files for each of your repositories. The provider should be willing/able to provide this - it <em>is</em> <strong>your</strong> code!</li>\n<li>Create an SVN repository locally.</li>\n<li>Perform the actions listed above for the dump files.</li>\n<li>Verify the repository structure is correct with your favorite client.</li>\n<li>Create a dump file for the combined repositories.</li>\n<li>Request that the provider populate a new repository from this dump file.</li>\n</ul>\n\n<p>YMMV: This seems to be a reasonable approach, but I've never worked with a third party provider like this.</p>\n"
},
{
"answer_id": 267328,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't have access to svnadmin, it would be hard but doable. Let's say you have repositories A and B, and want to merge them into repository C. Here's the steps you would have to use to accomplish this.</p>\n\n<ol>\n<li><p>Check out revision 1 of repository A to your hard disk. </p></li>\n<li><p>Create a directory, called Repository_A on the root of your C repository, and check this out to your local hard disk.</p></li>\n<li><p>Copy the files from your check out of A (minus) the .svn files, to your checkout of C, in the Repository_A folder. </p></li>\n<li><p>Perform a Commit on C. </p></li>\n</ol>\n\n<p>Update your working copy of repository A to revision 2 , and perform steps 3 and 4, and repeat with each successive revision until you reach the head.</p>\n\n<p>Now do the same with B. </p>\n\n<p>This would basically do the same as @Davide Gualano was suggesting, without requiring svnadmin. You could probably write a simple script to do this for your, of if there aren't a lot of revisions, you could just do it manually.</p>\n"
},
{
"answer_id": 8529409,
"author": "Scott Coldwell",
"author_id": 483403,
"author_profile": "https://Stackoverflow.com/users/483403",
"pm_score": 4,
"selected": false,
"text": "<p>With Subversion 1.7, you are now able to do dumps remotely. That is, without having access to the local file system and the <code>svnadmin dump</code> command.</p>\n\n<p>You can use <code>svnrdump</code> to get a complete dump of a remote repository. See the documentation for syntax details.</p>\n\n<p>Note that the server does not have to be running 1.7, only the client.</p>\n\n<p><a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnrdump.c.dump.html\">http://svnbook.red-bean.com/en/1.7/svn.ref.svnrdump.c.dump.html</a></p>\n"
},
{
"answer_id": 11254635,
"author": "sthysel",
"author_id": 203449,
"author_profile": "https://Stackoverflow.com/users/203449",
"pm_score": 1,
"selected": false,
"text": "<p>The other answers for this question enabled me to make the script below. Adapt the REPOS map for your case. Also, you may want to move the tags and branches into a \"preaggregate\" directory in stead of directly into the new branches and trunk.</p>\n\n<pre><code>#!/bin/bash\n\nNEWREPO=$(pwd)/newrepo\nNEWREPOCO=\"${NEWREPO}_co\"\nDUMPS=repodumps\nREV=\"0:HEAD\"\nREPOROOT=/data/svn/2.2.1/repositories/\nTOOLDIR=/opt/svn/2.2.1/bin/\nPATH=${PATH}:${TOOLDIR}\n\n# Old Repository mapping \ndeclare -A REPOS=( \n [BlaEntityBeans]='(\n [newname]=\"EntityBeans\"\n )'\n [OldServletRepoServlet]='(\n [newname]=\"SpreadsheetImportServlet\"\n )'\n [ExperimentalMappingXML]='(\n [newname]=\"SpreadsheetMappingXML\"\n )'\n [NewImportProcess]='(\n [newname]=\"SpreadsheetImportProcess\"\n )' \n)\n\ndump() {\n rm -fr ${DUMPS}\n mkdir ${DUMPS}\n for repo in \"${!REPOS[@]}\"\n do\n local dumpfile=${DUMPS}/${repo}.dmp\n echo \"Dumpimg Repo ${repo} to ${dumpfile}\"\n svnadmin dump -r ${REV} ${REPOROOT}/${repo} > ${dumpfile}\n done\n}\n\nloadRepos() {\n # new big repo\n rm -fr ${NEWREPO}\n svnadmin create ${NEWREPO}\n svn mkdir file:///${NEWREPO}/trunk -m \"\"\n svn mkdir file:///${NEWREPO}/branches -m \"\"\n svn mkdir file:///${NEWREPO}/tags -m \"\"\n\n # add the old projects as modules\n for currentname in \"${!REPOS[@]}\"\n do \n declare -A repo=${REPOS[$currentname]}\n local newname=${repo[newname]}\n echo \"Loading repo ${currentname} soon to be ${newname}\"\n dumpfile=${DUMPS}/${currentname}.dmp\n\n # import the current repo into a trmporary root position\n svn mkdir file:///${NEWREPO}/${currentname} -m \"Made module ${currentname}\"\n svnadmin load --parent-dir ${currentname} ${NEWREPO} < ${dumpfile}\n\n # now move stuff arround\n # first rename to new repo\n svn move file:///${NEWREPO}/${currentname} file:///${NEWREPO}/${newname} -m \"Moved ${currentname} to ${newname}\"\n # now move trunk, branches and tags\n for vc in {trunk,branches,tags}\n do\n echo \"Moving the current content of $vc into ${NEWREPO}/${vc}/${newname}\"\n svn move file:///${NEWREPO}/${newname}/${vc} file:///${NEWREPO}/${vc}/${newname} -m \"Done by $0\"\n done\n svn rm file:///${NEWREPO}/${newname} -m \"Removed old ${newname}\"\n done\n}\n\ndump\nloadRepos\n</code></pre>\n"
},
{
"answer_id": 14263244,
"author": "Hatim",
"author_id": 1860511,
"author_profile": "https://Stackoverflow.com/users/1860511",
"pm_score": 3,
"selected": false,
"text": "<p>You can load many dump files in one repository with the following steps. </p>\n\n<p>Repository root:</p>\n\n<pre><code> projectA\n branches \n tags\n trunk\n projectB\n branches\n tags\n trunk\n</code></pre>\n\n<p>First you must create the directory (project A, project B) in your repository root like this: </p>\n\n<pre><code>$ svn mkdir -m \"Initial project root\" \\\nfile:///var/svn/repository_root/Project_A\\\nfile:///var/svn/repository_root/Project_B\\\nfile:///var/svn/repository_root/Project_C\\\n\nRevision 1 committed.\n</code></pre>\n\n<p>And after that you can load your dump files:</p>\n\n<p>Use the parameter <code>--parent-dir DIRECTORY</code></p>\n\n<pre><code>$ svnadmin load /var/svn/repository_root --parent-dir Project_A < file-dump-PRJA.dump\n…\n$ svnadmin load /var/svn/repository_root --parent-dir Project_B < file-dump-PRJB.dump\n</code></pre>\n\n<p>This way you'll have a repository which contains many dumped repositories.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267256",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
After considering the answers to my previous question ([One SVN Repository or many?](https://stackoverflow.com/questions/252459/one-svn-repository-or-many)), I've decided to take the 4 or so repositories I have and consolidate them into one. This of course leads to the question, **what's the best way to do this?**
Is there a way to combine two or more repositories maintaining the version history for both?
Edit: *I should also point out that I'm using Assembla.com, which does not provide access to the svnadmin command, AFAIK*
Another edit: *Does this even matter? If svnadmin works on URLs, then it's no problem then.*
|
Edit: Oh well, the question edit was made while I was typing. This is an answer to
>
> Is there a way to combine two or more
> repositories maintaining the version
> history for both?
>
>
>
---
Assuming that
The existing repositories have a structure like:
* repository root
+ branches
+ tags
+ trunk
and you want a structure something like:
* repository root
+ projectA
- branches
- tags
- trunk
+ projectB
- branches
- tags
- trunk
Then for each of your project repositories:
```
svnadmin dump > project<n>.dmp
```
Then for each of the dump files:
```
svn mkdir "<repo url>/project<n>"
svnadmin load --parent-dir "project<n>" <filesystem path to repos>
```
More complex manipulations are possible, but this is the simplest, most straightforward. Changing the source repository structure during a dump/load is hazardous, but doable through a combination of `svnadmin dump`, `svndumpfilter`, hand-editing or additional text filters and `svnadmin load`
---
**Dealing with a third party provider**
* Request `svnadmin dump` files for each of your repositories. The provider should be willing/able to provide this - it *is* **your** code!
* Create an SVN repository locally.
* Perform the actions listed above for the dump files.
* Verify the repository structure is correct with your favorite client.
* Create a dump file for the combined repositories.
* Request that the provider populate a new repository from this dump file.
YMMV: This seems to be a reasonable approach, but I've never worked with a third party provider like this.
|
267,259 |
<p>So, I've been doing Java for a number of years now, but now I'm starting a C++ project. I'm trying to determine best practices for setting up said project.</p>
<p>Within the project, how do you generally structure their code? Do you do it Java style with namespace folders and break up your source that way? Do you keep your public headers in an include directory for easy referencing?</p>
<p>I've seen both and other ways mentioned, but what's a good method for a large project?</p>
<p>Also, how do you deal with resources/folders in your application structure? It's all well and good for the final project to install with a <code>log</code> folder for storing logs, maybe a <code>lib</code> folder for library files, maybe a <code>data</code> folder for data, but how do you manage those bits within the project? Is there a way to define that so when you build the solution it constructs the structure for you? Or, do you simply have to go into your built configuration folders (Debug, Release, etc.), and construct the file structure manually, thus ensuring paths your EXE file is expecting to find are properly positioned?</p>
|
[
{
"answer_id": 267284,
"author": "Davide Gualano",
"author_id": 28582,
"author_profile": "https://Stackoverflow.com/users/28582",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, using <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svnadmin.c.dump.html\" rel=\"noreferrer\">svnadmin dump</a> and <a href=\"http://svnbook.red-bean.com/en/1.5/svn.ref.svnadmin.c.load.html\" rel=\"noreferrer\">svnadmin load</a>.</p>\n\n<p>Let's assume that you have to repositories, one with HEAD revision 100 and the other with HEAD revision 150.</p>\n\n<p>You dump the first repository and load it in the new one: you end up with the full story of the first repository, from revision 0 to revision 150.</p>\n\n<p>Then you dump the second repository and load it in the new one: it gets loaded with its full history, the only things that change are the actual revision numbers. The history of the second repository will be represented in the new repository from revision 151 to revision 250.</p>\n\n<p>The full history of both repositories is preserver, only the revision numbers change for the repository that is imported for second.</p>\n\n<p>The same of course applies for more than two repositories.</p>\n\n<p>EDIT: I posted while you were editing, so I didn't see your note...</p>\n"
},
{
"answer_id": 267307,
"author": "Ken Gentle",
"author_id": 8709,
"author_profile": "https://Stackoverflow.com/users/8709",
"pm_score": 7,
"selected": true,
"text": "<p>Edit: Oh well, the question edit was made while I was typing. This is an answer to</p>\n\n<blockquote>\n <p>Is there a way to combine two or more\n repositories maintaining the version\n history for both?</p>\n</blockquote>\n\n<hr>\n\n<p>Assuming that </p>\n\n<p>The existing repositories have a structure like:</p>\n\n<ul>\n<li>repository root\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n</ul>\n\n<p>and you want a structure something like:</p>\n\n<ul>\n<li>repository root\n\n<ul>\n<li>projectA\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n<li>projectB\n\n<ul>\n<li>branches</li>\n<li>tags</li>\n<li>trunk</li>\n</ul></li>\n</ul></li>\n</ul>\n\n<p>Then for each of your project repositories:</p>\n\n<pre><code>svnadmin dump > project<n>.dmp\n</code></pre>\n\n<p>Then for each of the dump files:</p>\n\n<pre><code>svn mkdir \"<repo url>/project<n>\"\nsvnadmin load --parent-dir \"project<n>\" <filesystem path to repos>\n</code></pre>\n\n<p>More complex manipulations are possible, but this is the simplest, most straightforward. Changing the source repository structure during a dump/load is hazardous, but doable through a combination of <code>svnadmin dump</code>, <code>svndumpfilter</code>, hand-editing or additional text filters and <code>svnadmin load</code></p>\n\n<hr>\n\n<p><strong>Dealing with a third party provider</strong></p>\n\n<ul>\n<li>Request <code>svnadmin dump</code> files for each of your repositories. The provider should be willing/able to provide this - it <em>is</em> <strong>your</strong> code!</li>\n<li>Create an SVN repository locally.</li>\n<li>Perform the actions listed above for the dump files.</li>\n<li>Verify the repository structure is correct with your favorite client.</li>\n<li>Create a dump file for the combined repositories.</li>\n<li>Request that the provider populate a new repository from this dump file.</li>\n</ul>\n\n<p>YMMV: This seems to be a reasonable approach, but I've never worked with a third party provider like this.</p>\n"
},
{
"answer_id": 267328,
"author": "Kibbee",
"author_id": 1862,
"author_profile": "https://Stackoverflow.com/users/1862",
"pm_score": 2,
"selected": false,
"text": "<p>If you don't have access to svnadmin, it would be hard but doable. Let's say you have repositories A and B, and want to merge them into repository C. Here's the steps you would have to use to accomplish this.</p>\n\n<ol>\n<li><p>Check out revision 1 of repository A to your hard disk. </p></li>\n<li><p>Create a directory, called Repository_A on the root of your C repository, and check this out to your local hard disk.</p></li>\n<li><p>Copy the files from your check out of A (minus) the .svn files, to your checkout of C, in the Repository_A folder. </p></li>\n<li><p>Perform a Commit on C. </p></li>\n</ol>\n\n<p>Update your working copy of repository A to revision 2 , and perform steps 3 and 4, and repeat with each successive revision until you reach the head.</p>\n\n<p>Now do the same with B. </p>\n\n<p>This would basically do the same as @Davide Gualano was suggesting, without requiring svnadmin. You could probably write a simple script to do this for your, of if there aren't a lot of revisions, you could just do it manually.</p>\n"
},
{
"answer_id": 8529409,
"author": "Scott Coldwell",
"author_id": 483403,
"author_profile": "https://Stackoverflow.com/users/483403",
"pm_score": 4,
"selected": false,
"text": "<p>With Subversion 1.7, you are now able to do dumps remotely. That is, without having access to the local file system and the <code>svnadmin dump</code> command.</p>\n\n<p>You can use <code>svnrdump</code> to get a complete dump of a remote repository. See the documentation for syntax details.</p>\n\n<p>Note that the server does not have to be running 1.7, only the client.</p>\n\n<p><a href=\"http://svnbook.red-bean.com/en/1.7/svn.ref.svnrdump.c.dump.html\">http://svnbook.red-bean.com/en/1.7/svn.ref.svnrdump.c.dump.html</a></p>\n"
},
{
"answer_id": 11254635,
"author": "sthysel",
"author_id": 203449,
"author_profile": "https://Stackoverflow.com/users/203449",
"pm_score": 1,
"selected": false,
"text": "<p>The other answers for this question enabled me to make the script below. Adapt the REPOS map for your case. Also, you may want to move the tags and branches into a \"preaggregate\" directory in stead of directly into the new branches and trunk.</p>\n\n<pre><code>#!/bin/bash\n\nNEWREPO=$(pwd)/newrepo\nNEWREPOCO=\"${NEWREPO}_co\"\nDUMPS=repodumps\nREV=\"0:HEAD\"\nREPOROOT=/data/svn/2.2.1/repositories/\nTOOLDIR=/opt/svn/2.2.1/bin/\nPATH=${PATH}:${TOOLDIR}\n\n# Old Repository mapping \ndeclare -A REPOS=( \n [BlaEntityBeans]='(\n [newname]=\"EntityBeans\"\n )'\n [OldServletRepoServlet]='(\n [newname]=\"SpreadsheetImportServlet\"\n )'\n [ExperimentalMappingXML]='(\n [newname]=\"SpreadsheetMappingXML\"\n )'\n [NewImportProcess]='(\n [newname]=\"SpreadsheetImportProcess\"\n )' \n)\n\ndump() {\n rm -fr ${DUMPS}\n mkdir ${DUMPS}\n for repo in \"${!REPOS[@]}\"\n do\n local dumpfile=${DUMPS}/${repo}.dmp\n echo \"Dumpimg Repo ${repo} to ${dumpfile}\"\n svnadmin dump -r ${REV} ${REPOROOT}/${repo} > ${dumpfile}\n done\n}\n\nloadRepos() {\n # new big repo\n rm -fr ${NEWREPO}\n svnadmin create ${NEWREPO}\n svn mkdir file:///${NEWREPO}/trunk -m \"\"\n svn mkdir file:///${NEWREPO}/branches -m \"\"\n svn mkdir file:///${NEWREPO}/tags -m \"\"\n\n # add the old projects as modules\n for currentname in \"${!REPOS[@]}\"\n do \n declare -A repo=${REPOS[$currentname]}\n local newname=${repo[newname]}\n echo \"Loading repo ${currentname} soon to be ${newname}\"\n dumpfile=${DUMPS}/${currentname}.dmp\n\n # import the current repo into a trmporary root position\n svn mkdir file:///${NEWREPO}/${currentname} -m \"Made module ${currentname}\"\n svnadmin load --parent-dir ${currentname} ${NEWREPO} < ${dumpfile}\n\n # now move stuff arround\n # first rename to new repo\n svn move file:///${NEWREPO}/${currentname} file:///${NEWREPO}/${newname} -m \"Moved ${currentname} to ${newname}\"\n # now move trunk, branches and tags\n for vc in {trunk,branches,tags}\n do\n echo \"Moving the current content of $vc into ${NEWREPO}/${vc}/${newname}\"\n svn move file:///${NEWREPO}/${newname}/${vc} file:///${NEWREPO}/${vc}/${newname} -m \"Done by $0\"\n done\n svn rm file:///${NEWREPO}/${newname} -m \"Removed old ${newname}\"\n done\n}\n\ndump\nloadRepos\n</code></pre>\n"
},
{
"answer_id": 14263244,
"author": "Hatim",
"author_id": 1860511,
"author_profile": "https://Stackoverflow.com/users/1860511",
"pm_score": 3,
"selected": false,
"text": "<p>You can load many dump files in one repository with the following steps. </p>\n\n<p>Repository root:</p>\n\n<pre><code> projectA\n branches \n tags\n trunk\n projectB\n branches\n tags\n trunk\n</code></pre>\n\n<p>First you must create the directory (project A, project B) in your repository root like this: </p>\n\n<pre><code>$ svn mkdir -m \"Initial project root\" \\\nfile:///var/svn/repository_root/Project_A\\\nfile:///var/svn/repository_root/Project_B\\\nfile:///var/svn/repository_root/Project_C\\\n\nRevision 1 committed.\n</code></pre>\n\n<p>And after that you can load your dump files:</p>\n\n<p>Use the parameter <code>--parent-dir DIRECTORY</code></p>\n\n<pre><code>$ svnadmin load /var/svn/repository_root --parent-dir Project_A < file-dump-PRJA.dump\n…\n$ svnadmin load /var/svn/repository_root --parent-dir Project_B < file-dump-PRJB.dump\n</code></pre>\n\n<p>This way you'll have a repository which contains many dumped repositories.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267259",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9450/"
] |
So, I've been doing Java for a number of years now, but now I'm starting a C++ project. I'm trying to determine best practices for setting up said project.
Within the project, how do you generally structure their code? Do you do it Java style with namespace folders and break up your source that way? Do you keep your public headers in an include directory for easy referencing?
I've seen both and other ways mentioned, but what's a good method for a large project?
Also, how do you deal with resources/folders in your application structure? It's all well and good for the final project to install with a `log` folder for storing logs, maybe a `lib` folder for library files, maybe a `data` folder for data, but how do you manage those bits within the project? Is there a way to define that so when you build the solution it constructs the structure for you? Or, do you simply have to go into your built configuration folders (Debug, Release, etc.), and construct the file structure manually, thus ensuring paths your EXE file is expecting to find are properly positioned?
|
Edit: Oh well, the question edit was made while I was typing. This is an answer to
>
> Is there a way to combine two or more
> repositories maintaining the version
> history for both?
>
>
>
---
Assuming that
The existing repositories have a structure like:
* repository root
+ branches
+ tags
+ trunk
and you want a structure something like:
* repository root
+ projectA
- branches
- tags
- trunk
+ projectB
- branches
- tags
- trunk
Then for each of your project repositories:
```
svnadmin dump > project<n>.dmp
```
Then for each of the dump files:
```
svn mkdir "<repo url>/project<n>"
svnadmin load --parent-dir "project<n>" <filesystem path to repos>
```
More complex manipulations are possible, but this is the simplest, most straightforward. Changing the source repository structure during a dump/load is hazardous, but doable through a combination of `svnadmin dump`, `svndumpfilter`, hand-editing or additional text filters and `svnadmin load`
---
**Dealing with a third party provider**
* Request `svnadmin dump` files for each of your repositories. The provider should be willing/able to provide this - it *is* **your** code!
* Create an SVN repository locally.
* Perform the actions listed above for the dump files.
* Verify the repository structure is correct with your favorite client.
* Create a dump file for the combined repositories.
* Request that the provider populate a new repository from this dump file.
YMMV: This seems to be a reasonable approach, but I've never worked with a third party provider like this.
|
267,275 |
<p>Despite an earlier question (<a href="https://stackoverflow.com/questions/223894/opengl-rotation-using-gldrawpixels">asked here</a>), our project is constrained to using glDrawPixels, so we have to do some hackery.</p>
<p>One of the feature requirements is to be able to have a magnified view show up on a clicked region of an image; so, looking at an image, I want to click the mouse, and have a 200% image window show up where the mouse is. As I drag my cursor, the window should follow the cursor.</p>
<p>The context is set up like:</p>
<p>The Big Red Book has code that looks like this:</p>
<pre><code> Gl.glShadeModel(Gl.GL_FLAT);
Gl.glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
Gl.glPixelStorei(Gl.GL_UNPACK_ALIGNMENT, 2);
Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE);
Gl.glDisable(Gl.GL_SCISSOR_TEST);
Gl.glDisable(Gl.GL_ALPHA_TEST);
Gl.glDisable(Gl.GL_STENCIL_TEST);
Gl.glDisable(Gl.GL_DEPTH_TEST);
Gl.glDisable(Gl.GL_BLEND);
Gl.glDisable(Gl.GL_DITHER);
Gl.glDisable(Gl.GL_LOGIC_OP);
Gl.glDisable(Gl.GL_LIGHTING);
Gl.glDisable(Gl.GL_FOG);
Gl.glDisable(Gl.GL_TEXTURE_1D);
Gl.glDisable(Gl.GL_TEXTURE_2D);
Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_TRUE);
Gl.glPixelTransferf(Gl.GL_RED_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_RED_BIAS, 0);
Gl.glPixelTransferf(Gl.GL_GREEN_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_GREEN_BIAS, 0);
Gl.glPixelTransferf(Gl.GL_BLUE_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_BLUE_BIAS, 0);
Gl.glPixelTransferi(Gl.GL_ALPHA_SCALE, 1);
Gl.glPixelTransferi(Gl.GL_ALPHA_BIAS, 0);
</code></pre>
<p>And then the call to make the smaller-but-zoomed image looks like</p>
<pre><code> int width = (int)((this.Width * 0.2)/2.0);
Gl.glReadBuffer(Gl.GL_FRONT_AND_BACK);
Gl.glRasterPos2i(0, 0);
Gl.glBitmap(0, 0, 0, 0, mStartX - (width*2), mStartY, null);
Gl.glPixelZoom(2.0f, 2.0f);
Gl.glCopyPixels(mStartX - width, mStartY, width, width, Gl.GL_COLOR);
</code></pre>
<p>where mStartY and mStartX are the points where the click happened.</p>
<p>Problem is, the window that shows up is really mangling the lookup tables, and really clamping the image down to essentially a black-and-white binary image (ie, no shades of grey). </p>
<p>The data is a black-and-white unsigned short array, and is set with this code:</p>
<pre><code> float step = (65535.0f / (float)(max - min));
mColorTable = new ushort[65536];
int i;
for (i = 0; i < 65536; i++)
{
if (i < min)
mColorTable[i] = 0;
else if (i > max)
mColorTable[i] = 65535;
else
mColorTable[i] = (ushort)((float)(i - min) * step);
}
.... //some irrelevant code
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_R_TO_R, 65536, mColorTable);
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_G_TO_G, 65536, mColorTable);
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_B_TO_B, 65536, mColorTable);
</code></pre>
<p>Now, according to <a href="http://www.ugrad.cs.ubc.ca/~cs414/opengl/glCopyPixels.html" rel="nofollow noreferrer">this documentation</a>, I should use GL_PIXEL_MAP_I_TO_I and set INDEX_SCALE and INDEX_BIAS to zero, but doing that does not change the result, that the image is severely clamped. And by 'severely clamped' I mean it's either black or white, with very few shades of grey, but the original non-magnified image looks like what's expected.</p>
<p>So, how do I avoid the clamping of the magnified view? Should I make a second control that follows the cursor and gets filled in with data from the first control? That approach seems like it would take the array copies outside of the graphics card and into C#, which would almost by definition be slower, and so make the control nonresponsive. </p>
<p>Oh, I'm using C# and the Tao framework, if that matters.</p>
|
[
{
"answer_id": 267867,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 0,
"selected": false,
"text": "<p>Please, pretty please with loads of sugar, molasses, sprinkles and a mist of high-fructose corn syrup on top and all over, explain <i>why</i> you cannot just use <b>texture-mapping</b> to draw this imagery.</p>\n\n<p>Texture-mapping is a core, basic, everyday, run of the mill, garden-variety, standard, typical, expected, and just generally nice feature of OpenGL. It is in version 1.4. Why not use it as a starting point?</p>\n"
},
{
"answer_id": 273878,
"author": "thing2k",
"author_id": 3180,
"author_profile": "https://Stackoverflow.com/users/3180",
"pm_score": 0,
"selected": false,
"text": "<p>If I understand you correctly then this should be close to what you after, using glReadPixels and glDrawPixels.</p>\n\n<p><a href=\"http://img392.imageshack.us/img392/8540/zoomla1.jpg\" rel=\"nofollow noreferrer\"></a></p>\n\n<p>Sorry it's C++ not C# but the OpenGL function should still be the same.</p>\n\n<pre><code>// main.cpp\n// glut Text\n\n#ifdef __WIN32__\n #define WIN32_LEAN_AND_MEAN\n #include <windows.h>\n#endif\n#include <GL/glut.h>\n#include <cstdio>\n\nint WIDTH = 800;\nint HEIGHT = 600;\nint MouseButton, MouseY = 0, MouseX = 0;\nconst int size = 80;\nchar *image, rect[size*size*3];\nint imagewidth, imageheight;\n\nbool Init()\n{\n int offset;\n FILE* file = fopen(\"image.bmp\", \"rb\");\n if (file == NULL)\n return false;\n fseek(file, 10, SEEK_SET);\n fread(&offset, sizeof(int), 1, file);\n fseek(file, 18, SEEK_SET);\n fread(&imagewidth, sizeof(int), 1, file);\n fread(&imageheight, sizeof(int), 1, file);\n fseek(file, offset, SEEK_SET);\n image = new char[imagewidth*imageheight*3];\n if (image == NULL)\n return false;\n fread(image, 1, imagewidth*imageheight*3, file);\n fclose(file);\n return true;\n}\n\nvoid Reshape(int width, int height)\n{\n WIDTH = width;\n HEIGHT = height;\n glViewport(0 , 0, width, height);\n glMatrixMode(GL_PROJECTION);\n glLoadIdentity();\n gluOrtho2D(0, width, 0, height);\n}\n\nvoid Display()\n{\n int size2 = size/2;\n\n glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);\n glMatrixMode(GL_MODELVIEW);\n glLoadIdentity();\n glRasterPos2i(0,0);\n glPixelZoom(1.f, 1.f);\n glDrawPixels(imagewidth, imageheight, 0x80E0/*GL_RGB*/, GL_UNSIGNED_BYTE, image);\n glReadPixels(MouseX-size2, MouseY-size2, size, size, GL_RGB, GL_UNSIGNED_BYTE, rect);\n glPixelZoom(2.f, 2.f);\n glRasterPos2i(MouseX-size, MouseY-size);\n glDrawPixels(size, size, GL_RGB, GL_UNSIGNED_BYTE, rect);\n glFlush();\n glutSwapBuffers();\n}\n\nvoid Mouse(int button, int state, int x, int y)\n{\n if (state == GLUT_DOWN)\n MouseButton &= (1<<button);\n else\n MouseButton &= ~(1<<button);\n}\n\nvoid MouseMove(int x, int y)\n{\n MouseX = x;\n MouseY = HEIGHT - y;\n}\n\nint main(int argc, char* argv[])\n{\n glutInit(&argc, argv);\n if (Init() == false)\n return 1;\n glutInitWindowSize(WIDTH, HEIGHT);\n glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA);\n glutCreateWindow(\"glut_Text\");\n glClearColor(0.25, 0.25, 0.25, 1.0);\n glutReshapeFunc(Reshape);\n glutDisplayFunc(Display);\n glutIdleFunc(Display);\n glutMouseFunc(Mouse);\n glutMotionFunc(MouseMove);\n glutPassiveMotionFunc(MouseMove);\n\n glutMainLoop();\n return 0;\n}\n</code></pre>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 290468,
"author": "mmr",
"author_id": 21981,
"author_profile": "https://Stackoverflow.com/users/21981",
"pm_score": 3,
"selected": true,
"text": "<p>Here's the answer. The problem is that the LUT is being applied twice, so before calling the copy, call:</p>\n\n<pre><code>Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_FALSE);\n</code></pre>\n\n<p>Then, once done, call:</p>\n\n<pre><code>Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_TRUE);\n</code></pre>\n\n<p>That way, the 'extreme clamping' I was describing is removed.</p>\n\n<p>@thing2k-- your solution causes the copy to happen outside the graphics card, so slows down the drawing on mouse drag, but doesn't fix the double clamp.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267275",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21981/"
] |
Despite an earlier question ([asked here](https://stackoverflow.com/questions/223894/opengl-rotation-using-gldrawpixels)), our project is constrained to using glDrawPixels, so we have to do some hackery.
One of the feature requirements is to be able to have a magnified view show up on a clicked region of an image; so, looking at an image, I want to click the mouse, and have a 200% image window show up where the mouse is. As I drag my cursor, the window should follow the cursor.
The context is set up like:
The Big Red Book has code that looks like this:
```
Gl.glShadeModel(Gl.GL_FLAT);
Gl.glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
Gl.glPixelStorei(Gl.GL_UNPACK_ALIGNMENT, 2);
Gl.glPolygonMode(Gl.GL_FRONT_AND_BACK, Gl.GL_LINE);
Gl.glDisable(Gl.GL_SCISSOR_TEST);
Gl.glDisable(Gl.GL_ALPHA_TEST);
Gl.glDisable(Gl.GL_STENCIL_TEST);
Gl.glDisable(Gl.GL_DEPTH_TEST);
Gl.glDisable(Gl.GL_BLEND);
Gl.glDisable(Gl.GL_DITHER);
Gl.glDisable(Gl.GL_LOGIC_OP);
Gl.glDisable(Gl.GL_LIGHTING);
Gl.glDisable(Gl.GL_FOG);
Gl.glDisable(Gl.GL_TEXTURE_1D);
Gl.glDisable(Gl.GL_TEXTURE_2D);
Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_TRUE);
Gl.glPixelTransferf(Gl.GL_RED_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_RED_BIAS, 0);
Gl.glPixelTransferf(Gl.GL_GREEN_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_GREEN_BIAS, 0);
Gl.glPixelTransferf(Gl.GL_BLUE_SCALE, 1.0f);
Gl.glPixelTransferi(Gl.GL_BLUE_BIAS, 0);
Gl.glPixelTransferi(Gl.GL_ALPHA_SCALE, 1);
Gl.glPixelTransferi(Gl.GL_ALPHA_BIAS, 0);
```
And then the call to make the smaller-but-zoomed image looks like
```
int width = (int)((this.Width * 0.2)/2.0);
Gl.glReadBuffer(Gl.GL_FRONT_AND_BACK);
Gl.glRasterPos2i(0, 0);
Gl.glBitmap(0, 0, 0, 0, mStartX - (width*2), mStartY, null);
Gl.glPixelZoom(2.0f, 2.0f);
Gl.glCopyPixels(mStartX - width, mStartY, width, width, Gl.GL_COLOR);
```
where mStartY and mStartX are the points where the click happened.
Problem is, the window that shows up is really mangling the lookup tables, and really clamping the image down to essentially a black-and-white binary image (ie, no shades of grey).
The data is a black-and-white unsigned short array, and is set with this code:
```
float step = (65535.0f / (float)(max - min));
mColorTable = new ushort[65536];
int i;
for (i = 0; i < 65536; i++)
{
if (i < min)
mColorTable[i] = 0;
else if (i > max)
mColorTable[i] = 65535;
else
mColorTable[i] = (ushort)((float)(i - min) * step);
}
.... //some irrelevant code
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_R_TO_R, 65536, mColorTable);
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_G_TO_G, 65536, mColorTable);
Gl.glPixelMapusv(Gl.GL_PIXEL_MAP_B_TO_B, 65536, mColorTable);
```
Now, according to [this documentation](http://www.ugrad.cs.ubc.ca/~cs414/opengl/glCopyPixels.html), I should use GL\_PIXEL\_MAP\_I\_TO\_I and set INDEX\_SCALE and INDEX\_BIAS to zero, but doing that does not change the result, that the image is severely clamped. And by 'severely clamped' I mean it's either black or white, with very few shades of grey, but the original non-magnified image looks like what's expected.
So, how do I avoid the clamping of the magnified view? Should I make a second control that follows the cursor and gets filled in with data from the first control? That approach seems like it would take the array copies outside of the graphics card and into C#, which would almost by definition be slower, and so make the control nonresponsive.
Oh, I'm using C# and the Tao framework, if that matters.
|
Here's the answer. The problem is that the LUT is being applied twice, so before calling the copy, call:
```
Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_FALSE);
```
Then, once done, call:
```
Gl.glPixelTransferi(Gl.GL_MAP_COLOR, Gl.GL_TRUE);
```
That way, the 'extreme clamping' I was describing is removed.
@thing2k-- your solution causes the copy to happen outside the graphics card, so slows down the drawing on mouse drag, but doesn't fix the double clamp.
|
267,287 |
<p>Attempting to print out a list of values from 2 different variables that are aligned correctly.</p>
<pre><code>foreach finalList ($correctList $wrongList)
printf "%20s%s\n" $finalList
end
</code></pre>
<p>This prints them out an they are aligned, but it's one after another. How would I have it go through each item in each list and THEN go to a new line? </p>
<p>I want them to eventually appear like this:</p>
<pre><code>Correct Incorrect
Good1 Bad1
Good2 Bad2
Good3 Bad3
</code></pre>
<p>Good comes from correctList
Bad comes from wrongList</p>
<p>Getting rid of \n makes it Like this:</p>
<pre><code>Good1 Bad1 Good2 Bad2
</code></pre>
<p>I just want 2 columns.</p>
|
[
{
"answer_id": 267313,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": 0,
"selected": false,
"text": "<p>try getting rid of the \\n</p>\n"
},
{
"answer_id": 267340,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "<p>You can iterate over both lists at the same time like this:</p>\n\n<pre><code># Get the max index of the smallest list\nset maxIndex = $#correctList\nif ( $#wrongList < $#correctList ) then\n set maxIndex = $#wrongList\nendif\n\nset index = 1\nwhile ($index <= $maxIndex)\n printf \"%-20s %s\\n\" \"$correctList[$index]\" \"$wrongList[$index]\"\n @ index++\nend\n</code></pre>\n"
},
{
"answer_id": 269571,
"author": "mpez0",
"author_id": 27898,
"author_profile": "https://Stackoverflow.com/users/27898",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the pr(1) command with the -m option will help do what you want. Look at its man page to eliminate the header/trailer options and set the column widths.</p>\n\n<p>Also, I recommend you not use the C-Shell for scripting; you'll find the sh-syntax shells (sh, bash, ksh, etc) are more consistent and much easier to debug.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28392/"
] |
Attempting to print out a list of values from 2 different variables that are aligned correctly.
```
foreach finalList ($correctList $wrongList)
printf "%20s%s\n" $finalList
end
```
This prints them out an they are aligned, but it's one after another. How would I have it go through each item in each list and THEN go to a new line?
I want them to eventually appear like this:
```
Correct Incorrect
Good1 Bad1
Good2 Bad2
Good3 Bad3
```
Good comes from correctList
Bad comes from wrongList
Getting rid of \n makes it Like this:
```
Good1 Bad1 Good2 Bad2
```
I just want 2 columns.
|
You can iterate over both lists at the same time like this:
```
# Get the max index of the smallest list
set maxIndex = $#correctList
if ( $#wrongList < $#correctList ) then
set maxIndex = $#wrongList
endif
set index = 1
while ($index <= $maxIndex)
printf "%-20s %s\n" "$correctList[$index]" "$wrongList[$index]"
@ index++
end
```
|
267,303 |
<p>I'm am building my asp.net web application using MVC (Preview 5),
and am also using the Master pages concept. </p>
<p>My PageA and PageB are both content pages. I'm doing a form submit
in a method via JavaScript from PageA to PageB.
PageB has its PreviousPageType attribute set to PageA, but when I access the
PreviousPage property in PageB, it returns null.</p>
<p>Am I missing out on something here?</p>
|
[
{
"answer_id": 267313,
"author": "Ray Tayek",
"author_id": 51292,
"author_profile": "https://Stackoverflow.com/users/51292",
"pm_score": 0,
"selected": false,
"text": "<p>try getting rid of the \\n</p>\n"
},
{
"answer_id": 267340,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 4,
"selected": true,
"text": "<p>You can iterate over both lists at the same time like this:</p>\n\n<pre><code># Get the max index of the smallest list\nset maxIndex = $#correctList\nif ( $#wrongList < $#correctList ) then\n set maxIndex = $#wrongList\nendif\n\nset index = 1\nwhile ($index <= $maxIndex)\n printf \"%-20s %s\\n\" \"$correctList[$index]\" \"$wrongList[$index]\"\n @ index++\nend\n</code></pre>\n"
},
{
"answer_id": 269571,
"author": "mpez0",
"author_id": 27898,
"author_profile": "https://Stackoverflow.com/users/27898",
"pm_score": 0,
"selected": false,
"text": "<p>I believe the pr(1) command with the -m option will help do what you want. Look at its man page to eliminate the header/trailer options and set the column widths.</p>\n\n<p>Also, I recommend you not use the C-Shell for scripting; you'll find the sh-syntax shells (sh, bash, ksh, etc) are more consistent and much easier to debug.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31622/"
] |
I'm am building my asp.net web application using MVC (Preview 5),
and am also using the Master pages concept.
My PageA and PageB are both content pages. I'm doing a form submit
in a method via JavaScript from PageA to PageB.
PageB has its PreviousPageType attribute set to PageA, but when I access the
PreviousPage property in PageB, it returns null.
Am I missing out on something here?
|
You can iterate over both lists at the same time like this:
```
# Get the max index of the smallest list
set maxIndex = $#correctList
if ( $#wrongList < $#correctList ) then
set maxIndex = $#wrongList
endif
set index = 1
while ($index <= $maxIndex)
printf "%-20s %s\n" "$correctList[$index]" "$wrongList[$index]"
@ index++
end
```
|
267,318 |
<p>I'm trying to create an OS X Service. I found <a href="http://developer.apple.com/documentation/Cocoa/Conceptual/SysServices/Tasks/providing.html#//apple_ref/doc/uid/20000853" rel="nofollow noreferrer">Providing System Services</a> in Apple's documentation, however I'm finding it less than clear on what exactly I need to do. I'm currently using an application to register my service (thinking that would be more straight forward - eventually I'd like to create a .service), however even after a logout/login my service still doesn't appear in the list of services in the menu.</p>
<p>Is there some step missing from the linked document that I'm missing? I feel like there is some registration step so that the OS knows about my service (in addition to what is listed in that doc), but I'm not able to find anything.</p>
<p>Thanks in advance. :)</p>
<p>Edit: Here is my NSServices dictionary from my Info.plist file:</p>
<pre><code> <key>NSServices</key>
<array>
<dict>
<key>NSPortName</key>
<string>POPrlTest</string>
<key>NSMessage</key>
<string>shortenUrlService</string>
<key>NSSendTypes</key>
<string>NSStringPboardType</string>
<key>NSReturnTypes</key>
<string>NSStringPboardType</string>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Shorten URL</string>
</dict>
</dict>
</array>
</code></pre>
|
[
{
"answer_id": 267363,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>You might want to look at some commercial products to help you with this. See this posting on <a href=\"http://pmougin.wordpress.com/2008/01/28/become-a-mac-os-x-services-ninja/\" rel=\"nofollow noreferrer\">Fun Script</a>.</p>\n"
},
{
"answer_id": 267715,
"author": "Peter Hosey",
"author_id": 30461,
"author_profile": "https://Stackoverflow.com/users/30461",
"pm_score": 2,
"selected": false,
"text": "<p>Make sure your NSServices dictionary has everything it needs. If you're not sure, please post it so we can tell you.</p>\n"
},
{
"answer_id": 279109,
"author": "mgorbach",
"author_id": 36331,
"author_profile": "https://Stackoverflow.com/users/36331",
"pm_score": 2,
"selected": true,
"text": "<p>Make sure you are launching your app first to get the system to see the Service.\nMake sure you are registering the services handler in your app using\n- setServicesProvider:</p>\n\n<p>Also, check the Console log as that might give you some useful error info.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3857/"
] |
I'm trying to create an OS X Service. I found [Providing System Services](http://developer.apple.com/documentation/Cocoa/Conceptual/SysServices/Tasks/providing.html#//apple_ref/doc/uid/20000853) in Apple's documentation, however I'm finding it less than clear on what exactly I need to do. I'm currently using an application to register my service (thinking that would be more straight forward - eventually I'd like to create a .service), however even after a logout/login my service still doesn't appear in the list of services in the menu.
Is there some step missing from the linked document that I'm missing? I feel like there is some registration step so that the OS knows about my service (in addition to what is listed in that doc), but I'm not able to find anything.
Thanks in advance. :)
Edit: Here is my NSServices dictionary from my Info.plist file:
```
<key>NSServices</key>
<array>
<dict>
<key>NSPortName</key>
<string>POPrlTest</string>
<key>NSMessage</key>
<string>shortenUrlService</string>
<key>NSSendTypes</key>
<string>NSStringPboardType</string>
<key>NSReturnTypes</key>
<string>NSStringPboardType</string>
<key>NSMenuItem</key>
<dict>
<key>default</key>
<string>Shorten URL</string>
</dict>
</dict>
</array>
```
|
Make sure you are launching your app first to get the system to see the Service.
Make sure you are registering the services handler in your app using
- setServicesProvider:
Also, check the Console log as that might give you some useful error info.
|
267,351 |
<p>The Dragon Book includes an exercise on converting integers to roman numerals using a syntax-directed translation scheme.</p>
<p>How can this be completed?</p>
|
[
{
"answer_id": 267587,
"author": "Oddthinking",
"author_id": 8014,
"author_profile": "https://Stackoverflow.com/users/8014",
"pm_score": 3,
"selected": true,
"text": "<p>I would consider parsing from right-to-left.</p>\n\n<p>First, I would map the units column:</p>\n\n<pre><code>0 -> ''\n1 -> 'I'\n2 -> 'II'\n3 -> 'III'\n4 -> 'IV'\n...\n9 -> 'IX'\n</code></pre>\n\n<p>Then, if there was a second column (e.g. second from the right = tens column), I would use that to map to </p>\n\n<pre><code>0 -> ''\n1 -> 'X'\n2 -> 'XX'\n...\n9 -> 'XC'\n</code></pre>\n\n<p>That would need to be prepended to the initial output.</p>\n\n<p>Repeat for next columns (hundreds, thousands) until you run out of letters.</p>\n\n<p>Double-check the number isn't '0' or negative.</p>\n"
},
{
"answer_id": 275699,
"author": "Lukman",
"author_id": 34586,
"author_profile": "https://Stackoverflow.com/users/34586",
"pm_score": 2,
"selected": false,
"text": "<p>Another way is to store in two-dimensional array the roman numerals for 1, 5, 10, 50, 100, 500, 1000 and so on. Example (in PHP array):</p>\n\n<pre><code>$roman = array(\n [0] = array( 1=>\"I\", 5=>\"V\", 10=>\"X\" ),\n [1] = array( 1=>\"X\", 5=>\"L\", 10=>\"C\" ),\n [2] = array( 1=>\"C\", 5=>\"D\", 10=>\"M\" ),\n [3] = array( 1=>\"M\", 5=>\"^V\", 10=>\"^X\" ),\n);\n</code></pre>\n\n<p>Then take each digit from right-to-left and apply the following translation. Set a variable $level = 0 and increase its value by 1 after every digit processed:</p>\n\n<pre><code>1 => $roman[$level][1]\n2 => $roman[$level][1].$roman[$level][1]\n3 => $roman[$level][1].$roman[$level][1].$roman[$level][1]\n4 => $roman[$level][1].$roman[$level][5]\n5 => $roman[$level][5]\n6 => $roman[$level][5].$roman[$level][1]\n7 => $roman[$level][5].$roman[$level][1].$roman[$level][1]\n8 => $roman[$level][5].$roman[$level][1].$roman[$level][1].$roman[$level][1]\n9 => $roman[$level][1].$roman[$level][10]\n</code></pre>\n\n<p>(in PHP a '.' concats two strings)</p>\n\n<p>Example: 1945</p>\n\n<pre><code>5 => $roman[0][5] = \"V\"\n4 => $roman[1][1].$roman[1][5] = \"XL\"\n9 => $roman[2][1].$roman[2][10] = \"CM\"\n1 => $roman[3][1] = \"M\"\n</code></pre>\n\n<p>So the translated number is \"MCMXLV\"</p>\n\n<p>Sorry this might not fully answer your question but I hope it helps in any way ..</p>\n"
},
{
"answer_id": 7860665,
"author": "Yola",
"author_id": 312896,
"author_profile": "https://Stackoverflow.com/users/312896",
"pm_score": 2,
"selected": false,
"text": "<p>Next is grammar to represent syntax directed translation from number in format 1xxx into roman numerals.</p>\n\n<p><em>number = OneThousand digit3 digit2 digit1 | nzdigit3 digit2 digit1 | nzdigit2 digit1 | nzdigit1</em></p>\n\n<blockquote>\n <p>OneThousand -> 1 {print('M')}</p>\n \n <p>digit3 -> 0 digit3 -> nzdigit3</p>\n \n <p>nzdigit3 -> 1 print('C') nzdigit3 -> 2 print('CC') nzdigit3 -> 3\n print('CCC') nzdigit3 -> 4 print('CCCC') nzdigit3 -> 5 print('D')\n nzdigit3 -> 6 print('DC') nzdigit3 -> 7 print('DCC') nzdigit3 -> 8\n print('DCCC') nzdigit3 -> 9 print('DCCCc')</p>\n</blockquote>\n\n<p>In similar manner write definition for digits in 2 and 1 position and you will have needed translation.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
The Dragon Book includes an exercise on converting integers to roman numerals using a syntax-directed translation scheme.
How can this be completed?
|
I would consider parsing from right-to-left.
First, I would map the units column:
```
0 -> ''
1 -> 'I'
2 -> 'II'
3 -> 'III'
4 -> 'IV'
...
9 -> 'IX'
```
Then, if there was a second column (e.g. second from the right = tens column), I would use that to map to
```
0 -> ''
1 -> 'X'
2 -> 'XX'
...
9 -> 'XC'
```
That would need to be prepended to the initial output.
Repeat for next columns (hundreds, thousands) until you run out of letters.
Double-check the number isn't '0' or negative.
|
267,367 |
<p>For example:</p>
<p>Base class header file has:</p>
<pre><code>enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
</code></pre>
<p>Then the derived class has:</p>
<pre><code>enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
</code></pre>
<p>Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.</p>
<pre><code>class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
</code></pre>
|
[
{
"answer_id": 267390,
"author": "Mark Kegel",
"author_id": 14788,
"author_profile": "https://Stackoverflow.com/users/14788",
"pm_score": 2,
"selected": false,
"text": "<p>Yes, as long as the enum's are both members of a class. If they weren't then they would be of the same type and the compiler would be very unhappy.</p>\n"
},
{
"answer_id": 268262,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 3,
"selected": true,
"text": "<p>No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.</p>\n\n<p>So if the base class header has</p>\n\n<pre><code>enum Foo {\n A,\n B,\n MAX = 1<<15\n};\n</code></pre>\n\n<p>a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.</p>\n"
},
{
"answer_id": 269967,
"author": "Marcin",
"author_id": 22724,
"author_profile": "https://Stackoverflow.com/users/22724",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, this works. To simplify your code a bit, I would suggest this, more common method of \"extending\" enums:</p>\n\n<pre><code>enum FOO // Base class's FOO\n{\nFOO_A,\nFOO_B,\nFOO_C,\nFOO_BASE_MAX // Always keep this as the last value in the base class\n};\n\nenum FOO // Derived class's FOO\n{\nFOO_USERA=FOO_BASE_MAX+1, // Always keep this as the first value in the derived class\nFOO_USERB,\nFOO_USERC\n};</code></pre>\n\n<p>You still need to watch out for \"out of order\" enums. (Example: FOO_A=15, FOO_B=11, etc.)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13676/"
] |
For example:
Base class header file has:
```
enum FOO
{
FOO_A,
FOO_B,
FOO_C,
FOO_USERSTART
};
```
Then the derived class has:
```
enum FOO
{
FOO_USERA=FOO_USERSTART
FOO_USERB,
FOO_USERC
};
```
Just to be clear on my usage it is for having an event handler where the base class has events and then derived classes can add events. The derived classes event handler would check for it's events and if the event was not for it, then it would pass the event down to the base class.
```
class Base
{
public:
virtual void HandleFoo(FOO event);
};
class Derived: public Base
{
public:
void HandleFoo(FOO event);
};
void Base::HandleFoo(FOO event)
{
switch(event)
{
case FOO_A:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
case FOO_B:
/* do stuff */
break;
}
}
void Derived::HandleFoo(FOO event)
{
switch(event)
{
case FOO_USERA:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
case FOO_USERB:
/* do stuff */
break;
default:
/* not my event, must be for someone else */
Base::HandleFoo(event);
break;
}
}
```
|
No. The compiler needs to be able to decide whether the enum fits in a char, short, int or long once it sees the }.
So if the base class header has
```
enum Foo {
A,
B,
MAX = 1<<15
};
```
a compiler may decide the enum fits in 16 bits. It can then use that, e.g. when laying out the base class. If you were later able to add 1<<31 to the enum, the base class enum member would not be able to hold one of the enum values.
|
267,369 |
<p>When beginning a new web project, i'm always a bit worried about removing pieces of the web.config. It seems there are more entries than ever with Net 3.5 SP1.</p>
<p>Which bits of the .config do you delete for the following scenarios:</p>
<ul>
<li>WCF Web Service, no Javascript support</li>
<li>Simple MVC Website</li>
</ul>
<p>EDIT
Can someone document a basic list of things left in and taken out of the web.config for a simple website?</p>
|
[
{
"answer_id": 267380,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<p>I usually just delete items from the web.config until things break -- a process of trial and error.</p>\n\n<p>It's astonishing how much of web.config you can remove without affecting anything. It's gotten quite crufty in .NET 3.5.</p>\n"
},
{
"answer_id": 267565,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 1,
"selected": false,
"text": "<p>Largely agree with Jeff that it is a process of trial and error as to what you can remove from the file. </p>\n\n<p>In terms of tweaking the runtime and the http pipeline, it can often be a process of adding things to the web.config, in order to turn things off.</p>\n\n<p>The out of the box configuration adds a lot of modules to the pipeline, depending on what you are doing, you may not need half of them.</p>\n\n<p>Have come across a few articles on this on MSDN, and also this one <a href=\"http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/aspnet/10ASPNetPerformance.aspx</a>, by Omar from PageFlakes, which was the only one I could find in my (poorly organised) bookmarks, which is a good starting point on optimising the runtime.</p>\n"
},
{
"answer_id": 506074,
"author": "Andrew Harry",
"author_id": 30576,
"author_profile": "https://Stackoverflow.com/users/30576",
"pm_score": 1,
"selected": true,
"text": "<p>Here is a stripped down Web.config i use for a simple WCF service</p>\n\n<pre><code><?xml version=\"1.0\"?>\n<configuration>\n <system.web>\n <compilation debug=\"true\">\n <assemblies>\n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n </assemblies>\n </compilation>\n <authentication mode=\"Windows\" />\n <customErrors mode=\"RemoteOnly\" defaultRedirect=\"error.htm\">\n <error statusCode=\"403\" redirect=\"NoAccess.htm\" />\n <error statusCode=\"404\" redirect=\"FileNotFound.htm\" />\n </customErrors>\n </system.web>\n <system.codedom>\n <compilers>\n <compiler language=\"c#;cs;csharp\" extension=\".cs\" warningLevel=\"4\"\n type=\"Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\">\n <providerOption name=\"CompilerVersion\" value=\"v3.5\"/>\n <providerOption name=\"WarnAsError\" value=\"false\"/>\n </compiler>\n </compilers>\n </system.codedom>\n <system.serviceModel>\n <services>\n <service behaviorConfiguration=\"Service.ServiceBehavior\" name=\"Service.Service\">\n <endpoint address=\"\" binding=\"basicHttpBinding\" contract=\"Service.IService\">\n <identity>\n <dns value=\"localhost\" />\n </identity>\n </endpoint>\n <endpoint address=\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"Service.ServiceBehavior\">\n <serviceMetadata httpGetEnabled=\"true\"/>\n <serviceDebug includeExceptionDetailInFaults=\"false\"/>\n </behavior>\n </serviceBehaviors>\n </behaviors>\n </system.serviceModel>\n</configuration>\n</code></pre>\n\n<p>I removed a lot of extras especially the script modules which i won't require</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267369",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30576/"
] |
When beginning a new web project, i'm always a bit worried about removing pieces of the web.config. It seems there are more entries than ever with Net 3.5 SP1.
Which bits of the .config do you delete for the following scenarios:
* WCF Web Service, no Javascript support
* Simple MVC Website
EDIT
Can someone document a basic list of things left in and taken out of the web.config for a simple website?
|
Here is a stripped down Web.config i use for a simple WCF service
```
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<authentication mode="Windows" />
<customErrors mode="RemoteOnly" defaultRedirect="error.htm">
<error statusCode="403" redirect="NoAccess.htm" />
<error statusCode="404" redirect="FileNotFound.htm" />
</customErrors>
</system.web>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" warningLevel="4"
type="Microsoft.CSharp.CSharpCodeProvider, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<providerOption name="CompilerVersion" value="v3.5"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
<system.serviceModel>
<services>
<service behaviorConfiguration="Service.ServiceBehavior" name="Service.Service">
<endpoint address="" binding="basicHttpBinding" contract="Service.IService">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="Service.ServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
```
I removed a lot of extras especially the script modules which i won't require
|
267,374 |
<p>People in java/.net world has framework which provides methods for sorting a list.</p>
<p>In CS, we all might have gone through Bubble/Insertion/Merge/Shell sorting algorithms.
Do you write any of it these days?</p>
<p>With frameworks in place, do you write code for sorting?<br></p>
<p>Do you think it makes sense to ask people to write code to sort in an interview? (other than for intern/junior developer requirement)</p>
|
[
{
"answer_id": 267381,
"author": "tunaranch",
"author_id": 27708,
"author_profile": "https://Stackoverflow.com/users/27708",
"pm_score": 1,
"selected": false,
"text": "<p>Personally, I've not had a need to write my own sorting code for a while.</p>\n\n<p>As far as interview questions go, it would weed out those who didn't pay attention during CS classes.</p>\n\n<p>You could test API knowledge by asking how would you build Comparable (Capital C) objects, or something along those lines.</p>\n"
},
{
"answer_id": 267382,
"author": "JB King",
"author_id": 8745,
"author_profile": "https://Stackoverflow.com/users/8745",
"pm_score": 2,
"selected": false,
"text": "<p>I don't write the sorting algorithm, but I have implemented the IComparer in .Net for a few classes which was kind of interesting the first couple of times.</p>\n\n<p>I wouldn't write the code for sorting given what is in the frameworks in most cases. There should be an understanding of why a particular sorting strategy like Quick sort is often used in frameworks like .Net.</p>\n\n<p>I could see giving or being given a sorting question where some of the work is implementing the IComparer and understanding the different ways to sort a class. It would be a fairly easy thing to show someone a Bubble sort and ask, \"Why wouldn't you want to do this in most applications?\"</p>\n"
},
{
"answer_id": 267383,
"author": "Seiti",
"author_id": 27959,
"author_profile": "https://Stackoverflow.com/users/27959",
"pm_score": 2,
"selected": false,
"text": "<p>only on employer's interview/test =)</p>\n"
},
{
"answer_id": 267387,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 0,
"selected": false,
"text": "<p>Man, if someone asked me in an interview what the best sort algorithm was, and didn't understand immediately when I said 'timsort', I'd seriously reconsider if I wanted to work there.</p>\n\n<p>Timsort</p>\n\n<blockquote>\n <p>This describes an adaptive, stable,\n natural mergesort, modestly called\n timsort (hey, I earned it ). It\n has supernatural performance on many\n kinds of partially ordered arrays\n (less than lg(N!) comparisons needed,\n and as few as N-1), yet as fast as\n Python's previous highly tuned\n samplesort hybrid on random arrays.</p>\n \n <p>In a nutshell, the main routine\n marches over the array once, left to\n right, alternately identifying the\n next run, then merging it into the\n previous runs \"intelligently\". \n Everything else is complication for\n speed, and some hard-won measure of\n memory efficiency.</p>\n</blockquote>\n\n<p><a href=\"http://svn.python.org/projects/python/trunk/Objects/listsort.txt\" rel=\"nofollow noreferrer\">http://svn.python.org/projects/python/trunk/Objects/listsort.txt</a>\n<a href=\"https://stackoverflow.com/questions/154504/is-timsort-general-purpose-or-python-specific\">Is timsort general-purpose or Python-specific?</a></p>\n"
},
{
"answer_id": 267406,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 3,
"selected": false,
"text": "<p>There are two pieces of code I write today in order to sort data</p>\n\n<pre><code>list.Sort();\nenumerable.OrderBy(x => x); // Occasionally a different lambda is used\n</code></pre>\n"
},
{
"answer_id": 267417,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 0,
"selected": false,
"text": "<p>I haven't really implemented a sort, except as coding exercise and to observe interesting features of a language (like how you can do quicksort on one line in Python).</p>\n\n<p>I think it's a valid question to ask in an interview because it reflects whether the developer thinks about these kind of things... I feel it's important to know what that list.sort() is doing when you call it. It's just part of my theory that you should know the fundamentals behind everything as a programmer. </p>\n"
},
{
"answer_id": 267425,
"author": "Whytespot",
"author_id": 33185,
"author_profile": "https://Stackoverflow.com/users/33185",
"pm_score": 2,
"selected": false,
"text": "<p>I can say with 100% certainty that I haven't written one of the 'traditional' sort routines since leaving University. It's nice to know the theory behind it, but to apply them to real-world situations that can't be done by other means doesn't happen very often (at least from my experience...).</p>\n"
},
{
"answer_id": 267434,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 0,
"selected": false,
"text": "<p>I never write anything for which there's a library routine. I haven't coded a sort in decades. Nor would I ever. With quicksort and timsort directly available, there's no reason to write a sort.</p>\n\n<p>I note that SQL does sorting for me. </p>\n\n<p>There are lots of things I don't write, sorts being just one of them.</p>\n\n<p>I never write my own I/O drivers. (Although I have in the past.)</p>\n\n<p>I never write my own graphics libraries. (Yes, I did this once, too, in the '80s)</p>\n\n<p>I never write my own file system. (Avoided this.)</p>\n"
},
{
"answer_id": 267459,
"author": "mscccc",
"author_id": 2510,
"author_profile": "https://Stackoverflow.com/users/2510",
"pm_score": 0,
"selected": false,
"text": "<p>There is definitely no reason to code one anymore. I think it is important though to understand the efficiency of what you are using so that you can pick the best one for the data you are sorting.</p>\n"
},
{
"answer_id": 267478,
"author": "Barry Kelly",
"author_id": 3712,
"author_profile": "https://Stackoverflow.com/users/3712",
"pm_score": 3,
"selected": false,
"text": "<p>I work for a developer tools company, and as such I sometimes need to write new RTL types and routines. Sorting is something developers need, so it's something I sometimes need to write.</p>\n\n<p>Don't forget, all that library code wasn't handed down from some mountain: some developer somewhere had to write it.</p>\n"
},
{
"answer_id": 267493,
"author": "Gabe",
"author_id": 9835,
"author_profile": "https://Stackoverflow.com/users/9835",
"pm_score": 1,
"selected": false,
"text": "<p>The way I see it, just like many others fields of knowledge, programming also has a theoretical and a practical approach to it.</p>\n\n<p>The field of \"theoretical programming\" is the one that gave us quicksort, Radix Sort, Djikstra's Algorithm and many other things absolutely necessary to the advance of computing.</p>\n\n<p>The field of \"practical programming\" deals with the fact that the solutions created in \"theoretical programming\" should be easily accessible to all in a much easier way, so that the theoretical ideas can get many, many creative uses. This gave us high-level languages like Python and allowed pretty much any language to implement packed methods for the most basics operations like sorting or searching with a good enough performance to be fit for almost everyone.</p>\n\n<p>One can't live without the other...\nmost of us not needing to hard code a sorting algorithm doesn't mean no one should.</p>\n"
},
{
"answer_id": 267667,
"author": "baash05",
"author_id": 31325,
"author_profile": "https://Stackoverflow.com/users/31325",
"pm_score": 1,
"selected": false,
"text": "<p>I've reciently had to write a sort, of sorts. \nI had a list of text.. the ten most common had to show up according to the frequency at which they were selected. All other entries had to show up according to alpha sort. </p>\n\n<p>It wasn't crazy hard to do but I did have to write a sort to support it. </p>\n\n<p>I've also had to sort objects whose elements aren't easily sorted with an out of the box code. </p>\n\n<p>Same goes for searching.. I had to walk a file and search staticly sized records.. When I found a record I had to move one record back, because I was inserting before it. \nFor the most part it was very simple and I mearly pasted in a binary search. Some changes needed to be done to support the method of access, because I wasn't using an array that was acutally in memory.. Ah c&@p.. I could have treated it like a stream.. See now I want to go back and take a look.. </p>\n"
},
{
"answer_id": 267673,
"author": "Joshua",
"author_id": 14768,
"author_profile": "https://Stackoverflow.com/users/14768",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. Sometimes digging out Shell sort beats the builtin sort routine when your list is only expected to be at most a few tens of records.</p>\n"
},
{
"answer_id": 267706,
"author": "Mark Ransom",
"author_id": 5987,
"author_profile": "https://Stackoverflow.com/users/5987",
"pm_score": 2,
"selected": false,
"text": "<p>I wrote a merge sort when I had to sort multi-gigabyte files with a custom key comparison. I love merge sort - it's easy to comprehend, stable, and has a worst-case O(n log n) performance.</p>\n\n<p>I've been looking for an excuse to try <a href=\"http://en.wikipedia.org/wiki/Radix_sort\" rel=\"nofollow noreferrer\">radix sort</a> too. It's not as general purpose as most sorting algorithms, so there aren't going to be any libraries that provide it, but under the right circumstances it should be a good speedup.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267374",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23574/"
] |
People in java/.net world has framework which provides methods for sorting a list.
In CS, we all might have gone through Bubble/Insertion/Merge/Shell sorting algorithms.
Do you write any of it these days?
With frameworks in place, do you write code for sorting?
Do you think it makes sense to ask people to write code to sort in an interview? (other than for intern/junior developer requirement)
|
There are two pieces of code I write today in order to sort data
```
list.Sort();
enumerable.OrderBy(x => x); // Occasionally a different lambda is used
```
|
267,399 |
<p>Thinking about <a href="https://stackoverflow.com/questions/267351/how-can-i-convert-from-integers-to-roman-numerals-using-a-syntax-directed-trans">my other problem</a>, i decided I can't even create a regular expression that will match roman numerals (let alone a context-free grammar that will generate them)</p>
<p>The problem is matching only valid roman numerals.
Eg, 990 is NOT "XM", it's "CMXC"</p>
<p>My problem in making the regex for this is that in order to allow or not allow certain characters, I need to look back.
Let's take thousands and hundreds, for example.</p>
<p>I can allow M{0,2}C?M (to allow for 900, 1000, 1900, 2000, 2900 and 3000). However, If the match is on CM, I can't allow following characters to be C or D (because I'm already at 900).</p>
<p>How can I express this in a regex?<br>
If it's simply not expressible in a regex, is it expressible in a context-free grammar?</p>
|
[
{
"answer_id": 267405,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 10,
"selected": true,
"text": "<p>You can use the following regex for this:</p>\n\n<pre><code>^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$\n</code></pre>\n\n<p>Breaking it down, <code>M{0,4}</code> specifies the thousands section and basically restrains it to between <code>0</code> and <code>4000</code>. It's a relatively simple:</p>\n\n<pre><code> 0: <empty> matched by M{0}\n1000: M matched by M{1}\n2000: MM matched by M{2}\n3000: MMM matched by M{3}\n4000: MMMM matched by M{4}\n</code></pre>\n\n<p>You could, of course, use something like <code>M*</code> to allow <em>any</em> number (including zero) of thousands, if you want to allow bigger numbers.</p>\n\n<p>Next is <code>(CM|CD|D?C{0,3})</code>, slightly more complex, this is for the hundreds section and covers all the possibilities:</p>\n\n<pre><code> 0: <empty> matched by D?C{0} (with D not there)\n100: C matched by D?C{1} (with D not there)\n200: CC matched by D?C{2} (with D not there)\n300: CCC matched by D?C{3} (with D not there)\n400: CD matched by CD\n500: D matched by D?C{0} (with D there)\n600: DC matched by D?C{1} (with D there)\n700: DCC matched by D?C{2} (with D there)\n800: DCCC matched by D?C{3} (with D there)\n900: CM matched by CM\n</code></pre>\n\n<p>Thirdly, <code>(XC|XL|L?X{0,3})</code> follows the same rules as previous section but for the tens place:</p>\n\n<pre><code> 0: <empty> matched by L?X{0} (with L not there)\n10: X matched by L?X{1} (with L not there)\n20: XX matched by L?X{2} (with L not there)\n30: XXX matched by L?X{3} (with L not there)\n40: XL matched by XL\n50: L matched by L?X{0} (with L there)\n60: LX matched by L?X{1} (with L there)\n70: LXX matched by L?X{2} (with L there)\n80: LXXX matched by L?X{3} (with L there)\n90: XC matched by XC\n</code></pre>\n\n<p>And, finally, <code>(IX|IV|V?I{0,3})</code> is the units section, handling <code>0</code> through <code>9</code> and also similar to the previous two sections (Roman numerals, despite their seeming weirdness, follow some logical rules once you figure out what they are):</p>\n\n<pre><code>0: <empty> matched by V?I{0} (with V not there)\n1: I matched by V?I{1} (with V not there)\n2: II matched by V?I{2} (with V not there)\n3: III matched by V?I{3} (with V not there)\n4: IV matched by IV\n5: V matched by V?I{0} (with V there)\n6: VI matched by V?I{1} (with V there)\n7: VII matched by V?I{2} (with V there)\n8: VIII matched by V?I{3} (with V there)\n9: IX matched by IX\n</code></pre>\n\n<hr>\n\n<p>Just keep in mind that that regex will also match an empty string. If you don't want this (and your regex engine is modern enough), you can use positive look-behind and look-ahead:</p>\n\n<pre><code>(?<=^)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})(?=$)\n</code></pre>\n\n<p>(the other alternative being to just check that the length is not zero beforehand).</p>\n"
},
{
"answer_id": 267409,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 3,
"selected": false,
"text": "<p>Fortunately, the range of numbers is limited to 1..3999 or thereabouts. Therefore, you can build up the regex piece-meal.</p>\n\n<pre><code><opt-thousands-part><opt-hundreds-part><opt-tens-part><opt-units-part>\n</code></pre>\n\n<p>Each of those parts will deal with the vagaries of Roman notation. For example, using Perl notation:</p>\n\n<pre><code><opt-hundreds-part> = m/(CM|DC{0,3}|CD|C{1,3})?/;\n</code></pre>\n\n<p>Repeat and assemble.</p>\n\n<p><em>Added</em>: The <code><opt-hundreds-part></code> can be compressed further:</p>\n\n<pre><code><opt-hundreds-part> = m/(C[MD]|D?C{0,3})/;\n</code></pre>\n\n<p>Since the 'D?C{0,3}' clause can match nothing, there's no need for the question mark. And, most likely, the parentheses should be the non-capturing type - in Perl:</p>\n\n<pre><code><opt-hundreds-part> = m/(?:C[MD]|D?C{0,3})/;\n</code></pre>\n\n<p>Of course, it should all be case-insensitive, too.</p>\n\n<p>You can also extend this to deal with the options mentioned by James Curran (to allow XM or IM for 990 or 999, and CCCC for 400, etc).</p>\n\n<pre><code><opt-hundreds-part> = m/(?:[IXC][MD]|D?C{0,4})/;\n</code></pre>\n"
},
{
"answer_id": 267430,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 5,
"selected": false,
"text": "<p>Actually, your premise is flawed. 990 <strong>IS</strong> \"XM\", as well as \"CMXC\".</p>\n\n<p>The Romans were far less concerned about the \"rules\" than your third grade teacher. As long as it added up, it was OK. Hence \"IIII\" was just as good as \"IV\" for 4. And \"IIM\" was completely cool for 998.</p>\n\n<p>(If you have trouble dealing with that... Remember English spellings were not formalized until the 1700s. Until then, as long as the reader could figure it out, it was good enough).</p>\n"
},
{
"answer_id": 5326535,
"author": "Marvin Frommhold",
"author_id": 662635,
"author_profile": "https://Stackoverflow.com/users/662635",
"pm_score": -1,
"selected": false,
"text": "<p>The problem of the solution from Jeremy and Pax is, that it does also match \"nothing\".</p>\n\n<p>The following regex expects at least one roman numeral:</p>\n\n<pre><code>^(M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|[IDCXMLV])$\n</code></pre>\n"
},
{
"answer_id": 10441405,
"author": "Corin",
"author_id": 302306,
"author_profile": "https://Stackoverflow.com/users/302306",
"pm_score": 4,
"selected": false,
"text": "<p>To avoid matching the empty string you'll need to repeat the pattern four times and replace each <code>0</code> with a <code>1</code> in turn, and account for <code>V</code>, <code>L</code> and <code>D</code>:</p>\n\n<pre><code>(M{1,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|C?D|D?C{1,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|X?L|L?X{1,3})(IX|IV|V?I{0,3})|M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|I?V|V?I{1,3}))\n</code></pre>\n\n<p>In this case (because this pattern uses <code>^</code> and <code>$</code>) you would be better off checking for empty lines first and don't bother matching them. If you are using <a href=\"http://www.regular-expressions.info/wordboundaries.html\">word boundaries</a> then you don't have a problem because there's no such thing as an empty word. (At least regex doesn't define one; don't start philosophising, I'm being pragmatic here!)</p>\n\n<hr>\n\n<p>In my own particular (real world) case I needed match numerals at word endings and I found no other way around it. I needed to scrub off the footnote numbers from my plain text document, where text such as \"the Red Sea<sup>cl</sup> and the Great Barrier Reef<sup>cli</sup>\" had been converted to <code>the Red Seacl and the Great Barrier Reefcli</code>. But I still had problems with valid words like <code>Tahiti</code> and <code>fantastic</code> are scrubbed into <code>Tahit</code> and <code>fantasti</code>.</p>\n"
},
{
"answer_id": 24354880,
"author": "Mottie",
"author_id": 145346,
"author_profile": "https://Stackoverflow.com/users/145346",
"pm_score": 0,
"selected": false,
"text": "<p>Steven Levithan uses this regex in <a href=\"http://blog.stevenlevithan.com/archives/javascript-roman-numeral-converter\" rel=\"nofollow\">his post</a> which validates roman numerals prior to \"deromanizing\" the value:</p>\n\n<pre><code>/^M*(?:D?C{0,3}|C[MD])(?:L?X{0,3}|X[CL])(?:V?I{0,3}|I[XV])$/\n</code></pre>\n"
},
{
"answer_id": 26669245,
"author": "Salvador Dali",
"author_id": 1090562,
"author_profile": "https://Stackoverflow.com/users/1090562",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import re\npattern = '^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$'\nif re.search(pattern, 'XCCMCI'):\n print 'Valid Roman'\nelse:\n print 'Not valid Roman'\n</code></pre>\n\n<p>For people who really want to understand the logic, please take a look at a step by step explanation on 3 pages on <a href=\"http://www.diveintopython.net/regular_expressions/roman_numerals.html\" rel=\"noreferrer\">diveintopython</a>.</p>\n\n<p>The only difference from original solution (which had <code>M{0,4}</code>) is because I found that 'MMMM' is not a valid Roman numeral (also old Romans most probably have not thought about that huge number and will disagree with me). If you are one of disagreing old Romans, please forgive me and use {0,4} version.</p>\n"
},
{
"answer_id": 27730606,
"author": "Vince Ypma",
"author_id": 3879027,
"author_profile": "https://Stackoverflow.com/users/3879027",
"pm_score": -1,
"selected": false,
"text": "<p>I would write functions to my work for me.\nHere are two roman numeral functions in PowerShell.</p>\n\n<pre><code>function ConvertFrom-RomanNumeral\n{\n <#\n .SYNOPSIS\n Converts a Roman numeral to a number.\n .DESCRIPTION\n Converts a Roman numeral - in the range of I..MMMCMXCIX - to a number.\n .EXAMPLE\n ConvertFrom-RomanNumeral -Numeral MMXIV\n .EXAMPLE\n \"MMXIV\" | ConvertFrom-RomanNumeral\n #>\n [CmdletBinding()]\n [OutputType([int])]\n Param\n (\n [Parameter(Mandatory=$true,\n HelpMessage=\"Enter a roman numeral in the range I..MMMCMXCIX\",\n ValueFromPipeline=$true,\n Position=0)]\n [ValidatePattern(\"^M{0,3}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$\")]\n [string]\n $Numeral\n )\n\n Begin\n {\n $RomanToDecimal = [ordered]@{\n M = 1000\n CM = 900\n D = 500\n CD = 400\n C = 100\n XC = 90\n L = 50\n X = 10\n IX = 9\n V = 5\n IV = 4\n I = 1\n }\n }\n Process\n {\n $roman = $Numeral + \" \"\n $value = 0\n\n do\n {\n foreach ($key in $RomanToDecimal.Keys)\n {\n if ($key.Length -eq 1)\n {\n if ($key -match $roman.Substring(0,1))\n {\n $value += $RomanToDecimal.$key\n $roman = $roman.Substring(1)\n break\n }\n }\n else\n {\n if ($key -match $roman.Substring(0,2))\n {\n $value += $RomanToDecimal.$key\n $roman = $roman.Substring(2)\n break\n }\n }\n }\n }\n until ($roman -eq \" \")\n\n $value\n }\n End\n {\n }\n}\n\nfunction ConvertTo-RomanNumeral\n{\n <#\n .SYNOPSIS\n Converts a number to a Roman numeral.\n .DESCRIPTION\n Converts a number - in the range of 1 to 3,999 - to a Roman numeral.\n .EXAMPLE\n ConvertTo-RomanNumeral -Number (Get-Date).Year\n .EXAMPLE\n (Get-Date).Year | ConvertTo-RomanNumeral\n #>\n [CmdletBinding()]\n [OutputType([string])]\n Param\n (\n [Parameter(Mandatory=$true,\n HelpMessage=\"Enter an integer in the range 1 to 3,999\",\n ValueFromPipeline=$true,\n Position=0)]\n [ValidateRange(1,3999)]\n [int]\n $Number\n )\n\n Begin\n {\n $DecimalToRoman = @{\n Ones = \"\",\"I\",\"II\",\"III\",\"IV\",\"V\",\"VI\",\"VII\",\"VIII\",\"IX\";\n Tens = \"\",\"X\",\"XX\",\"XXX\",\"XL\",\"L\",\"LX\",\"LXX\",\"LXXX\",\"XC\";\n Hundreds = \"\",\"C\",\"CC\",\"CCC\",\"CD\",\"D\",\"DC\",\"DCC\",\"DCCC\",\"CM\";\n Thousands = \"\",\"M\",\"MM\",\"MMM\"\n }\n\n $column = @{Thousands = 0; Hundreds = 1; Tens = 2; Ones = 3}\n }\n Process\n {\n [int[]]$digits = $Number.ToString().PadLeft(4,\"0\").ToCharArray() |\n ForEach-Object { [Char]::GetNumericValue($_) }\n\n $RomanNumeral = \"\"\n $RomanNumeral += $DecimalToRoman.Thousands[$digits[$column.Thousands]]\n $RomanNumeral += $DecimalToRoman.Hundreds[$digits[$column.Hundreds]]\n $RomanNumeral += $DecimalToRoman.Tens[$digits[$column.Tens]]\n $RomanNumeral += $DecimalToRoman.Ones[$digits[$column.Ones]]\n\n $RomanNumeral\n }\n End\n {\n }\n}\n</code></pre>\n"
},
{
"answer_id": 36576402,
"author": "smileart",
"author_id": 209557,
"author_profile": "https://Stackoverflow.com/users/209557",
"pm_score": 4,
"selected": false,
"text": "<p>Just to save it here:</p>\n\n<pre><code>(^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$)\n</code></pre>\n\n<p>Matches all the Roman numerals. Doesn't care about empty strings (requires at least one Roman numeral letter). Should work in PCRE, Perl, Python and Ruby.</p>\n\n<p>Online Ruby demo: <a href=\"http://rubular.com/r/KLPR1zq3Hj\" rel=\"noreferrer\">http://rubular.com/r/KLPR1zq3Hj</a></p>\n\n<p>Online Conversion: <a href=\"http://www.onlineconversion.com/roman_numerals_advanced.htm\" rel=\"noreferrer\">http://www.onlineconversion.com/roman_numerals_advanced.htm</a></p>\n"
},
{
"answer_id": 53895776,
"author": "user2936263",
"author_id": 2936263,
"author_profile": "https://Stackoverflow.com/users/2936263",
"pm_score": 2,
"selected": false,
"text": "<p>In my case, I was trying to find and replace all occurences of roman numbers by one word inside the text, so I couldn't use the start and end of lines. So the @paxdiablo solution found many zero-length matches.\nI ended up with the following expression:</p>\n\n<pre><code>(?=\\b[MCDXLVI]{1,6}\\b)M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})\n</code></pre>\n\n<p>My final Python code was like this:</p>\n\n<pre><code>import re\ntext = \"RULES OF LIFE: I. STAY CURIOUS; II. NEVER STOP LEARNING\"\ntext = re.sub(r'(?=\\b[MCDXLVI]{1,6}\\b)M{0,4}(?:CM|CD|D?C{0,3})(?:XC|XL|L?X{0,3})(?:IX|IV|V?I{0,3})', 'ROMAN', text)\nprint(text)\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>RULES OF LIFE: ROMAN. STAY CURIOUS; ROMAN. NEVER STOP LEARNING\n</code></pre>\n"
},
{
"answer_id": 59311062,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Im answering this question <a href=\"https://stackoverflow.com/questions/59310128/regular-expression-in-python-for-roman-numerals\">Regular Expression in Python for Roman Numerals</a> here<br>\nbecause it was marked as an exact duplicate of this question. </p>\n\n<p>It might be similar in name, but this is a specific regex question / problem<br>\nas can be seen by this answer to that question. </p>\n\n<p>The items being sought can be combined into a single alternation and then<br>\nencased inside a capture group that will be put into a list with the findall()<br>\nfunction.<br>\nIt is done like this : </p>\n\n<pre><code>>>> import re\n>>> target = (\n... r\"this should pass v\" + \"\\n\"\n... r\"this is a test iii\" + \"\\n\"\n... )\n>>>\n>>> re.findall( r\"(?m)\\s(i{1,3}v*|v)$\", target )\n['v', 'iii']\n</code></pre>\n\n<p>The regex modifications to factor and capture just the numerals are this : </p>\n\n<pre><code> (?m)\n \\s \n ( # (1 start)\n i{1,3} \n v* \n | v\n ) # (1 end)\n $\n</code></pre>\n"
},
{
"answer_id": 60461765,
"author": "ketenks",
"author_id": 7071412,
"author_profile": "https://Stackoverflow.com/users/7071412",
"pm_score": 0,
"selected": false,
"text": "<p>This works in Java and PCRE regex engines and should now work in the latest JavaScript but may not work in all contexts.</p>\n\n<p><code>(?<![A-Z])(M*(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3}))(?![A-Z])</code></p>\n\n<p>The first part is the atrocious negative lookbehind. But, for logical purposes it is the easiest to understand. Basically, the first <code>(?<!)</code> is saying don't match the middle <code>([MATCH])</code> if there are letters coming before the middle <code>([MATCH])</code> and the last <code>(?!)</code> is saying don't match the middle <code>([MATCH])</code> if there are letters coming after it.</p>\n\n<p>The middle <code>([MATCH])</code> is just the most commonly used regex for matching the sequence of Roman Numerals. But now, you don't want to match that if there are any letters around it.</p>\n\n<p>See for yourself.\n<a href=\"https://regexr.com/4vce5\" rel=\"nofollow noreferrer\">https://regexr.com/4vce5</a></p>\n"
},
{
"answer_id": 60469651,
"author": "Bernardo Duarte",
"author_id": 7395911,
"author_profile": "https://Stackoverflow.com/users/7395911",
"pm_score": 2,
"selected": false,
"text": "<p>I've seen multiple answers that doesn't cover empty strings or uses lookaheads to solve this. And I want to add a new answer that does cover empty strings and doesn't use lookahead. The regex is the following one:</p>\n\n<p><code>^(I[VX]|VI{0,3}|I{1,3})|((X[LC]|LX{0,3}|X{1,3})(I[VX]|V?I{0,3}))|((C[DM]|DC{0,3}|C{1,3})(X[LC]|L?X{0,3})(I[VX]|V?I{0,3}))|(M+(C[DM]|D?C{0,3})(X[LC]|L?X{0,3})(I[VX]|V?I{0,3}))$</code></p>\n\n<p>I'm allowing for infinite <code>M</code>, with <code>M+</code> but of course someone could change to <code>M{1,4}</code> to allow only 1 or 4 if desired.</p>\n\n<p>Below is a visualization that helps to understand what it is doing, preceded by two online demos:</p>\n\n<p><a href=\"https://www.debuggex.com/r/zuVcMMzMYq-RsXMA\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n\n<p><a href=\"https://regex101.com/r/7mw0Pe/1/\" rel=\"nofollow noreferrer\">Regex 101 Demo</a></p>\n\n<p><img src=\"https://www.debuggex.com/i/zuVcMMzMYq-RsXMA.png\" alt=\"Regular expression visualization\"></p>\n"
},
{
"answer_id": 63774849,
"author": "Rafayet Ullah",
"author_id": 5409601,
"author_profile": "https://Stackoverflow.com/users/5409601",
"pm_score": 1,
"selected": false,
"text": "<p>The following expression worked for me to validate the roman number.</p>\n<pre><code>^M{0,4}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$\n</code></pre>\n<p>Here,</p>\n<ul>\n<li><code>M{0,4}</code> will match thousands</li>\n<li><code>C[MD]|D?C{0,3}</code> will match Hundreds</li>\n<li><code>X[CL]|L?X{0,3}</code> will match Tens</li>\n<li><code>I[XV]|V?I{0,3}</code> will match Units</li>\n</ul>\n<p>Below is a visualization that helps to understand what it is doing, preceded by two online demos:</p>\n<p><a href=\"https://www.debuggex.com/r/Sf3WDxwcjtYHUZ1L\" rel=\"nofollow noreferrer\">Debuggex Demo</a></p>\n<p><a href=\"https://regex101.com/r/5atuBs/1\" rel=\"nofollow noreferrer\">Regex 101 Demo</a></p>\n<p>Python Code:</p>\n<pre><code>import re\nregex = re.compile("^M{0,4}(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$")\nmatchArray = regex.match("MMMCMXCIX")\n</code></pre>\n"
},
{
"answer_id": 64034764,
"author": "Pigeo",
"author_id": 10001863,
"author_profile": "https://Stackoverflow.com/users/10001863",
"pm_score": 1,
"selected": false,
"text": "<p>The <strong>positive</strong> look-behind and look-ahead suggested by @paxdiablo in order to avoid matching empty strings seems not working to me.</p>\n<p>I have fixed it by using <strong>negative</strong> look-ahead instead :</p>\n<pre><code>(?!$)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})\n</code></pre>\n<p>NB: if you append something (eg. "foobar" at the end of the regex, then obviously you'll have to replace <code>(?!$)</code> by <code>(?!f)</code> (where <code>f</code> is the first character of "foobar").</p>\n"
},
{
"answer_id": 68450933,
"author": "mekwall",
"author_id": 358556,
"author_profile": "https://Stackoverflow.com/users/358556",
"pm_score": 2,
"selected": false,
"text": "<p>Some really amazing answers here but none fit the bill for me since I needed to be able to match only valid Roman numerals within a string without matching empty strings and only match numerals that are on their own (i.e. not within a word).</p>\n<p>Let me present you to <a href=\"https://www.oreilly.com/library/view/regular-expressions-cookbook/9780596802837/ch06s09.html\" rel=\"nofollow noreferrer\">Reilly's Modern roman numerals strict expression</a>:</p>\n<pre><code>^(?=[MDCLXVI])M*(C[MD]|D?C{0,3})(X[CL]|L?X{0,3})(I[XV]|V?I{0,3})$\n</code></pre>\n<p>Out of the box it was pretty close to what I needed but it will only match standalone Roman numerals and when changed to match in string it will match empty strings at certain points (where a word begins with an uppercase V, M etc.) and will also give partial matches of invalid Roman numerals such as MMLLVVDD, XXLLVVDD, MMMMDLVX, XVXDLMM and MMMCCMLXXV.</p>\n<p>So, after a bit of modification I and ended up with this:</p>\n<pre><code>(?<![MDCLXVI])(?=[MDCLXVI])M{0,3}(?:C[MD]|D?C{0,3})(?:X[CL]|L?X{0,3})(?:I[XV]|V?I{0,3})[^ ]\\b\n</code></pre>\n<p>The added <a href=\"https://www.regular-expressions.info/lookaround.html#lookbehind\" rel=\"nofollow noreferrer\">negative lookbehind</a> will ensure that it doesn't do partial matches of invalid Roman numerals and locking down the first M to 3 since that is the highest it goes in the <a href=\"https://en.wikipedia.org/wiki/Roman_numerals#Standard_form\" rel=\"nofollow noreferrer\">Roman numeral standard form</a>.</p>\n<p>As of right now, this is the only regular expression that passes my <a href=\"https://github.com/mekwall/romanizr/blob/main/src/__tests__/matchRomans.spec.ts\" rel=\"nofollow noreferrer\">extensive test suit</a> of over 4000 tests that includes all possible Roman numerals from 1-3999, Roman numerals within strings and invalid Roman numerals like the ones I mentioned above.</p>\n<p>Here's a screenshot of it in action from <a href=\"https://regex101.com/\" rel=\"nofollow noreferrer\">https://regex101.com/</a>:\n<a href=\"https://i.stack.imgur.com/TokEY.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TokEY.png\" alt=\"4\" /></a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267399",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3314/"
] |
Thinking about [my other problem](https://stackoverflow.com/questions/267351/how-can-i-convert-from-integers-to-roman-numerals-using-a-syntax-directed-trans), i decided I can't even create a regular expression that will match roman numerals (let alone a context-free grammar that will generate them)
The problem is matching only valid roman numerals.
Eg, 990 is NOT "XM", it's "CMXC"
My problem in making the regex for this is that in order to allow or not allow certain characters, I need to look back.
Let's take thousands and hundreds, for example.
I can allow M{0,2}C?M (to allow for 900, 1000, 1900, 2000, 2900 and 3000). However, If the match is on CM, I can't allow following characters to be C or D (because I'm already at 900).
How can I express this in a regex?
If it's simply not expressible in a regex, is it expressible in a context-free grammar?
|
You can use the following regex for this:
```
^M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})$
```
Breaking it down, `M{0,4}` specifies the thousands section and basically restrains it to between `0` and `4000`. It's a relatively simple:
```
0: <empty> matched by M{0}
1000: M matched by M{1}
2000: MM matched by M{2}
3000: MMM matched by M{3}
4000: MMMM matched by M{4}
```
You could, of course, use something like `M*` to allow *any* number (including zero) of thousands, if you want to allow bigger numbers.
Next is `(CM|CD|D?C{0,3})`, slightly more complex, this is for the hundreds section and covers all the possibilities:
```
0: <empty> matched by D?C{0} (with D not there)
100: C matched by D?C{1} (with D not there)
200: CC matched by D?C{2} (with D not there)
300: CCC matched by D?C{3} (with D not there)
400: CD matched by CD
500: D matched by D?C{0} (with D there)
600: DC matched by D?C{1} (with D there)
700: DCC matched by D?C{2} (with D there)
800: DCCC matched by D?C{3} (with D there)
900: CM matched by CM
```
Thirdly, `(XC|XL|L?X{0,3})` follows the same rules as previous section but for the tens place:
```
0: <empty> matched by L?X{0} (with L not there)
10: X matched by L?X{1} (with L not there)
20: XX matched by L?X{2} (with L not there)
30: XXX matched by L?X{3} (with L not there)
40: XL matched by XL
50: L matched by L?X{0} (with L there)
60: LX matched by L?X{1} (with L there)
70: LXX matched by L?X{2} (with L there)
80: LXXX matched by L?X{3} (with L there)
90: XC matched by XC
```
And, finally, `(IX|IV|V?I{0,3})` is the units section, handling `0` through `9` and also similar to the previous two sections (Roman numerals, despite their seeming weirdness, follow some logical rules once you figure out what they are):
```
0: <empty> matched by V?I{0} (with V not there)
1: I matched by V?I{1} (with V not there)
2: II matched by V?I{2} (with V not there)
3: III matched by V?I{3} (with V not there)
4: IV matched by IV
5: V matched by V?I{0} (with V there)
6: VI matched by V?I{1} (with V there)
7: VII matched by V?I{2} (with V there)
8: VIII matched by V?I{3} (with V there)
9: IX matched by IX
```
---
Just keep in mind that that regex will also match an empty string. If you don't want this (and your regex engine is modern enough), you can use positive look-behind and look-ahead:
```
(?<=^)M{0,4}(CM|CD|D?C{0,3})(XC|XL|L?X{0,3})(IX|IV|V?I{0,3})(?=$)
```
(the other alternative being to just check that the length is not zero beforehand).
|
267,410 |
<p>I have a datasource that I want to bind to a listview that has multiple columns. How do I bind my datasource to that listview</p>
<p>Here is some pseudo code that doesn't work to help illustrate what I am trying to do:</p>
<pre><code>MyDataTable dt = GetDataSource();
ListView1.DataBindings.Add("Column1.Text", dt, "MyDBCol1");
ListView1.DataBindings.Add("Column2.Text", dt, "MyDBCol2");
</code></pre>
<p>-- edit --</p>
<p>Sorry, I forgot to mention it was winforms. </p>
|
[
{
"answer_id": 267466,
"author": "Handruin",
"author_id": 26173,
"author_profile": "https://Stackoverflow.com/users/26173",
"pm_score": -1,
"selected": false,
"text": "<p>Check out this <a href=\"https://web.archive.org/web/20200221035838/http://geekswithblogs.net:80/rashid/archive/2007/09/09/Asp.net-ListView---DataBinding.aspx\" rel=\"nofollow noreferrer\">reference on binding datasource to listview</a>. Is that what you were looking for?</p>\n"
},
{
"answer_id": 267720,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>Can you please clarify whether this is winforms vs webforms? Both have a <code>ListView</code>. From the <code>DataBindings.Add</code> I'm assuming winforms.</p>\n\n<p>Would <code>DataGridView</code> be a pragmatic option? This will support multi-column binding out of the box?</p>\n"
},
{
"answer_id": 267767,
"author": "Alexander Prokofyev",
"author_id": 11256,
"author_profile": "https://Stackoverflow.com/users/11256",
"pm_score": 3,
"selected": true,
"text": "<p>It seems there is a lacuna in functionality of WinForms ListView control (thought it's possible to <a href=\"http://msdn.microsoft.com/en-us/library/ms750972.aspx#BindingDatatoaListView\" rel=\"nofollow noreferrer\">databind</a> new WPF ListBox). </p>\n\n<p>This article by Nick Karnik describes how to add databinding capability to custom control inherited from WinForms ListView - <a href=\"http://www.codeproject.com/KB/list/ListView_DataBinding.aspx\" rel=\"nofollow noreferrer\">Data binding a ListView</a>.</p>\n"
},
{
"answer_id": 368325,
"author": "Peter Gfader",
"author_id": 35693,
"author_profile": "https://Stackoverflow.com/users/35693",
"pm_score": 0,
"selected": false,
"text": "<p>Listview has no Datasource, Items must be added manually.</p>\n\n<p>I would suggest to use the DatagridView instead of the Listview.<br>\nParticularly if you have a <strong>lot of items</strong>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1632/"
] |
I have a datasource that I want to bind to a listview that has multiple columns. How do I bind my datasource to that listview
Here is some pseudo code that doesn't work to help illustrate what I am trying to do:
```
MyDataTable dt = GetDataSource();
ListView1.DataBindings.Add("Column1.Text", dt, "MyDBCol1");
ListView1.DataBindings.Add("Column2.Text", dt, "MyDBCol2");
```
-- edit --
Sorry, I forgot to mention it was winforms.
|
It seems there is a lacuna in functionality of WinForms ListView control (thought it's possible to [databind](http://msdn.microsoft.com/en-us/library/ms750972.aspx#BindingDatatoaListView) new WPF ListBox).
This article by Nick Karnik describes how to add databinding capability to custom control inherited from WinForms ListView - [Data binding a ListView](http://www.codeproject.com/KB/list/ListView_DataBinding.aspx).
|
267,418 |
<p>Is there an elegant way to specialize a template based on one of its template parameters?</p>
<p>Ie.</p>
<pre><code>template<int N> struct Junk {
static int foo() {
// stuff
return Junk<N - 1>::foo();
}
};
// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
static int foo() {
// stuff
return N;
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
</code></pre>
<p>Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:</p>
<pre><code>template<int N> struct JunkDivisibleBy5 {
static int foo() {
// stuff
return N;
}
};
template<int N> struct Junk {
static int foo() {
// stuff
if ((N - 1) % 5 == 0 && N != 1)
return JunkDivisibleBy5<N - 1>::foo();
else
return Junk<N - 1>::foo();
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
</code></pre>
<p>But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.</p>
|
[
{
"answer_id": 267514,
"author": "jwfearn",
"author_id": 10559,
"author_profile": "https://Stackoverflow.com/users/10559",
"pm_score": 5,
"selected": true,
"text": "<p>How's this:</p>\n\n<pre><code>#include <iostream>\nusing namespace std;\n\ntemplate < typename T, T N, T D >\nstruct fraction {\n typedef T value_type;\n static const value_type num = N;\n static const value_type denom = D;\n static const bool is_div = (num % denom == 0);\n};\n\ntemplate< typename T, T N, T D, bool P >\nstruct do_if {\n static void op() { cout << N << \" NOT divisible by \" << D << endl; }\n};\n\ntemplate< typename T, T N, T D >\nstruct do_if< T, N, D, true > {\n static void op() { cout << N << \" divisible by \" << D << endl; }\n};\n\ntemplate < int N >\nvoid foo() {\n typedef fraction< int, N, 5 > f;\n do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();\n}\n\nint main() {\n foo< -5 >();\n foo< -1 >();\n foo< 0 >();\n foo< 1 >();\n foo< 5 >();\n foo< 10000005 >();\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 267535,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 0,
"selected": false,
"text": "<p>I would hardly call it elegant, but here's my version of your code using only templates for computation (along with a test thing) --</p>\n\n<pre><code>#include <iostream>\n\ntemplate < int N > struct JunkDivBy5 {\n static int foo() {\n return N;\n }\n};\n\ntemplate < int N > struct Junk {\n template < int N1 > struct _JunkCond {\n enum { val = ( N1 != 1 && ( N1 - 1 ) % 5 == 0 ) ? 1 : 0 };\n };\n\n template < int M, int N1 > struct _JunkBranch { /* Error */ };\n\n template < int N1 > struct _JunkBranch< 1, N1 > {\n typedef JunkDivBy5< N1 - 1 > Type;\n };\n\n template < int N1 > struct _JunkBranch< 0, N1 > {\n typedef Junk< N1 - 1 > Type;\n };\n\n static int foo() {\n return _JunkBranch< _JunkCond< N >::val, N >::Type::foo();\n }\n};\n\ntemplate <> struct Junk< 0 > {\n static int foo() {\n return 0;\n }\n};\n\nint main( int argc, char *argv[] ) {\n std::cout << Junk< 0 >::foo() << std::endl;\n std::cout << Junk< 5 >::foo() << std::endl;\n std::cout << Junk< 7 >::foo() << std::endl;\n std::cout << Junk< 25 >::foo() << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 267899,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 3,
"selected": false,
"text": "<p>All calculations could be made in compile-time:</p>\n\n<pre><code>#include <iostream>\n\ntemplate<int N> struct Junk {\n enum { IsDivisibleBy5 = (N % 5 == 0) };\n template<bool D> struct JunkInternal {\n enum { Result = Junk<N-1>::Result };\n };\n template<> struct JunkInternal<true> {\n enum { Result = N };\n };\n enum { Result = JunkInternal<IsDivisibleBy5>::Result };\n};\n\nint main(int, char**)\n{\n std::cout << Junk< 0 >::Result << std::endl;\n std::cout << Junk< 7 >::Result << std::endl;\n std::cout << Junk< 10 >::Result << std::endl;\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 268255,
"author": "MSalters",
"author_id": 15416,
"author_profile": "https://Stackoverflow.com/users/15416",
"pm_score": 2,
"selected": false,
"text": "<p>Inheritance works quite well:</p>\n\n<pre><code>template<int N> struct Junk : private JunkBase < N % 5 > { };\n\ntemplate<int N> struct JunkBase {\n static int foo() {\n // stuff\n return Junk<N - 1>::foo();\n }\n};\ntemplate< > struct JunkBase<0> {\n static int foo() {\n return 0;\n }\n};\n</code></pre>\n\n<p>You might need to pass N to JunkBase::foo, if you need N/5 too.</p>\n"
},
{
"answer_id": 275254,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 2,
"selected": false,
"text": "<p>Code</p>\n\n<pre><code>template<int A, bool = !(A % 5)>\nstruct select : select<A-1> { };\n\ntemplate<int A>\nstruct select<A, true> { static int const value = A; };\n\ntemplate<>\nstruct select<0, true> { static int const value = 0; };\n\nint main() {\n std::cout << select<1>::value; // 0\n std::cout << select<7>::value; // 5\n std::cout << select<10>::value; // 10\n}\n</code></pre>\n\n<p>Keep the divisor variable</p>\n\n<pre><code>template<int A, int D, bool = !(A % D)>\nstruct select : select<A-1, D> { };\n\ntemplate<int A, int D>\nstruct select<A, D, true> { static int const value = A; };\n\ntemplate<int D>\nstruct select<0, D, true> { static int const value = 0; };\n\nint main() {\n std::cout << select<1, 3>::value; // 0\n std::cout << select<7, 3>::value; // 6\n std::cout << select<10, 3>::value; // 9\n}\n</code></pre>\n"
},
{
"answer_id": 280697,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 3,
"selected": false,
"text": "<p>Using D programming language templates, one could write it as:</p>\n\n<pre><code>struct Junk(int N)\n{\n static int foo()\n {\n static if (N == 0)\n return 0;\n else static if ((N % 5) == 0)\n return N;\n else\n return Junk!(N - 1).foo();\n }\n}\n</code></pre>\n\n<p>static if's are executed at compile time.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267418",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5963/"
] |
Is there an elegant way to specialize a template based on one of its template parameters?
Ie.
```
template<int N> struct Junk {
static int foo() {
// stuff
return Junk<N - 1>::foo();
}
};
// compile error: template argument '(size * 5)' involves template parameter(s)
template<int N> struct Junk<N*5> {
static int foo() {
// stuff
return N;
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
```
Ie. I am trying to specialize a template based on the parameter being divisible by 5. The only way I can seem to do it is like below:
```
template<int N> struct JunkDivisibleBy5 {
static int foo() {
// stuff
return N;
}
};
template<int N> struct Junk {
static int foo() {
// stuff
if ((N - 1) % 5 == 0 && N != 1)
return JunkDivisibleBy5<N - 1>::foo();
else
return Junk<N - 1>::foo();
}
};
template<> struct Junk<0> {
static int foo() {
// stuff
return 0;
}
};
```
But this is significantly less elegant, and also necessitates instantiation of all templates even if the template argument shouldn't require it.
|
How's this:
```
#include <iostream>
using namespace std;
template < typename T, T N, T D >
struct fraction {
typedef T value_type;
static const value_type num = N;
static const value_type denom = D;
static const bool is_div = (num % denom == 0);
};
template< typename T, T N, T D, bool P >
struct do_if {
static void op() { cout << N << " NOT divisible by " << D << endl; }
};
template< typename T, T N, T D >
struct do_if< T, N, D, true > {
static void op() { cout << N << " divisible by " << D << endl; }
};
template < int N >
void foo() {
typedef fraction< int, N, 5 > f;
do_if< typename f::value_type, f::num, f::denom, f::is_div >::op();
}
int main() {
foo< -5 >();
foo< -1 >();
foo< 0 >();
foo< 1 >();
foo< 5 >();
foo< 10000005 >();
return 0;
}
```
|
267,427 |
<p>I have a file with data listed as follows:</p>
<pre><code>0, 2, 10
10, 8, 10
10, 10, 10
10, 16, 10
15, 10, 16
17, 10, 16
</code></pre>
<p>I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.</p>
<p>For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.</p>
<p>This is the python equivalent of what I would like to have in C++:</p>
<pre><code>f = open('input_hard.dat')
lines = f.readlines()
f.close()
#declarations
inint, inbase, outbase = [], [], []
#input parsing
for line in lines:
bits = string.split(line, ',')
inint.append(int(bits[0].strip()))
inbase.append(int(bits[1].strip()))
outbase.append(int(bits[2].strip()))
</code></pre>
<p>The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.</p>
<p>Any help would be appreciated, thanks!</p>
|
[
{
"answer_id": 267449,
"author": "Matthew Smith",
"author_id": 20889,
"author_profile": "https://Stackoverflow.com/users/20889",
"pm_score": 2,
"selected": false,
"text": "<p>Something like:</p>\n\n<pre><code>vector<int> inint;\nvector<int> inbase;\nvector<int> outbase;\nwhile (fgets(buf, fh)) {\n char *tok = strtok(buf, \", \");\n inint.push_back(atoi(tok));\n tok = strtok(NULL, \", \");\n inbase.push_back(atoi(tok));\n tok = strtok(NULL, \", \");\n outbase.push_back(atoi(tok));\n}\n</code></pre>\n\n<p>Except with error checking.</p>\n"
},
{
"answer_id": 267497,
"author": "Raymond Martineau",
"author_id": 33952,
"author_profile": "https://Stackoverflow.com/users/33952",
"pm_score": 1,
"selected": false,
"text": "<p>std::getline allows you to read a line of text, and you can use a string stream to parse the individual line:</p>\n\n<pre><code>string buf;\ngetline(cin, buf); \nstringstream par(buf);\n\nchar buf2[512];\npar.getline(buf2, 512, ','); /* Reads until the first token. */\n</code></pre>\n\n<p>Once you get the line of text into the string, you can actually use any parsing function you want, even sscanf(buf.c_str(), \"%d,%d'%d\", &i1, &i2, &i3), by using atoi on the substring with the integer, or through some other method. </p>\n\n<p>You can also ignore unwanted characters in the input stream, if you know they're there:</p>\n\n<pre><code>if (cin.peek() == ',')\n cin.ignore(1, ',');\ncin >> nextInt; \n</code></pre>\n"
},
{
"answer_id": 267563,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 1,
"selected": false,
"text": "<p>If you don't mind using the Boost libraries...</p>\n\n<pre><code>#include <string>\n#include <vector>\n#include <boost/lexical_cast.hpp>\n#include <boost/regex.hpp>\n\nstd::vector<int> ParseFile(std::istream& in) {\n const boost::regex cItemPattern(\" *([0-9]+),?\");\n std::vector<int> return_value;\n\n std::string line;\n while (std::getline(in, line)) {\n string::const_iterator b=line.begin(), e=line.end();\n boost::smatch match;\n while (b!=e && boost::regex_search(b, e, match, cItemPattern)) {\n return_value.push_back(boost::lexical_cast<int>(match[1].str()));\n b=match[0].second;\n };\n };\n\n return return_value;\n}\n</code></pre>\n\n<p>That pulls the lines from the stream, then uses the Boost::RegEx library (with a capture group) to extract each number from the lines. It automatically ignores anything that isn't a valid number, though that can be changed if you wish.</p>\n\n<p>It's still about twenty lines with the <code>#include</code>s, but you can use it to extract essentially <em>anything</em> from the file's lines. This is a trivial example, I'm using pretty much identical code to extract tags and optional values from a database field, the only major difference is the regular expression.</p>\n\n<p>EDIT: Oops, you wanted three separate vectors. Try this slight modification instead:</p>\n\n<pre><code>const boost::regex cItemPattern(\" *([0-9]+), *([0-9]+), *([0-9]+)\");\nstd::vector<int> vector1, vector2, vector3;\n\nstd::string line;\nwhile (std::getline(in, line)) {\n string::const_iterator b=line.begin(), e=line.end();\n boost::smatch match;\n while (b!=e && boost::regex_search(b, e, match, cItemPattern)) {\n vector1.push_back(boost::lexical_cast<int>(match[1].str()));\n vector2.push_back(boost::lexical_cast<int>(match[2].str()));\n vector3.push_back(boost::lexical_cast<int>(match[3].str()));\n b=match[0].second;\n };\n};\n</code></pre>\n"
},
{
"answer_id": 267722,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 3,
"selected": false,
"text": "<p>There's no real need to use boost in this example as streams will do the trick nicely:</p>\n\n<pre><code>int main(int argc, char* argv[])\n{\n ifstream file(argv[1]);\n\n const unsigned maxIgnore = 10;\n const int delim = ',';\n int x,y,z;\n\n vector<int> vecx, vecy, vecz;\n\n while (file)\n {\n file >> x;\n file.ignore(maxIgnore, delim);\n file >> y;\n file.ignore(maxIgnore, delim);\n file >> z;\n\n vecx.push_back(x);\n vecy.push_back(y);\n vecz.push_back(z);\n }\n}\n</code></pre>\n\n<p>Though if I were going to use boost I'd prefer the simplicity of <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/tokenizer/tokenizer.htm\" rel=\"noreferrer\">tokenizer</a> to regex... :)</p>\n"
},
{
"answer_id": 267936,
"author": "ididak",
"author_id": 28888,
"author_profile": "https://Stackoverflow.com/users/28888",
"pm_score": 4,
"selected": true,
"text": "<p>There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:</p>\n\n<pre><code>FILE *fp = fopen(\"file.dat\", \"r\");\nint x, y, z;\nstd::vector<int> vx, vy, vz;\n\nwhile (fscanf(fp, \"%d, %d, %d\", &x, &y, &z) == 3) {\n vx.push_back(x);\n vy.push_back(y);\n vz.push_back(z);\n}\nfclose(fp);\n</code></pre>\n"
},
{
"answer_id": 267999,
"author": "da_m_n",
"author_id": 7165,
"author_profile": "https://Stackoverflow.com/users/7165",
"pm_score": 2,
"selected": false,
"text": "<p>why not the same code as in python :) ?</p>\n\n<pre><code>std::ifstream file(\"input_hard.dat\");\nstd::vector<int> inint, inbase, outbase;\n\nwhile (file.good()){\n int val1, val2, val3;\n char delim;\n file >> val1 >> delim >> val2 >> delim >> val3;\n\n inint.push_back(val1);\n inbase.push_back(val2);\n outbase.push_back(val3);\n}\n</code></pre>\n"
},
{
"answer_id": 268063,
"author": "David Pierre",
"author_id": 18296,
"author_profile": "https://Stackoverflow.com/users/18296",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to be able to scale to harder input formats, you should consider spirit, boost parser combinator library.</p>\n\n<p><a href=\"http://www.boost.org/doc/libs/1_37_0/libs/spirit/classic/doc/quick_start.html\" rel=\"nofollow noreferrer\">This page</a> has an example which almost do what you need (with reals and one vector though)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267427",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/338360/"
] |
I have a file with data listed as follows:
```
0, 2, 10
10, 8, 10
10, 10, 10
10, 16, 10
15, 10, 16
17, 10, 16
```
I want to be able to input the file and split it into three arrays, in the process trimming all excess spaces and converting each element to integers.
For some reason I can't find an easy way to do this in c++. The only success I've had is by inputting each line into an array, and then regexing out all the spaces and then splitting it up. This entire process took me a good 20-30 lines of code and its a pain to modify for say another separator(eg. space), etc.
This is the python equivalent of what I would like to have in C++:
```
f = open('input_hard.dat')
lines = f.readlines()
f.close()
#declarations
inint, inbase, outbase = [], [], []
#input parsing
for line in lines:
bits = string.split(line, ',')
inint.append(int(bits[0].strip()))
inbase.append(int(bits[1].strip()))
outbase.append(int(bits[2].strip()))
```
The ease of use of doing this in python is one of the reasons why I moved to it in the first place. However, I require to do this in C++ now and I would hate to have to use my ugly 20-30 line code.
Any help would be appreciated, thanks!
|
There is really nothing wrong with fscanf, which is probably the fastest solution in this case. And it's as short and readable as the python code:
```
FILE *fp = fopen("file.dat", "r");
int x, y, z;
std::vector<int> vx, vy, vz;
while (fscanf(fp, "%d, %d, %d", &x, &y, &z) == 3) {
vx.push_back(x);
vy.push_back(y);
vz.push_back(z);
}
fclose(fp);
```
|
267,436 |
<p>For example, if I have a <em>unicode</em> string, I can encode it as an <em>ASCII</em> string like so:</p>
<pre><code>>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'
</code></pre>
<p>However, I have e.g. this <em>ASCII</em> string:</p>
<pre><code>'\u003foo\u003e'
</code></pre>
<p>... that I want to turn into the same <em>ASCII</em> string as in my first example above:</p>
<pre><code>'<foo/>'
</code></pre>
|
[
{
"answer_id": 267444,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 0,
"selected": false,
"text": "<p>It's a little dangerous depending on where the string is coming from, but how about:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> eval('u\"'+s.replace('\"', r'\\\"')+'\"').encode('ascii')\n'<foo>'\n</code></pre>\n"
},
{
"answer_id": 267475,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 7,
"selected": true,
"text": "<p>It took me a while to figure this one out, but <a href=\"http://www.egenix.com/www2002/python/unicode-proposal.txt\" rel=\"noreferrer\">this page</a> had the best answer:</p>\n\n<pre><code>>>> s = '\\u003cfoo/\\u003e'\n>>> s.decode( 'unicode-escape' )\nu'<foo/>'\n>>> s.decode( 'unicode-escape' ).encode( 'ascii' )\n'<foo/>'\n</code></pre>\n\n<p>There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the \"Unicode Constructors\" section of the linked page for more details (since I'm not that Unicode-saavy).</p>\n\n<p>EDIT: See also <a href=\"http://www.python.org/doc/2.5.2/lib/standard-encodings.html\" rel=\"noreferrer\">Python Standard Encodings</a>.</p>\n"
},
{
"answer_id": 1750741,
"author": "Kaniabi",
"author_id": 212997,
"author_profile": "https://Stackoverflow.com/users/212997",
"pm_score": 2,
"selected": false,
"text": "<p>On Python 2.5 the correct encoding is \"unicode_escape\", not \"unicode-escape\" (note the underscore).</p>\n\n<p>I'm not sure if the newer version of Python changed the unicode name, but here only worked with the underscore. </p>\n\n<p>Anyway, this is it.</p>\n"
},
{
"answer_id": 11281948,
"author": "MakerDrone",
"author_id": 915372,
"author_profile": "https://Stackoverflow.com/users/915372",
"pm_score": 1,
"selected": false,
"text": "<p><em>Ned Batchelder</em> said:</p>\n\n<blockquote>\n <p>It's a little dangerous depending on where the string is coming from,\n but how about:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> eval('u\"'+s.replace('\"', r'\\\"')+'\"').encode('ascii')\n'<foo>'\n</code></pre>\n</blockquote>\n\n<p>Actually this method can be made safe like so:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> s_unescaped = eval('u\"\"\"'+s.replace('\"', r'\\\"')+'-\"\"\"')[:-1]\n</code></pre>\n\n<p>Mind the triple-quote string and the dash right before the closing 3-quotes.</p>\n\n<ol>\n<li>Using a 3-quoted string will ensure that if the user enters ' \\\\\" ' (spaces added for visual clarity) in the string it would not disrupt the evaluator;</li>\n<li>The dash at the end is a failsafe in case the user's string ends with a ' \\\" ' . Before we assign the result we slice the inserted dash with [:-1]</li>\n</ol>\n\n<p>So there would be no need to worry about what the users enter, as long as it is captured in raw format.</p>\n"
},
{
"answer_id": 22726482,
"author": "Okezie",
"author_id": 751528,
"author_profile": "https://Stackoverflow.com/users/751528",
"pm_score": 2,
"selected": false,
"text": "<p>At some point you will run into issues when you encounter special characters like Chinese characters or emoticons in a string you want to decode i.e. errors that look like this:</p>\n\n<pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 109-123: ordinal not in range(128)\n</code></pre>\n\n<p>For my case (twitter data processing), I decoded as follows to allow me to see all characters with no errors</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> s.decode( 'unicode-escape' ).encode( 'utf-8' )\n>>> <foo>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267436",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2168/"
] |
For example, if I have a *unicode* string, I can encode it as an *ASCII* string like so:
```
>>> u'\u003cfoo/\u003e'.encode('ascii')
'<foo/>'
```
However, I have e.g. this *ASCII* string:
```
'\u003foo\u003e'
```
... that I want to turn into the same *ASCII* string as in my first example above:
```
'<foo/>'
```
|
It took me a while to figure this one out, but [this page](http://www.egenix.com/www2002/python/unicode-proposal.txt) had the best answer:
```
>>> s = '\u003cfoo/\u003e'
>>> s.decode( 'unicode-escape' )
u'<foo/>'
>>> s.decode( 'unicode-escape' ).encode( 'ascii' )
'<foo/>'
```
There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy).
EDIT: See also [Python Standard Encodings](http://www.python.org/doc/2.5.2/lib/standard-encodings.html).
|
267,439 |
<p>Much related to <a href="https://stackoverflow.com/questions/245687/managing-reference-paths-between-x86-and-x64-workstations-in-a-team">this question</a>, we have a scenario on my team where we need to copy the contents of a folder for a suite of libraries and configuration files for said libraries to our folder where our test code is running from, as part of the test's deployment step.</p>
<p>Due to the installation size, and other factors, checking in this install folder into source control for sharing between team members just isn't viable.</p>
<p>The install path for the folder is either <strong>/Program Files/InternalTool/</strong> or <strong>/Program Files (x86)/InternalTool/</strong> depending on the installed environment. I want to setup my .testrunconfig file such that when a person gets the latest version of the solution, they don't have to worry about fixups for the path to the shared internal library suite.</p>
<p>Is there a way to make this seamless for all members involved, and if so, how could one accomplish this?</p>
<p>Restrictions are as follows:</p>
<ul>
<li>can't check in shared suite</li>
<li>shared suite has no override for installation path</li>
</ul>
<p>Is this possible, or am I asking for too much?</p>
|
[
{
"answer_id": 267444,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 0,
"selected": false,
"text": "<p>It's a little dangerous depending on where the string is coming from, but how about:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> eval('u\"'+s.replace('\"', r'\\\"')+'\"').encode('ascii')\n'<foo>'\n</code></pre>\n"
},
{
"answer_id": 267475,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 7,
"selected": true,
"text": "<p>It took me a while to figure this one out, but <a href=\"http://www.egenix.com/www2002/python/unicode-proposal.txt\" rel=\"noreferrer\">this page</a> had the best answer:</p>\n\n<pre><code>>>> s = '\\u003cfoo/\\u003e'\n>>> s.decode( 'unicode-escape' )\nu'<foo/>'\n>>> s.decode( 'unicode-escape' ).encode( 'ascii' )\n'<foo/>'\n</code></pre>\n\n<p>There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the \"Unicode Constructors\" section of the linked page for more details (since I'm not that Unicode-saavy).</p>\n\n<p>EDIT: See also <a href=\"http://www.python.org/doc/2.5.2/lib/standard-encodings.html\" rel=\"noreferrer\">Python Standard Encodings</a>.</p>\n"
},
{
"answer_id": 1750741,
"author": "Kaniabi",
"author_id": 212997,
"author_profile": "https://Stackoverflow.com/users/212997",
"pm_score": 2,
"selected": false,
"text": "<p>On Python 2.5 the correct encoding is \"unicode_escape\", not \"unicode-escape\" (note the underscore).</p>\n\n<p>I'm not sure if the newer version of Python changed the unicode name, but here only worked with the underscore. </p>\n\n<p>Anyway, this is it.</p>\n"
},
{
"answer_id": 11281948,
"author": "MakerDrone",
"author_id": 915372,
"author_profile": "https://Stackoverflow.com/users/915372",
"pm_score": 1,
"selected": false,
"text": "<p><em>Ned Batchelder</em> said:</p>\n\n<blockquote>\n <p>It's a little dangerous depending on where the string is coming from,\n but how about:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> eval('u\"'+s.replace('\"', r'\\\"')+'\"').encode('ascii')\n'<foo>'\n</code></pre>\n</blockquote>\n\n<p>Actually this method can be made safe like so:</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> s_unescaped = eval('u\"\"\"'+s.replace('\"', r'\\\"')+'-\"\"\"')[:-1]\n</code></pre>\n\n<p>Mind the triple-quote string and the dash right before the closing 3-quotes.</p>\n\n<ol>\n<li>Using a 3-quoted string will ensure that if the user enters ' \\\\\" ' (spaces added for visual clarity) in the string it would not disrupt the evaluator;</li>\n<li>The dash at the end is a failsafe in case the user's string ends with a ' \\\" ' . Before we assign the result we slice the inserted dash with [:-1]</li>\n</ol>\n\n<p>So there would be no need to worry about what the users enter, as long as it is captured in raw format.</p>\n"
},
{
"answer_id": 22726482,
"author": "Okezie",
"author_id": 751528,
"author_profile": "https://Stackoverflow.com/users/751528",
"pm_score": 2,
"selected": false,
"text": "<p>At some point you will run into issues when you encounter special characters like Chinese characters or emoticons in a string you want to decode i.e. errors that look like this:</p>\n\n<pre><code>UnicodeEncodeError: 'ascii' codec can't encode characters in position 109-123: ordinal not in range(128)\n</code></pre>\n\n<p>For my case (twitter data processing), I decoded as follows to allow me to see all characters with no errors</p>\n\n<pre><code>>>> s = '\\u003cfoo\\u003e'\n>>> s.decode( 'unicode-escape' ).encode( 'utf-8' )\n>>> <foo>\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14409/"
] |
Much related to [this question](https://stackoverflow.com/questions/245687/managing-reference-paths-between-x86-and-x64-workstations-in-a-team), we have a scenario on my team where we need to copy the contents of a folder for a suite of libraries and configuration files for said libraries to our folder where our test code is running from, as part of the test's deployment step.
Due to the installation size, and other factors, checking in this install folder into source control for sharing between team members just isn't viable.
The install path for the folder is either **/Program Files/InternalTool/** or **/Program Files (x86)/InternalTool/** depending on the installed environment. I want to setup my .testrunconfig file such that when a person gets the latest version of the solution, they don't have to worry about fixups for the path to the shared internal library suite.
Is there a way to make this seamless for all members involved, and if so, how could one accomplish this?
Restrictions are as follows:
* can't check in shared suite
* shared suite has no override for installation path
Is this possible, or am I asking for too much?
|
It took me a while to figure this one out, but [this page](http://www.egenix.com/www2002/python/unicode-proposal.txt) had the best answer:
```
>>> s = '\u003cfoo/\u003e'
>>> s.decode( 'unicode-escape' )
u'<foo/>'
>>> s.decode( 'unicode-escape' ).encode( 'ascii' )
'<foo/>'
```
There's also a 'raw-unicode-escape' codec to handle the other way to specify Unicode strings -- check the "Unicode Constructors" section of the linked page for more details (since I'm not that Unicode-saavy).
EDIT: See also [Python Standard Encodings](http://www.python.org/doc/2.5.2/lib/standard-encodings.html).
|
267,451 |
<p>I would like to read/write encrypted XML files using LINQ to XML. Does anyone know how to use encryption algorithms built into the .NET Framework to encrypt the Stream used by the XDocument object?</p>
<p>I did try it, but you can't set the CryptoStream to Read/Write access. It only support Read or Write, which causes LINQ to XML to throw an exception.</p>
<p>Update: It would be nice to read/write the document "on the fly", but I am only required to read the encrypted xml file, manipulate it, then write it back out encrypted again.</p>
|
[
{
"answer_id": 267713,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 4,
"selected": true,
"text": "<p>The easiest approach is probably an XDocument.Load(), Linq around, then XDocument.Save(). From a quick test app (go easy on non-disposed resources):</p>\n\n<pre><code>XDocument writeContacts = new XDocument(\n new XElement(\"contacts\",\n new XElement(\"contact\",\n new XElement(\"name\", \"Patrick Hines\"),\n new XElement(\"phone\", \"206-555-0144\",\n new XAttribute(\"type\", \"home\")),\n new XElement(\"phone\", \"425-555-0145\",\n new XAttribute(\"type\", \"work\")),\n new XElement(\"address\",\n new XElement(\"street1\", \"123 Main St\"),\n new XElement(\"city\", \"Mercer Island\"),\n new XElement(\"state\", \"WA\"),\n new XElement(\"postal\", \"68042\")\n )\n )\n )\n);\n\nRijndael RijndaelAlg = Rijndael.Create();\n\nFileStream writeStream = File.Open(\"data.xml\", FileMode.Create);\nCryptoStream cStream = new CryptoStream(writeStream,\n RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV),\n CryptoStreamMode.Write);\n\nStreamWriter writer = new StreamWriter(cStream);\n\nwriteContacts.Save(writer);\n\nwriter.Flush();\nwriter.Close();\n\nFileStream readStream = File.OpenRead(\"data.xml\");\n\ncStream = new CryptoStream(readStream,\n RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV),\n CryptoStreamMode.Read);\n\nXmlTextReader reader = new XmlTextReader(cStream);\n\nXDocument readContacts = XDocument.Load(reader);\n\n//manipulate with Linq and Save() when needed\n</code></pre>\n\n<p>Swap your favorite ICryptoTransform into the CryptoStream.</p>\n"
},
{
"answer_id": 267714,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "<p>[update: kudos to Corbin March, who (in the same time) wrote the same, but in code!]</p>\n\n<p>Most streams <em>are</em> one way. I imagine you'd have to:</p>\n\n<ul>\n<li>create a <code>CryptoStream</code> reading from the (file etc)</li>\n<li>read the data (for example into <code>XDocument</code>)</li>\n<li>do your code (read the document, make changes, etc)</li>\n<li>crate a new <code>CryptoStream</code> writing to the (file etc) [starting with the same IV etc)</li>\n<li>save the docuemnt to the stream</li>\n</ul>\n\n<p>Depending on what the underlying stream is (<code>FileStream</code>, <code>MemoryStream</code>, etc) you may well also have to completely close/re-open it between the read and write (i.e. the <code>CryptoStream</code> will probably feel ownership of the base-stream, and will <code>.Close()</code> it).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7831/"
] |
I would like to read/write encrypted XML files using LINQ to XML. Does anyone know how to use encryption algorithms built into the .NET Framework to encrypt the Stream used by the XDocument object?
I did try it, but you can't set the CryptoStream to Read/Write access. It only support Read or Write, which causes LINQ to XML to throw an exception.
Update: It would be nice to read/write the document "on the fly", but I am only required to read the encrypted xml file, manipulate it, then write it back out encrypted again.
|
The easiest approach is probably an XDocument.Load(), Linq around, then XDocument.Save(). From a quick test app (go easy on non-disposed resources):
```
XDocument writeContacts = new XDocument(
new XElement("contacts",
new XElement("contact",
new XElement("name", "Patrick Hines"),
new XElement("phone", "206-555-0144",
new XAttribute("type", "home")),
new XElement("phone", "425-555-0145",
new XAttribute("type", "work")),
new XElement("address",
new XElement("street1", "123 Main St"),
new XElement("city", "Mercer Island"),
new XElement("state", "WA"),
new XElement("postal", "68042")
)
)
)
);
Rijndael RijndaelAlg = Rijndael.Create();
FileStream writeStream = File.Open("data.xml", FileMode.Create);
CryptoStream cStream = new CryptoStream(writeStream,
RijndaelAlg.CreateEncryptor(RijndaelAlg.Key, RijndaelAlg.IV),
CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cStream);
writeContacts.Save(writer);
writer.Flush();
writer.Close();
FileStream readStream = File.OpenRead("data.xml");
cStream = new CryptoStream(readStream,
RijndaelAlg.CreateDecryptor(RijndaelAlg.Key, RijndaelAlg.IV),
CryptoStreamMode.Read);
XmlTextReader reader = new XmlTextReader(cStream);
XDocument readContacts = XDocument.Load(reader);
//manipulate with Linq and Save() when needed
```
Swap your favorite ICryptoTransform into the CryptoStream.
|
267,473 |
<p>The exception mentions</p>
<pre><code>FILE* __cdecl _getstream
</code></pre>
<p>I'm calling <code>fopen</code> and it keeps crashing. </p>
<pre><code>AfxMessageBox("getting here 1");
FILE* filePtr = fopen(fileName, "rb");
AfxMessageBox("getting here 2");
</code></pre>
<p>For some reason, I never get to the second message box. Interestingly, when I'm in debug mode, the app works perfectly. Why?</p>
|
[
{
"answer_id": 267739,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": -1,
"selected": false,
"text": "<p>I guess that something is wrong with fileName (does it have trailing zero ?)</p>\n\n<p>Try to comment <em>fopen</em> line out and see what will happen.</p>\n"
},
{
"answer_id": 267773,
"author": "Head Geek",
"author_id": 12193,
"author_profile": "https://Stackoverflow.com/users/12193",
"pm_score": 0,
"selected": false,
"text": "<p>I would suspect there's nothing wrong with that part of your program. The most likely scenario is that you've got some kind of memory corruption earlier in the code, and that just happens to be where it shows up.</p>\n\n<p>Have you tried running it through the rest of the program (after that part) in debug mode? If it <em>is</em> some kind of memory corruption, the debug-mode allocator should catch it when it goes to deallocate the corrupted areas of memory, if not sooner. Assuming you're using a compiler with a thorough debugging memory allocator, of course.</p>\n"
},
{
"answer_id": 272098,
"author": "Lou Franco",
"author_id": 3937,
"author_profile": "https://Stackoverflow.com/users/3937",
"pm_score": 2,
"selected": false,
"text": "<p>I think memory corruption. On Windows (which the __cdecl makes me think you are using), there is the gflags utility which comes with the Windows Debugging Tools. With it, you can make each heap allocation have it's own page -- this will help catch memory overruns and double freeing immediately at the point of the problem.</p>\n\n<p>I wrote up instructions on my blog:</p>\n\n<p><a href=\"http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx\" rel=\"nofollow noreferrer\">http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx</a></p>\n\n<p>There are other tips for finding this kind of bug there too.</p>\n"
},
{
"answer_id": 24874294,
"author": "ArtHare",
"author_id": 1158478,
"author_profile": "https://Stackoverflow.com/users/1158478",
"pm_score": 0,
"selected": false,
"text": "<p>I doubt this will affect many people since this is fairly obscure, but if you get your FILE* like this:</p>\n\n<pre><code>HANDLE hMyFile = CreateFile(...);\nFILE* pFile = _fdopen( _open_osfhandle((long)hMyFile, <flags>), \"rb\" );\nCloseHandle(hMyFile);\n</code></pre>\n\n<p>Then you'll leak a stream for each file you open. After doing _open_osfhandle and _fdopen, you must call fclose() on the pFile to close your handle. CloseHandle is apparently not smart enough to free the cruft that fdopen associates with your handle, but fclose is smart enough to close your handle along with the FILE*-related cruft.</p>\n\n<p>The app I was working on did this because a certain API passed around HANDLEs, and a particular implementor of the API needed a FILE*, so the implementor did the _fdopen/_open_osfhandle stuff to get a FILE*. However, this meant that the caller's CloseHandle call was insufficient to fully close the HANDLE. The fix was to duplicate the incoming HANDLE first, then the FILE* code could properly fclose() the FILE* without breaking the caller's HANDLE.</p>\n\n<p>Sample broken program:</p>\n\n<pre><code>#include \"stdafx.h\"\n#include <Windows.h>\n#include <io.h>\n#include <assert.h>\n#include <fcntl.h>\nint _tmain(int argc, _TCHAR* argv[])\n{\n\n for(int x = 0;x < 1024; x++)\n {\n HANDLE hFile = CreateFile(L\"c:\\\\temp\\\\rawdata.txt\",GENERIC_READ,FILE_SHARE_READ,NULL,OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);\n FILE* pFile = _fdopen( _open_osfhandle((long)hFile, _O_RDONLY | _O_BINARY), \"rb\" );\n assert(pFile); // this assert will go off at x=509, because _getstream() only has 512 streams, and 3 are reserved for stdin/stdout/stderr\n CloseHandle(hFile);\n }\n\n return 0;\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267473",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31325/"
] |
The exception mentions
```
FILE* __cdecl _getstream
```
I'm calling `fopen` and it keeps crashing.
```
AfxMessageBox("getting here 1");
FILE* filePtr = fopen(fileName, "rb");
AfxMessageBox("getting here 2");
```
For some reason, I never get to the second message box. Interestingly, when I'm in debug mode, the app works perfectly. Why?
|
I think memory corruption. On Windows (which the \_\_cdecl makes me think you are using), there is the gflags utility which comes with the Windows Debugging Tools. With it, you can make each heap allocation have it's own page -- this will help catch memory overruns and double freeing immediately at the point of the problem.
I wrote up instructions on my blog:
<http://www.atalasoft.com/cs/blogs/loufranco/archive/2007/02/06/6-_2200_Pointers_2200_-on-Debugging-Unmanaged-Code.aspx>
There are other tips for finding this kind of bug there too.
|
267,477 |
<p>I know that you can use a dummy "int" parameter on <code>operator++</code> and <code>operator--</code> to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did?</p>
<p>This was in my old Turbo C++ tutorial books, which I read when I was a teenager (i.e. a <em>long</em> time ago), so I might be completely misremembering it. That was also very early C++, before it was standardized, so it's possible that it was something Turbo C++-specific.</p>
|
[
{
"answer_id": 267482,
"author": "David Nehme",
"author_id": 14167,
"author_profile": "https://Stackoverflow.com/users/14167",
"pm_score": 3,
"selected": false,
"text": "<p>Either you are misremembering, or you should try to forget it. Destructors don't have parameters, return types and they shouldn't throw exceptions.</p>\n"
},
{
"answer_id": 267485,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 2,
"selected": false,
"text": "<p>I swear I've heard the same thing, but the <a href=\"http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.4\" rel=\"nofollow noreferrer\">C++ FAQ seems to say that there is no such form</a>. </p>\n"
},
{
"answer_id": 267505,
"author": "Thomas L Holaday",
"author_id": 29403,
"author_profile": "https://Stackoverflow.com/users/29403",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you are thinking of placement new?</p>\n\n<pre><code>class MyClass { /* ... */ };\n\nchar * raw_mem = new char [sizeof (MyClass)];\npMyClass = new (raw_mem) MyClass;\n// ...\npMyClass-->(~MyClass());\ndelete[] raw_mem;\n</code></pre>\n"
},
{
"answer_id": 267561,
"author": "puetzk",
"author_id": 14312,
"author_profile": "https://Stackoverflow.com/users/14312",
"pm_score": 4,
"selected": true,
"text": "<p>You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures:</p>\n\n<pre><code>void operator delete(void *, void *) throw();\nvoid operator delete(void *, const std::nothrow_t&) throw();\nvoid operator delete[](void *, void *) throw();\nvoid operator delete[](void *, const std::nothrow_t&) throw();\n</code></pre>\n\n<p>These are never called during normal operation, but would be used in the case where the constructor for an object being constructed with <a href=\"http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10\" rel=\"nofollow noreferrer\">placement new</a> throws an exception. Generally you don't have to define them, since the compiler already called the destructor(s) on the dead object's bases and members, and for placement new there's no memory to be freed. But can exist if you are overloading placement new and need a corresponding operator.</p>\n\n<p>The second argument is not really used, and just distinguishes the signature for the ordinary:</p>\n\n<pre><code>void operator delete(void *)\n</code></pre>\n\n<p>These aren't special dummy arguments the way the operator++ ones are, though. They're just an instance of the general rule that call to new with extra arguments, such as:</p>\n\n<pre><code>obj = new(x,y,z) Object(a,b,c) \n</code></pre>\n\n<p>will generate implicit code to clean up from constructor errors that passes those same additional arguments to the operator delete, which will function (approximately) like:</p>\n\n<pre><code>void *raw = operator new(sizeof(Object), x,y,z)\ntry {\n obj = new(raw) Object(a,b,c);\n} catch(...) {\n operator delete(raw,x,y,z);\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 300883,
"author": "mikeyk",
"author_id": 24389,
"author_profile": "https://Stackoverflow.com/users/24389",
"pm_score": 1,
"selected": false,
"text": "<p>You're not crazy. I have definitely seen an int parameter in a destructor before. Using HP's compiler on OpenVMS, I compiled a sample program show below. The list of symbols does include an destructor with an int parameter. I can only guess this is compiler specific.</p>\n\n<pre><code>$ create foo.cxx\nclass foo\n{\n ~foo() {}\n};\n\n$ cxx foo.cxx\n\n$ type [.CXX_REPOSITORY]cxx$demangler_db.\nCX3$_ZN3FOOD1EV31GNTHJ foo::$complete$~foo()\nCX3$_ZN3FOOD2EV30KQI3A foo::$subobject$~foo()\nCX3$_ZN3FOOD9EV36HH9SB foo::~foo(int)\nCXXL$_ZDLPV void operator delete(void *)\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12193/"
] |
I know that you can use a dummy "int" parameter on `operator++` and `operator--` to override the postfix versions of those operators, but I vaguely recall something about a dummy parameter that you could declare on a destructor. Does anyone know anything about that, and if so, what that dummy parameter did?
This was in my old Turbo C++ tutorial books, which I read when I was a teenager (i.e. a *long* time ago), so I might be completely misremembering it. That was also very early C++, before it was standardized, so it's possible that it was something Turbo C++-specific.
|
You're possibly thinking of the placement and nothrow forms of operator delete, which have the signatures:
```
void operator delete(void *, void *) throw();
void operator delete(void *, const std::nothrow_t&) throw();
void operator delete[](void *, void *) throw();
void operator delete[](void *, const std::nothrow_t&) throw();
```
These are never called during normal operation, but would be used in the case where the constructor for an object being constructed with [placement new](http://www.parashift.com/c++-faq-lite/dtors.html#faq-11.10) throws an exception. Generally you don't have to define them, since the compiler already called the destructor(s) on the dead object's bases and members, and for placement new there's no memory to be freed. But can exist if you are overloading placement new and need a corresponding operator.
The second argument is not really used, and just distinguishes the signature for the ordinary:
```
void operator delete(void *)
```
These aren't special dummy arguments the way the operator++ ones are, though. They're just an instance of the general rule that call to new with extra arguments, such as:
```
obj = new(x,y,z) Object(a,b,c)
```
will generate implicit code to clean up from constructor errors that passes those same additional arguments to the operator delete, which will function (approximately) like:
```
void *raw = operator new(sizeof(Object), x,y,z)
try {
obj = new(raw) Object(a,b,c);
} catch(...) {
operator delete(raw,x,y,z);
throw;
}
```
|
267,487 |
<p>I want to do something like this:</p>
<pre><code>SQL.Text := Format('select foo from bar where baz like ''%s%''',[SearchTerm]);
</code></pre>
<p>But Format doesn't like that last '%', of course. So how can I escape it? <code>\%</code>? <code>%%</code>? </p>
<p>Or do I have to do this:</p>
<pre><code>SQL.Text := Format('select foo from bar where baz like ''%s''',[SearchTerm+'%']);
</code></pre>
<p>?</p>
|
[
{
"answer_id": 267499,
"author": "moobaa",
"author_id": 3569,
"author_profile": "https://Stackoverflow.com/users/3569",
"pm_score": 3,
"selected": false,
"text": "<p>%% , IIRC.</p>\n"
},
{
"answer_id": 267506,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 6,
"selected": true,
"text": "<p>Use another % in the format string:</p>\n\n<pre><code>SQL.Text := Format('select foo from bar where baz like ''%s%%''',[SearchTerm]);\n</code></pre>\n"
},
{
"answer_id": 268227,
"author": "Ondrej Kelle",
"author_id": 11480,
"author_profile": "https://Stackoverflow.com/users/11480",
"pm_score": 2,
"selected": false,
"text": "<p>Obligatory:\n<a href=\"http://xkcd.com/327/\" rel=\"nofollow noreferrer\">http://xkcd.com/327/</a>\n:-)</p>\n\n<p>Depending on context, your approach might be vulnerable to SQL injection. If the search term comes from user input it would probably be better to use a parameterized query or at least try to sanitize the input.</p>\n"
},
{
"answer_id": 18956816,
"author": "Charmy Vora",
"author_id": 1309923,
"author_profile": "https://Stackoverflow.com/users/1309923",
"pm_score": 1,
"selected": false,
"text": "<p>Add 2 percent sign to have 1 single %<br>\nExample :</p>\n\n<pre><code> Format('select foo from bar where baz like ''%%%s%%'',[SearchString])\n</code></pre>\n\n<p>Gives you</p>\n\n<pre><code>select foo from bar where baz like '%SearchString%'\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/369/"
] |
I want to do something like this:
```
SQL.Text := Format('select foo from bar where baz like ''%s%''',[SearchTerm]);
```
But Format doesn't like that last '%', of course. So how can I escape it? `\%`? `%%`?
Or do I have to do this:
```
SQL.Text := Format('select foo from bar where baz like ''%s''',[SearchTerm+'%']);
```
?
|
Use another % in the format string:
```
SQL.Text := Format('select foo from bar where baz like ''%s%%''',[SearchTerm]);
```
|
267,488 |
<p>I'm having some trouble figuring out how to use more than one left outer join using LINQ to SQL. I understand how to use one left outer join. I'm using VB.NET. Below is my SQL syntax.</p>
<p><strong>T-SQL</strong></p>
<pre><code>SELECT
o.OrderNumber,
v.VendorName,
s.StatusName
FROM
Orders o
LEFT OUTER JOIN Vendors v ON
v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
s.Id = o.StatusId
WHERE
o.OrderNumber >= 100000 AND
o.OrderNumber <= 200000
</code></pre>
|
[
{
"answer_id": 267542,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 2,
"selected": false,
"text": "<p>I think you should be able to follow the method used in <a href=\"http://blogs.msdn.com/vbteam/archive/2008/01/31/converting-sql-to-linq-part-8-left-right-outer-join-bill-horst.aspx\" rel=\"nofollow noreferrer\">this</a> post. It looks really ugly, but I would think you could do it twice and get the result you want.</p>\n\n<p>I wonder if this is actually a case where you'd be better off using <code>DataContext.ExecuteCommand(...)</code> instead of converting to linq.</p>\n"
},
{
"answer_id": 267632,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 6,
"selected": false,
"text": "<p>Don't have access to VisualStudio (I'm on my Mac), but using the information from <a href=\"http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx\" rel=\"noreferrer\">http://bhaidar.net/cs/archive/2007/08/01/left-outer-join-in-linq-to-sql.aspx</a> it looks like you may be able to do something like this:</p>\n\n<pre><code>var query = from o in dc.Orders\n join v in dc.Vendors on o.VendorId equals v.Id into ov\n from x in ov.DefaultIfEmpty()\n join s in dc.Status on o.StatusId equals s.Id into os\n from y in os.DefaultIfEmpty()\n select new { o.OrderNumber, x.VendorName, y.StatusName }\n</code></pre>\n"
},
{
"answer_id": 268991,
"author": "Bryan Roth",
"author_id": 299,
"author_profile": "https://Stackoverflow.com/users/299",
"pm_score": 5,
"selected": false,
"text": "<p>I figured out how to use multiple left outer joins in VB.NET using LINQ to SQL:</p>\n\n<pre><code>Dim db As New ContractDataContext()\n\nDim query = From o In db.Orders _\n Group Join v In db.Vendors _\n On v.VendorNumber Equals o.VendorNumber _\n Into ov = Group _\n From x In ov.DefaultIfEmpty() _\n Group Join s In db.Status _\n On s.Id Equals o.StatusId Into os = Group _\n From y In os.DefaultIfEmpty() _\n Where o.OrderNumber >= 100000 And o.OrderNumber <= 200000 _\n Select Vendor_Name = x.Name, _\n Order_Number = o.OrderNumber, _\n Status_Name = y.StatusName\n</code></pre>\n"
},
{
"answer_id": 1971086,
"author": "Amir",
"author_id": 40914,
"author_profile": "https://Stackoverflow.com/users/40914",
"pm_score": 9,
"selected": true,
"text": "<p>This may be cleaner (<strong>you dont need all the <code>into</code> statements</strong>):</p>\n\n<pre><code>var query = \n from order in dc.Orders\n from vendor \n in dc.Vendors\n .Where(v => v.Id == order.VendorId)\n .DefaultIfEmpty()\n from status \n in dc.Status\n .Where(s => s.Id == order.StatusId)\n .DefaultIfEmpty()\n select new { Order = order, Vendor = vendor, Status = status } \n //Vendor and Status properties will be null if the left join is null\n</code></pre>\n\n<p>Here is another left join example</p>\n\n<pre><code>var results = \n from expense in expenseDataContext.ExpenseDtos\n where expense.Id == expenseId //some expense id that was passed in\n from category \n // left join on categories table if exists\n in expenseDataContext.CategoryDtos\n .Where(c => c.Id == expense.CategoryId)\n .DefaultIfEmpty() \n // left join on expense type table if exists\n from expenseType \n in expenseDataContext.ExpenseTypeDtos\n .Where(e => e.Id == expense.ExpenseTypeId)\n .DefaultIfEmpty()\n // left join on currency table if exists\n from currency \n in expenseDataContext.CurrencyDtos\n .Where(c => c.CurrencyID == expense.FKCurrencyID)\n .DefaultIfEmpty() \n select new \n { \n Expense = expense,\n // category will be null if join doesn't exist\n Category = category,\n // expensetype will be null if join doesn't exist\n ExpenseType = expenseType,\n // currency will be null if join doesn't exist\n Currency = currency \n }\n</code></pre>\n"
},
{
"answer_id": 12452159,
"author": "Mitul",
"author_id": 581922,
"author_profile": "https://Stackoverflow.com/users/581922",
"pm_score": 3,
"selected": false,
"text": "<p>In VB.NET using Function,</p>\n\n<pre><code>Dim query = From order In dc.Orders\n From vendor In \n dc.Vendors.Where(Function(v) v.Id = order.VendorId).DefaultIfEmpty()\n From status In \n dc.Status.Where(Function(s) s.Id = order.StatusId).DefaultIfEmpty()\n Select Order = order, Vendor = vendor, Status = status \n</code></pre>\n"
},
{
"answer_id": 47174324,
"author": "Iam ck",
"author_id": 7707003,
"author_profile": "https://Stackoverflow.com/users/7707003",
"pm_score": 0,
"selected": false,
"text": "<p>I am using this linq query for my application. if this match your requirement you can refer this. here i have joined(Left outer join) with 3 tables. </p>\n\n<pre><code> Dim result = (From csL In contractEntity.CSLogin.Where(Function(cs) cs.Login = login AndAlso cs.Password = password).DefaultIfEmpty\n From usrT In contractEntity.UserType.Where(Function(uTyp) uTyp.UserTypeID = csL.UserTyp).DefaultIfEmpty ' <== makes join left join\n From kunD In contractEntity.EmployeeMaster.Where(Function(kunDat) kunDat.CSLoginID = csL.CSLoginID).DefaultIfEmpty\n Select New With {\n .CSLoginID = csL.CSLoginID,\n .UserType = csL.UserTyp}).ToList()\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267488",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/299/"
] |
I'm having some trouble figuring out how to use more than one left outer join using LINQ to SQL. I understand how to use one left outer join. I'm using VB.NET. Below is my SQL syntax.
**T-SQL**
```
SELECT
o.OrderNumber,
v.VendorName,
s.StatusName
FROM
Orders o
LEFT OUTER JOIN Vendors v ON
v.Id = o.VendorId
LEFT OUTER JOIN Status s ON
s.Id = o.StatusId
WHERE
o.OrderNumber >= 100000 AND
o.OrderNumber <= 200000
```
|
This may be cleaner (**you dont need all the `into` statements**):
```
var query =
from order in dc.Orders
from vendor
in dc.Vendors
.Where(v => v.Id == order.VendorId)
.DefaultIfEmpty()
from status
in dc.Status
.Where(s => s.Id == order.StatusId)
.DefaultIfEmpty()
select new { Order = order, Vendor = vendor, Status = status }
//Vendor and Status properties will be null if the left join is null
```
Here is another left join example
```
var results =
from expense in expenseDataContext.ExpenseDtos
where expense.Id == expenseId //some expense id that was passed in
from category
// left join on categories table if exists
in expenseDataContext.CategoryDtos
.Where(c => c.Id == expense.CategoryId)
.DefaultIfEmpty()
// left join on expense type table if exists
from expenseType
in expenseDataContext.ExpenseTypeDtos
.Where(e => e.Id == expense.ExpenseTypeId)
.DefaultIfEmpty()
// left join on currency table if exists
from currency
in expenseDataContext.CurrencyDtos
.Where(c => c.CurrencyID == expense.FKCurrencyID)
.DefaultIfEmpty()
select new
{
Expense = expense,
// category will be null if join doesn't exist
Category = category,
// expensetype will be null if join doesn't exist
ExpenseType = expenseType,
// currency will be null if join doesn't exist
Currency = currency
}
```
|
267,530 |
<p>I have two tables that I would like to join but I am getting an error from MySQL</p>
<pre><code>Table: books
bookTagNum ShelfTagNum
book1 1
book2 2
book3 2
Table: shelf
shelfNum shelfTagNum
1 shelf1
2 shelf2
</code></pre>
<p>I want my results to be:</p>
<pre><code>bookTagNum ShelfTagNum shelfNum
book1 shelf1 1
book2 shelf2 2
book3 shelf2 2
</code></pre>
<p>but instead I am also getting an extra result:</p>
<pre><code>book1 shelf2 2
</code></pre>
<p>I think my query is doing a cross product instead of a join:</p>
<pre><code>SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , `books`.`title`
FROM books, shelf
where `books`.`shelfNum`=`books`.`shelfNum`
ORDER BY `shelf`.`shelfTagNum` ASC
LIMIT 0 , 30
</code></pre>
<p>What am I doing wrong?</p>
|
[
{
"answer_id": 267531,
"author": "Blair Conrad",
"author_id": 1199,
"author_profile": "https://Stackoverflow.com/users/1199",
"pm_score": 3,
"selected": false,
"text": "<p>I think you want</p>\n\n<pre><code>where `books`.`shelfTagNum`=`shelf`.`shelfNum`\n</code></pre>\n\n<p>In order to match rows from the <code>books</code> and <code>shelf</code> tables, you need to have terms from each in your <code>where</code> clause - otherwise, you're just performing a no-operation check on the rows of <code>books</code>, since every row's <code>shelfNum</code> will be equal to its <code>shelfNum</code>.</p>\n\n<p>As @fixme.myopenid.com suggests, you could also go the explicit <code>JOIN</code> route, but it's not necessary.</p>\n"
},
{
"answer_id": 267532,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 0,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , \n `books`.`title`\nFROM books, shelf\nwhere `books`.`shelftagNum`=`shelf`.`shelfNum`\nORDER BY `shelf`.`shelfTagNum` ASC\nLIMIT 0 , 30\n</code></pre>\n\n<p>Because the implicit JOIN condition was not properly stated the result was a cross product.</p>\n"
},
{
"answer_id": 267536,
"author": "Tor Haugen",
"author_id": 32050,
"author_profile": "https://Stackoverflow.com/users/32050",
"pm_score": 1,
"selected": false,
"text": "<p>Check your SQL. Your where clause cannot possibly be <code>books</code>.<code>shelfNum</code>=<code>books</code>.<code>shelfNum</code></p>\n\n<p>And what are all those single quotes for?</p>\n"
},
{
"answer_id": 267544,
"author": "Tor Haugen",
"author_id": 32050,
"author_profile": "https://Stackoverflow.com/users/32050",
"pm_score": 3,
"selected": false,
"text": "<p>if you want to be sure you're doing a join instead of a cross product, you should state it explicitly in the SQL, thus:</p>\n\n<pre><code>SELECT books.bookTagNum,books.shelfNum, shelf.shelfTagNum, books.title\nFROM books INNER JOIN shelf ON books.shelfNum = shelf.shelfTagNum\nORDER BY shelf.shelfTagNum\n</code></pre>\n\n<p>(which will return only those rows which exist in both tables), or:</p>\n\n<pre><code>SELECT books.bookTagNum,books.shelfNum, shelf.shelfTagNum, books.title\nFROM books LEFT OUTER JOIN shelf ON books.shelfNum = shelf.shelfTagNum\nORDER BY shelf.shelfTagNum\n</code></pre>\n\n<p>(which will return all rows from books), or:</p>\n\n<pre><code>SELECT books.bookTagNum,books.shelfNum, shelf.shelfTagNum, books.title\nFROM books RIGHT OUTER JOIN shelf ON books.shelfNum = shelf.shelfTagNum\nORDER BY shelf.shelfTagNum\n</code></pre>\n\n<p>(which will return all rows from shelf)</p>\n"
},
{
"answer_id": 267634,
"author": "Robert Paulson",
"author_id": 14033,
"author_profile": "https://Stackoverflow.com/users/14033",
"pm_score": 2,
"selected": false,
"text": "<p>FYI: If you rewrite your names to be consistent, things get a lot easier to read.</p>\n\n<pre><code>Table 1: Book\nBookID ShelfID BookName\n1 1 book1\n2 2 book2\n3 2 book3\n\nTable 2: Shelf\nShelfID ShelfName\n1 shelf1\n2 shelf2\n</code></pre>\n\n<p>now, a query to extract books to shelves is</p>\n\n<pre><code>SELECT \n b.BookName,\n s.ShelfName\nFROM\n Book b\nJOIN Shelf s ON s.ShelfID = b.ShelfID\n</code></pre>\n\n<hr>\n\n<p>To answer the original question:</p>\n\n<pre><code>> where `books`.`shelfNum`=`books`.`shelfNum`\n> ^^^^^--------------^^^^^------------- books repeated - this is an error\n</code></pre>\n\n<p>the <code>WHERE</code> clause, as written, does nothing, and because your where clause isn't limiting any rows, you are indeed getting the cross product.</p>\n"
},
{
"answer_id": 39905067,
"author": "Spechal",
"author_id": 427387,
"author_profile": "https://Stackoverflow.com/users/427387",
"pm_score": 0,
"selected": false,
"text": "<p>As others have mentioned, the problem you faced was with your ON condition. To specifically answer your question:</p>\n\n<p>In MySQL, if you omit a JOIN, an INNER JOIN/CROSS JOIN is used. For other databases, it is different. For example, PostgreSQL uses a CROSS JOIN, not an INNER JOIN.</p>\n\n<p>Re: <a href=\"http://dev.mysql.com/doc/refman/5.7/en/join.html\" rel=\"nofollow\">http://dev.mysql.com/doc/refman/5.7/en/join.html</a></p>\n\n<p>\"In MySQL, JOIN, CROSS JOIN, and INNER JOIN are syntactic equivalents (they can replace each other). In standard SQL, they are not equivalent. INNER JOIN is used with an ON clause, CROSS JOIN is used otherwise.\"</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267530",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28462/"
] |
I have two tables that I would like to join but I am getting an error from MySQL
```
Table: books
bookTagNum ShelfTagNum
book1 1
book2 2
book3 2
Table: shelf
shelfNum shelfTagNum
1 shelf1
2 shelf2
```
I want my results to be:
```
bookTagNum ShelfTagNum shelfNum
book1 shelf1 1
book2 shelf2 2
book3 shelf2 2
```
but instead I am also getting an extra result:
```
book1 shelf2 2
```
I think my query is doing a cross product instead of a join:
```
SELECT `books`.`bookTagNum` , `books`.`shelfNum` , `shelf`.`shelfTagNum` , `books`.`title`
FROM books, shelf
where `books`.`shelfNum`=`books`.`shelfNum`
ORDER BY `shelf`.`shelfTagNum` ASC
LIMIT 0 , 30
```
What am I doing wrong?
|
I think you want
```
where `books`.`shelfTagNum`=`shelf`.`shelfNum`
```
In order to match rows from the `books` and `shelf` tables, you need to have terms from each in your `where` clause - otherwise, you're just performing a no-operation check on the rows of `books`, since every row's `shelfNum` will be equal to its `shelfNum`.
As @fixme.myopenid.com suggests, you could also go the explicit `JOIN` route, but it's not necessary.
|
267,534 |
<p>I asked this question before, <a href="https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line">Here</a> however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again.</p>
<p>Is there a single-line native method in php that would allow me to do the following.
Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist <strong>natively in PHP</strong> that will <strong>grant me access to the array</strong> values directly <strong>without having to create a temporary array</strong>.</p>
<pre><code>$rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)};
</code></pre>
<p>This is a syntax error, however ideally it would be great if this worked!</p>
<p>Currently, it seems unavoidable that one must create a temporary array, ie</p>
<p><strong>The following is what I want to avoid:</strong></p>
<pre><code>$temporary_places_array = explode(",",loadFile("csvOf20000places.txt"));
$rand_place = $temporary_places_array[rand(0,1000)];
</code></pre>
<p>Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. <strong>I simply want access into the string without a temporary variable</strong>. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable.</p>
<p><strong>NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.</strong></p>
|
[
{
"answer_id": 267543,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p><strong>No, there is no way to do that natively.</strong></p>\n\n<p>You can, however:</p>\n\n<p>1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion.</p>\n\n<p>Also, don't forget you can <a href=\"http://php.net/unset\" rel=\"nofollow noreferrer\">unset()</a></p>\n\n<p>2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here.</p>\n\n<p>3.- Create a function.</p>\n"
},
{
"answer_id": 267545,
"author": "Matthew Scharley",
"author_id": 15537,
"author_profile": "https://Stackoverflow.com/users/15537",
"pm_score": 0,
"selected": false,
"text": "<p>If it's memory concerns, there are other ways of going about this that don't split out into an array. But no, there is nothing builtin to handle this sort of situation.</p>\n\n<p>As an alternative, you might try:</p>\n\n<pre><code>$pos = 0;\n$num = 0;\nwhile(($pos = strpos($places, ',', $pos+1)) !== false) {$num++;}\n$which = rand(0, $num);\n$num = 0;\nwhile($num <= $which) {$pos = strpos($places, ',', $pos+1);}\n$random_place = substr($places, $pos, strpos($places, ',', $pos+1));\n</code></pre>\n\n<p>I havn't tested this, so there may be a few off-by-one issues in it, but you get the idea. This could be made shorter (and quicker) by cacheing the positions that you work out in the first loop, but this brings you back to the memory issues.</p>\n"
},
{
"answer_id": 267552,
"author": "Paige Ruten",
"author_id": 813,
"author_profile": "https://Stackoverflow.com/users/813",
"pm_score": 1,
"selected": false,
"text": "<p>There is no native PHP method of doing this.</p>\n\n<p>You could make a function like this:</p>\n\n<pre><code>function array_value($array, $key) {\n return $array[$key];\n}\n</code></pre>\n\n<p>And then use it like this:</p>\n\n<pre><code>$places = \"alabama,alaska,arizona .... zimbabway\"; \n$random_place = array_value(explode(\",\", $places), rand(0, 1000));\n</code></pre>\n"
},
{
"answer_id": 267576,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 0,
"selected": false,
"text": "<p>You can do this:</p>\n\n<pre><code><?php\nfunction foo() {\n return new ArrayObject(explode(\",\", \"zero,one,two\"));\n}\necho foo()->offsetGet(1); // \"one\"\n?>\n</code></pre>\n\n<p>Sadly you <strong>can't</strong> do this:</p>\n\n<pre><code>echo (new ArrayObject(explode(\",\", \"zero,one,two\")))->offsetGet(2);\n</code></pre>\n"
},
{
"answer_id": 267606,
"author": "Jim Nelson",
"author_id": 32168,
"author_profile": "https://Stackoverflow.com/users/32168",
"pm_score": 1,
"selected": false,
"text": "<p>I know it's poor form to answer a question with a question, but why are you concerned about this? Is it a nitpick, or an optimization question? The Zend engine will optimize this away.</p>\n\n<p>However, I'd point out you don't have to create a temporary variable <em>necessarily</em>:</p>\n\n<pre><code>$rand_place = explode(\",\",loadFile(\"csvOf20000places.txt\"));\n$rand_place = $rand_place[rand(0,1000)];\n</code></pre>\n\n<p>Because of type mutability, you could reuse the variable. Of course, you're still not skipping a step.</p>\n"
},
{
"answer_id": 267611,
"author": "David",
"author_id": 9908,
"author_profile": "https://Stackoverflow.com/users/9908",
"pm_score": 0,
"selected": false,
"text": "<p>I spent a great deal of last year researching advanced CSV parsing for PHP and I admit it would be nice to randomly seek at will on a file. One of my semi-deadend's was to scan through a known file and make an index of the position of all known \\n's that were not at the beginning of the line. </p>\n\n<pre><code> //Grab and load our index\n$index = unserialize(file_get_contents('somefile.ext.ind'));\n//What it looks like\n$index = array( 0 => 83, 1 => 162, 2 => 178, ....);\n\n$fHandle = fopen(\"somefile.ext\",'RB');\n$randPos = rand(0, count($index));\nfseek($fHandle, $index[$randPos]);\n$line = explode(\",\", fgets($fHandle));\n</code></pre>\n\n<p>Tha's the only way I could see it being done anywhere close to what you need. As for creating the index, that's rudimentary stuff.</p>\n\n<pre><code>$fHandle = fopen('somefile.ext','rb');\n$index = array();\nfor($i = 0; false !== ($char = fgetc($fHandle)); $i++){\n if($char === \"\\n\") $index[] = $i; \n}\n</code></pre>\n"
},
{
"answer_id": 267616,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 1,
"selected": false,
"text": "<pre><code>list($rand_place) = array_slice(explode(',', loadFile(\"csvOf20000places.txt\")), array_rand(explode(',', loadFile(\"csvOf20000places.txt\"))), 1);\n</code></pre>\n\n<p><strong>EDIT:</strong> Ok, you're right. The question is <em>very</em> hard to understand but, I think this is it. The code above will pull random items from the csv file but, to just pull whatever you want out, use this:</p>\n\n<pre><code>list($rand_place) = array_slice(explode(',', loadFile(\"csvOf20000places.txt\")), {YOUR_NUMBER}, 1);\n</code></pre>\n\n<p>Replace the holder with the numeric key of the value you want to pull out.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267534",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34561/"
] |
I asked this question before, [Here](https://stackoverflow.com/questions/264441/does-a-native-php-5-function-exist-that-does-the-following-in-1-line) however I think I presented the problem poorly, and got quite a few replies that may have been useful to someone but did not address the actual question and so I pose the question again.
Is there a single-line native method in php that would allow me to do the following.
Please, please, I understand there are other ways to do this simple thing, but the question I present is does something exist **natively in PHP** that will **grant me access to the array** values directly **without having to create a temporary array**.
```
$rand_place = explode(",",loadFile("csvOf20000places.txt")){rand(0,1000)};
```
This is a syntax error, however ideally it would be great if this worked!
Currently, it seems unavoidable that one must create a temporary array, ie
**The following is what I want to avoid:**
```
$temporary_places_array = explode(",",loadFile("csvOf20000places.txt"));
$rand_place = $temporary_places_array[rand(0,1000)];
```
Also, i must note that my actual intentions are not to parse strings, or pull randomly from an array. **I simply want access into the string without a temporary variable**. This is just an example which i hope is easy to understand. There are many times service calls or things you do not have control over returns an array (such as the explode() function) and you just want access into it without having to create a temporary variable.
**NATIVELY NATIVELY NATIVELY, i know i can create a function that does it.**
|
**No, there is no way to do that natively.**
You can, however:
1.- Store the unavoidable array instead of the string. Given PHP's limitation this is what makes most sense in my opinion.
Also, don't forget you can [unset()](http://php.net/unset)
2.- Use strpos() and friends to parse the string into what you need, as shown in other answers I won't paste here.
3.- Create a function.
|
267,540 |
<p>I've met a really strange problem.</p>
<p>The code is as follow:</p>
<pre><code>::boost::shared_ptr<CQImageFileInfo> pInfo=CQUserViewDataManager::GetInstance()->GetImageFileInfo(nIndex);
Image* pImage=pInfo->m_pThumbnail;
if(pImage==NULL)
pImage=m_pStretchedDefaultThumbImage;
else
{
//
int sourceWidth = pInfo->GetWidth();
int sourceHeight = pInfo->GetHeight();
int destX = 0,
destY = 0;
float nPercent = 0;
float nPercentW = ((float)GetThumbImageWidth()/(float)sourceWidth);;
float nPercentH = ((float)GetThumbImageHeight()/(float)sourceHeight);
if(nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((GetThumbImageWidth() - (sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = (int)((GetThumbImageHeight() - (sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
rcShowImage=CRect(rc.left+destX, rc.top+destY,rc.left+destX+destWidth,rc.top+destY+destHeight);
}
ASSERT(pImage != NULL); // passed assertion...
graphics.DrawImage(pImage,rcShowImage.left,rcShowImage.top,
rcShowImage.Width(),rcShowImage.Height()); // problem happened here.
</code></pre>
<p>I received the following exception:</p>
<pre><code>First-chance exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
Unhandled exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
</code></pre>
<p>I have checked the <code>pImage</code>, I am sure when <code>graphics.DrawImage</code> is called, it is not <code>NULL</code>.</p>
<ul>
<li>why such a problem happened?</li>
<li>What is <code>0xfeeefef2</code>?</li>
</ul>
|
[
{
"answer_id": 267559,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 0,
"selected": false,
"text": "<p>What happens if <code>pImage == NULL</code> on the third line you pasted? In that case, <code>rcShowImage</code> is not assigned a value.</p>\n"
},
{
"answer_id": 267564,
"author": "Martin Cote",
"author_id": 9936,
"author_profile": "https://Stackoverflow.com/users/9936",
"pm_score": 2,
"selected": false,
"text": "<p>When you do</p>\n\n<pre><code>pImage=m_pStretchedDefaultThumbImage;\n</code></pre>\n\n<p>Is there a possibility that m_pStretchedDefaultThumbImage is uninitialized?</p>\n"
},
{
"answer_id": 267584,
"author": "bk1e",
"author_id": 8090,
"author_profile": "https://Stackoverflow.com/users/8090",
"pm_score": 4,
"selected": false,
"text": "<p><code>0xfeeefeee</code> is a fill pattern that the debug version of the Windows heap (not the C runtime heap) uses for uninitialized memory. <code>0xfeeefef2</code> is <code>0xfeeefeee+4</code>. It sounds like you're dereferencing an uninitialized pointer located in (or copied from) a block of memory allocated from the heap.</p>\n\n<p>The debug heap automatically gets enabled when you start your program in the debugger, as opposed to attaching to an already-running program with the debugger.</p>\n\n<p>The book <em><a href=\"http://www.advancedwindowsdebugging.com/\" rel=\"noreferrer\">Advanced Windows Debugging</a></em> by Mario Hewardt and Daniel Pravat has some decent information about the Windows heap, and it turns out that the chapter on heaps is <a href=\"http://www.advancedwindowsdebugging.com/ch06.pdf\" rel=\"noreferrer\">up on the web site as a sample chapter</a>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267540",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25749/"
] |
I've met a really strange problem.
The code is as follow:
```
::boost::shared_ptr<CQImageFileInfo> pInfo=CQUserViewDataManager::GetInstance()->GetImageFileInfo(nIndex);
Image* pImage=pInfo->m_pThumbnail;
if(pImage==NULL)
pImage=m_pStretchedDefaultThumbImage;
else
{
//
int sourceWidth = pInfo->GetWidth();
int sourceHeight = pInfo->GetHeight();
int destX = 0,
destY = 0;
float nPercent = 0;
float nPercentW = ((float)GetThumbImageWidth()/(float)sourceWidth);;
float nPercentH = ((float)GetThumbImageHeight()/(float)sourceHeight);
if(nPercentH < nPercentW)
{
nPercent = nPercentH;
destX = (int)((GetThumbImageWidth() - (sourceWidth * nPercent))/2);
}
else
{
nPercent = nPercentW;
destY = (int)((GetThumbImageHeight() - (sourceHeight * nPercent))/2);
}
int destWidth = (int)(sourceWidth * nPercent);
int destHeight = (int)(sourceHeight * nPercent);
rcShowImage=CRect(rc.left+destX, rc.top+destY,rc.left+destX+destWidth,rc.top+destY+destHeight);
}
ASSERT(pImage != NULL); // passed assertion...
graphics.DrawImage(pImage,rcShowImage.left,rcShowImage.top,
rcShowImage.Width(),rcShowImage.Height()); // problem happened here.
```
I received the following exception:
```
First-chance exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
Unhandled exception at 0x004095b0 in ec.exe: 0xC0000005: Access violation reading location 0xfeeefef2.
```
I have checked the `pImage`, I am sure when `graphics.DrawImage` is called, it is not `NULL`.
* why such a problem happened?
* What is `0xfeeefef2`?
|
`0xfeeefeee` is a fill pattern that the debug version of the Windows heap (not the C runtime heap) uses for uninitialized memory. `0xfeeefef2` is `0xfeeefeee+4`. It sounds like you're dereferencing an uninitialized pointer located in (or copied from) a block of memory allocated from the heap.
The debug heap automatically gets enabled when you start your program in the debugger, as opposed to attaching to an already-running program with the debugger.
The book *[Advanced Windows Debugging](http://www.advancedwindowsdebugging.com/)* by Mario Hewardt and Daniel Pravat has some decent information about the Windows heap, and it turns out that the chapter on heaps is [up on the web site as a sample chapter](http://www.advancedwindowsdebugging.com/ch06.pdf).
|
267,553 |
<p>Just to make this clear - what is the difference between:</p>
<pre><code>String(value)
</code></pre>
<p>and</p>
<pre><code>value as String
</code></pre>
<p>What are the cases where you would use one over the other? They seem interchangeable...</p>
|
[
{
"answer_id": 267568,
"author": "Randy Stegbauer",
"author_id": 34301,
"author_profile": "https://Stackoverflow.com/users/34301",
"pm_score": 4,
"selected": true,
"text": "<p>Casting with Type(variable) can cause a runtime exeception (RTE), while \"variable as type\" will return null instead of throwing an exception.</p>\n\n<p>See <a href=\"http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/\" rel=\"nofollow noreferrer\">http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/</a> for more explanations.</p>\n"
},
{
"answer_id": 268959,
"author": "RickDT",
"author_id": 5421,
"author_profile": "https://Stackoverflow.com/users/5421",
"pm_score": 1,
"selected": false,
"text": "<p>String (value) creates a new String object from a string literal. If the constructor argument is not a string literal, I assume it calls the argument object's .toString() method.</p>\n\n<p>value as String will simply pass back value IF value is a String or a subclass of String. It will pass back null if value is not of type String.</p>\n\n<p>The important thing to note is that String(val) creates a new object whereas value as String simply refers to value (and tests for compatibility to String).</p>\n\n<p><a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/String.html</a></p>\n\n<p><a href=\"http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/operators.html#as\" rel=\"nofollow noreferrer\">http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/operators.html#as</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3435/"
] |
Just to make this clear - what is the difference between:
```
String(value)
```
and
```
value as String
```
What are the cases where you would use one over the other? They seem interchangeable...
|
Casting with Type(variable) can cause a runtime exeception (RTE), while "variable as type" will return null instead of throwing an exception.
See <http://raghuonflex.wordpress.com/2007/07/27/casting-vs-the-as-operator/> for more explanations.
|
267,613 |
<p>Im trying to get into some basic JavaFX game development and I'm getting confused with some circle maths.</p>
<p>I have a circle at (x:250, y:250) with a radius of 50.</p>
<p>My objective is to make a smaller circle to be placed on the circumference of the above circle based on the position of the mouse.</p>
<p>Where Im getting confused is with the coordinate space and the Trig behind it all.</p>
<p>My issues come from the fact that the X/Y space on the screen is not centered at 0,0. But the top left of the screen is 0,0 and the bottom right is 500,500.</p>
<p>My calculations are:</p>
<pre><code>var xpos:Number = mouseEvent.getX();
var ypos:Number = mouseEvent.getY();
var center_pos_x:Number = 250;
var center_pos_y:Number = 250;
var length = ypos - center_pos_y;
var height = xpos - center_pos_x;
var angle_deg = Math.toDegrees(Math.atan(height / length));
var angle_rad = Math.toRadians(angle_deg);
var radius = 50;
moving_circ_xpos = (radius * Math.cos(angle_rad)) + center_pos_x;
moving_circ_ypos = (radius * Math.sin(angle_rad)) + center_pos_y;
</code></pre>
<p>I made the app print out the angle (angle_deg) that I have calculated when I move the mouse and my output is below:</p>
<p>When the mouse is (in degrees moving anti-clockwise):</p>
<ul>
<li>directly above the circle and horizontally inline with the center, the angle is -0</li>
<li>to the left and vertically centered, the angle is -90</li>
<li>directly below the circle and horizontally inline with the center, the angle is 0</li>
<li>to the right and vertically centered, the angle is 90</li>
</ul>
<p>So, what can I do to make it 0, 90, 180, 270??</p>
<p>I know it must be something small, but I just cant think of what it is...</p>
<p>Thanks for any help
(and no, this is not an assignment)</p>
|
[
{
"answer_id": 267622,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 3,
"selected": true,
"text": "<p><code>atan(height/length)</code> is not enough to get the angle. You need to compensate for each quadrant, as well as the possibility of \"division-by-zero\". Most programming language libraries supply a method called <code>atan2</code> which take two arguments; <code>y</code> and <code>x</code>. This method does this calculation for you.</p>\n\n<p>More information on <a href=\"http://en.wikipedia.org/wiki/Atan2\" rel=\"nofollow noreferrer\">Wikipedia: atan2</a></p>\n"
},
{
"answer_id": 267649,
"author": "Adam Liss",
"author_id": 29157,
"author_profile": "https://Stackoverflow.com/users/29157",
"pm_score": 2,
"selected": false,
"text": "<p>You can get away without calculating the angle. Instead, use the center of your circle (250,250) and the position of the mouse (xpos,ypos) to define a line. The line intersects your circle when its length is equal to the radius of your circle:</p>\n\n<pre>\n// Calculate distance from center to mouse.\nxlen = xpos - x_center_pos;\nylen = ypos - y_center_pos;\n\nline_len = sqrt(xlen*xlen + ylen*ylen); // Pythagoras: x^2 + y^2 = distance^2\n\n// Find the intersection with the circle.\nmoving_circ_xpos = x_center_pos + (xlen * radius / line_len);\nmoving_circ_ypos = y_center_pos + (ylen * radius / line_len);\n</pre>\n\n<p>Just verify that the mouse isn't at the center of your circle, or the line_len will be zero and the mouse will be sucked into a black hole.</p>\n"
},
{
"answer_id": 267662,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 0,
"selected": false,
"text": "<p>There's a <a href=\"https://rads.stackoverflow.com/amzn/click/com/0122861663\" rel=\"nofollow noreferrer\" rel=\"nofollow noreferrer\">great book called \"Graphics Gems\"</a> that can help with this kind of problem. It is a cookbook of algorithms and source code (in C I think), and allows you to quickly solve a problem using tested functionality. I would totally recommend getting your hands on it - it saved me big time when I quickly needed to add code to do fairly complex operations with normals to surfaces, and collision detections.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267613",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26310/"
] |
Im trying to get into some basic JavaFX game development and I'm getting confused with some circle maths.
I have a circle at (x:250, y:250) with a radius of 50.
My objective is to make a smaller circle to be placed on the circumference of the above circle based on the position of the mouse.
Where Im getting confused is with the coordinate space and the Trig behind it all.
My issues come from the fact that the X/Y space on the screen is not centered at 0,0. But the top left of the screen is 0,0 and the bottom right is 500,500.
My calculations are:
```
var xpos:Number = mouseEvent.getX();
var ypos:Number = mouseEvent.getY();
var center_pos_x:Number = 250;
var center_pos_y:Number = 250;
var length = ypos - center_pos_y;
var height = xpos - center_pos_x;
var angle_deg = Math.toDegrees(Math.atan(height / length));
var angle_rad = Math.toRadians(angle_deg);
var radius = 50;
moving_circ_xpos = (radius * Math.cos(angle_rad)) + center_pos_x;
moving_circ_ypos = (radius * Math.sin(angle_rad)) + center_pos_y;
```
I made the app print out the angle (angle\_deg) that I have calculated when I move the mouse and my output is below:
When the mouse is (in degrees moving anti-clockwise):
* directly above the circle and horizontally inline with the center, the angle is -0
* to the left and vertically centered, the angle is -90
* directly below the circle and horizontally inline with the center, the angle is 0
* to the right and vertically centered, the angle is 90
So, what can I do to make it 0, 90, 180, 270??
I know it must be something small, but I just cant think of what it is...
Thanks for any help
(and no, this is not an assignment)
|
`atan(height/length)` is not enough to get the angle. You need to compensate for each quadrant, as well as the possibility of "division-by-zero". Most programming language libraries supply a method called `atan2` which take two arguments; `y` and `x`. This method does this calculation for you.
More information on [Wikipedia: atan2](http://en.wikipedia.org/wiki/Atan2)
|
267,615 |
<p>Using jquery how do I focus the first element (edit field, text area, dropdown field, etc)
in the form when the page load?</p>
<p>Something like:</p>
<pre><code>document.forms[0].elements[0].focus();
</code></pre>
<p>but using jquery.</p>
<p>Another requirement, don't focus the first element when the form has class="filter".</p>
|
[
{
"answer_id": 267645,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 6,
"selected": false,
"text": "<pre><code>$('form:not(.filter) :input:visible:enabled:first').focus()\n</code></pre>\n\n<p>This will select the first visible input element (<code><input /></code>, <code><select></code>, <code><textarea></code>) that doesn't have the class <code>filter</code> in it.</p>\n"
},
{
"answer_id": 267646,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": false,
"text": "<p>I like to mark my chosen element with a class and select by class rather than leaving it up to the order of the elements on the page. I find this much easier than trying to remember to update my \"what's the real first element\" algorithm when selecting elements that may or may not be hidden, may or may not be injected by the framework, ...</p>\n\n<pre><code> $(document).ready( function() {\n $('input.js-initial-focus:first').focus(); // choose first just in case\n });\n</code></pre>\n"
},
{
"answer_id": 268076,
"author": "Zakaria",
"author_id": 3370,
"author_profile": "https://Stackoverflow.com/users/3370",
"pm_score": 6,
"selected": true,
"text": "<p>For the background I used the script in <em>ruby on rails</em> app.\nAfter trying all your answer and found out they all <strong>doesn't works</strong>,\nWith a search on google i found this snippet that <strong>works</strong>:</p>\n\n<pre><code>$(function() {\n $(\"form:not(.filter) :input:visible:enabled:first\").focus();\n});\n</code></pre>\n\n<p>It turn out <code>$('form :input:first')</code> match the hidden input that <em>rails</em> insert on every form.</p>\n"
},
{
"answer_id": 2321161,
"author": "stun",
"author_id": 138284,
"author_profile": "https://Stackoverflow.com/users/138284",
"pm_score": 2,
"selected": false,
"text": "<p>This is not a one line solution, but it takes into consideration of the <strong>real</strong> first user input field (may it be <input /> or <select> tag).</p>\n\n<p>You just have to tweak this a bit more and you get what you need.</p>\n\n<p>P.S: I have tested this code works in FireFox, Chrome, and IE6.</p>\n\n<pre><code>function focusFirstFormField() {\n try {\n var selector = $(\"#formid\");\n if (selector.length >= 1 && selector[0] && selector[0].elements && selector[0].elements.length > 0) {\n var elements = selector[0].elements;\n var length = elements.length;\n for (var i = 0; i < length; i++) {\n var elem = elements[i];\n var type = elem.type;\n\n // ignore images, hidden fields, buttons, and submit-buttons\n if (elem.style.display != \"none\" /* check for visible */ && type != \"image\" && type != \"hidden\" && type != \"button\" && type != \"submit\") {\n elem.focus();\n break;\n }\n }\n }\n }\n catch(err) { /* ignore error if any */ }\n}\n</code></pre>\n"
},
{
"answer_id": 7668717,
"author": "George",
"author_id": 421601,
"author_profile": "https://Stackoverflow.com/users/421601",
"pm_score": 0,
"selected": false,
"text": "<p>I had some problems with jQuery dialogs which were invisible on the page but were still selected by the selector:</p>\n\n<pre><code>$(\":text:visible:enabled:first\").focus();\n</code></pre>\n\n<p>After alot of playing around I finally came up with a solution that excluded all inputs in divs with a class of .dialog by adding a \".not() on the end. This may be useful to somebody else.\nThis is my selector:</p>\n\n<pre><code>$(\":text:visible:enabled:first\").not(\"div .dialog input\").focus();\n</code></pre>\n"
},
{
"answer_id": 18567102,
"author": "Avinash Saini",
"author_id": 2226601,
"author_profile": "https://Stackoverflow.com/users/2226601",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$(\"form\").find('input[type=text],textarea,select').filter(':visible:first').focus();\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3370/"
] |
Using jquery how do I focus the first element (edit field, text area, dropdown field, etc)
in the form when the page load?
Something like:
```
document.forms[0].elements[0].focus();
```
but using jquery.
Another requirement, don't focus the first element when the form has class="filter".
|
For the background I used the script in *ruby on rails* app.
After trying all your answer and found out they all **doesn't works**,
With a search on google i found this snippet that **works**:
```
$(function() {
$("form:not(.filter) :input:visible:enabled:first").focus();
});
```
It turn out `$('form :input:first')` match the hidden input that *rails* insert on every form.
|
267,618 |
<p>I've been trying to use Firebug's profiler to better understand the source of some JavaScript performance issues we are seeing, but I'm a little confused by the output.</p>
<p>When I profile some code the profiler reports <strong>Profile (464.323 ms, 26,412 calls)</strong>. I suspect that the 464.323 ms is the sum of the execution time for those 26,412 calls.</p>
<p>However, when I drill down into the detailed results I see individual results with an <em>average</em> execution time greater than 464.323 ms, e.g. the result with the highest average time reports the following details:</p>
<pre><code>Calls: **1**
Percent: **0%**
Own Time: **0.006 ms**
Time: **783.506 ms**
Avg: **783.506 ms**
Min: **783.506 ms**
Max: **783.506 ms**
</code></pre>
<p>Another result reports:</p>
<pre><code>Calls: **4**
Percent: **0.01%**
Own Time: **0.032 ms**
Time: **785.279 ms**
Avg: **196.32 ms**
Min: **0.012 ms**
Max: **783.741 ms**
</code></pre>
<p>Between these two results the sum of the Time results is a lot more than 464.323.</p>
<p>So, what do these various numbers mean? Which ones should I trust?</p>
|
[
{
"answer_id": 267865,
"author": "Gene",
"author_id": 22673,
"author_profile": "https://Stackoverflow.com/users/22673",
"pm_score": 3,
"selected": false,
"text": "<p>If I understand things correctly it goes something like this:</p>\n\n<p>On the first line you'll see that the Own time is \"only 0.006ms\". That means that even though time spent in that function was 783.506ms most of it was spent inside functions called from that function. </p>\n\n<p>When I use Firebug to optimize code I try to reduce the \"own time\" of functions that are called the most. (obviously checking also for any unnecessary function calls to remove altogether)</p>\n"
},
{
"answer_id": 601155,
"author": "Dan Lew",
"author_id": 60261,
"author_profile": "https://Stackoverflow.com/users/60261",
"pm_score": 6,
"selected": true,
"text": "<p>Each column has a description of what it means if you set your mouse to hover over it in Firebug. I'll assume you can read up on how each column works on your own then. However, you have definitely come across some odd behavior which needs to be explained.</p>\n\n<p>The <em>own time</em> is the amount of time the function spent executing code inside of itself. If the function calls no other functions, then <em>own time</em> should be the same as <em>time</em>. However, if there are nested function calls, then <em>time</em> also counts the time spent executing them. Therefore, <em>time</em> will almost always be larger than <em>own time</em>, and will in most cases add up to more than the total time reported by the profiler.</p>\n\n<p>However, no <strong>single</strong> function's <em>time</em> should be larger than the total time the profiler logged for JavaScript calls. This problem is definitely a bug, and I can see why you have trouble trusting Firebug when it gives you such a paradoxical output. I believe I've tracked down the reason this bug occurs: AJAX.</p>\n\n<p>It appears that AJAX calls are causing columns that count nested function calls to report incorrect information. They end up counting both the time of JavaScript execution <strong>and</strong> the request to the server.</p>\n\n<p>You can reproduce this profiler bug by doing the following:</p>\n\n<ol>\n<li>Go to any site that uses AJAX. (I used\n<a href=\"http://juicystudio.com/experiments/ajax/index.php\" rel=\"noreferrer\">http://juicystudio.com/experiments/ajax/index.php</a>)</li>\n<li>Enable Console/Script debugging.</li>\n<li>Turn on the profiler.</li>\n<li>Make an AJAX call. (Multiple ones may illuminate the issue more.)</li>\n<li>Stop the profiler, examine the output.</li>\n</ol>\n\n<p>In this example, with regards to <em>time</em> vs. <em>own time</em>, the <em>own time</em> of each function adds up to the profiler's total time but the <em>time</em> column incorporates the amount of time the AJAX call took to talk to the server. This means that the <em>time</em> column is incorrect if you're looking for just the speed of JavaScript execution.</p>\n\n<p>It gets worst: since <em>time</em>, <em>average time</em>, <em>min</em> and <em>max</em> all count nested function calls, they're all incorrect if you're using AJAX. On top of that, any function that eventually uses AJAX (in a nested function call) will also report their time incorrectly. This means that a whole lot of functions may be reporting incorrect information! So don't trust any of those columns for now until Firebug fixes the issue. (It's possible they intended the behavior to be this way, though it is confusing at best to leave it this way.)</p>\n\n<p>If you're not using AJAX, then another issue is at play; let us know if you are or not.</p>\n"
},
{
"answer_id": 601238,
"author": "Luis Melgratti",
"author_id": 17032,
"author_profile": "https://Stackoverflow.com/users/17032",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://michaelsync.net/2007/09/10/firebug-tutorial-logging-profiling-and-commandline-part-ii\" rel=\"nofollow noreferrer\">Firebug Tutorial - Logging, Profiling and CommandLine (Part II)</a>:\n(the examples there are good)</p>\n\n<blockquote>\n <p>Columns and Description of Profiler</p>\n \n <p><strong>Function column</strong> : It show the name of each function.<br>\n <strong>Call column</strong> : It shows the count of how many a particular function has been invoked. <br>\n <strong>Percent column</strong> : It shows the time consuming of each function in percentage.<br>\n <strong>Time column</strong> : It shows the duration of execution from start point of a function to the end point of a function. <br>\n <strong>Avg column</strong> : It shows the average execution time of a particular function. If you are calling a function one time only, you won’t see the differences. If you are calling more than one time, you will see the differences.<br>\n The formula for that column is<br>\n Avg = Own Ttime / Call;<br>\n <strong>Min column and Max column</strong>: It shows the minimum execution time of a particular function. <br>\n <strong>File column</strong>: the file name of file where the function located.<br></p>\n</blockquote>\n"
},
{
"answer_id": 11060650,
"author": "user1460126",
"author_id": 1460126,
"author_profile": "https://Stackoverflow.com/users/1460126",
"pm_score": 2,
"selected": false,
"text": "<p>From what I understand this is how it works... total profiler time is the sum of the 'Own Time' column. However, you may notice that some <strong>single</strong> Time values may be greater than the total profiler time. Those overtimes were spent outside of JavaScript, eg. in a plugin call. If your JS function makes a plugin call for eg., and waits for the plugin function to return to JS, then those waiting times will NOT be reported by the total profiler time, but will be included in the Time column.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267618",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1654/"
] |
I've been trying to use Firebug's profiler to better understand the source of some JavaScript performance issues we are seeing, but I'm a little confused by the output.
When I profile some code the profiler reports **Profile (464.323 ms, 26,412 calls)**. I suspect that the 464.323 ms is the sum of the execution time for those 26,412 calls.
However, when I drill down into the detailed results I see individual results with an *average* execution time greater than 464.323 ms, e.g. the result with the highest average time reports the following details:
```
Calls: **1**
Percent: **0%**
Own Time: **0.006 ms**
Time: **783.506 ms**
Avg: **783.506 ms**
Min: **783.506 ms**
Max: **783.506 ms**
```
Another result reports:
```
Calls: **4**
Percent: **0.01%**
Own Time: **0.032 ms**
Time: **785.279 ms**
Avg: **196.32 ms**
Min: **0.012 ms**
Max: **783.741 ms**
```
Between these two results the sum of the Time results is a lot more than 464.323.
So, what do these various numbers mean? Which ones should I trust?
|
Each column has a description of what it means if you set your mouse to hover over it in Firebug. I'll assume you can read up on how each column works on your own then. However, you have definitely come across some odd behavior which needs to be explained.
The *own time* is the amount of time the function spent executing code inside of itself. If the function calls no other functions, then *own time* should be the same as *time*. However, if there are nested function calls, then *time* also counts the time spent executing them. Therefore, *time* will almost always be larger than *own time*, and will in most cases add up to more than the total time reported by the profiler.
However, no **single** function's *time* should be larger than the total time the profiler logged for JavaScript calls. This problem is definitely a bug, and I can see why you have trouble trusting Firebug when it gives you such a paradoxical output. I believe I've tracked down the reason this bug occurs: AJAX.
It appears that AJAX calls are causing columns that count nested function calls to report incorrect information. They end up counting both the time of JavaScript execution **and** the request to the server.
You can reproduce this profiler bug by doing the following:
1. Go to any site that uses AJAX. (I used
<http://juicystudio.com/experiments/ajax/index.php>)
2. Enable Console/Script debugging.
3. Turn on the profiler.
4. Make an AJAX call. (Multiple ones may illuminate the issue more.)
5. Stop the profiler, examine the output.
In this example, with regards to *time* vs. *own time*, the *own time* of each function adds up to the profiler's total time but the *time* column incorporates the amount of time the AJAX call took to talk to the server. This means that the *time* column is incorrect if you're looking for just the speed of JavaScript execution.
It gets worst: since *time*, *average time*, *min* and *max* all count nested function calls, they're all incorrect if you're using AJAX. On top of that, any function that eventually uses AJAX (in a nested function call) will also report their time incorrectly. This means that a whole lot of functions may be reporting incorrect information! So don't trust any of those columns for now until Firebug fixes the issue. (It's possible they intended the behavior to be this way, though it is confusing at best to leave it this way.)
If you're not using AJAX, then another issue is at play; let us know if you are or not.
|
267,658 |
<p>I have the following table schema;</p>
<pre><code>CREATE TABLE `db1`.`sms_queue` (
`Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error',
`CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None',
`Phone` VARCHAR(14) DEFAULT NULL,
`Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`TriesLeft` tinyint NOT NULL DEFAULT 3,
PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;
</code></pre>
<p>It fails with the following error:</p>
<pre><code>ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.
</code></pre>
<p>My question is, can I have both of those fields? or do I have to manually set a LastUpdated field during each transaction?</p>
|
[
{
"answer_id": 267663,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 5,
"selected": false,
"text": "<p>You can have them both, just take off the \"CURRENT_TIMESTAMP\" flag on the created field. Whenever you create a new record in the table, just use \"NOW()\" for a value.</p>\n\n<p>Or.</p>\n\n<p>On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.</p>\n"
},
{
"answer_id": 267675,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 8,
"selected": true,
"text": "<p><a href=\"http://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html\" rel=\"noreferrer\">From the <strong>MySQL 5.5</strong> documentation</a>:</p>\n\n<blockquote>\n <p>One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. <strong>It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.</strong></p>\n</blockquote>\n\n<p><a href=\"http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html\" rel=\"noreferrer\">Changes in <strong>MySQL 5.6.5</strong></a>:</p>\n\n<blockquote>\n <p>Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. <strong>This restriction has been lifted.</strong> Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.</p>\n</blockquote>\n"
},
{
"answer_id": 807613,
"author": "Bogdan Gusiev",
"author_id": 91610,
"author_profile": "https://Stackoverflow.com/users/91610",
"pm_score": 7,
"selected": false,
"text": "<p><a href=\"http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/\" rel=\"noreferrer\">There is a trick</a> to have both timestamps, but with a little limitation.</p>\n\n<p>You can use only one of the definitions in one table. Create both timestamp columns like so: </p>\n\n<pre><code>create table test_table( \n id integer not null auto_increment primary key, \n stamp_created timestamp default '0000-00-00 00:00:00', \n stamp_updated timestamp default now() on update now() \n); \n</code></pre>\n\n<p>Note that it is necessary to enter <code>null</code> into both columns during <code>insert</code>:</p>\n\n<pre><code>mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); \nQuery OK, 1 row affected (0.06 sec)\n\nmysql> select * from test_table; \n+----+---------------------+---------------------+ \n| id | stamp_created | stamp_updated |\n+----+---------------------+---------------------+\n| 2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |\n+----+---------------------+---------------------+\n2 rows in set (0.00 sec) \n\nmysql> update test_table set id = 3 where id = 2; \nQuery OK, 1 row affected (0.05 sec) Rows matched: 1 Changed: 1 Warnings: 0 \n\nmysql> select * from test_table;\n+----+---------------------+---------------------+\n| id | stamp_created | stamp_updated | \n+----+---------------------+---------------------+ \n| 3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | \n+----+---------------------+---------------------+ \n2 rows in set (0.00 sec) \n</code></pre>\n"
},
{
"answer_id": 6470406,
"author": "webkraller",
"author_id": 814368,
"author_profile": "https://Stackoverflow.com/users/814368",
"pm_score": 5,
"selected": false,
"text": "<p>If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.</p>\n\n<pre><code>CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;\n</code></pre>\n\n<p>MySQL Reference: <a href=\"http://dev.mysql.com/doc/refman/5.0/en/triggers.html\" rel=\"noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/triggers.html</a></p>\n"
},
{
"answer_id": 16414306,
"author": "alien",
"author_id": 1611949,
"author_profile": "https://Stackoverflow.com/users/1611949",
"pm_score": 5,
"selected": false,
"text": "<p>This is how can you have automatic & flexible createDate/lastModified fields using triggers:</p>\n\n<p>First define them like this:</p>\n\n<pre><code>CREATE TABLE `entity` (\n `entityid` int(11) NOT NULL AUTO_INCREMENT,\n `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',\n `name` varchar(255) DEFAULT NULL,\n `comment` text,\n PRIMARY KEY (`entityid`),\n)\n</code></pre>\n\n<p>Then add these triggers:</p>\n\n<pre><code>DELIMITER ;;\nCREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;\nDELIMITER ;\nCREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);\n</code></pre>\n\n<ul>\n<li>If you <strong>insert</strong> without specifying createDate or lastModified, they will be equal and set to the current timestamp.</li>\n<li>If you <strong>update</strong> them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.</li>\n</ul>\n\n<p>But here's the nice part:</p>\n\n<ul>\n<li>If you <strong>insert</strong>, you can specify a <em>createDate older than the current timestamp</em>, allowing imports from older times to work well (lastModified will be equal to createDate).</li>\n<li>If you <strong>update</strong>, you can specify a <em>lastModified older than the previous value</em> ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to <strong>keep the old lastModified</strong> date. This will not modify the lastModified date.</li>\n</ul>\n"
},
{
"answer_id": 19984380,
"author": "Kingz",
"author_id": 1642266,
"author_profile": "https://Stackoverflow.com/users/1642266",
"pm_score": 2,
"selected": false,
"text": "<p>This issue seemed to have been resolved in MySQL 5.6. I have noticed this until MySQL 5.5; here is an example code:</p>\n\n<pre><code>DROP TABLE IF EXISTS `provider_org_group` ;\nCREATE TABLE IF NOT EXISTS `provider_org_group` (\n `id` INT NOT NULL,\n `name` VARCHAR(100) NOT NULL,\n `type` VARCHAR(100) NULL,\n `inserted` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,\n `insert_src_ver_id` INT NULL,\n `updated` TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,\n `update_src_ver_id` INT NULL,\n `version` INT NULL,\n PRIMARY KEY (`id`),\n UNIQUE INDEX `id_UNIQUE` (`id` ASC),\n UNIQUE INDEX `name_UNIQUE` (`name` ASC))\nENGINE = InnoDB;\n</code></pre>\n\n<p>Running this on MySQL 5.5 gives:</p>\n\n<pre><code>ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause\n</code></pre>\n\n<p>Running this on MySQL 5.6 </p>\n\n<pre><code>0 row(s) affected 0.093 sec\n</code></pre>\n"
},
{
"answer_id": 20347643,
"author": "Shaheen Ghiassy",
"author_id": 1179897,
"author_profile": "https://Stackoverflow.com/users/1179897",
"pm_score": 5,
"selected": false,
"text": "<p>As of MySQL 5.6 its easy-peasy... give it a try: </p>\n\n<pre><code>create table tweet ( \n id integer not null auto_increment primary key, \n stamp_created timestamp default now(), \n stamp_updated timestamp default now() on update now(),\n message varchar(163)\n)\n</code></pre>\n"
},
{
"answer_id": 35291337,
"author": "user5903005",
"author_id": 5903005,
"author_profile": "https://Stackoverflow.com/users/5903005",
"pm_score": 2,
"selected": false,
"text": "<pre><code>create table test_table( \nid integer not null auto_increment primary key, \nstamp_created timestamp default '0000-00-00 00:00:00', \nstamp_updated timestamp default now() on update now() \n); \n</code></pre>\n\n<p><a href=\"http://i.stack.imgur.com/LlQMS.png\" rel=\"nofollow\">source: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/</a></p>\n"
},
{
"answer_id": 49496049,
"author": "Nathan Prather",
"author_id": 44595,
"author_profile": "https://Stackoverflow.com/users/44595",
"pm_score": 0,
"selected": false,
"text": "<p>My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions: </p>\n\n<p><a href=\"http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/\" rel=\"nofollow noreferrer\">http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/</a></p>\n"
},
{
"answer_id": 50190396,
"author": "Josua Marcel C",
"author_id": 1562112,
"author_profile": "https://Stackoverflow.com/users/1562112",
"pm_score": 2,
"selected": false,
"text": "<p>i think this is the better query for stamp_created and stamp_updated</p>\n\n<pre><code>CREATE TABLE test_table( \n id integer not null auto_increment primary key, \n stamp_created TIMESTAMP DEFAULT now(), \n stamp_updated TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE now() \n); \n</code></pre>\n\n<p>because when the record created, <code>stamp_created</code> should be filled by <code>now()</code> and <code>stamp_updated</code> should be filled by <code>'0000-00-00 00:00:00'</code></p>\n"
},
{
"answer_id": 50860455,
"author": "Ioannis Chrysochos",
"author_id": 5796809,
"author_profile": "https://Stackoverflow.com/users/5796809",
"pm_score": 2,
"selected": false,
"text": "<p>For mysql 5.7.21 I use the following and works fine:</p>\n\n<p>CREATE TABLE <code>Posts</code> (\n <code>modified_at</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n <code>created_at</code> timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP\n) </p>\n"
},
{
"answer_id": 70290588,
"author": "Flash Noob",
"author_id": 12106367,
"author_profile": "https://Stackoverflow.com/users/12106367",
"pm_score": 2,
"selected": false,
"text": "<p>this will add two column for creation and updation.\nboth will get updated while inserting and updating.</p>\n<pre><code> create table users( \n id integer not null auto_increment primary key, \n created_date timestamp default now(), \n modified_date timestamp default now() on update now() \n ); \n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267658",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/264/"
] |
I have the following table schema;
```
CREATE TABLE `db1`.`sms_queue` (
`Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
`Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error',
`CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None',
`Phone` VARCHAR(14) DEFAULT NULL,
`Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
`LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
`TriesLeft` tinyint NOT NULL DEFAULT 3,
PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;
```
It fails with the following error:
```
ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.
```
My question is, can I have both of those fields? or do I have to manually set a LastUpdated field during each transaction?
|
[From the **MySQL 5.5** documentation](http://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html):
>
> One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. **It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.**
>
>
>
[Changes in **MySQL 5.6.5**](http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html):
>
> Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. **This restriction has been lifted.** Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT\_TIMESTAMP and ON UPDATE CURRENT\_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.
>
>
>
|
267,672 |
<p>I am trying to use native windows API with Qt using mingw toolset. There are link problems with some functions. What happens? Is this a bug with mingw name mangling?</p>
<pre><code>#ifdef Q_WS_WIN
HWND hwnd = QWidget::winId();
HDC hdcEMF = CreateEnhMetaFile(NULL, NULL, NULL, NULL ) ;
Rectangle(hdcEMF,100,100,200,200);
HENHMETAFILE hemf = CloseEnhMetaFile(hdcEMF);
OpenClipboard(hwnd);
EmptyClipboard();
SetClipboardData(CF_ENHMETAFILE,hemf);
CloseClipboard();
#else </code></pre>
<p>The errors:</p>
<p>undefined reference to `CreateEnhMetaFileW@16'</p>
<p>undefined reference to `Rectangle@20'</p>
<p>undefined reference to `CloseEnhMetaFile@4'</p>
|
[
{
"answer_id": 267678,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 3,
"selected": true,
"text": "<p>The functions <code>CreateEnhMetaFileW()</code> and <code>CloseEnhMetaFile()</code> are defined in the static library Gdi32.lib, so you have to make sure to link against that. Try adding <code>-lgdi32</code> to the end of your command line you're using to compile. If that doesn't work, you might have to specify the full path to Gdi32.lib by adding <code>-L/path/to/folder/containing/the/library -lgdi32</code> instead.</p>\n"
},
{
"answer_id": 267684,
"author": "Kieveli",
"author_id": 15852,
"author_profile": "https://Stackoverflow.com/users/15852",
"pm_score": 0,
"selected": false,
"text": "<p>It's possible that the functions are included, but getting mangled due to the C++ assumption.</p>\n\n<p>Look into the extern C { } declaration. It's intended to declare functions that should not be name mangled to account for polymorphism / overloading. (IE two functions with the same name).</p>\n"
},
{
"answer_id": 3670693,
"author": "torn",
"author_id": 340318,
"author_profile": "https://Stackoverflow.com/users/340318",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to use Windows API in a Qt app then there's no need to declare WinAPI functions extern \"C\", just include:</p>\n\n<pre><code>#include <qt_windows.h>\n</code></pre>\n\n<p>In your project file (.pro) add the libraries you use:</p>\n\n<pre><code>LIBS += -luser32 -lshell32 -lgdi32\n</code></pre>\n"
},
{
"answer_id": 4658524,
"author": "Samvid",
"author_id": 559296,
"author_profile": "https://Stackoverflow.com/users/559296",
"pm_score": 0,
"selected": false,
"text": "<p>@torn your solution worked for me. </p>\n\n<p>I wanted to use a win32 api call in my qt application.</p>\n\n<p>the #include \nthe #include your-win32-api-header</p>\n\n<p>and finally the LIBS += -llibrary name. </p>\n\n<p>Note that you might have to give -L for the right paths too.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19884/"
] |
I am trying to use native windows API with Qt using mingw toolset. There are link problems with some functions. What happens? Is this a bug with mingw name mangling?
```
#ifdef Q_WS_WIN
HWND hwnd = QWidget::winId();
HDC hdcEMF = CreateEnhMetaFile(NULL, NULL, NULL, NULL ) ;
Rectangle(hdcEMF,100,100,200,200);
HENHMETAFILE hemf = CloseEnhMetaFile(hdcEMF);
OpenClipboard(hwnd);
EmptyClipboard();
SetClipboardData(CF_ENHMETAFILE,hemf);
CloseClipboard();
#else
```
The errors:
undefined reference to `CreateEnhMetaFileW@16'
undefined reference to `Rectangle@20'
undefined reference to `CloseEnhMetaFile@4'
|
The functions `CreateEnhMetaFileW()` and `CloseEnhMetaFile()` are defined in the static library Gdi32.lib, so you have to make sure to link against that. Try adding `-lgdi32` to the end of your command line you're using to compile. If that doesn't work, you might have to specify the full path to Gdi32.lib by adding `-L/path/to/folder/containing/the/library -lgdi32` instead.
|
267,674 |
<p>Is it possible to inspect the return value of a function in gdb assuming the return value is <strong>not</strong> assigned to a variable?</p>
|
[
{
"answer_id": 267682,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, just examine the <code>EAX</code> register by typing <code>print $eax</code>. For most functions, the return value is stored in that register, even if it's not used.</p>\n\n<p>The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (<code>long long</code>), <code>double</code>s, and <code>structs</code> or <code>classes</code>.</p>\n\n<p>The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.</p>\n"
},
{
"answer_id": 267687,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 8,
"selected": true,
"text": "<p>I imagine there are better ways to do it, but the <a href=\"http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_6.html#SEC37\" rel=\"noreferrer\">finish</a> command executes until the current stack frame is popped off and prints the return value -- given the program</p>\n\n<pre><code>int fun() {\n return 42;\n}\n\nint main( int argc, char *v[] ) {\n fun();\n return 0;\n}\n</code></pre>\n\n<p>You can debug it as such --</p>\n\n<pre><code>(gdb) r\nStarting program: /usr/home/hark/a.out \n\nBreakpoint 1, fun () at test.c:2\n2 return 42;\n(gdb) finish\nRun till exit from #0 fun () at test.c:2\nmain () at test.c:7\n7 return 0;\nValue returned is $1 = 42\n(gdb) \n</code></pre>\n\n<p>The <code>finish</code> command can be abbreviated as <code>fin</code>. Do NOT use the <code>f</code>, which is abbreviation of <code>frame</code> command!</p>\n"
},
{
"answer_id": 1123107,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how todo this with no symbols.</p>\n\n<pre><code>gdb ls\nThis GDB was configured as \"ppc64-yellowdog-linux-gnu\"...\n(no debugging symbols found)\nUsing host libthread_db library \"/lib64/libthread_db.so.1\".\n\n(gdb) break __libc_start_main\nBreakpoint 1 at 0x10013cb0\n(gdb) r\nStarting program: /bin/ls\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\nBreakpoint 1 at 0xfdfed3c\n(no debugging symbols found)\n[Thread debugging using libthread_db enabled]\n[New Thread 4160418656 (LWP 10650)]\n(no debugging symbols found)\n(no debugging symbols found)\n[Switching to Thread 4160418656 (LWP 10650)]\n\nBreakpoint 1, 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6\n(gdb) info frame\nStack level 0, frame at 0xffd719a0:\n pc = 0xfdfed3c in __libc_start_main; saved pc 0x0\n called by frame at 0x0\n Arglist at 0xffd71970, args:\n Locals at 0xffd71970, Previous frame's sp is 0xffd719a0\n Saved registers:\n r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,\n r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,\n pc at 0xffd719a4, lr at 0xffd719a4\n(gdb) frame 0\n#0 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6\n(gdb) info fr\nStack level 0, frame at 0xffd719a0:\n pc = 0xfdfed3c in __libc_start_main; saved pc 0x0\n called by frame at 0x0\n Arglist at 0xffd71970, args:\n Locals at 0xffd71970, Previous frame's sp is 0xffd719a0\n Saved registers:\n r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,\n r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,\n pc at 0xffd719a4, lr at 0xffd719a4\n</code></pre>\n\n<p>Formatting kinda messed up there, note the use of \"info frame\" to inspect frames, and \"frame #\" to navigate your context to another context (up and down the stack)</p>\n\n<p>bt also show's an abbreviated stack to help out.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11688/"
] |
Is it possible to inspect the return value of a function in gdb assuming the return value is **not** assigned to a variable?
|
I imagine there are better ways to do it, but the [finish](http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_6.html#SEC37) command executes until the current stack frame is popped off and prints the return value -- given the program
```
int fun() {
return 42;
}
int main( int argc, char *v[] ) {
fun();
return 0;
}
```
You can debug it as such --
```
(gdb) r
Starting program: /usr/home/hark/a.out
Breakpoint 1, fun () at test.c:2
2 return 42;
(gdb) finish
Run till exit from #0 fun () at test.c:2
main () at test.c:7
7 return 0;
Value returned is $1 = 42
(gdb)
```
The `finish` command can be abbreviated as `fin`. Do NOT use the `f`, which is abbreviation of `frame` command!
|
267,685 |
<p>This question is regarding the performance issue in Mac OS X</p>
<p>Canvas3D object is embedded in a JPanel; then the panel is integrated with the rest of the Swing-built application. Within that Canvas I am rendering a simple cube by applying
certain transformations. At the initial launch It works fine. But when i try to resize the window or perform some operations on vertical or horizontal split bar buttons.Swing components take certain time to appear on the screen. A flashy white coloured thing appears first then swing components will appear? ( Totally saying flickering kind of stuff will happen). Is there any to solve this issue? </p>
<p>Kindly help me in this regard.</p>
<p>J3DSwinger</p>
|
[
{
"answer_id": 267682,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 6,
"selected": false,
"text": "<p>Yes, just examine the <code>EAX</code> register by typing <code>print $eax</code>. For most functions, the return value is stored in that register, even if it's not used.</p>\n\n<p>The exceptions to this are functions returning types larger than 32 bits, specifically 64-bit integers (<code>long long</code>), <code>double</code>s, and <code>structs</code> or <code>classes</code>.</p>\n\n<p>The other exception is if you're not running on an Intel architecture. In that case, you'll have to figure out which register is used, if any.</p>\n"
},
{
"answer_id": 267687,
"author": "hark",
"author_id": 34826,
"author_profile": "https://Stackoverflow.com/users/34826",
"pm_score": 8,
"selected": true,
"text": "<p>I imagine there are better ways to do it, but the <a href=\"http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_6.html#SEC37\" rel=\"noreferrer\">finish</a> command executes until the current stack frame is popped off and prints the return value -- given the program</p>\n\n<pre><code>int fun() {\n return 42;\n}\n\nint main( int argc, char *v[] ) {\n fun();\n return 0;\n}\n</code></pre>\n\n<p>You can debug it as such --</p>\n\n<pre><code>(gdb) r\nStarting program: /usr/home/hark/a.out \n\nBreakpoint 1, fun () at test.c:2\n2 return 42;\n(gdb) finish\nRun till exit from #0 fun () at test.c:2\nmain () at test.c:7\n7 return 0;\nValue returned is $1 = 42\n(gdb) \n</code></pre>\n\n<p>The <code>finish</code> command can be abbreviated as <code>fin</code>. Do NOT use the <code>f</code>, which is abbreviation of <code>frame</code> command!</p>\n"
},
{
"answer_id": 1123107,
"author": "RandomNickName42",
"author_id": 67819,
"author_profile": "https://Stackoverflow.com/users/67819",
"pm_score": 3,
"selected": false,
"text": "<p>Here's how todo this with no symbols.</p>\n\n<pre><code>gdb ls\nThis GDB was configured as \"ppc64-yellowdog-linux-gnu\"...\n(no debugging symbols found)\nUsing host libthread_db library \"/lib64/libthread_db.so.1\".\n\n(gdb) break __libc_start_main\nBreakpoint 1 at 0x10013cb0\n(gdb) r\nStarting program: /bin/ls\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\n(no debugging symbols found)\nBreakpoint 1 at 0xfdfed3c\n(no debugging symbols found)\n[Thread debugging using libthread_db enabled]\n[New Thread 4160418656 (LWP 10650)]\n(no debugging symbols found)\n(no debugging symbols found)\n[Switching to Thread 4160418656 (LWP 10650)]\n\nBreakpoint 1, 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6\n(gdb) info frame\nStack level 0, frame at 0xffd719a0:\n pc = 0xfdfed3c in __libc_start_main; saved pc 0x0\n called by frame at 0x0\n Arglist at 0xffd71970, args:\n Locals at 0xffd71970, Previous frame's sp is 0xffd719a0\n Saved registers:\n r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,\n r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,\n pc at 0xffd719a4, lr at 0xffd719a4\n(gdb) frame 0\n#0 0x0fdfed3c in __libc_start_main () from /lib/libc.so.6\n(gdb) info fr\nStack level 0, frame at 0xffd719a0:\n pc = 0xfdfed3c in __libc_start_main; saved pc 0x0\n called by frame at 0x0\n Arglist at 0xffd71970, args:\n Locals at 0xffd71970, Previous frame's sp is 0xffd719a0\n Saved registers:\n r24 at 0xffd71980, r25 at 0xffd71984, r26 at 0xffd71988, r27 at 0xffd7198c,\n r28 at 0xffd71990, r29 at 0xffd71994, r30 at 0xffd71998, r31 at 0xffd7199c,\n pc at 0xffd719a4, lr at 0xffd719a4\n</code></pre>\n\n<p>Formatting kinda messed up there, note the use of \"info frame\" to inspect frames, and \"frame #\" to navigate your context to another context (up and down the stack)</p>\n\n<p>bt also show's an abbreviated stack to help out.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This question is regarding the performance issue in Mac OS X
Canvas3D object is embedded in a JPanel; then the panel is integrated with the rest of the Swing-built application. Within that Canvas I am rendering a simple cube by applying
certain transformations. At the initial launch It works fine. But when i try to resize the window or perform some operations on vertical or horizontal split bar buttons.Swing components take certain time to appear on the screen. A flashy white coloured thing appears first then swing components will appear? ( Totally saying flickering kind of stuff will happen). Is there any to solve this issue?
Kindly help me in this regard.
J3DSwinger
|
I imagine there are better ways to do it, but the [finish](http://www.chemie.fu-berlin.de/chemnet/use/info/gdb/gdb_6.html#SEC37) command executes until the current stack frame is popped off and prints the return value -- given the program
```
int fun() {
return 42;
}
int main( int argc, char *v[] ) {
fun();
return 0;
}
```
You can debug it as such --
```
(gdb) r
Starting program: /usr/home/hark/a.out
Breakpoint 1, fun () at test.c:2
2 return 42;
(gdb) finish
Run till exit from #0 fun () at test.c:2
main () at test.c:7
7 return 0;
Value returned is $1 = 42
(gdb)
```
The `finish` command can be abbreviated as `fin`. Do NOT use the `f`, which is abbreviation of `frame` command!
|
267,693 |
<p>I have a .NET assembly that (for reasons outside my control) <em>must</em> be in the GAC. However, the same assembly is used by another program, which has a its own copy of an older version of the same assembly. It must use its own copy and not whatever is in the GAC. Proper versioning is probably more hassle than it's worth in this case, for reasons I won't go into. My questions is: <strong>is there anyway to tell .NET: just use THIS DLL, right here in this directory - ignore whatever you find in the GAC or anywhere else</strong>.</p>
|
[
{
"answer_id": 267710,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 2,
"selected": false,
"text": "<p>Have you tried Assembly.LoadFromFile()? This is a manual thing to do, but should load your assembly into memory before it is needed. .NET will then use the one in memory instead of hunting for it. </p>\n\n<p>Another way would be if the local assembly was unsigned, you could differentiate it that way.</p>\n\n<p>Rob</p>\n"
},
{
"answer_id": 267729,
"author": "Corbin March",
"author_id": 7625,
"author_profile": "https://Stackoverflow.com/users/7625",
"pm_score": 6,
"selected": false,
"text": "<p>Make sure the GAC Assembly and local Assembly have different version numbers (not a bad idea to let your build number, at least, auto-increment by wild-carding your AssemblyVersion in AssemblyInfo: [assembly: AssemblyVersion(\"1.0.0.*\")] ). Then, redirect your assembly binding using your app's config: </p>\n\n<ul>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/2fc472t2(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/2fc472t2(VS.80).aspx</a> </li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/433ysdt1(VS.80).aspx\" rel=\"noreferrer\">http://msdn.microsoft.com/en-us/library/433ysdt1(VS.80).aspx.</a></li>\n</ul>\n\n<p>In your case, you won't need the \"appliesTo\" attribute of the assemblyBinding config. You just need something like:</p>\n\n<pre><code><runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"YourAssembly\" publicKeyToken=\"AAAAAAAAAAAA\" culture=\"neutral\"/>\n <bindingRedirect oldVersion=\"0.0.0.0-5.2.1.0\" newVersion=\"5.0.8.1\"/>\n </dependentAssembly>\n </assemblyBinding>\n</runtime>\n</code></pre>\n"
},
{
"answer_id": 267745,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 5,
"selected": false,
"text": "<p>If they have the same version number the answer is you can't. If you attempt to load an assembly that has the same full assembly name (name, version, key) as a GAC'd assembly the CLR will pick the GAC'd assembly every single time. </p>\n"
},
{
"answer_id": 1037792,
"author": "Ying",
"author_id": 92494,
"author_profile": "https://Stackoverflow.com/users/92494",
"pm_score": 4,
"selected": false,
"text": "<p>You can set the DEVPATH to force load an assembly, see <a href=\"http://msdn.microsoft.com/en-us/library/cskzh7h6.aspx\" rel=\"noreferrer\">link text</a></p>\n\n<p>This doesn't answer your question since it only meant for development use and even then not really recommended as it doesn't mirror production usage. However I thought I'll share it anyway since it's good to know. </p>\n"
},
{
"answer_id": 25195931,
"author": "dasons",
"author_id": 2728644,
"author_profile": "https://Stackoverflow.com/users/2728644",
"pm_score": 2,
"selected": false,
"text": "<p>I had a similar issue. I changed the publicKeyToken of the target dll by using <code>ildasm</code> and <code>ilasm</code> to generate a new dll. I then updated it in the project reference to point to the new dll. The steps I took are <a href=\"https://stackoverflow.com/questions/1379954/how-i-do-a-sign-an-assembly-that-has-already-been-built-into-a-dll-specifically\">here</a>.</p>\n\n<p>This worked for me.</p>\n"
},
{
"answer_id": 52767635,
"author": "Charles Owen",
"author_id": 4151175,
"author_profile": "https://Stackoverflow.com/users/4151175",
"pm_score": 1,
"selected": false,
"text": "<p>One reason the binding redirect doesn't work is because the Oracle.ManagedDataAccess provider has a different search order for dlls than the unmanaged provider. The unmanaged provider starts in the application directory, then looks in the dllpath in the registry, then the dll path in machine.config, then dll path in web.config. According to the Oracle documentation, the search order for managed provider works like this:</p>\n\n<blockquote>\n <p>Managed Driver will reference these assemblies by using the following search order:</p>\n</blockquote>\n\n<ol>\n<li>Global Assembly Cache</li>\n<li>The web application's bin directory or Windows application's EXE directory </li>\n<li>The x86 or x64 subdirectory based on whether the application runs in 32-bit or 64-bit .NET Framework. If the application is built using AnyCPU, then ODP.NET will use the correct DLL bitness as long as the assembly is available. Oracle recommends using this method of finding dependent assemblies if your application is AnyCPU. </li>\n</ol>\n\n<p><a href=\"https://docs.oracle.com/en/database/oracle/oracle-database/12.2/odpnt/installODPmd.html#GUID-0E834EC7-21DF-4913-B712-2B0A07FD58FD\" rel=\"nofollow noreferrer\">https://docs.oracle.com/en/database/oracle/oracle-database/12.2/odpnt/installODPmd.html#GUID-0E834EC7-21DF-4913-B712-2B0A07FD58FD</a></p>\n\n<p>So the way to resolve this problem is to unregister the GAC assembly OR simply put a different version of Oracle.ManagedDataAccess in your bin and web.config than what's in GAC, if you can't uninstall it.</p>\n"
},
{
"answer_id": 72407162,
"author": "gharel",
"author_id": 1689023,
"author_profile": "https://Stackoverflow.com/users/1689023",
"pm_score": 0,
"selected": false,
"text": "<p>I change the name of the assembly in the GAC, put an "_" as the first character.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267693",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20336/"
] |
I have a .NET assembly that (for reasons outside my control) *must* be in the GAC. However, the same assembly is used by another program, which has a its own copy of an older version of the same assembly. It must use its own copy and not whatever is in the GAC. Proper versioning is probably more hassle than it's worth in this case, for reasons I won't go into. My questions is: **is there anyway to tell .NET: just use THIS DLL, right here in this directory - ignore whatever you find in the GAC or anywhere else**.
|
Make sure the GAC Assembly and local Assembly have different version numbers (not a bad idea to let your build number, at least, auto-increment by wild-carding your AssemblyVersion in AssemblyInfo: [assembly: AssemblyVersion("1.0.0.\*")] ). Then, redirect your assembly binding using your app's config:
* <http://msdn.microsoft.com/en-us/library/2fc472t2(VS.80).aspx>
* [http://msdn.microsoft.com/en-us/library/433ysdt1(VS.80).aspx.](http://msdn.microsoft.com/en-us/library/433ysdt1(VS.80).aspx)
In your case, you won't need the "appliesTo" attribute of the assemblyBinding config. You just need something like:
```
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="YourAssembly" publicKeyToken="AAAAAAAAAAAA" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.1.0" newVersion="5.0.8.1"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
```
|
267,704 |
<p>Is there an easy way to modify this code so that the target URL opens in the SAME window?</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>``</code></pre>
</div>
</div>
</p>
|
[
{
"answer_id": 267705,
"author": "Stephen Walcher",
"author_id": 25375,
"author_profile": "https://Stackoverflow.com/users/25375",
"pm_score": 3,
"selected": false,
"text": "<pre><code><a href=\"javascript:;\" onclick=\"window.location = 'http://example.com/submit.php?url=' + escape(document.location.href);'\">Go</a>;\n</code></pre>\n"
},
{
"answer_id": 267712,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 7,
"selected": true,
"text": "<p>The second parameter of <em>window.open()</em> is a string representing the name of the target window. </p>\n\n<p>Set it to: \"_self\".</p>\n\n<pre><code><a href=\"javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));\">click here</a>\n</code></pre>\n\n<p><br/>\n<strong>Sidenote:</strong>\nThe following question gives an overview of an arguably better way to bind event handlers to HTML links.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/266327/whats-the-best-way-to-replace-links-with-js-functions#266443\"><strong>What's the best way to replace links with js functions?</strong></a></p>\n"
},
{
"answer_id": 267775,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)</p>\n\n<pre><code>$(function() {\n $('a[href$=\"url=\"]') // all links whose href ends in \"url=\"\n .each(function(i, el) {\n this.href += escape(document.location.href);\n })\n ;\n});\n</code></pre>\n\n<p>and write your HTML like this:</p>\n\n<pre><code><a href=\"http://example.com/submit.php?url=\">...</a>\n</code></pre>\n\n<p>the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.</p>\n\n<p>All this said, it looks like you're using PHP... why not add it in server-side?</p>\n"
},
{
"answer_id": 5186883,
"author": "Brett Melton",
"author_id": 643739,
"author_profile": "https://Stackoverflow.com/users/643739",
"pm_score": 1,
"selected": false,
"text": "<p>So by adding the URL at the the end of the href, Each link will open in the same window? You could also probably use _BLANK within the HTML to do the same thing.</p>\n"
},
{
"answer_id": 6747873,
"author": "Valentine Nzekwe",
"author_id": 852055,
"author_profile": "https://Stackoverflow.com/users/852055",
"pm_score": 2,
"selected": false,
"text": "<p>try this it worked for me in ie 7 and ie 8</p>\n\n<pre><code> $(this).click(function (j) {\n var href = ($(this).attr('href'));\n window.location = href;\n return true;\n</code></pre>\n"
},
{
"answer_id": 7181778,
"author": "parwaze",
"author_id": 910527,
"author_profile": "https://Stackoverflow.com/users/910527",
"pm_score": 6,
"selected": false,
"text": "<pre><code><script type=\"text/javascript\">\nwindow.open ('YourNewPage.htm','_self',false)\n</script>\n</code></pre>\n\n<p>see reference:\n<a href=\"http://www.w3schools.com/jsref/met_win_open.asp\" rel=\"noreferrer\">http://www.w3schools.com/jsref/met_win_open.asp</a></p>\n"
},
{
"answer_id": 36172829,
"author": "Felceris Juozas",
"author_id": 5665432,
"author_profile": "https://Stackoverflow.com/users/5665432",
"pm_score": 2,
"selected": false,
"text": "<p>Here's what worked for me:</p>\n\n<pre><code><button name=\"redirect\" onClick=\"redirect()\">button name</button>\n<script type=\"text/javascript\">\nfunction redirect(){\nvar url = \"http://www.google.com\";\nwindow.open(url, '_top');\n}\n</script>\n</code></pre>\n"
},
{
"answer_id": 55719795,
"author": "Kamil Kiełczewski",
"author_id": 860099,
"author_profile": "https://Stackoverflow.com/users/860099",
"pm_score": 0,
"selected": false,
"text": "<p>try</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-html lang-html prettyprint-override\"><code><a href=\"#\" \r\n onclick=\"location='http://example.com/submit.php?url='+escape(location)\"\r\n >click here</a></code></pre>\r\n</div>\r\n</div>\r\n</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34964/"
] |
Is there an easy way to modify this code so that the target URL opens in the SAME window?
```html
<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>``
```
|
The second parameter of *window.open()* is a string representing the name of the target window.
Set it to: "\_self".
```
<a href="javascript:q=(document.location.href);void(open('http://example.com/submit.php?url='+escape(q),'_self','resizable,location,menubar,toolbar,scrollbars,status'));">click here</a>
```
**Sidenote:**
The following question gives an overview of an arguably better way to bind event handlers to HTML links.
[**What's the best way to replace links with js functions?**](https://stackoverflow.com/questions/266327/whats-the-best-way-to-replace-links-with-js-functions#266443)
|
267,707 |
<p>I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.</p>
<p>I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.</p>
<p>So, if this is my object:</p>
<pre><code>public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
</code></pre>
<p>I'd like my controller method to look something like this:</p>
<pre><code>public JsonResult Save(Widget widget)
{
...
}
</code></pre>
<p>Currently, my jQuery looks like this:</p>
<pre><code>var formData = $("#Form1").serializeArray();
$.post("/Widget/Save",
formData,
function(result){}, "json");
</code></pre>
<p>My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.</p>
<p>Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?</p>
|
[
{
"answer_id": 267731,
"author": "Sugendran",
"author_id": 22466,
"author_profile": "https://Stackoverflow.com/users/22466",
"pm_score": 2,
"selected": false,
"text": "<p>What you want to do is structure your javascript form object in the same way your backend object is structured:</p>\n\n<pre><code>{ Id : \"id\", Name : \"name\", Price : 1.0 }\n</code></pre>\n\n<p>Then use the toJSON plugin to convert it into the above string. You send this string to your backend and use something like the JayRock libraries to convert it to a new Widget object.</p>\n"
},
{
"answer_id": 268787,
"author": "Jeff Sheldon",
"author_id": 33910,
"author_profile": "https://Stackoverflow.com/users/33910",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.haacked.com\" rel=\"nofollow noreferrer\">Phil Haack</a> has <a href=\"http://www.haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx\" rel=\"nofollow noreferrer\">a good blog post</a> about model binding that might be helpful. Not 100% what you're talking about here, but I think it might give you a better overall understand about the DefaultModelBinder.</p>\n"
},
{
"answer_id": 269127,
"author": "MrDustpan",
"author_id": 34720,
"author_profile": "https://Stackoverflow.com/users/34720",
"pm_score": 6,
"selected": true,
"text": "<p>Thanks Jeff, that got me on the right path. The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type. In my haste, my type was defined as:</p>\n\n<pre><code>public class Widget\n{\n public int Id;\n public string Name;\n public decimal Price;\n}\n</code></pre>\n\n<p>Notice that the type has public fields instead of public properties. Once I changed those to properties, it worked. Here's the final source code that works correctly:</p>\n\n<p>Widget.aspx:</p>\n\n<pre><code><%@ Page Title=\"\" Language=\"C#\" MasterPageFile=\"~/Views/Shared/Site.Master\" AutoEventWireup=\"true\" CodeBehind=\"Widget.aspx.cs\" Inherits=\"MvcAjaxApp2.Views.Home.Widget\" %>\n<asp:Content ID=\"Content1\" ContentPlaceHolderID=\"MainContent\" runat=\"server\">\n <script src=\"../../Scripts/jquery-1.2.6.js\" type=\"text/javascript\"></script> \n <script type=\"text/javascript\"> \n function SaveWidget()\n {\n var formData = $(\"#Form1\").serializeArray();\n\n $.post(\"/Home/SaveWidget\",\n formData,\n function(data){\n alert(data.Result);\n }, \"json\");\n }\n </script>\n <form id=\"Form1\">\n <input type=\"hidden\" name=\"widget.Id\" value=\"1\" />\n <input type=\"text\" name=\"widget.Name\" value=\"my widget\" />\n <input type=\"text\" name=\"widget.Price\" value=\"5.43\" />\n <input type=\"button\" value=\"Save\" onclick=\"SaveWidget()\" />\n </form>\n</asp:Content>\n</code></pre>\n\n<p>HomeController.cs:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.Mvc;\nusing System.Web.Mvc.Ajax;\n\nnamespace MvcAjaxApp2.Controllers\n{\n [HandleError]\n public class HomeController : Controller\n {\n public ActionResult Index()\n {\n ViewData[\"Title\"] = \"Home Page\";\n ViewData[\"Message\"] = \"Welcome to ASP.NET MVC!\";\n return View();\n }\n\n public ActionResult About()\n {\n ViewData[\"Title\"] = \"About Page\";\n return View();\n }\n\n public ActionResult Widget()\n {\n ViewData[\"Title\"] = \"Widget\";\n return View();\n }\n\n public JsonResult SaveWidget(Widget widget)\n {\n // Save the Widget\n return Json(new { Result = String.Format(\"Saved widget: '{0}' for ${1}\", widget.Name, widget.Price) });\n }\n }\n public class Widget\n {\n public int Id { get; set; }\n public string Name { get; set; }\n public decimal Price { get; set; }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 463907,
"author": "Simon Sanderson",
"author_id": 57335,
"author_profile": "https://Stackoverflow.com/users/57335",
"pm_score": 3,
"selected": false,
"text": "<p>Note that (in <em>MrDustpan's</em> solution) the parameter <em>name</em> <strong>widget</strong> in the MVC Action method must match with the prefix used in the <em>name</em> attribute in the ASPX file.</p>\n\n<p>If this is not the case then the Action method will always receive a <strong>null</strong> object.</p>\n\n<pre><code><input type=\"text\" name=\"widget.Text\" value=\"Hello\" /> - OK\n<input type=\"text\" name=\"mywidget.Text\" value=\"Hello\" /> - FAILS\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34720/"
] |
I have a View that allows a user to enter/edit data for a new Widget. I'd like to form up that data into a json object and send it to my controller via AJAX so I can do the validation on the server without a postback.
I've got it all working, except I can't figure out how to pass the data so my controller method can accept a complex Widget type instead of individual parameters for each property.
So, if this is my object:
```
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
```
I'd like my controller method to look something like this:
```
public JsonResult Save(Widget widget)
{
...
}
```
Currently, my jQuery looks like this:
```
var formData = $("#Form1").serializeArray();
$.post("/Widget/Save",
formData,
function(result){}, "json");
```
My form (Form1) has an input field for each property on the Widget (Id, Name, Price). This works great, but it ultimately passes each property of the Widget as a separate parameter to my controller method.
Is there a way I could "intercept" the data, maybe using an ActionFilterAttribute, and deserialize it to a Widget object before my controller method gets called?
|
Thanks Jeff, that got me on the right path. The DefaultModelBinder is smart enough to do all the magic for me...my problem was in my Widget type. In my haste, my type was defined as:
```
public class Widget
{
public int Id;
public string Name;
public decimal Price;
}
```
Notice that the type has public fields instead of public properties. Once I changed those to properties, it worked. Here's the final source code that works correctly:
Widget.aspx:
```
<%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" AutoEventWireup="true" CodeBehind="Widget.aspx.cs" Inherits="MvcAjaxApp2.Views.Home.Widget" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<script src="../../Scripts/jquery-1.2.6.js" type="text/javascript"></script>
<script type="text/javascript">
function SaveWidget()
{
var formData = $("#Form1").serializeArray();
$.post("/Home/SaveWidget",
formData,
function(data){
alert(data.Result);
}, "json");
}
</script>
<form id="Form1">
<input type="hidden" name="widget.Id" value="1" />
<input type="text" name="widget.Name" value="my widget" />
<input type="text" name="widget.Price" value="5.43" />
<input type="button" value="Save" onclick="SaveWidget()" />
</form>
</asp:Content>
```
HomeController.cs:
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Ajax;
namespace MvcAjaxApp2.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Title"] = "Home Page";
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult About()
{
ViewData["Title"] = "About Page";
return View();
}
public ActionResult Widget()
{
ViewData["Title"] = "Widget";
return View();
}
public JsonResult SaveWidget(Widget widget)
{
// Save the Widget
return Json(new { Result = String.Format("Saved widget: '{0}' for ${1}", widget.Name, widget.Price) });
}
}
public class Widget
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}
}
```
|
267,719 |
<p>I just recently installed the MVC beta.
However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.</p>
<p>However, it has.</p>
<p>What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?</p>
|
[
{
"answer_id": 267762,
"author": "Raj",
"author_id": 219862,
"author_profile": "https://Stackoverflow.com/users/219862",
"pm_score": 3,
"selected": true,
"text": "<p>ASP.NET MVC beta is also bin-deployable, Move the following DLL's from GAC to the bin folder of your app</p>\n\n<pre><code>* System.Web.Mvc\n* System.Web.Routing\n* System.Web.Abstractions\n</code></pre>\n\n<p><a href=\"http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx\" rel=\"nofollow noreferrer\">Check this article for more information</a></p>\n"
},
{
"answer_id": 267798,
"author": "Brad Wilson",
"author_id": 1554,
"author_profile": "https://Stackoverflow.com/users/1554",
"pm_score": 2,
"selected": false,
"text": "<p>You'll need to force uninstall (gacutil /u /f System.Web.Mvc) the Beta DLL from the GAC, and then use bin deployment for all versions (including the beta).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
I just recently installed the MVC beta.
However, I assumed because the versioning numbers have changed and because it now uses the GAC instead of the bin folder that it wouldn't break existing applications.
However, it has.
What steps do I need to follow to ensure my existing preview 3 applications use a bin copy of the .dlls and are not broken by the installation of the beta?
|
ASP.NET MVC beta is also bin-deployable, Move the following DLL's from GAC to the bin folder of your app
```
* System.Web.Mvc
* System.Web.Routing
* System.Web.Abstractions
```
[Check this article for more information](http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx)
|
267,721 |
<p>I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'</p>
<p>Currently i am doing this:</p>
<pre><code>SELECT from_days(to_days(my_date))
</code></pre>
<p>Is there a proper way of doing this?</p>
|
[
{
"answer_id": 267732,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 9,
"selected": true,
"text": "<p>Yes, use the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date\" rel=\"noreferrer\">date</a> function:</p>\n\n<pre><code>SELECT date(my_date)\n</code></pre>\n"
},
{
"answer_id": 267733,
"author": "Andy Lester",
"author_id": 8454,
"author_profile": "https://Stackoverflow.com/users/8454",
"pm_score": 2,
"selected": false,
"text": "<p>In PostgreSQL you use the TRUNC() function, but I'm not seeing it for MySQL. From my brief Googling, it looks like you'll need to cast your DATETIME value to be just DATE.</p>\n\n<pre><code>date_col = CAST(NOW() AS DATE)\n</code></pre>\n\n<p>See <a href=\"http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html\" rel=\"nofollow noreferrer\">http://dev.mysql.com/doc/refman/5.0/en/date-and-time-types.html</a></p>\n"
},
{
"answer_id": 267743,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "<p><code>select date(somedate)</code> is the most common. </p>\n\n<p>If you need to accommodate other formats, you can use:</p>\n\n<pre><code>SELECT DATE_FORMAT(your_date, '%Y-%m-%d');\n</code></pre>\n"
},
{
"answer_id": 12590455,
"author": "Jupirao Bolado",
"author_id": 1617912,
"author_profile": "https://Stackoverflow.com/users/1617912",
"pm_score": -1,
"selected": false,
"text": "<p>You could use <code>ToShortDateString();</code></p>\n"
},
{
"answer_id": 16407166,
"author": "Rajeev Kumar",
"author_id": 1214848,
"author_profile": "https://Stackoverflow.com/users/1214848",
"pm_score": 0,
"selected": false,
"text": "<p>Just a simple way of doing it <code>date(\"d F Y\",strtotime($row['date']))</code> where <code>$row['date']</code> comes from your query</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24390/"
] |
I need to do a date comparison in Mysql without taking into account the time component i.e. i need to convert '2008-11-05 14:30:00' to '2008-11-05'
Currently i am doing this:
```
SELECT from_days(to_days(my_date))
```
Is there a proper way of doing this?
|
Yes, use the [date](http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html#function_date) function:
```
SELECT date(my_date)
```
|
267,724 |
<p>I'm writing code to do Xml serialization. With below function.</p>
<pre><code>public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
</code></pre>
<p>If the argument is a instance of class without parameterless constructor, it will throw a exception.</p>
<blockquote>
<p>Unhandled Exception:
System.InvalidOperationException:
CSharpConsole.Foo cannot be serialized
because it does not have a
parameterless constructor. at
System.Xml.Serialization.TypeDesc.CheckSupported()
at
System.Xml.Serialization.TypeScope.GetTypeDesc(Type
type, MemberInfo sourc e, Boolean
directReference, Boolean throwOnError)
at
System.Xml.Serialization.ModelScope.GetTypeModel(Type
type, Boolean direct Reference) at
System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type
type , XmlRootAttribute root, String
defaultNamespace) at
System.Xml.Serialization.XmlSerializer..ctor(Type
type, String defaultName space) at
System.Xml.Serialization.XmlSerializer..ctor(Type
type)</p>
</blockquote>
<p>Why must there be a parameterless constructor in order to allow xml serialization to succeed?</p>
<p>EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.</p>
|
[
{
"answer_id": 267727,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 9,
"selected": true,
"text": "<p>During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.</p>\n\n<p>You can make your constructor <code>private</code> or <code>internal</code> if you want, just so long as it's parameterless.</p>\n"
},
{
"answer_id": 267734,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, this what is written in <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.serialization.ixmlserializable.aspx\" rel=\"nofollow noreferrer\">documentation</a>. I think it is one of your class fields, not the main one - and how you want deserialiser to construct it back w/o parameterless construction ? </p>\n\n<p>I think there is a workaround to make constructor private.</p>\n"
},
{
"answer_id": 267904,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": false,
"text": "<p>This is a limitation of <code>XmlSerializer</code>. Note that <code>BinaryFormatter</code> and <code>DataContractSerializer</code> <em>do not</em> require this - they can create an uninitialized object out of the ether and initialize it during deserialization.</p>\n\n<p>Since you are using xml, you might consider using <code>DataContractSerializer</code> and marking your class with <code>[DataContract]</code>/<code>[DataMember</code>], but note that this changes the schema (for example, there is no equivalent of <code>[XmlAttribute]</code> - everything becomes elements).</p>\n\n<p>Update: if you really want to know, <code>BinaryFormatter</code> et al use <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.formatterservices.getuninitializedobject.aspx\" rel=\"noreferrer\"><code>FormatterServices.GetUninitializedObject()</code></a> to create the object without invoking the constructor. Probably dangerous; I don't recommend using it too often ;-p See also the remarks on MSDN:</p>\n\n<blockquote>\n <p>Because the new instance of the object\n is initialized to zero and no\n constructors are run, the object might\n not represent a state that is regarded\n as valid by that object. The current\n method should only be used for\n deserialization when the user intends\n to immediately populate all fields. It\n does not create an uninitialized\n string, since creating an empty\n instance of an immutable type serves\n no purpose.</p>\n</blockquote>\n\n<p>I have my <a href=\"http://code.google.com/p/protobuf-net/\" rel=\"noreferrer\">own</a> serialization engine, but I don't intend making it use <code>FormatterServices</code>; I quite like knowing that a constructor (<em>any</em> constructor) has actually executed.</p>\n"
},
{
"answer_id": 58674797,
"author": "Mike Nakis",
"author_id": 773113,
"author_profile": "https://Stackoverflow.com/users/773113",
"pm_score": 3,
"selected": false,
"text": "<p>The answer is: <strong><em>for no good reason whatsoever.</em></strong></p>\n\n<p>Contrary to its name, the <code>XmlSerializer</code> class is used not only for serialization, but also for deserialization. It performs certain checks on your class to make sure that it will work, and some of those checks are only pertinent to deserialization, but it performs them all anyway, because it does not know what you intend to do later on.</p>\n\n<p>The check that your class fails to pass is one of the checks that are only pertinent to deserialization. Here is what happens:</p>\n\n<ul>\n<li><p>During deserialization, the <code>XmlSerializer</code> class will need to create\ninstances of your type. </p></li>\n<li><p>In order to create an instance of a type, a constructor of that type\nneeds to be invoked. </p></li>\n<li><p>If you did not declare a constructor, the compiler has already\nsupplied a default parameterless constructor, but if you did declare\na constructor, then that's the only constructor available.</p></li>\n<li><p>So, if the constructor that you declared accepts parameters, then the\nonly way to instantiate your class is by invoking that constructor\nwhich accepts parameters.</p></li>\n<li><p>However, <code>XmlSerializer</code> is not capable of invoking any constructor\nexcept a parameterless constructor, because it does not know what\nparameters to pass to constructors that accept parameters. So, it checks to see if your class has a parameterless constructor, and since it does not, it fails.</p></li>\n</ul>\n\n<p>So, if the <code>XmlSerializer</code> class had been written in such a way as to only perform the checks pertinent to serialization, then your class would pass, because there is absolutely nothing about serialization that makes it necessary to have a parameterless constructor. </p>\n\n<p>As others have already pointed out, the quick solution to your problem is to simply add a parameterless constructor. Unfortunately, it is also a dirty solution, because it means that you cannot have any <code>readonly</code> members initialized from constructor parameters.</p>\n\n<p>In addition to all this, the <code>XmlSerializer</code> class <em>could</em> have been written in such a way as to allow even deserialization of classes without parameterless constructors. All it would take would be to make use of <a href=\"https://en.wikipedia.org/wiki/Factory_method_pattern\" rel=\"noreferrer\">\"The Factory Method Design Pattern\" (Wikipedia)</a>. From the looks of it, Microsoft decided that this design pattern is far too advanced for DotNet programmers, who apparently should not be unnecessarily confused with such things. So, DotNet programmers should better stick to parameterless constructors, according to Microsoft.</p>\n"
},
{
"answer_id": 72314333,
"author": "swissmawi",
"author_id": 8444429,
"author_profile": "https://Stackoverflow.com/users/8444429",
"pm_score": 2,
"selected": false,
"text": "<p>Seems nobody actually read the original post... it is about SERIALIZATION and not DE-... and for this, no constructors are needed or called at all. The issue is simply poor coding practice from Microsoft.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26349/"
] |
I'm writing code to do Xml serialization. With below function.
```
public static string SerializeToXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
using (StringWriter writer = new StringWriter())
{
serializer.Serialize(writer, obj);
return writer.ToString();
}
}
```
If the argument is a instance of class without parameterless constructor, it will throw a exception.
>
> Unhandled Exception:
> System.InvalidOperationException:
> CSharpConsole.Foo cannot be serialized
> because it does not have a
> parameterless constructor. at
> System.Xml.Serialization.TypeDesc.CheckSupported()
> at
> System.Xml.Serialization.TypeScope.GetTypeDesc(Type
> type, MemberInfo sourc e, Boolean
> directReference, Boolean throwOnError)
> at
> System.Xml.Serialization.ModelScope.GetTypeModel(Type
> type, Boolean direct Reference) at
> System.Xml.Serialization.XmlReflectionImporter.ImportTypeMapping(Type
> type , XmlRootAttribute root, String
> defaultNamespace) at
> System.Xml.Serialization.XmlSerializer..ctor(Type
> type, String defaultName space) at
> System.Xml.Serialization.XmlSerializer..ctor(Type
> type)
>
>
>
Why must there be a parameterless constructor in order to allow xml serialization to succeed?
EDIT: thanks for cfeduke's answer. The parameterless constructor can be private or internal.
|
During an object's de-serialization, the class responsible for de-serializing an object creates an instance of the serialized class and then proceeds to populate the serialized fields and properties only after acquiring an instance to populate.
You can make your constructor `private` or `internal` if you want, just so long as it's parameterless.
|
267,750 |
<p>What is the difference in the accessibility of the following variables in Java?</p>
<pre><code>public class Joe {
public int a;
protected int b;
private int b;
int c;
}
</code></pre>
<p>I'm most interested in what the last one is doing.</p>
|
[
{
"answer_id": 267756,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 4,
"selected": true,
"text": "<ul>\n<li><code>public</code>: read/writable for anyone</li>\n<li><code>protected</code>: read/writable for\ninstances of subclasses <strong>and from within the enclosing package</strong></li>\n<li><code>private</code>: read/writable for <strong>any</strong> instance of the class\nand inner or outer (enclosing) instance</li>\n<li><code>int c</code>:\npackage-private, read/writable for\nall classes inside same package</li>\n</ul>\n\n<p>See the <a href=\"http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285\" rel=\"nofollow noreferrer\">JLS</a> for more details</p>\n\n<p>EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for <code>private</code>. I remember now... ;-)</p>\n"
},
{
"answer_id": 267769,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 0,
"selected": false,
"text": "<p>And all of these are compile time protections, they can be readily overridden through reflection at runtime.</p>\n"
},
{
"answer_id": 267772,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p>I try to avoid package level access completely (the last access you mention).</p>\n\n<p>I like to keep classes self-contained. If another class needs access to something in my class it should be <code>public</code> (and it should by a method, not an attribute). Otherwise I feel you've broken <a href=\"https://stackoverflow.com/questions/99688/private-vs-public-members-in-practice-how-important-is-encapsulation#100035\">encapsulation</a>, as explained in <a href=\"https://stackoverflow.com/questions/24626/abstraction-vs-information-hiding-vs-encapsulation\">Abstraction VS Information Hiding VS Encapsulation</a>.</p>\n"
},
{
"answer_id": 267877,
"author": "jfpoilpret",
"author_id": 1440720,
"author_profile": "https://Stackoverflow.com/users/1440720",
"pm_score": 2,
"selected": false,
"text": "<p>Sorry for answering corrections to one previous answer but I don't have enough reputation to modify directly...</p>\n\n<ul>\n<li><code>public</code> - read/writable for anyone</li>\n<li><code>protected</code> - read/writable for\ninstances subclasses and all classes\ninside same package</li>\n<li><code>int c</code> : package-private,\nread/writable for all classes inside\nsame package</li>\n<li><code>private</code> - read/writable for any member of that class itself and inner classes (if any)</li>\n</ul>\n\n<p>It is better to order the access modifiers this way, from the broadest access (<code>public</code>) to the narrowest (<code>private</code>), knowing that when going from narrow to broad, you don't lose any possibilities. </p>\n\n<p>That's particularly important for \"protected\", where it is often misunderstood that classes in the same package can also access protected members of a class (not only its subclasses).</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267750",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
What is the difference in the accessibility of the following variables in Java?
```
public class Joe {
public int a;
protected int b;
private int b;
int c;
}
```
I'm most interested in what the last one is doing.
|
* `public`: read/writable for anyone
* `protected`: read/writable for
instances of subclasses **and from within the enclosing package**
* `private`: read/writable for **any** instance of the class
and inner or outer (enclosing) instance
* `int c`:
package-private, read/writable for
all classes inside same package
See the [JLS](http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html#104285) for more details
EDIT: Added the comment for protected stating that access is granted from inside same package, you guys are totally right. Also added comment for `private`. I remember now... ;-)
|
267,752 |
<p>So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.</p>
<pre><code>#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;
int main()
{
io_service io;
serial_port port( io, "COM3" );
port.set_option( serial_port_base::baud_rate( 19200 ) );
unsigned char commands[4] = { 1, 128, 240, 0 };
// write the commands to the device
return 0;
}
</code></pre>
<p>In short: need help with the io part of the serial_port.</p>
|
[
{
"answer_id": 269148,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 5,
"selected": true,
"text": "<p>In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:</p>\n\n<pre><code>boost::asio::write(port, boost::asio::buffer(commands, 4));\n</code></pre>\n\n<p>The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview/core/buffers.html\" rel=\"noreferrer\">Buffers</a>.</p>\n"
},
{
"answer_id": 274262,
"author": "Brian Paden",
"author_id": 3176,
"author_profile": "https://Stackoverflow.com/users/3176",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks to the help from here and other places I got it working. Wrote a small program that might help some people figure out the boost serial port stuff as well.</p>\n\n<p><a href=\"http://www.college-code.com/blog/wp-content/uploads/2008/11/boost_serial_port_demo.cpp\" rel=\"noreferrer\">boostserialportdemo.cpp</a></p>\n"
},
{
"answer_id": 27681980,
"author": "xinthose",
"author_id": 4056146,
"author_profile": "https://Stackoverflow.com/users/4056146",
"pm_score": 0,
"selected": false,
"text": "<p>If you are wondering why his example gives a compile error, change CSIZE to C_SIZE on both lines. This is probably the only good example program on the web.<br>\n<a href=\"https://stackoverflow.com/questions/12641149/serial-port-configuration-using-boost-asio\">Thanks</a>. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267752",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3176/"
] |
So I've been trying to learn the boost::asio stuff to communicate to a serial device using RS232. The documementation is sparse and the examples are non-existent. Can't figure out exactly how to communicate with the device. The device can't send data so all I need to do is write, but other projects require actual back and forth communication so help with that would be appreciated. What code I have so far follows.
```
#include <boost/asio/serial_port.hpp>
using namespace::boost::asio;
int main()
{
io_service io;
serial_port port( io, "COM3" );
port.set_option( serial_port_base::baud_rate( 19200 ) );
unsigned char commands[4] = { 1, 128, 240, 0 };
// write the commands to the device
return 0;
}
```
In short: need help with the io part of the serial\_port.
|
In addition to the baud rate, you may also need to set other options like: character\_size, flow\_control, parity and stop\_bits. To write your data to the serial port you can do the following:
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: [Buffers](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview/core/buffers.html).
|
267,754 |
<p>I'm impressed with the simplicity of Microsoft's Virtual Earth Street Address search service.</p>
<p>My requirement is to type rough address info with no comma separators into a simple text box, press a find button, wait a few seconds and then observe a result picklist.</p>
<p>I mocked up something <a href="http://www.garyrusso.org/map.html" rel="nofollow noreferrer">here</a> using the <a href="http://dev.live.com/virtualearth/sdk/" rel="nofollow noreferrer">virtual earth SDK</a>.</p>
<p>Does Google Maps have a similar API?</p>
<p>Which street address search service is better?</p>
|
[
{
"answer_id": 269148,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 5,
"selected": true,
"text": "<p>In addition to the baud rate, you may also need to set other options like: character_size, flow_control, parity and stop_bits. To write your data to the serial port you can do the following:</p>\n\n<pre><code>boost::asio::write(port, boost::asio::buffer(commands, 4));\n</code></pre>\n\n<p>The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview/core/buffers.html\" rel=\"noreferrer\">Buffers</a>.</p>\n"
},
{
"answer_id": 274262,
"author": "Brian Paden",
"author_id": 3176,
"author_profile": "https://Stackoverflow.com/users/3176",
"pm_score": 4,
"selected": false,
"text": "<p>Thanks to the help from here and other places I got it working. Wrote a small program that might help some people figure out the boost serial port stuff as well.</p>\n\n<p><a href=\"http://www.college-code.com/blog/wp-content/uploads/2008/11/boost_serial_port_demo.cpp\" rel=\"noreferrer\">boostserialportdemo.cpp</a></p>\n"
},
{
"answer_id": 27681980,
"author": "xinthose",
"author_id": 4056146,
"author_profile": "https://Stackoverflow.com/users/4056146",
"pm_score": 0,
"selected": false,
"text": "<p>If you are wondering why his example gives a compile error, change CSIZE to C_SIZE on both lines. This is probably the only good example program on the web.<br>\n<a href=\"https://stackoverflow.com/questions/12641149/serial-port-configuration-using-boost-asio\">Thanks</a>. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3048/"
] |
I'm impressed with the simplicity of Microsoft's Virtual Earth Street Address search service.
My requirement is to type rough address info with no comma separators into a simple text box, press a find button, wait a few seconds and then observe a result picklist.
I mocked up something [here](http://www.garyrusso.org/map.html) using the [virtual earth SDK](http://dev.live.com/virtualearth/sdk/).
Does Google Maps have a similar API?
Which street address search service is better?
|
In addition to the baud rate, you may also need to set other options like: character\_size, flow\_control, parity and stop\_bits. To write your data to the serial port you can do the following:
```
boost::asio::write(port, boost::asio::buffer(commands, 4));
```
The libraries acceptance of buffer types is very flexible and you may want to read further on that topic here: [Buffers](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio/overview/core/buffers.html).
|
267,763 |
<p>Ever since I first wrote</p>
<pre><code>if ($a = 5) {
# do something with $a, e.g.
print "$a";
}
</code></pre>
<p>and went through the normal puzzling session of </p>
<ul>
<li>why is the result always true</li>
<li>why is $a always 5</li>
</ul>
<p>until I realized, I'd assigned 5 to $a, instead of performing a comparison.</p>
<p>So I decided to write that kind of condition above as </p>
<pre><code> if (5 == $a)
</code></pre>
<p>in other words: </p>
<p><strong>always place the constant value to the left side of the comparison operator, resulting in a compilation error, should you forget to add the second "=" sign.</strong></p>
<p>I tend to call this <strong>defensive coding</strong> and tend to believe it's <strong>a cousin to defensive-programming</strong>, not on the algorithmic scale, but keyword by keyword. </p>
<p>What defensive coding practices have you developed? </p>
<hr>
<p><strong>One Week Later:</strong> </p>
<p>A big "thank you" to all who answered or might add another answer in the future. </p>
<p>Unfortunately (or rather fortunately!) there is no single correct answer. For that my question was to broad, asking more for opinions or learnings of experience, rather than facts. </p>
|
[
{
"answer_id": 267776,
"author": "Torbjørn",
"author_id": 22621,
"author_profile": "https://Stackoverflow.com/users/22621",
"pm_score": 4,
"selected": false,
"text": "<p>This is a simple and obvious one, but I NEVER EVER NEVER repeat the same string constant twice in my code, cause I KNOW that if I do I will be spelling one of them wrong :) Use constants, people! </p>\n"
},
{
"answer_id": 267778,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "<p>I stopped using languages where you can do</p>\n\n<pre><code>if a = 5: print a\n</code></pre>\n\n<p>This has saved me tons of headaches =). </p>\n\n<p>On a more serious note... I now always write the curly braces right after I write my <code>if</code>s and <code>for</code> loops, and then fill them in afterwards. This makes sure my brackets are always aligned.</p>\n"
},
{
"answer_id": 267782,
"author": "PW.",
"author_id": 927,
"author_profile": "https://Stackoverflow.com/users/927",
"pm_score": 3,
"selected": false,
"text": "<p>Always put curly braces after an if/for/while ... even if there's only one single statement after. BTW D. Crockford thinks it's better too: <a href=\"http://www.jslint.com/lint.html\" rel=\"nofollow noreferrer\">Required blocks</a></p>\n"
},
{
"answer_id": 267785,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 2,
"selected": false,
"text": "<p>Returning a copy of a mutable object, i.e. a copy of an array, not the mutable object itself.</p>\n"
},
{
"answer_id": 267802,
"author": "Wairapeti",
"author_id": 34370,
"author_profile": "https://Stackoverflow.com/users/34370",
"pm_score": 4,
"selected": false,
"text": "<p>Always use braces:</p>\n\n<pre><code>if(boolean)\n oneliner();\nnextLineOfCode();\n</code></pre>\n\n<p>is not the same as:</p>\n\n<pre><code>if(boolean)\n{\n oneliner();\n}\nnextLineOfCode();\n</code></pre>\n\n<p>If oneliner() is a #defined function, and it isn't defined then your next line of code suddenly becomes subject to the if(). Same thing applies to for loops etc. With braces then the next piece of code never unintentionally becomes conditional on the if/for etc.</p>\n"
},
{
"answer_id": 267806,
"author": "JaredPar",
"author_id": 23283,
"author_profile": "https://Stackoverflow.com/users/23283",
"pm_score": 4,
"selected": false,
"text": "<p>The top 3 defensive coding practices I employ are</p>\n\n<ol>\n<li>unit testing</li>\n<li>unit testing</li>\n<li>unit testing</li>\n</ol>\n\n<p>There is no better defense for the quality of your code than a good unit test to back you up.</p>\n"
},
{
"answer_id": 267811,
"author": "yesraaj",
"author_id": 22076,
"author_profile": "https://Stackoverflow.com/users/22076",
"pm_score": 2,
"selected": false,
"text": "<p>Avoid unnecessary test.\nExample </p>\n\n<ol>\n<li>if(bool == true)</li>\n<li>Pointer checks if(pointer)</li>\n</ol>\n\n<p>EDIT:\nif(pointer) is not readable so nowadays I prefer if(NULL != pointer)</p>\n"
},
{
"answer_id": 267813,
"author": "billjamesdev",
"author_id": 13824,
"author_profile": "https://Stackoverflow.com/users/13824",
"pm_score": 2,
"selected": false,
"text": "<p>Couple things:</p>\n\n<ul>\n<li>Yes, the 1-line blocks. Use the braces... heck, most good IDE's will make em for you.</li>\n<li>Comment your code after you write it, or re-read your comments if you did it ahead of time. Make sure your code still does what the comments say.</li>\n<li>Unit testing is a great fallback to re-reading your code.</li>\n<li>Always log an exception... or, NEVER catch an exception without saying so, at least in debug.</li>\n</ul>\n"
},
{
"answer_id": 267837,
"author": "Tom Barta",
"author_id": 29839,
"author_profile": "https://Stackoverflow.com/users/29839",
"pm_score": 3,
"selected": false,
"text": "<ul>\n<li>Always initialize variables</li>\n<li>Use <code>const</code> wherever I can (without using <code>mutable</code>)</li>\n<li>Avoid bare dynamic allocation of memory or other resources</li>\n<li>Always use curly braces</li>\n<li>Code use-cases and tests for any class before coding implementation</li>\n<li>Turn on as many useful warnings as I can (<code>-Wall -Wextra -ansi -pedantic -Werror</code> at a minimum)</li>\n<li>Use the simplest tool that solves the problem (in my current environment, that's <code>bash</code> -> <code>grep</code> -> awk -> Python -> C++).</li>\n</ul>\n"
},
{
"answer_id": 267897,
"author": "Tal",
"author_id": 11287,
"author_profile": "https://Stackoverflow.com/users/11287",
"pm_score": 3,
"selected": false,
"text": "<p>Personally, I dislike this defensive style, it makes the code hard ro read.</p>\n\n<p>VC compiler warning level 4 will spot this (possible) error.<br>\n\"warning C4706: assignment within conditional expression\"</p>\n\n<p>You can enable just this specific compiler warning, at any level:<br></p>\n\n<pre><code>#pragma warning(3,4706)\n</code></pre>\n"
},
{
"answer_id": 267948,
"author": "Tobias Schulte",
"author_id": 969,
"author_profile": "https://Stackoverflow.com/users/969",
"pm_score": 3,
"selected": false,
"text": "<p>When comparing a string with a constant, write</p>\n\n<pre><code>if (\"blah\".equals(value)){}\n</code></pre>\n\n<p>instead of </p>\n\n<pre><code>if (value.equals(\"blah\")){}\n</code></pre>\n\n<p>to prevent a NullPointerException. But this is the only time I use the suggested coding-style (cause \"if (a = 1)...\" is not possible in Java).</p>\n"
},
{
"answer_id": 267967,
"author": "James Hughes",
"author_id": 34671,
"author_profile": "https://Stackoverflow.com/users/34671",
"pm_score": 3,
"selected": false,
"text": "<p>One of the things I always try to remember when I am in the Javascript world is to always start the return value of a function on the same line as the return key word.</p>\n\n<pre><code>function one(){\n return {\n result:\"result\"\n };\n}\n\nfunction two(){\n return \n {\n result:\"result\"\n };\n}\n</code></pre>\n\n<p>These 2 functions will not return the same value. The first function will return an Object with a property results set to \"result\". The second function will return <code>undefined</code>. It's a really simple mistake and it happens because of Javascript's over-zealous Semi-Colon Insertion strategy. Semi-colons are semi-optional in Javascript and because of this the Javascript engine will add semi-coons where it thinks it's should be. Because <code>return</code> is actually a valid statement a semi-colon will be inserted after the return statement and the rest of the function will essentially be ignored.</p>\n"
},
{
"answer_id": 267974,
"author": "Aaron Digulla",
"author_id": 34088,
"author_profile": "https://Stackoverflow.com/users/34088",
"pm_score": 3,
"selected": false,
"text": "<p>From my blog:</p>\n\n<ol>\n<li><p>Think positive and return early plus avoid deep nesting. Instead of</p>\n\n<p>if (value != null) {\n ... do something with value ...\n}\nreturn</p>\n\n<p>write</p>\n\n<p>if (value == null) {\n return\n}\n... do something with value ...</p></li>\n<li><p>Avoid \"string constants\" (i.e. the same text in quotes in more than one place). Always define a real constant (with a name and an optional comment what it means) and use that.</p></li>\n</ol>\n"
},
{
"answer_id": 313238,
"author": "Paul Kapustin",
"author_id": 38325,
"author_profile": "https://Stackoverflow.com/users/38325",
"pm_score": 1,
"selected": false,
"text": "<p>Installed Resharper ;)\nThen I don't need to write \"5 == a\" to get warned if I did something wrong :)</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31472/"
] |
Ever since I first wrote
```
if ($a = 5) {
# do something with $a, e.g.
print "$a";
}
```
and went through the normal puzzling session of
* why is the result always true
* why is $a always 5
until I realized, I'd assigned 5 to $a, instead of performing a comparison.
So I decided to write that kind of condition above as
```
if (5 == $a)
```
in other words:
**always place the constant value to the left side of the comparison operator, resulting in a compilation error, should you forget to add the second "=" sign.**
I tend to call this **defensive coding** and tend to believe it's **a cousin to defensive-programming**, not on the algorithmic scale, but keyword by keyword.
What defensive coding practices have you developed?
---
**One Week Later:**
A big "thank you" to all who answered or might add another answer in the future.
Unfortunately (or rather fortunately!) there is no single correct answer. For that my question was to broad, asking more for opinions or learnings of experience, rather than facts.
|
This is a simple and obvious one, but I NEVER EVER NEVER repeat the same string constant twice in my code, cause I KNOW that if I do I will be spelling one of them wrong :) Use constants, people!
|
267,764 |
<p>I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button. </p>
<p>Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?</p>
|
[
{
"answer_id": 270326,
"author": "Lance Roberts",
"author_id": 13295,
"author_profile": "https://Stackoverflow.com/users/13295",
"pm_score": 1,
"selected": false,
"text": "<p>If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:</p>\n\n<pre><code>Sub Copybutton_Click()\n\nRange(\"Copyend\").value = Range(\"Copystart\").value\nRange(\"Copyend\").visible = True\n\nEnd Sub\n</code></pre>\n\n<p>If you have multiple named ranges with the same name, then add [Sheetname]. in front of the range, where Sheetname is the name of the sheet that the named range is in that you want to reference.</p>\n"
},
{
"answer_id": 270381,
"author": "Phil.Wheeler",
"author_id": 15609,
"author_profile": "https://Stackoverflow.com/users/15609",
"pm_score": 0,
"selected": false,
"text": "<p>There are no native functions in Excel that will allow you to do this. You will need to write a macro and assign that to a button control (which you can drop onto your worksheet by using the Control Toolbox toolbar - View > Toolbars > Control Toolbox).</p>\n\n<p>You would usually then assign the macro to that button by double-clicking the button (while it's still in Design View) and calling your macro in the newly-generated `CommandButton_Click` event. As Lance says, named ranges would be the easiest to work with.</p>\n\n<p>To answer the last part of your question, programmatically copying a range doesn't copy the formatting or formula as well. It only takes the value of the cell. So regardless of whether your source range is hidden, the destination will not need to have its `visible` property explicitly set - the hidden attribute is ignored when copying.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I need to copy a set of rows from one tab to another tab of the same Excel document by just clicking a button.
Also, can I also get information on how can I copy a set of rows that are hidden and paste it in the same tab without copying the "hidden" format?
|
If 'Copystart' is your original rows, and 'Copyend' is where you want to paste them, then using named ranges:
```
Sub Copybutton_Click()
Range("Copyend").value = Range("Copystart").value
Range("Copyend").visible = True
End Sub
```
If you have multiple named ranges with the same name, then add [Sheetname]. in front of the range, where Sheetname is the name of the sheet that the named range is in that you want to reference.
|
267,781 |
<p>Slightly related to my <a href="https://stackoverflow.com/questions/267750/java-instance-variable-accessibility">other question</a>: What is the difference between the following:</p>
<pre><code>private class Joe
protected class Joe
public class Joe
class Joe
</code></pre>
<p>Once again, the difference between the last 2 is what I'm most interested in.</p>
|
[
{
"answer_id": 267793,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 5,
"selected": true,
"text": "<p>A public class is accessible to a class in any package.</p>\n\n<p>A class with default access (<code>class Joe</code>) is only visible to other classes in the same package. </p>\n\n<p>The private and protected modifiers can only be applied to inner classes. </p>\n\n<p>A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.</p>\n\n<p>A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.</p>\n"
},
{
"answer_id": 267794,
"author": "Daniel Hiller",
"author_id": 16193,
"author_profile": "https://Stackoverflow.com/users/16193",
"pm_score": 1,
"selected": false,
"text": "<ul>\n<li>private: visible for outer classes only</li>\n<li>protected: visible for outer classes only</li>\n<li>public: visible for all other classes</li>\n<li>class: package-private, so visible for classes within the same package</li>\n</ul>\n\n<p>See <a href=\"http://java.sun.com/docs/books/jls/third_edition/html/names.html#104285\" rel=\"nofollow noreferrer\">JLS</a> for more info.</p>\n"
},
{
"answer_id": 267815,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://java-expert.blogspot.com/2007/07/class-declarations-and-modifiers.html\" rel=\"nofollow noreferrer\">A class with default access</a> has no modifier preceding it in the declaration. </p>\n\n<p>The <a href=\"http://java-expert.blogspot.com/2007/07/class-declarations-and-modifiers.html\" rel=\"nofollow noreferrer\">default access</a> is a package-level access, because a class with default access can be seen only by classes within the same package. </p>\n\n<p>If a class has default access, <strong>a class in another package won’t be able to create a instance of that class, or even declare a variable or return type</strong>. The compiler will complain. For example:</p>\n\n<pre><code>package humanity;\nclass Person {}\n\npackage family;\nimport humanity.Person;\nclass Child extends Person {}\n</code></pre>\n\n<p>Try to compile this 2 sources. As you can see, they are in different packages, and the compilation will fail. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
Slightly related to my [other question](https://stackoverflow.com/questions/267750/java-instance-variable-accessibility): What is the difference between the following:
```
private class Joe
protected class Joe
public class Joe
class Joe
```
Once again, the difference between the last 2 is what I'm most interested in.
|
A public class is accessible to a class in any package.
A class with default access (`class Joe`) is only visible to other classes in the same package.
The private and protected modifiers can only be applied to inner classes.
A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.
A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.
|
267,804 |
<p>I'm trying to figure out the best way to insert a record into a single table but only if the item doesn't already exist. The KEY in this case is an NVARCHAR(400) field. For this example, lets pretend it's the name of a <em>word</em> in the Oxford English Dictionary / insert your fav dictionary here. Also, i'm guessing i will need to make the Word field a primary key. (the table will also have a unique identifier PK also).</p>
<p>So .. i might get these words that i need to add to the table...</p>
<p>eg.</p>
<ul>
<li>Cat </li>
<li>Dog </li>
<li>Foo</li>
<li>Bar</li>
<li>PewPew </li>
<li>etc...</li>
</ul>
<p>So traditionally, i would try the following (pseudo code)</p>
<pre><code>SELECT WordID FROM Words WHERE Word = @Word
IF WordID IS NULL OR WordID <= 0
INSERT INTO Words VALUES (@Word)
</code></pre>
<p>ie. <em>If the word doesn't exist, then insert it.</em></p>
<p>Now .. the problem i'm worried about is that we're getting LOTS of hits .. so is it possible that the word could be inserted from another process in between the SELECT and the INSERT .. which would then throw a constraint error? (ie. a <a href="http://en.wikipedia.org/wiki/Race_condition" rel="noreferrer" title="Race Condition">Race Condition</a>).</p>
<p>I then thought that i might be able to do the following ...</p>
<pre><code>INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
</code></pre>
<p>basically, <em>insert a word when it doesn't exist.</em></p>
<p>Bad syntax aside, i'm not sure if this is bad or good because of how it locks down the table (if it does) and is not that performant on a table that it getting massive reads and plenty of writes.</p>
<p>So - what do you Sql gurus think / do?</p>
<p>I was hoping to have a simple insert and 'catch' that for any errors thrown.</p>
|
[
{
"answer_id": 267859,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 6,
"selected": true,
"text": "<p>Your solution:</p>\n\n<pre><code>INSERT INTO Words (Word)\n SELECT @Word\nWHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)\n</code></pre>\n\n<p>...is about as good as it gets. You could simplify it to this:</p>\n\n<pre><code>INSERT INTO Words (Word)\n SELECT @Word\nWHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word)\n</code></pre>\n\n<p>...because EXISTS doesn't actually need to return any records, so the query optimiser won't bother looking at which fields you asked for.</p>\n\n<p>As you mention, however, this isn't particularly performant, because it'll lock the whole table during the INSERT. Except that, if you add a unique index (it doesn't need to be the primary key) to Word, then it'll only need to lock the relevant pages.</p>\n\n<p>Your best option is to simulate the expected load and look at the performance with SQL Server Profiler. As with any other field, premature optimisation is a bad thing. Define acceptable performance metrics, and then measure before doing anything else.</p>\n\n<p>If that's still not giving you adequate performance, then there's a bunch of techniques from the data warehousing field that could help.</p>\n"
},
{
"answer_id": 267863,
"author": "Bogdan Maxim",
"author_id": 23795,
"author_profile": "https://Stackoverflow.com/users/23795",
"pm_score": 2,
"selected": false,
"text": "<p>If you are using MS SQL Server, you can create a unique index on your table's columns that need to be unique (documented <a href=\"http://msdn.microsoft.com/en-us/library/ms191166.aspx\" rel=\"nofollow noreferrer\">here</a>):</p>\n\n<pre><code>CREATE UNIQUE [ CLUSTERED | NONCLUSTERED ] INDEX <index_name>\n ON Words ( word [ ASC | DESC ])\n</code></pre>\n\n<p>Specify <code>Clustered</code> or <code>NonClustered</code>, depending on your case. Also, if you want it sorted (to enable faster seeking), specify <code>ASC</code> or <code>DESC</code> for the sort order.</p>\n\n<p>See <a href=\"http://en.wikipedia.org/wiki/Index_(database)\" rel=\"nofollow noreferrer\">here</a>, if you want to learn more about indexes architecture.</p>\n\n<p>Otherwise, you could use <code>UNIQUE CONSTRAINTS</code> like documented <a href=\"http://msdn.microsoft.com/en-us/library/ms191166.aspx\" rel=\"nofollow noreferrer\">here</a>:</p>\n\n<pre><code>ALTER TABLE Words\nADD CONSTRAINT UniqueWord\nUNIQUE (Word); \n</code></pre>\n"
},
{
"answer_id": 267940,
"author": "Dan Fego",
"author_id": 34426,
"author_profile": "https://Stackoverflow.com/users/34426",
"pm_score": 0,
"selected": false,
"text": "<p>I can't speak to the particulars of MS SQL, but one point of a primary key in SQL is to ensure uniqueness. So by definition in generic SQL terms, a primary key is one or more fields that is unique to a table. While there are different ways to enforce this behavior (replace the old entry with the new one vs. reject the new one) I would be surprised if MS SQL both didn't have a mechanism for enforcing this behavior and that it wasn't to reject the new entry. Just make sure you set the primary key to the Word field and it <em>should</em> work.</p>\n\n<p>Once again though, I disclaim this is all from my knowledge from MySQL programming and my databases class, so apologies if I'm off on the intricacies of MS SQL.</p>\n"
},
{
"answer_id": 268265,
"author": "Mladen Prajdic",
"author_id": 31345,
"author_profile": "https://Stackoverflow.com/users/31345",
"pm_score": 1,
"selected": false,
"text": "<p>while unique constraint is certaily one way to go you can also use this for your insert logic:\n<a href=\"http://www.sqlteam.com/article/application-locks-or-mutexes-in-sql-server-2005\" rel=\"nofollow noreferrer\">http://www.sqlteam.com/article/application-locks-or-mutexes-in-sql-server-2005</a></p>\n\n<p>basicaly you don't put any locks on the table below thus not worrying about the reads \nwhile your existance checks will be performed ok.</p>\n\n<p>it's a mutex in sql code.</p>\n"
},
{
"answer_id": 268293,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": -1,
"selected": false,
"text": "<pre><code>declare @Error int\n\nbegin transaction\n INSERT INTO Words (Word) values(@word)\n set @Error = @@ERROR\n if @Error <> 0 --if error is raised\n begin\n goto LogError\n end\ncommit transaction\ngoto ProcEnd\n\nLogError:\nrollback transaction\n</code></pre>\n"
},
{
"answer_id": 915165,
"author": "Pbearne",
"author_id": 3582,
"author_profile": "https://Stackoverflow.com/users/3582",
"pm_score": 2,
"selected": false,
"text": "<p>I had similar problem and this is how I solved it</p>\n\n<pre><code>insert into Words\n( selectWord , Fixword)\nSELECT word,'theFixword'\nFROM OldWordsTable\nWHERE \n(\n (word LIKE 'junk%') OR\n (word LIKE 'orSomthing') \n\n)\nand word not in \n (\n SELECT selectWord FROM words WHERE selectWord = word\n ) \n</code></pre>\n"
},
{
"answer_id": 7838850,
"author": "Dennis Hostetler",
"author_id": 695823,
"author_profile": "https://Stackoverflow.com/users/695823",
"pm_score": 3,
"selected": false,
"text": "<p>I think I've found a better (or at least faster) answer to this.\nCreate an index like:</p>\n\n<pre><code>CREATE UNIQUE NONCLUSTERED INDEX [IndexTableUniqueRows] ON [dbo].[table] \n(\n [Col1] ASC,\n [Col2] ASC,\n\n)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = ON, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]\n</code></pre>\n\n<p>Include all the columns that define uniqueness. The important part is IGNORE_DUP_KEY = ON. That turns non unique inserts into warnings. SSIS ignores these warnings and you can still use fastload too.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267804",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30674/"
] |
I'm trying to figure out the best way to insert a record into a single table but only if the item doesn't already exist. The KEY in this case is an NVARCHAR(400) field. For this example, lets pretend it's the name of a *word* in the Oxford English Dictionary / insert your fav dictionary here. Also, i'm guessing i will need to make the Word field a primary key. (the table will also have a unique identifier PK also).
So .. i might get these words that i need to add to the table...
eg.
* Cat
* Dog
* Foo
* Bar
* PewPew
* etc...
So traditionally, i would try the following (pseudo code)
```
SELECT WordID FROM Words WHERE Word = @Word
IF WordID IS NULL OR WordID <= 0
INSERT INTO Words VALUES (@Word)
```
ie. *If the word doesn't exist, then insert it.*
Now .. the problem i'm worried about is that we're getting LOTS of hits .. so is it possible that the word could be inserted from another process in between the SELECT and the INSERT .. which would then throw a constraint error? (ie. a [Race Condition](http://en.wikipedia.org/wiki/Race_condition "Race Condition")).
I then thought that i might be able to do the following ...
```
INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
```
basically, *insert a word when it doesn't exist.*
Bad syntax aside, i'm not sure if this is bad or good because of how it locks down the table (if it does) and is not that performant on a table that it getting massive reads and plenty of writes.
So - what do you Sql gurus think / do?
I was hoping to have a simple insert and 'catch' that for any errors thrown.
|
Your solution:
```
INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT WordID FROM Words WHERE Word = @Word)
```
...is about as good as it gets. You could simplify it to this:
```
INSERT INTO Words (Word)
SELECT @Word
WHERE NOT EXISTS (SELECT * FROM Words WHERE Word = @Word)
```
...because EXISTS doesn't actually need to return any records, so the query optimiser won't bother looking at which fields you asked for.
As you mention, however, this isn't particularly performant, because it'll lock the whole table during the INSERT. Except that, if you add a unique index (it doesn't need to be the primary key) to Word, then it'll only need to lock the relevant pages.
Your best option is to simulate the expected load and look at the performance with SQL Server Profiler. As with any other field, premature optimisation is a bad thing. Define acceptable performance metrics, and then measure before doing anything else.
If that's still not giving you adequate performance, then there's a bunch of techniques from the data warehousing field that could help.
|
267,808 |
<p>(Note: This is for MySQL's SQL, not SQL Server.)</p>
<p>I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.</p>
|
[
{
"answer_id": 267814,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 0,
"selected": false,
"text": "<p>Check the <a href=\"http://dev.mysql.com/doc/refman/5.0/en/pattern-matching.html\" rel=\"nofollow noreferrer\">Pattern Matching</a> and <a href=\"http://dev.mysql.com/doc/refman/5.0/en/regexp.html\" rel=\"nofollow noreferrer\">Regular Expressions</a> sections of the MySQL Reference Manual.</p>\n"
},
{
"answer_id": 267910,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 4,
"selected": true,
"text": "<p>Using REGEXP opearator:</p>\n\n<pre><code>SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'\n</code></pre>\n\n<p>It returns records where column body contains words starting with a,c,g or i (case insensitive)</p>\n\n<p>Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)</p>\n"
},
{
"answer_id": 267912,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "<p>You can use a <code>LIKE</code> operation. If your words are space-separated, append a space to the start of the string to give the first word a chance to match:</p>\n\n<pre><code>SELECT\n StringCol\nFROM\n MyTable\nWHERE\n ' ' + StringCol LIKE '% ' + MyLetterParam + '%'\n</code></pre>\n\n<p>Where <code>MyLetterParam</code> could be something like this:</p>\n\n<pre><code>'[acgj]'\n</code></pre>\n\n<p>To look for more than a space as a word separator, you can expand that technique. The following would treat TAB, CR, LF, space and NBSP as word separators.</p>\n\n<pre><code>WHERE\n ' ' + StringCol LIKE '%['+' '+CHAR(9)+CHAR(10)+CHAR(13)+CHAR(160)+'][acgj]%'\n</code></pre>\n\n<p>This approach has the nice touch of being standard SQL. It would work unchanged across the major SQL dialects.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267808",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17307/"
] |
(Note: This is for MySQL's SQL, not SQL Server.)
I have a database column with values like "abc def GHI JKL". I want to write a WHERE clause that includes a case-insensitive test for any word that begins with a specific letter. For example, that example would test true for the letters a,c,g,j because there's a 'word' beginning with each of those letters. The application is for a search that offers to find records that have only words beginning with the specified letter. Also note that there is not a fulltext index for this table.
|
Using REGEXP opearator:
```
SELECT * FROM `articles` WHERE `body` REGEXP '[[:<:]][acgj]'
```
It returns records where column body contains words starting with a,c,g or i (case insensitive)
Be aware though: this is not a very good idea if you expect any heavy load (not using index - it scans every row!)
|
267,832 |
<p>Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.</p>
<p>The code is the following:</p>
<pre><code>#include<stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1+ N/BITSPERWORD];
void set(int i)
{
a[i>>SHIFT] |= (1<<(i & MASK));
}
void clr(int i)
{
a[i>>SHIFT] &= ~(1<<(i & MASK));
}
int test(int i)
{
a[i>>SHIFT] & (1<<(i & MASK));
}
</code></pre>
<p>Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?</p>
<p>I've already read the previous related <a href="https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c">question</a>.</p>
|
[
{
"answer_id": 267839,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>From <a href=\"http://bytes.com/forum/thread847594.html\" rel=\"nofollow noreferrer\">Here</a> (General answer to get this thread started)</p>\n\n<p>A bit mask is a value (which may be stored in a variable) that enables you to isolate a specific set of bits within an integer type.</p>\n\n<p>Normally the masked will have the bits you are interested in set to 1 and all the other bits set to 0. The mask then allows you to isolate the value of the bits, clear all the bits or set all the bits or set a new value to the bits.</p>\n\n<p>Masks (particularly multi-bit ones) often have an associated shift value which is the amount the bits need shifting left so that the least significant masked bit is shifted to the least significant bit in the type.</p>\n\n<p>For example using a 16 bit short data type suppose you wanted to be able to mask bits 3, 4 and 5 (LSB is number 0). You mask and shift would look something like</p>\n\n<pre><code>#define MASK 0x0038\n#define SHIFT 3\n</code></pre>\n\n<p>Masks are often assigned in hexadecimal because it is easier to work with bits in the data type in that base as opposed to decimal. Historically octal has also been used for bit masks.</p>\n\n<p>If I have a variable, var, that contains data that the mask is relevant to then I can isolate the bits like this</p>\n\n<pre><code>var & MASK\n</code></pre>\n\n<p>I can isolate all the other bits like this</p>\n\n<pre><code>var & ~MASK\n</code></pre>\n\n<p>I can clear the bits like this</p>\n\n<pre><code>var &= ~MASK;\n</code></pre>\n\n<p>I can clear all the other bits like this</p>\n\n<pre><code>var &= MASK;\n</code></pre>\n\n<p>I can set all the bits like this</p>\n\n<pre><code>var |= MASK;\n</code></pre>\n\n<p>I can set all the other bits like this</p>\n\n<pre><code>var |= ~MASK;\n</code></pre>\n\n<p>I can extract the decimal value of the bits like this</p>\n\n<pre><code>(var & MASK) >> SHIFT\n</code></pre>\n\n<p>I can assign a new value to the bits like this</p>\n\n<pre><code>var &= ~MASK;\nvar |= (newValue << SHIFT) & MASK;\n</code></pre>\n"
},
{
"answer_id": 267844,
"author": "Roger Lipscombe",
"author_id": 8446,
"author_profile": "https://Stackoverflow.com/users/8446",
"pm_score": 4,
"selected": true,
"text": "<p>VonC posted a good answer about bitmasks in general. Here's some information that's more specific to the code you posted.</p>\n\n<p>Given an integer representing a bit, we work out which member of the array holds that bit. That is: Bits 0 to 31 live in <code>a[0]</code>, bits 32 to 63 live in <code>a[1]</code>, etc. All that <code>i>>SHIFT</code> does is <code>i / 32</code>. This works out which member of <code>a</code> the bit lives in. With an optimising compiler, these are probably equivalent.</p>\n\n<p>Obviously, now we've found out which member of <code>a</code> that bitflag lives in, we need to ensure that we set the correct bit in that integer. This is what <code>1 << i</code> does. However, we need to ensure that we don't try to access the 33rd bit in a 32-bit integer, so the shift operation is constrained by using <code>1 << (i & 0x1F)</code>. The magic here is that <code>0x1F</code> is 31, so we'll never left-shift the bit represented by <code>i</code> more than 31 places (otherwise it should have gone in the next member of <code>a</code>).</p>\n"
},
{
"answer_id": 267848,
"author": "zoul",
"author_id": 17279,
"author_profile": "https://Stackoverflow.com/users/17279",
"pm_score": 3,
"selected": false,
"text": "<p>When You want to set a bit inside the array, You have to </p>\n\n<ol>\n<li>seek to the right array index and</li>\n<li>set the appropriate bit inside this array item. </li>\n</ol>\n\n<p>There are <code>BITSPERWORD</code> (=32) bits in one array item, which means that the index <code>i</code> has to be split into two parts: </p>\n\n<ul>\n<li>rightmost 5 bits serve as an index in the array item and </li>\n<li>the rest of the bits (leftmost 28) serve as an index into the array. </li>\n</ul>\n\n<p>You get:</p>\n\n<ul>\n<li>the <strong>leftmost 28 bits by discarding the rightmost five</strong>, which is exactly what <strong><code>i>>SHIFT</code></strong> does, and </li>\n<li>the <strong>rightmost five bits by masking out anything but the rightmost five bits</strong>, which is what <strong><code>i & MASK</code></strong> does. </li>\n</ul>\n\n<p>I guess You understand the rest.</p>\n"
},
{
"answer_id": 267855,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://en.wikipedia.org/wiki/Bitwise_operation\" rel=\"nofollow noreferrer\">Bitwise operation</a> and the leading paragraphs of <a href=\"http://en.wikipedia.org/wiki/Mask_(computing)\" rel=\"nofollow noreferrer\">Mask</a> are a concise explanation, and contain some pointers for further study.</p>\n\n<p>Think of an 8-bit byte as a set of elements from an 8-member universe. A member is <strong>IN</strong> the set when the corresponding bit is set. Setting a bit more then once doesn't modify <a href=\"http://en.wikipedia.org/wiki/Set_membership\" rel=\"nofollow noreferrer\">set membership</a> (a bit can have only 2 states). The <a href=\"http://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Bitwise_operators\" rel=\"nofollow noreferrer\">bitwise operators</a> in <em>C</em> provide access to bits by <em>masking</em> and <em>shifting</em>.</p>\n"
},
{
"answer_id": 267885,
"author": "tingyu",
"author_id": 18612,
"author_profile": "https://Stackoverflow.com/users/18612",
"pm_score": 0,
"selected": false,
"text": "<p>The code is trying to store <code>N</code> bits by an array, where each element of the array contains <code>BITSPERWORD</code> (32) bits.</p>\n\n<p>Thus if you're trying to access bit <code>i</code>, you need to calculate the index of the array element stores it (<code>i/32</code>), which is what <code>i>>SHIFT</code> does.</p>\n\n<p>And then you need to access that bit in the array element we just got.</p>\n\n<p><code>(i & MASK)</code> gives the bit position at the array element (word).\n<code>(1<<(i & MASK))</code> makes the bit at that position to be set.</p>\n\n<p>Now you can set/clear/test that bit in <code>a[i>>SHIFT]</code> by <code>(1<<i & MASK))</code>.</p>\n\n<p>You may also think <code>i</code> is a 32 bits number, that bits 6~31 is the index of the array element stores it, bits 0~5 represents the bit position in the word.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20915/"
] |
Hey, in the Programming Pearls book, there is a source code for setting, clearing and testing a bit of the given index in an array of ints that is actually a set representation.
The code is the following:
```
#include<stdio.h>
#define BITSPERWORD 32
#define SHIFT 5
#define MASK 0x1F
#define N 10000000
int a[1+ N/BITSPERWORD];
void set(int i)
{
a[i>>SHIFT] |= (1<<(i & MASK));
}
void clr(int i)
{
a[i>>SHIFT] &= ~(1<<(i & MASK));
}
int test(int i)
{
a[i>>SHIFT] & (1<<(i & MASK));
}
```
Could somebody explain me the reason of the SHIFT and the MASK defines? And what are their purposes in the code?
I've already read the previous related [question](https://stackoverflow.com/questions/47981/how-do-you-set-clear-and-toggle-a-single-bit-in-c).
|
VonC posted a good answer about bitmasks in general. Here's some information that's more specific to the code you posted.
Given an integer representing a bit, we work out which member of the array holds that bit. That is: Bits 0 to 31 live in `a[0]`, bits 32 to 63 live in `a[1]`, etc. All that `i>>SHIFT` does is `i / 32`. This works out which member of `a` the bit lives in. With an optimising compiler, these are probably equivalent.
Obviously, now we've found out which member of `a` that bitflag lives in, we need to ensure that we set the correct bit in that integer. This is what `1 << i` does. However, we need to ensure that we don't try to access the 33rd bit in a 32-bit integer, so the shift operation is constrained by using `1 << (i & 0x1F)`. The magic here is that `0x1F` is 31, so we'll never left-shift the bit represented by `i` more than 31 places (otherwise it should have gone in the next member of `a`).
|
267,841 |
<p>I am writing a Rails app that processes data into a graph (using Scruffy). I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser? </p>
|
[
{
"answer_id": 268036,
"author": "Codebeef",
"author_id": 12037,
"author_profile": "https://Stackoverflow.com/users/12037",
"pm_score": 3,
"selected": false,
"text": "<p>I think you will be able to use <a href=\"http://www.railsbrain.com/api/rails-2.1.0/doc/index.html?a=M000271&name=send_data\" rel=\"nofollow noreferrer\">send_data</a> for this purpose:</p>\n\n<pre><code>send_data data_string, :filename => 'icon.jpg', :type => 'image/jpeg', :disposition => 'inline'\n</code></pre>\n\n<p>If you put this in a controller action - say show on a picture controller, then all you need do is include the following in your view (assuming RESTful routes):</p>\n\n<pre><code><%= image_tag picture_path(@picture) %>\n</code></pre>\n"
},
{
"answer_id": 268408,
"author": "srboisvert",
"author_id": 6805,
"author_profile": "https://Stackoverflow.com/users/6805",
"pm_score": 0,
"selected": false,
"text": "<p>I wonder if sending direct to the browser is the best way? If there is the possibility that users will reload the page would this short circuit any cache possibilities? I ask because I really don't know.</p>\n"
},
{
"answer_id": 316748,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>\"If there is the possibility that users will reload the page would this short circuit any cache possibilities?\"</p>\n</blockquote>\n\n<p>No - whether you're serving from a file system or send_data doesn't matter. The browser is getting the data from your server anyway. Just make sure you've got your HTTP caching directives sorted out.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267841",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5004/"
] |
I am writing a Rails app that processes data into a graph (using Scruffy). I am wondering how can I render the graph to a blog/string and then send the blog/string directly to the the browser to be displayed (without saving it to a file)? Or do I need to render it, save it to a file, then display the saved image file in the browser?
|
I think you will be able to use [send\_data](http://www.railsbrain.com/api/rails-2.1.0/doc/index.html?a=M000271&name=send_data) for this purpose:
```
send_data data_string, :filename => 'icon.jpg', :type => 'image/jpeg', :disposition => 'inline'
```
If you put this in a controller action - say show on a picture controller, then all you need do is include the following in your view (assuming RESTful routes):
```
<%= image_tag picture_path(@picture) %>
```
|
267,861 |
<p>I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically_deleted" (a boolean field of the child table)</p>
<p>For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..<br>
How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "<code>Children.parent_id == Parent.id and Children.logically_deleted == False</code>", but is it correct to write "and" in this way?)</p>
<p><strong>Edit:</strong><br>
I managed to do it in this way</p>
<pre><code>children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))
</code></pre>
<p>but is there a way to use a string as primaryjoin instead?</p>
|
[
{
"answer_id": 267975,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "<p>I'm only currently developing agains 0.4.something, but here's how I'd suggest it:</p>\n\n<pre><code>db.query(Object).filter(Object.first==value).filter(Object.second==False).all()\n</code></pre>\n\n<p>I think that's what you are trying to do, right?</p>\n\n<p>(Note: written in a web browser, not real code!)</p>\n"
},
{
"answer_id": 278710,
"author": "Ants Aasma",
"author_id": 107366,
"author_profile": "https://Stackoverflow.com/users/107366",
"pm_score": 3,
"selected": true,
"text": "<p>The and_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the & operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators. </p>\n\n<p>You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.</p>\n\n<p>For logical deletion, it might be better to map the whole class over a select that ignores deleted values:</p>\n\n<pre><code>mapper(Something, select([sometable], sometable.c.deleted == False))\n</code></pre>\n"
},
{
"answer_id": 13887876,
"author": "Stanislav",
"author_id": 1905415,
"author_profile": "https://Stackoverflow.com/users/1905415",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>but is there a way to use a string as primaryjoin instead?</p>\n</blockquote>\n\n<p>You can use the following:</p>\n\n<pre><code>children = relationship(\"Children\", primaryjoin=\"and_(Parent.id==Children.parent_id, Children.logically_deleted==False)\"\n</code></pre>\n\n<p>This worked for me!</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267861",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3497/"
] |
I'm using SQLAlchemy 0.5rc, and I'd like to add an automatic filter to a relation, so that every time it tries to fetch records for that relation, it ignores the "remote" ones if they're flagged as "logically\_deleted" (a boolean field of the child table)
For example, if an object "parent" has a "children" relation that has
3 records, but one of them is logically deleted, when I query for "Parent" I'd like SQLA to
fetch the parent object with just two children..
How should I do it? By adding an "and" condition to the primaryjoin
parameter of the relation? (e.g. "`Children.parent_id == Parent.id and Children.logically_deleted == False`", but is it correct to write "and" in this way?)
**Edit:**
I managed to do it in this way
```
children = relation("Children", primaryjoin=and_(id == Children.parent_id, Children.logically_deleted==False))
```
but is there a way to use a string as primaryjoin instead?
|
The and\_() function is the correct way to do logical conjunctions in SQLAlchemy, together with the & operator, but be careful with the latter as it has surprising precedence rules, i.e. higher precedence than comparison operators.
You could also use a string as a primary join with the text() constructor, but that will make your code break with any table aliasing that comes with eagerloading and joins.
For logical deletion, it might be better to map the whole class over a select that ignores deleted values:
```
mapper(Something, select([sometable], sometable.c.deleted == False))
```
|
267,862 |
<p>Reading <a href="http://www.paulgraham.com/articles.html" rel="noreferrer">Paul Graham's essays</a> on programming languages one would think that <a href="http://wiki.c2.com/?LispMacro" rel="noreferrer">Lisp macros</a> are the only way to go. As a busy developer, working on other platforms, I have not had the privilege of using Lisp macros. As someone who wants to understand the buzz, please explain what makes this feature so powerful.</p>
<p>Please also relate this to something I would understand from the worlds of Python, Java, C# or C development.</p>
|
[
{
"answer_id": 267880,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 7,
"selected": false,
"text": "<p>You will find a comprehensive debate around <a href=\"http://lists.warhead.org.uk/pipermail/iwe/2005-July/000130.html\" rel=\"noreferrer\">lisp macro here</a>.</p>\n<p>An interesting subset of that article:</p>\n<blockquote>\n<p>In most programming languages, syntax is complex. Macros have to take apart program syntax, analyze it, and reassemble it. They do not have access to the program's parser, so they have to depend on heuristics and best-guesses. Sometimes their cut-rate analysis is wrong, and then they break.</p>\n<p>But Lisp is different. Lisp macros <em>do</em> have access to the parser, and it is a really simple parser. <strong>A Lisp macro is not handed a string, but a preparsed piece of source code in the form of a list, because the source of a Lisp program is not a string; it is a list.</strong> And Lisp programs are really good at taking apart lists and putting them back together. They do this reliably, every day.</p>\n<p>Here is an extended example. Lisp has a macro, called "setf", that performs assignment. The simplest form of setf is</p>\n<pre><code> (setf x whatever)\n</code></pre>\n<p>which sets the value of the symbol "x" to the value of the expression "whatever".</p>\n<p>Lisp also has lists; you can use the "car" and "cdr" functions to get the first element of a list or the rest of the list, respectively.</p>\n<p>Now what if you want to replace the first element of a list with a new value? There is a standard function for doing that, and incredibly, its name is even worse than "car". It is "rplaca". But you do not have to remember "rplaca", because you can write</p>\n<pre><code> (setf (car somelist) whatever)\n</code></pre>\n<p>to set the car of somelist.</p>\n<p>What is really happening here is that "setf" is a macro. At compile time, it examines its arguments, and it sees that the first one has the form (car SOMETHING). It says to itself "Oh, the programmer is trying to set the car of somthing. The function to use for that is 'rplaca'." And it quietly rewrites the code in place to:</p>\n<pre><code> (rplaca somelist whatever)\n</code></pre>\n</blockquote>\n"
},
{
"answer_id": 268041,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 6,
"selected": false,
"text": "<p>Lisp macros allow you to decide when (if at all) any part or expression will be evaluated. To put a simple example, think of C's:</p>\n\n<pre><code>expr1 && expr2 && expr3 ...\n</code></pre>\n\n<p>What this says is: Evaluate <code>expr1</code>, and, should it be true, evaluate <code>expr2</code>, etc.</p>\n\n<p>Now try to make this <code>&&</code> into a function... thats right, you can't. Calling something like:</p>\n\n<pre><code>and(expr1, expr2, expr3)\n</code></pre>\n\n<p>Will evaluate all three <code>exprs</code> before yielding an answer regardless of whether <code>expr1</code> was false!</p>\n\n<p>With lisp macros you can code something like:</p>\n\n<pre><code>(defmacro && (expr1 &rest exprs)\n `(if ,expr1 ;` Warning: I have not tested\n (&& ,@exprs) ; this and might be wrong!\n nil))\n</code></pre>\n\n<p>now you have an <code>&&</code>, which you can call just like a function and it won't evaluate any forms you pass to it unless they are all true.</p>\n\n<p>To see how this is useful, contrast:</p>\n\n<pre><code>(&& (very-cheap-operation)\n (very-expensive-operation)\n (operation-with-serious-side-effects))\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>and(very_cheap_operation(),\n very_expensive_operation(),\n operation_with_serious_side_effects());\n</code></pre>\n\n<p>Other things you can do with macros are creating new keywords and/or mini-languages (check out the <a href=\"http://www.ai.sri.com/pkarp/loop.html\" rel=\"noreferrer\"><code>(loop ...)</code></a> macro for an example), integrating other languages into lisp, for example, you could write a macro that lets you say something like:</p>\n\n<pre><code>(setvar *rows* (sql select count(*)\n from some-table\n where column1 = \"Yes\"\n and column2 like \"some%string%\")\n</code></pre>\n\n<p>And thats not even getting into <a href=\"http://dorophone.blogspot.com/2008/03/common-lisp-reader-macros-simple.html\" rel=\"noreferrer\">Reader macros</a>.</p>\n\n<p>Hope this helps.</p>\n"
},
{
"answer_id": 268091,
"author": "Vatine",
"author_id": 34771,
"author_profile": "https://Stackoverflow.com/users/34771",
"pm_score": 6,
"selected": false,
"text": "<p>Common Lisp macros essentially extend the \"syntactic primitives\" of your code.</p>\n\n<p>For example, in C, the switch/case construct only works with integral types and if you want to use it for floats or strings, you are left with nested if statements and explicit comparisons. There's also no way you can write a C macro to do the job for you.</p>\n\n<p>But, since a lisp macro is (essentially) a lisp program that takes snippets of code as input and returns code to replace the \"invocation\" of the macro, you can extend your \"primitives\" repertoire as far as you want, usually ending up with a more readable program.</p>\n\n<p>To do the same in C, you would have to write a custom pre-processor that eats your initial (not-quite-C) source and spits out something that a C compiler can understand. It's not a wrong way to go about it, but it's not necessarily the easiest.</p>\n"
},
{
"answer_id": 268226,
"author": "JacquesB",
"author_id": 7488,
"author_profile": "https://Stackoverflow.com/users/7488",
"pm_score": 4,
"selected": false,
"text": "<p>A lisp macro takes a program fragment as input. This program fragment is represented a data structure which can be manipulated and transformed any way you like. In the end the macro outputs another program fragment, and this fragment is what is executed at runtime.</p>\n\n<p>C# does not have a macro facility, however an equivalent would be if the compiler parsed the code into a CodeDOM-tree, and passed that to a method, which transformed this into another CodeDOM, which is then compiled into IL.</p>\n\n<p>This could be used to implement \"sugar\" syntax like the <code>for each</code>-statement <code>using</code>-clause, linq <code>select</code>-expressions and so on, as macros that transforms into the underlying code.</p>\n\n<p>If Java had macros, you could implement Linq syntax in Java, without needing Sun to change the base language.</p>\n\n<p>Here is pseudo-code for how a lisp-style macro in C# for implementing <code>using</code> could look:</p>\n\n<pre><code>define macro \"using\":\n using ($type $varname = $expression) $block\ninto:\n $type $varname;\n try {\n $varname = $expression;\n $block;\n } finally {\n $varname.Dispose();\n }\n</code></pre>\n"
},
{
"answer_id": 268360,
"author": "Matt Curtis",
"author_id": 17221,
"author_profile": "https://Stackoverflow.com/users/17221",
"pm_score": 4,
"selected": false,
"text": "<p>Think of what you can do in C or C++ with macros and templates. They're very useful tools for managing repetitive code, but they're limited in quite severe ways.</p>\n\n<ul>\n<li>Limited macro/template syntax restricts their use. For example, you can't write a template which expands to something other than a class or a function. Macros and templates can't easily maintain internal data.</li>\n<li>The complex, very irregular syntax of C and C++ makes it difficult to write very general macros.</li>\n</ul>\n\n<p>Lisp and Lisp macros solve these problems.</p>\n\n<ul>\n<li>Lisp macros are written in Lisp. You have the full power of Lisp to write the macro.</li>\n<li>Lisp has a very regular syntax.</li>\n</ul>\n\n<p>Talk to anyone that's mastered C++ and ask them how long they spent learning all the template fudgery they need to do template metaprogramming. Or all the crazy tricks in (excellent) books like <em>Modern C++ Design</em>, which are still tough to debug and (in practice) non-portable between real-world compilers even though the language has been standardised for a decade. All of that melts away if the langauge you use for metaprogramming is the same language you use for programming!</p>\n"
},
{
"answer_id": 268451,
"author": "Miguel Ping",
"author_id": 22992,
"author_profile": "https://Stackoverflow.com/users/22992",
"pm_score": 4,
"selected": false,
"text": "<p>I'm not sure I can add some insight to everyone's (excellent) posts, but...</p>\n\n<p>Lisp macros work great because of the Lisp syntax nature.</p>\n\n<p>Lisp is an <strong>extremely regular</strong> language (think of everything is a <strong>list</strong>); macros enables you to treat data and code as the same (no string parsing or other hacks are needed to modify lisp expressions). You combine these two features and you have a very <strong>clean</strong> way to modify code. </p>\n\n<p><strong>Edit:</strong> What I was trying to say is that Lisp is <a href=\"http://en.wikipedia.org/wiki/Homoiconic\" rel=\"noreferrer\">homoiconic</a>, which means that the data structure for a lisp program is written in lisp itself.</p>\n\n<p>So, you end up with a way of creating your own code generator on top of the language using the language itself with all its power (eg. in Java you have to hack your way with bytecode weaving, although some frameworks like AspectJ allows you to do this using a different approach, it's fundamentally a hack).</p>\n\n<p>In practice, with macros you end up building your own <em>mini-language</em> on top of lisp, without the need to learn additional languages or tooling, and with using the full power of the language itself.</p>\n"
},
{
"answer_id": 268492,
"author": "dmitry_vk",
"author_id": 35054,
"author_profile": "https://Stackoverflow.com/users/35054",
"pm_score": 3,
"selected": false,
"text": "<p>In short, macros are transformations of code. They allow to introduce many new syntax constructs. E.g., consider LINQ in C#. In lisp, there are similar language extensions that are implemented by macros (e.g., built-in loop construct, iterate). Macros significantly decrease code duplication. Macros allow embedding «little languages» (e.g., where in c#/java one would use xml to configure, in lisp the same thing can be achieved with macros). Macros may hide difficulties of using libraries usage.</p>\n\n<p>E.g., in lisp you can write</p>\n\n<pre><code>(iter (for (id name) in-clsql-query \"select id, name from users\" on-database *users-database*)\n (format t \"User with ID of ~A has name ~A.~%\" id name))\n</code></pre>\n\n<p>and this hides all the database stuff (transactions, proper connection closing, fetching data, etc.) whereas in C# this requires creating SqlConnections, SqlCommands, adding SqlParameters to SqlCommands, looping on SqlDataReaders, properly closing them.</p>\n"
},
{
"answer_id": 268878,
"author": "dnolen",
"author_id": 32797,
"author_profile": "https://Stackoverflow.com/users/32797",
"pm_score": 3,
"selected": false,
"text": "<p>Lisp macros represents a pattern that occurs in almost any sizeable programming project. Eventually in a large program you have a certain section of code where you realize it would be simpler and less error prone for you to write a program that outputs source code as text which you can then just paste in.</p>\n\n<p>In Python objects have two methods <code>__repr__</code> and <code>__str__</code>. <code>__str__</code> is simply the human readable representation. <code>__repr__</code> returns a representation that is valid Python code, which is to say, something that can be entered into the interpreter as valid Python. This way you can create little snippets of Python that generate valid code that can be pasted into your actually source.</p>\n\n<p>In Lisp this whole process has been formalized by the macro system. Sure it enables you to create extensions to the syntax and do all sorts of fancy things, but it's actual usefulness is summed up by the above. Of course it helps that the Lisp macro system allows you to manipulate these \"snippets\" with the full power of the entire language.</p>\n"
},
{
"answer_id": 4621584,
"author": "Rayne",
"author_id": 21734,
"author_profile": "https://Stackoverflow.com/users/21734",
"pm_score": 5,
"selected": false,
"text": "<p>I don't think I've ever seen Lisp macros explained better than by this fellow: <a href=\"http://www.defmacro.org/ramblings/lisp.html\" rel=\"noreferrer\">http://www.defmacro.org/ramblings/lisp.html</a></p>\n"
},
{
"answer_id": 4621882,
"author": "gte525u",
"author_id": 194605,
"author_profile": "https://Stackoverflow.com/users/194605",
"pm_score": 9,
"selected": false,
"text": "<p>To give the short answer, macros are used for defining language syntax extensions to Common Lisp or Domain Specific Languages (DSLs). These languages are embedded right into the existing Lisp code. Now, the DSLs can have syntax similar to Lisp (like Peter Norvig's <a href=\"http://norvig.com/paip/prolog.lisp\" rel=\"noreferrer\">Prolog Interpreter</a> for Common Lisp) or completely different (e.g. <a href=\"http://data-sorcery.org/2010/05/14/infix-math/\" rel=\"noreferrer\">Infix Notation Math</a> for Clojure).</p>\n<p>Here is a more concrete example:<br>Python has list comprehensions built into the language. This gives a simple syntax for a common case. The line</p>\n<pre><code>divisibleByTwo = [x for x in range(10) if x % 2 == 0]\n</code></pre>\n<p>yields a list containing all even numbers between 0 and 9. Back in the <a href=\"https://www.python.org/download/releases/1.5/\" rel=\"noreferrer\">Python 1.5</a> days there was no such syntax; you'd use something more like this:</p>\n<pre><code>divisibleByTwo = []\nfor x in range( 10 ):\n if x % 2 == 0:\n divisibleByTwo.append( x )\n</code></pre>\n<p>These are both functionally equivalent. Let's invoke our suspension of disbelief and pretend Lisp has a very limited loop macro that just does iteration and no easy way to do the equivalent of list comprehensions.</p>\n<p>In Lisp you could write the following. I should note this contrived example is picked to be identical to the Python code not a good example of Lisp code.</p>\n<pre><code>;; the following two functions just make equivalent of Python's range function\n;; you can safely ignore them unless you are running this code\n(defun range-helper (x)\n (if (= x 0)\n (list x)\n (cons x (range-helper (- x 1)))))\n\n(defun range (x)\n (reverse (range-helper (- x 1))))\n\n;; equivalent to the python example:\n;; define a variable\n(defvar divisibleByTwo nil)\n\n;; loop from 0 upto and including 9\n(loop for x in (range 10)\n ;; test for divisibility by two\n if (= (mod x 2) 0) \n ;; append to the list\n do (setq divisibleByTwo (append divisibleByTwo (list x))))\n</code></pre>\n<p>Before I go further, I should better explain what a macro is. It is a transformation performed on code <i>by</i> code. That is, a piece of code, read by the interpreter (or compiler), which takes in code as an argument, manipulates and the returns the result, which is then run in-place.</p>\n<p>Of course that's a lot of typing and programmers are lazy. So we could define DSL for doing list comprehensions. In fact, we're using one macro already (the loop macro).</p>\n<p>Lisp defines a couple of special syntax forms. The quote (<code>'</code>) indicates the next token is a literal. The quasiquote or backtick (<code>`</code>) indicates the next token is a literal with escapes. Escapes are indicated by the comma operator. The literal <code>'(1 2 3)</code> is the equivalent of Python's <code>[1, 2, 3]</code>. You can assign it to another variable or use it in place. You can think of <code>`(1 2 ,x)</code> as the equivalent of Python's <code>[1, 2, x]</code> where <code>x</code> is a variable previously defined. This list notation is part of the magic that goes into macros. The second part is the Lisp reader which intelligently substitutes macros for code but that is best illustrated below:</p>\n<p>So we can define a macro called <code>lcomp</code> (short for list comprehension). Its syntax will be exactly like the python that we used in the example <code>[x for x in range(10) if x % 2 == 0]</code> - <code>(lcomp x for x in (range 10) if (= (% x 2) 0))</code></p>\n<pre><code>(defmacro lcomp (expression for var in list conditional conditional-test)\n ;; create a unique variable name for the result\n (let ((result (gensym)))\n ;; the arguments are really code so we can substitute them \n ;; store nil in the unique variable name generated above\n `(let ((,result nil))\n ;; var is a variable name\n ;; list is the list literal we are suppose to iterate over\n (loop for ,var in ,list\n ;; conditional is if or unless\n ;; conditional-test is (= (mod x 2) 0) in our examples\n ,conditional ,conditional-test\n ;; and this is the action from the earlier lisp example\n ;; result = result + [x] in python\n do (setq ,result (append ,result (list ,expression))))\n ;; return the result \n ,result)))\n</code></pre>\n<p>Now we can execute at the command line:</p>\n<pre><code>CL-USER> (lcomp x for x in (range 10) if (= (mod x 2) 0))\n(0 2 4 6 8)\n</code></pre>\n<p>Pretty neat, huh? Now it doesn't stop there. You have a mechanism, or a paintbrush, if you like. You can have any syntax you could possibly want. Like Python or C#'s <code>with</code> syntax. Or .NET's LINQ syntax. In end, this is what attracts people to Lisp - ultimate flexibility.</p>\n"
},
{
"answer_id": 4628114,
"author": "stonemetal",
"author_id": 92601,
"author_profile": "https://Stackoverflow.com/users/92601",
"pm_score": -1,
"selected": false,
"text": "<p>In python you have decorators, you basically have a function that takes another function as input. You can do what ever you want: call the function, do something else, wrap the function call in a resource acquire release, etc. but you don't get to peek inside that function. Say we wanted to make it more powerful, say your decorator received the code of the function as a list then you could not only execute the function as is but you can now execute parts of it, reorder lines of the function etc.</p>\n"
},
{
"answer_id": 15769736,
"author": "nilsi",
"author_id": 804440,
"author_profile": "https://Stackoverflow.com/users/804440",
"pm_score": 0,
"selected": false,
"text": "<p>I got this from the common lisp cookbook and I think it explained why lisp macros are useful.</p>\n<p>"A macro is an ordinary piece of Lisp code that operates on another piece of putative Lisp code, translating it into (a version closer to) executable Lisp. That may sound a bit complicated, so let's give a simple example. Suppose you want a version of setq that sets two variables to the same value. So if you write</p>\n<pre><code>(setq2 x y (+ z 3))\n</code></pre>\n<p>when <code>z=8</code> both x and y are set to 11. (I can't think of any use for this, but it's just an example.)</p>\n<p>It should be obvious that we can't define setq2 as a function. If <code>x=50</code> and <code>y=-5</code>, this function would receive the values 50, -5, and 11; it would have no knowledge of what variables were supposed to be set. What we really want to say is, When you (the Lisp system) see <code>(setq2 v1 v2 e)</code>, treat it as equivalent to <code>(progn (setq v1 e) (setq v2 e))</code>. Actually, this isn't quite right, but it will do for now. A macro allows us to do precisely this, by specifying a program for transforming the input pattern <code>(setq2 v1 v2 e)</code>" into the output pattern <code>(progn ...)</code>."</p>\n<p>If you thought this was nice you can keep on reading here:\n<a href=\"http://cl-cookbook.sourceforge.net/macros.html\" rel=\"nofollow noreferrer\">http://cl-cookbook.sourceforge.net/macros.html</a></p>\n"
},
{
"answer_id": 21663942,
"author": "ZakW",
"author_id": 1234179,
"author_profile": "https://Stackoverflow.com/users/1234179",
"pm_score": 4,
"selected": false,
"text": "<p>Since the existing answers give good concrete examples explaining what macros achieve and how, perhaps it'd help to collect together some of the thoughts on why the macro facility is a significant gain <em>in relation to other languages</em>; first from these answers, then a great one from elsewhere:</p>\n\n<blockquote>\n <p>... in C, you would have to write a custom pre-processor [which would probably qualify as a <a href=\"https://en.wikipedia.org/wiki/Greenspun%27s_tenth_rule\" rel=\"noreferrer\">sufficiently complicated C program</a>] ...</p>\n</blockquote>\n\n<p>—<a href=\"https://stackoverflow.com/a/268091/1234179\">Vatine</a></p>\n\n<blockquote>\n <p>Talk to anyone that's mastered C++ and ask them how long they spent learning all the template fudgery they need to do template metaprogramming [which is still not as powerful].</p>\n</blockquote>\n\n<p>—<a href=\"https://stackoverflow.com/a/268360/1234179\">Matt Curtis</a></p>\n\n<blockquote>\n <p>... in Java you have to hack your way with bytecode weaving, although some frameworks like AspectJ allows you to do this using a different approach, it's fundamentally a hack.</p>\n</blockquote>\n\n<p>—<a href=\"https://stackoverflow.com/a/268451/1234179\">Miguel Ping</a></p>\n\n<blockquote>\n <p>DOLIST is similar to Perl's foreach or Python's for. Java added a similar kind of loop construct with the \"enhanced\" for loop in Java 1.5, as part of JSR-201. Notice what a difference macros make. A Lisp programmer who notices a common pattern in their code can write a macro to give themselves a source-level abstraction of that pattern. A Java programmer who notices the same pattern has to convince Sun that this particular abstraction is worth adding to the language. Then Sun has to publish a JSR and convene an industry-wide \"expert group\" to hash everything out. That process--according to Sun--takes an average of 18 months. After that, the compiler writers all have to go upgrade their compilers to support the new feature. And even once the Java programmer's favorite compiler supports the new version of Java, they probably ''still'' can't use the new feature until they're allowed to break source compatibility with older versions of Java. So an annoyance that Common Lisp programmers can resolve for themselves within five minutes plagues Java programmers for years.</p>\n</blockquote>\n\n<p>—<a href=\"http://www.gigamonkeys.com/book/macros-standard-control-constructs.html\" rel=\"noreferrer\">Peter Seibel, in \"Practical Common Lisp\"</a></p>\n"
},
{
"answer_id": 44060981,
"author": "Joerg Schmuecker",
"author_id": 2899748,
"author_profile": "https://Stackoverflow.com/users/2899748",
"pm_score": 2,
"selected": false,
"text": "<p>While the above all explains what macros are and even have cool examples, I think the key difference between a macro and a normal function is that LISP evaluates all the parameters first before calling the function. With a macro it's the reverse, LISP passes the parameters unevaluated to the macro. For example, if you pass (+ 1 2) to a function, the function will receive the value 3. If you pass this to a macro, it will receive a List( + 1 2). This can be used to do all kinds of incredibly useful stuff.</p>\n\n<ul>\n<li>Adding a new control structure, e.g. loop or the deconstruction of a list</li>\n<li><p>Measure the time it takes to execute a function passed in. With a function the parameter would be evaluated before control is passed to the function. With the macro, you can splice your code between the start and stop of your stopwatch. The below has the exact same code in a macro and a function and the output is very different. <em>Note: This is a contrived example and the implementation was chosen so that it is identical to better highlight the difference.</em></p>\n\n<pre><code>(defmacro working-timer (b) \n (let (\n (start (get-universal-time))\n (result (eval b))) ;; not splicing here to keep stuff simple\n ((- (get-universal-time) start))))\n\n(defun my-broken-timer (b)\n (let (\n (start (get-universal-time))\n (result (eval b))) ;; doesn't even need eval\n ((- (get-universal-time) start))))\n\n(working-timer (sleep 10)) => 10\n\n(broken-timer (sleep 10)) => 0\n</code></pre></li>\n</ul>\n"
},
{
"answer_id": 70552337,
"author": "Student",
"author_id": 11392504,
"author_profile": "https://Stackoverflow.com/users/11392504",
"pm_score": 1,
"selected": false,
"text": "<p><em>One-liner answer:</em></p>\n<p><em>Minimal syntax => Macros over Expressions => Conciseness => Abstraction => Power</em></p>\n<hr />\n<p>Lisp macros do nothing more than writing codes programmatically. That is, after expanding the macros, you got nothing more than Lisp code without macros. So, <em>in principle</em>, they achieve nothing new.</p>\n<p>However, they differ from macros in other programming languages in that they write codes on the level of expressions, whereas others' macros write codes on the level of strings. This is unique to lisp thanks to their parenthesis; or put more precisely, their <a href=\"http://blog.rongarret.info/2015/05/why-lisp.html\" rel=\"nofollow noreferrer\">minimal syntax</a> which is possible thanks to their parentheses.</p>\n<p>As shown in many examples in this thread, and also Paul Graham's <em>On Lisp</em>, lisp macros can then be a tool to make your code much more concise. When conciseness reaches a point, it offers new levels of abstractions for codes to be much cleaner. Going back to the first point again, <em>in principle</em> they do not offer anything new, but that's like saying since paper and pencils (almost) form a Turing machine, we do not need an actual computer.</p>\n<p>If one knows some math, think about why functors and natural transformations are useful ideas. <em>In principle</em>, they do not offer anything new. However by expanding what they are into lower-level math you'll see that a combination of a few simple ideas (in terms of category theory) could take 10 pages to be written down. Which one do you prefer?</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267862",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4491/"
] |
Reading [Paul Graham's essays](http://www.paulgraham.com/articles.html) on programming languages one would think that [Lisp macros](http://wiki.c2.com/?LispMacro) are the only way to go. As a busy developer, working on other platforms, I have not had the privilege of using Lisp macros. As someone who wants to understand the buzz, please explain what makes this feature so powerful.
Please also relate this to something I would understand from the worlds of Python, Java, C# or C development.
|
To give the short answer, macros are used for defining language syntax extensions to Common Lisp or Domain Specific Languages (DSLs). These languages are embedded right into the existing Lisp code. Now, the DSLs can have syntax similar to Lisp (like Peter Norvig's [Prolog Interpreter](http://norvig.com/paip/prolog.lisp) for Common Lisp) or completely different (e.g. [Infix Notation Math](http://data-sorcery.org/2010/05/14/infix-math/) for Clojure).
Here is a more concrete example:
Python has list comprehensions built into the language. This gives a simple syntax for a common case. The line
```
divisibleByTwo = [x for x in range(10) if x % 2 == 0]
```
yields a list containing all even numbers between 0 and 9. Back in the [Python 1.5](https://www.python.org/download/releases/1.5/) days there was no such syntax; you'd use something more like this:
```
divisibleByTwo = []
for x in range( 10 ):
if x % 2 == 0:
divisibleByTwo.append( x )
```
These are both functionally equivalent. Let's invoke our suspension of disbelief and pretend Lisp has a very limited loop macro that just does iteration and no easy way to do the equivalent of list comprehensions.
In Lisp you could write the following. I should note this contrived example is picked to be identical to the Python code not a good example of Lisp code.
```
;; the following two functions just make equivalent of Python's range function
;; you can safely ignore them unless you are running this code
(defun range-helper (x)
(if (= x 0)
(list x)
(cons x (range-helper (- x 1)))))
(defun range (x)
(reverse (range-helper (- x 1))))
;; equivalent to the python example:
;; define a variable
(defvar divisibleByTwo nil)
;; loop from 0 upto and including 9
(loop for x in (range 10)
;; test for divisibility by two
if (= (mod x 2) 0)
;; append to the list
do (setq divisibleByTwo (append divisibleByTwo (list x))))
```
Before I go further, I should better explain what a macro is. It is a transformation performed on code *by* code. That is, a piece of code, read by the interpreter (or compiler), which takes in code as an argument, manipulates and the returns the result, which is then run in-place.
Of course that's a lot of typing and programmers are lazy. So we could define DSL for doing list comprehensions. In fact, we're using one macro already (the loop macro).
Lisp defines a couple of special syntax forms. The quote (`'`) indicates the next token is a literal. The quasiquote or backtick (```) indicates the next token is a literal with escapes. Escapes are indicated by the comma operator. The literal `'(1 2 3)` is the equivalent of Python's `[1, 2, 3]`. You can assign it to another variable or use it in place. You can think of ``(1 2 ,x)` as the equivalent of Python's `[1, 2, x]` where `x` is a variable previously defined. This list notation is part of the magic that goes into macros. The second part is the Lisp reader which intelligently substitutes macros for code but that is best illustrated below:
So we can define a macro called `lcomp` (short for list comprehension). Its syntax will be exactly like the python that we used in the example `[x for x in range(10) if x % 2 == 0]` - `(lcomp x for x in (range 10) if (= (% x 2) 0))`
```
(defmacro lcomp (expression for var in list conditional conditional-test)
;; create a unique variable name for the result
(let ((result (gensym)))
;; the arguments are really code so we can substitute them
;; store nil in the unique variable name generated above
`(let ((,result nil))
;; var is a variable name
;; list is the list literal we are suppose to iterate over
(loop for ,var in ,list
;; conditional is if or unless
;; conditional-test is (= (mod x 2) 0) in our examples
,conditional ,conditional-test
;; and this is the action from the earlier lisp example
;; result = result + [x] in python
do (setq ,result (append ,result (list ,expression))))
;; return the result
,result)))
```
Now we can execute at the command line:
```
CL-USER> (lcomp x for x in (range 10) if (= (mod x 2) 0))
(0 2 4 6 8)
```
Pretty neat, huh? Now it doesn't stop there. You have a mechanism, or a paintbrush, if you like. You can have any syntax you could possibly want. Like Python or C#'s `with` syntax. Or .NET's LINQ syntax. In end, this is what attracts people to Lisp - ultimate flexibility.
|
267,869 |
<p>What is the best way to configure Tomcat 5.5 or later to authenticate users from Windows Active Directory?</p>
|
[
{
"answer_id": 267906,
"author": "Blauohr",
"author_id": 22176,
"author_profile": "https://Stackoverflow.com/users/22176",
"pm_score": 5,
"selected": false,
"text": "<p><strong>From <a href=\"http://www.jspwiki.org\" rel=\"nofollow noreferrer\">www.jspwiki.org</a></strong></p>\n<p>See : <a href=\"https://web.archive.org/web/20130526124801/http://www.jspwiki.org/wiki/ActiveDirectoryIntegration\" rel=\"nofollow noreferrer\">ActiveDirectoryIntegration</a></p>\n<p>Try this in the server.xml with your ldap-settings :</p>\n<pre><code><Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"\n connectionURL="ldap://youradsserver:389"\n alternateURL="ldap://youradsserver:389" \n userRoleName="member"\n userBase="cn=Users,dc=yourdomain"\n userPattern="cn={0},cn=Users,dc=yourdomain"\n roleBase="cn=Users,dc=yourdomain"\n roleName="cn"\n roleSearch="(member={0})"\n roleSubtree="false"\n userSubtree="true"/>\n</code></pre>\n<p>And define the role in the tomcat-users.xml and the web.xml of your application</p>\n<p>Edit <code>webapp_root/WEB_INF/Web.xml</code> file as follows:</p>\n<pre><code><security-constraint>\n <display-name>your web app display name</display-name>\n <web-resource-collection>\n <web-resource-name>Protected Area</web-resource-name>\n <url-pattern>*.jsp</url-pattern>\n <url-pattern>*.html</url-pattern>\n <url-pattern>*.xml</url-pattern>\n </web-resource-collection>\n <auth-constraint>\n <role-name>yourrolname(ADS Group)</role-name>\n </auth-constraint>\n </security-constraint>\n <login-config>\n <auth-method>FORM</auth-method>\n <form-login-config>\n <form-login-page>/login.jsp</form-login-page>\n <form-error-page>/error.jsp</form-error-page>\n </form-login-config>\n </login-config>\n <security-role>\n <description>your role description</description>\n <role-name>yourrolename(i.e ADS group)</role-name>\n </security-role>\n</code></pre>\n"
},
{
"answer_id": 1899798,
"author": "Hendrik Brummermann",
"author_id": 177701,
"author_profile": "https://Stackoverflow.com/users/177701",
"pm_score": 2,
"selected": false,
"text": "<p>The LDAP based authentication works without any additional steps on any operating system.</p>\n\n<p><a href=\"http://spnego.sf.net\" rel=\"nofollow noreferrer\">http://spnego.sf.net</a> can be used for silent authentication of users logged into the Windows Domain. This needs an domain account that is registered in the domain to be authoritative for the provided service. It works on both Windows and Linux.</p>\n"
},
{
"answer_id": 4224174,
"author": "Renani",
"author_id": 513358,
"author_profile": "https://Stackoverflow.com/users/513358",
"pm_score": 0,
"selected": false,
"text": "<p>\"Welcome to the SPNEGO SourceForge project\nIntegrated Windows Authentication in Java</p>\n\n<p>The intent of this project is to provide an alternative library (.jar file) that application servers (like Tomcat) can use as the means for authenticating clients (like web browsers).</p>\n\n<p>If your organization is running Active Directory (AD) and all of your web applications go through Microsoft's Internet Information Services (IIS), and IIS has Integrated Windows Authentication enabled, and everyone in your organization is using Internet Explorer (IE), then this project <strong>may not be</strong> of any interest to you.\"</p>\n"
},
{
"answer_id": 5860845,
"author": "Doug",
"author_id": 543770,
"author_profile": "https://Stackoverflow.com/users/543770",
"pm_score": 4,
"selected": false,
"text": "<p>Blauhr's answer is good, but the <code>CN</code> of a user in <code>AD</code> is based on their "Display Name", not their <code>saMAccountName</code> (which user's are used to logging in with). Based on his solution, it looks like someone would have to log in with their Display Name, based on the <code>userPattern</code>.</p>\n<p>I've personally used the following:</p>\n<pre><code><Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"\n connectionURL="ldap://DOMAIN_CONTROLLER:389"\n connectionName="[email protected]"\n connectionPassword="USER_PASSWORD"\n referrals="follow"\n userBase="OU=USER_GROUP,DC=DOMAIN,DC=com"\n userSearch="(sAMAccountName={0})"\n userSubtree="true"\n roleBase="OU=GROUPS_GROUP,DC=DOMAIN,DC=com"\n roleName="name"\n roleSubtree="true"\n roleSearch="(member={0})"/>\n</code></pre>\n<p>Everything else would pretty much work the same.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267869",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34986/"
] |
What is the best way to configure Tomcat 5.5 or later to authenticate users from Windows Active Directory?
|
**From [www.jspwiki.org](http://www.jspwiki.org)**
See : [ActiveDirectoryIntegration](https://web.archive.org/web/20130526124801/http://www.jspwiki.org/wiki/ActiveDirectoryIntegration)
Try this in the server.xml with your ldap-settings :
```
<Realm className="org.apache.catalina.realm.JNDIRealm" debug="99"
connectionURL="ldap://youradsserver:389"
alternateURL="ldap://youradsserver:389"
userRoleName="member"
userBase="cn=Users,dc=yourdomain"
userPattern="cn={0},cn=Users,dc=yourdomain"
roleBase="cn=Users,dc=yourdomain"
roleName="cn"
roleSearch="(member={0})"
roleSubtree="false"
userSubtree="true"/>
```
And define the role in the tomcat-users.xml and the web.xml of your application
Edit `webapp_root/WEB_INF/Web.xml` file as follows:
```
<security-constraint>
<display-name>your web app display name</display-name>
<web-resource-collection>
<web-resource-name>Protected Area</web-resource-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.html</url-pattern>
<url-pattern>*.xml</url-pattern>
</web-resource-collection>
<auth-constraint>
<role-name>yourrolname(ADS Group)</role-name>
</auth-constraint>
</security-constraint>
<login-config>
<auth-method>FORM</auth-method>
<form-login-config>
<form-login-page>/login.jsp</form-login-page>
<form-error-page>/error.jsp</form-error-page>
</form-login-config>
</login-config>
<security-role>
<description>your role description</description>
<role-name>yourrolename(i.e ADS group)</role-name>
</security-role>
```
|
267,892 |
<p>How are paged results commonly implemented in PHP?</p>
<p>I'd like to have a results page with 10 results. Paging forward in the navigation would give me the next and previous sets.</p>
<p>Is there a way this is commonly done? Does anyone have simple advice on getting started?</p>
|
[
{
"answer_id": 267900,
"author": "Factor Mystic",
"author_id": 1569,
"author_profile": "https://Stackoverflow.com/users/1569",
"pm_score": 0,
"selected": false,
"text": "<p>The term you are referring to is \"pagination\". Unfortunately you'll have to give some more information to get a more specific answer.</p>\n"
},
{
"answer_id": 267901,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 0,
"selected": false,
"text": "<p>What you are looking for is called <a href=\"https://stackoverflow.com/search?q=pagination\">pagination</a>. There have been several questions on SO about this subject. As your question is very broad, please provide more details or refer to the questions that have already been asked about this subject.</p>\n"
},
{
"answer_id": 267902,
"author": "keparo",
"author_id": 19468,
"author_profile": "https://Stackoverflow.com/users/19468",
"pm_score": 3,
"selected": false,
"text": "<p>You'll need a beginner's understanding of PHP, and probably some understanding of relational databases.</p>\n\n<p>Pagination is often implemented with some simple query parameters.</p>\n\n<pre><code>stackoverflow.com/myResults.php?page=1\n</code></pre>\n\n<p>The page increments the query parameter:</p>\n\n<pre><code>stackoverflow.com/myResults.php?page=2\n</code></pre>\n\n<p>On the back end, the page value usually corresponds to the limits and offsets in the query that is being used to generate the results.</p>\n\n<p><strong>Related Questions</strong>:</p>\n\n<ul>\n<li><a href=\"https://stackoverflow.com/questions/207223/php-dynamic-pagination-without-sql\"><strong>PHP Dynamic Pagination without SQL</strong></a></li>\n<li><a href=\"https://stackoverflow.com/questions/230058/paginated-query-using-sorting-on-different-columns-using-rownumber-over-in-sql\"><strong>Paginated Query sorting on different columns in SQL Server 2005</strong></a></li>\n<li><a href=\"https://stackoverflow.com/questions/163809/smart-pagination-algorithm\"><strong>Smart pagination algorithm</strong></a></li>\n</ul>\n"
},
{
"answer_id": 268006,
"author": "Ciaran McNulty",
"author_id": 34024,
"author_profile": "https://Stackoverflow.com/users/34024",
"pm_score": 0,
"selected": false,
"text": "<p>It may be worth looking at the Zend Framework's Zend_Paginator object. It encapsulates a lot of the logic of generating next/previous/first/last type links.</p>\n"
},
{
"answer_id": 268012,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 0,
"selected": false,
"text": "<p>The <a href=\"http://www.tinybutstrong.com\" rel=\"nofollow noreferrer\">TinyButStrong </a> template system comes with a pagination extension. Very easy to use. </p>\n"
},
{
"answer_id": 268114,
"author": "pbrodka",
"author_id": 33093,
"author_profile": "https://Stackoverflow.com/users/33093",
"pm_score": -1,
"selected": false,
"text": "<p>If database is not so big - I implement pagination on client side. I recommend jquery plugin tablefilter - it gives you not only pagination, but also filtering and sorting. You can easily browse through given recordset. It's very good solution if performance is not very important. \nThere's page: \n<a href=\"http://ideamill.synaptrixgroup\" rel=\"nofollow noreferrer\">http://ideamill.synaptrixgroup</a>.\nand demo for 830 records:\n<a href=\"http://ideamill.synaptrixgroup.com/jquery/tablefilter/largetabletest.htm\" rel=\"nofollow noreferrer\">http://ideamill.synaptrixgroup.com/jquery/tablefilter/largetabletest.htm</a></p>\n"
},
{
"answer_id": 271035,
"author": "starmonkey",
"author_id": 29854,
"author_profile": "https://Stackoverflow.com/users/29854",
"pm_score": 0,
"selected": false,
"text": "<p>For server-side paging, I use PEAR's Pager package (<a href=\"http://pear.php.net/package/Pager\" rel=\"nofollow noreferrer\">http://pear.php.net/package/Pager</a>).</p>\n\n<p>Take a look at example.php for basic usage, and Page_Wrapper.php (I started with Pager_Wrapper_DB).</p>\n\n<p>The end-user docs are quite comprehensive:\n<a href=\"http://pear.php.net/manual/en/package.html.pager.intro.php\" rel=\"nofollow noreferrer\">http://pear.php.net/manual/en/package.html.pager.intro.php</a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267892",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How are paged results commonly implemented in PHP?
I'd like to have a results page with 10 results. Paging forward in the navigation would give me the next and previous sets.
Is there a way this is commonly done? Does anyone have simple advice on getting started?
|
You'll need a beginner's understanding of PHP, and probably some understanding of relational databases.
Pagination is often implemented with some simple query parameters.
```
stackoverflow.com/myResults.php?page=1
```
The page increments the query parameter:
```
stackoverflow.com/myResults.php?page=2
```
On the back end, the page value usually corresponds to the limits and offsets in the query that is being used to generate the results.
**Related Questions**:
* [**PHP Dynamic Pagination without SQL**](https://stackoverflow.com/questions/207223/php-dynamic-pagination-without-sql)
* [**Paginated Query sorting on different columns in SQL Server 2005**](https://stackoverflow.com/questions/230058/paginated-query-using-sorting-on-different-columns-using-rownumber-over-in-sql)
* [**Smart pagination algorithm**](https://stackoverflow.com/questions/163809/smart-pagination-algorithm)
|
267,893 |
<p>Is there a way to customize Firebug's keyboard shortcuts? I love being able to step through JavaScript code using Firebug's <em>Script</em> panel, but it looks like I'm limited to either using the default keyboard shortcuts for stepping over/into/out of code or using the mouse to click the appropriate button. </p>
<p>Am I missing something? </p>
<p>Is there some secret <strong>about:config</strong> hack in Firefox/Firebug that would help me?</p>
|
[
{
"answer_id": 267905,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": false,
"text": "<p>As stated in their <a href=\"https://groups.google.com/forum/#!topic/firebug/tgDCmsg89yE\" rel=\"nofollow noreferrer\">discussion forum</a>, you can try <a href=\"http://forums.mozillazine.org/viewtopic.php?t=72994\" rel=\"nofollow noreferrer\">keyconfig</a>... otherwise, it is a <a href=\"https://github.com/firebug/firebug/issues/2665\" rel=\"nofollow noreferrer\">known bug/limitation</a>.</p>\n"
},
{
"answer_id": 359268,
"author": "pkaeding",
"author_id": 4257,
"author_profile": "https://Stackoverflow.com/users/4257",
"pm_score": 2,
"selected": false,
"text": "<p>As @VonC mentioned, there is an open ticket on this. In my experience, keyconfig doesn't work for this purpose. I did <a href=\"http://blog.kaeding.name/articles/2008/12/11/customize-firebug-shortcut-keys\" rel=\"nofollow noreferrer\">write a patch</a> that allows for the debugger execution control keys to be customized in about:config. I have also posted an XPI with this fix if you don't want to wait for it to be accepted upstream, and/or you don't want to build it yourself.</p>\n"
},
{
"answer_id": 438518,
"author": "Dirk Vollmar",
"author_id": 40347,
"author_profile": "https://Stackoverflow.com/users/40347",
"pm_score": 1,
"selected": false,
"text": "<p>Another option would be to configure the shortcuts manually in file</p>\n\n<pre><code>%APPDATA%\\Mozilla\\Firefox\\Profiles\\<profile>\\extensions\\[email protected]\\content\\firebug\\browserOverlay.xul\n</code></pre>\n\n<p>For example, I removed the shortcut on F12 by commenting the corresponding section because it conflicts with the <em>Undo Closed Tab</em> shortcut of Tab Mix Plus.</p>\n\n<p>Disadvantage: An update of Firebug will overwrite the modified configuration.</p>\n"
},
{
"answer_id": 4687500,
"author": "lepe",
"author_id": 196507,
"author_profile": "https://Stackoverflow.com/users/196507",
"pm_score": 4,
"selected": true,
"text": "<p>You can change them manually. Go to this directory:</p>\n\n<p>In recent versions the extension comes in a single file with the extension XPI. Just rename it to ZIP, create a directory and extract its contents into it.</p>\n\n<p>Linux:</p>\n\n<pre><code>.mozilla/firefox/*****.default/extensions/[email protected]/ \n</code></pre>\n\n<p>Windows:</p>\n\n<pre><code>%APPDATA%\\Mozilla\\Firefox\\Profiles\\<profile>\\extensions\\[email protected]\\\n</code></pre>\n\n<p>Then modify this file (these are my remapping settings):</p>\n\n<p><strong>content/firebug/debugger/script/scriptPanel.js</strong> (Firebug 2.0)</p>\n\n<pre><code> this.keyListeners =\n [\n chrome.keyCodeListen(\"F5\", Events.isShift, Obj.bind(this.rerun, this, context), true),\n chrome.keyCodeListen(\"F5\", null, Obj.bind(this.resume, this, context), true),\n chrome.keyCodeListen(\"F6\", null, Obj.bind(this.stepOver, this, context), true),\n chrome.keyCodeListen(\"F7\", null, Obj.bind(this.stepInto, this, context)),\n chrome.keyCodeListen(\"F8\", null, Obj.bind(this.stepOut, this, context))\n ];\n</code></pre>\n\n<p><strong>content/firebug/js/scriptPanel.js</strong> (before Firebug 2.0)</p>\n\n<pre><code> this.keyListeners =\n [\n chrome.keyCodeListen(\"F5\", null, Obj.bind(this.resume, this, context), true),\n chrome.keyListen(\"/\", Events.isControl, Obj.bind(this.resume, this, context)),\n chrome.keyCodeListen(\"F6\", null, Obj.bind(this.stepOver, this, context), true),\n chrome.keyListen(\"'\", Events.isControl, Obj.bind(this.stepOver, this, context)),\n chrome.keyCodeListen(\"F7\", null, Obj.bind(this.stepInto, this, context)),\n chrome.keyListen(\";\", Events.isControl, Obj.bind(this.stepInto, this, context)),\n chrome.keyCodeListen(\"F8\", null, Obj.bind(this.stepOut, this, context)),\n chrome.keyListen(\",\", Events.isControlShift, Obj.bind(this.stepOut, this, context))\n ];\n</code></pre>\n\n<p>In versions before 2.0 you should also change the localization file, so the tooltips should the correct keys:</p>\n\n<p><strong>locale/en-US/firebug.properties</strong></p>\n\n<pre><code>firebug.Continue=Continue (F5)\nfirebug.StepOver=Step Over (F6)\nfirebug.StepInto=Step Into (F7)\nfirebug.StepOut=Step Out (F8)\n</code></pre>\n\n<p>And that is all. Unfortunately, you have to do it every time you update Firebug. Though there is already a <a href=\"https://github.com/firebug/firebug/issues/2665\" rel=\"nofollow\">request to allow their customization directly within Firebug</a>.</p>\n"
},
{
"answer_id": 37293421,
"author": "Sebastian Zartner",
"author_id": 432681,
"author_profile": "https://Stackoverflow.com/users/432681",
"pm_score": 0,
"selected": false,
"text": "<p>While it is possible to <a href=\"https://github.com/firebug/firebug/blob/master/extension/content/firebug/debugger/script/scriptPanel.js#L1552-L1556\" rel=\"nofollow noreferrer\">change the shortcuts within Firebug's source code</a>, there is also a way to add different keys for those actions without touching the source.</p>\n\n<p>To do so you have to install an extension, which allows you to define custom shortcuts like <a href=\"https://addons.mozilla.org/firefox/addon/dorando-keyconfig/\" rel=\"nofollow noreferrer\">Dorando keyconfig</a>.</p>\n\n<p><strong>Steps to do for that extension:</strong></p>\n\n<ol>\n<li>Go to the Add-ons Manager.</li>\n<li>Click the <em>Options</em> button besides the extension to open the customization dialog.</li>\n<li>Click the <em>Add a new key</em> button to open the key editor.</li>\n<li>Give the shortcut a proper name</li>\n<li>Paste the <a href=\"https://github.com/firebug/firebug/blob/master/extension/content/firebug/firefox/firebugMenuOverlay.xul\" rel=\"nofollow noreferrer\">code related to the action</a>* into the code field.</li>\n<li>Click <em>OK</em></li>\n<li>Click into the shortcut field</li>\n<li>Add a custom shortcut by pressing the keys on the keyboard</li>\n<li>Click the <em>Apply</em> button</li>\n</ol>\n\n<p><strong>Screenshots for clarification:</strong></p>\n\n<p><a href=\"https://i.stack.imgur.com/IamfI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IamfI.png\" alt=\"Dorando keyconfig key customization dialog\"></a>\n<a href=\"https://i.stack.imgur.com/strS2.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/strS2.png\" alt=\"Dorando keyconfig key editor\"></a></p>\n\n<p>* That is the value of the <code>oncommand</code> attribute. So, if you want to add a shortcut for resuming the JavaScript execution, you need to copy <code>Firebug.Debugger.resume(Firebug.currentContext)</code> from the <code>cmd_firebug_resumeExecution</code> command.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267893",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19020/"
] |
Is there a way to customize Firebug's keyboard shortcuts? I love being able to step through JavaScript code using Firebug's *Script* panel, but it looks like I'm limited to either using the default keyboard shortcuts for stepping over/into/out of code or using the mouse to click the appropriate button.
Am I missing something?
Is there some secret **about:config** hack in Firefox/Firebug that would help me?
|
You can change them manually. Go to this directory:
In recent versions the extension comes in a single file with the extension XPI. Just rename it to ZIP, create a directory and extract its contents into it.
Linux:
```
.mozilla/firefox/*****.default/extensions/[email protected]/
```
Windows:
```
%APPDATA%\Mozilla\Firefox\Profiles\<profile>\extensions\[email protected]\
```
Then modify this file (these are my remapping settings):
**content/firebug/debugger/script/scriptPanel.js** (Firebug 2.0)
```
this.keyListeners =
[
chrome.keyCodeListen("F5", Events.isShift, Obj.bind(this.rerun, this, context), true),
chrome.keyCodeListen("F5", null, Obj.bind(this.resume, this, context), true),
chrome.keyCodeListen("F6", null, Obj.bind(this.stepOver, this, context), true),
chrome.keyCodeListen("F7", null, Obj.bind(this.stepInto, this, context)),
chrome.keyCodeListen("F8", null, Obj.bind(this.stepOut, this, context))
];
```
**content/firebug/js/scriptPanel.js** (before Firebug 2.0)
```
this.keyListeners =
[
chrome.keyCodeListen("F5", null, Obj.bind(this.resume, this, context), true),
chrome.keyListen("/", Events.isControl, Obj.bind(this.resume, this, context)),
chrome.keyCodeListen("F6", null, Obj.bind(this.stepOver, this, context), true),
chrome.keyListen("'", Events.isControl, Obj.bind(this.stepOver, this, context)),
chrome.keyCodeListen("F7", null, Obj.bind(this.stepInto, this, context)),
chrome.keyListen(";", Events.isControl, Obj.bind(this.stepInto, this, context)),
chrome.keyCodeListen("F8", null, Obj.bind(this.stepOut, this, context)),
chrome.keyListen(",", Events.isControlShift, Obj.bind(this.stepOut, this, context))
];
```
In versions before 2.0 you should also change the localization file, so the tooltips should the correct keys:
**locale/en-US/firebug.properties**
```
firebug.Continue=Continue (F5)
firebug.StepOver=Step Over (F6)
firebug.StepInto=Step Into (F7)
firebug.StepOut=Step Out (F8)
```
And that is all. Unfortunately, you have to do it every time you update Firebug. Though there is already a [request to allow their customization directly within Firebug](https://github.com/firebug/firebug/issues/2665).
|
267,908 |
<p>I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?</p>
<p>For example, I have a type that I need to use all over a particular application - should I define it thus:</p>
<pre><code>mytypes.h
typedef int MY_TYPE;
foo.cpp
MY_TYPE myType;
</code></pre>
<p>Or use a namespace:</p>
<pre><code>mytypes.h
namespace ns {
typedef int MY_TYPE;
}
foo.cpp
ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;
</code></pre>
<p>Which do you prefer? Are there times when it is acceptable to use the first method?</p>
|
[
{
"answer_id": 267914,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 4,
"selected": true,
"text": "<p>I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.</p>\n\n<p>The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.</p>\n\n<p>So, if your <code>MY_TYPE</code> is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.</p>\n"
},
{
"answer_id": 267917,
"author": "C. K. Young",
"author_id": 13,
"author_profile": "https://Stackoverflow.com/users/13",
"pm_score": 2,
"selected": false,
"text": "<p>I don't agree with using the global namespace at all (well, except for <code>main</code>, of course). For things that are used across the whole application, you can simply use <code>using namespace</code> at the top of your <code>.cpp</code> files, after all the relevant <code>#include</code> lines.</p>\n"
},
{
"answer_id": 267918,
"author": "Igor Semenov",
"author_id": 11401,
"author_profile": "https://Stackoverflow.com/users/11401",
"pm_score": 3,
"selected": false,
"text": "<p>You can define your type in a separate namespace, and use</p>\n\n<pre><code>using ns::MY_TYPE;\n</code></pre>\n"
},
{
"answer_id": 268765,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 3,
"selected": false,
"text": "<p>Libraries must not, Applications may. </p>\n\n<p>When multiple people work on an application, of course you need clear rules, and the clearest rule is \"don't\". However, this isn't ideal in all cases.</p>\n\n<p>\"using\" statements should go only on top of CPP files, never in headers - but that complicates writing templates since - for most compilers in the near future - they need to reside in headers.</p>\n\n<p>In my experience (mostly small team with a large but well-partioned project), namespace pollution isn't much of a problem as long a you controll the respective code, and insist on descriptive names. The cases I remember were few and far between and easily dealt with. There were major problems with 3rd party libraries, though - even with source available.</p>\n\n<p>YMMV with a huge team or a huge project that goes into a single compile. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9236/"
] |
I think most C++ programmers here would agree that polluting the global namespace is a bad idea, but are there times when this rule can be ignored?
For example, I have a type that I need to use all over a particular application - should I define it thus:
```
mytypes.h
typedef int MY_TYPE;
foo.cpp
MY_TYPE myType;
```
Or use a namespace:
```
mytypes.h
namespace ns {
typedef int MY_TYPE;
}
foo.cpp
ns::MY_TYPE myType;
...
using namespace ns;
MY_TYPE myType;
```
Which do you prefer? Are there times when it is acceptable to use the first method?
|
I use namespaces for partitioning library code from application-specific code, and in a big project to partition the various modules that make up the project.
The global namespace is thus useful for application-specific types and functions that are used across multiple modules in the application.
So, if your `MY_TYPE` is used throughout your application, put it in the global namespace, otherwise put it in a named namespace.
|
267,944 |
<p>Some background info;</p>
<ul>
<li>LanguageResource is the base class</li>
<li>LanguageTranslatorResource and LanguageEditorResource inherit from LanguageResource</li>
<li>LanguageEditorResource defines an IsDirty property</li>
<li>LanguageResourceCollection is a collection of LanguageResource</li>
<li>LanguageResourceCollection internally holds LanguageResources in <code>Dictionary<string, LanguageResource> _dict</code></li>
<li>LanguageResourceCollection.GetEnumerator() returns <code>_dict.Values.GetEnumerator()</code></li>
</ul>
<p>I have a LanguageResourceCollection _resources that contains only LanguageEditorResource objects and want to use LINQ to enumerate those that are dirty so I have tried the following. My specific questions are in bold.</p>
<ol>
<li><p><code>_resources.Where(r => (r as LanguageEditorResource).IsDirty)</code><br/><br/>
neither Where not other LINQ methods are displayed by Intellisense but I code it anyway and am told "LanguageResourceCollection does not contain a definition for 'Where' and no extension method...".<br/><br/>
<strong>Why does the way that LanguageResourceCollection implements IEnumerable preclude it from supporting LINQ?</strong></p></li>
<li><p>If I change the query to<br/><br/>
<code>(_resources as IEnumerable<LanguageEditorResource>).Where(r => r.IsDirty)</code><br/><br/>
Intellisense displays the LINQ methods and the solution compiles. But at runtime I get an ArgumentNullException "Value cannot be null. Parameter name: source".<br/><br/>
<strong>Is this a problem in my LINQ code?<br>
Is it a problem with the general design of the classes?<br>
How can I dig into what LINQ generates to try and see what the problem is?</strong></p></li>
</ol>
<p>My aim with this question is not to get a solution for the specific problem, as I will have to solve it now using other (non LINQ) means, but rather to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ.</p>
|
[
{
"answer_id": 267964,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": true,
"text": "<p>It sounds like your collection implements <code>IEnumerable</code>, not <code>IEnumerable<T></code>, hence you need:</p>\n\n<pre><code>_resources.Cast<LanguageEditorResource>().Where(r => r.IsDirty)\n</code></pre>\n\n<p>Note that <code>Enumerable.Where</code> is defined on <code>IEnumerable<T></code>, not <code>IEnumerable</code> - if you have the non-generic type, you need to use <code>Cast<T></code> (or <code>OfType<T></code>) to get the right type. The difference being that <code>Cast<T></code> will throw an exception if it finds something that isn't a <code>T</code>, where-as <code>OfType<T></code> simply ignores anything that isn't a <code>T</code>. Since you've stated that your collection <em>only</em> contains <code>LanguageEditorResource</code>, it is reasonable to check that assumption using <code>Cast<T></code>, rather than silently drop data.</p>\n\n<p>Check also that you have \"using System.Linq\" (and are referencing System.Core (.NET 3.5; else LINQBridge with .NET 2.0) to get the <code>Where</code> extension method(s).</p>\n\n<p>Actually, it would be worth having your collection implement <code>IEnumerable<LanguageResource></code> - which you could do quite simply using either the <code>Cast<T></code> method, or an iterator block (<code>yield return</code>).</p>\n\n<p>[edit]\nTo build on Richard Poole's note - you could write your <em>own</em> generic container here, presumably with <code>T : LanguageResource</code> (and using that <code>T</code> in the <code>Dictionary<string,T></code>, and implementing <code>IEnumerable<T></code> or <code>ICollection<T></code>). Just a thought.</p>\n"
},
{
"answer_id": 267997,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 1,
"selected": false,
"text": "<p>In addition to Marc G's answer, and if you're able to do so, you might want to consider dropping your custom <code>LanguageResourceCollection</code> class in favour of a generic <code>List<LanguageResource></code>. This will solve your current problem and get rid of that nasty .NET 1.1ish custom collection.</p>\n"
},
{
"answer_id": 269312,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n <p>How can I dig into what LINQ generates to try and see what the problem is?</p>\n</blockquote>\n\n<p>Linq isn't generating anything here. You can step through with the debugger.</p>\n\n<blockquote>\n <p>to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ.</p>\n</blockquote>\n\n<p>System.Linq.Enumerable methods rely heavily on the IEnumerable< T > contract. You need to understand how your class can produce targets that support this contract. The type that T represents is important!</p>\n\n<p>You could add this method to LanguageResourceCollection:</p>\n\n<pre><code>public IEnumerable<T> ParticularResources<T>()\n{\n return _dict.Values.OfType<T>();\n}\n</code></pre>\n\n<p>and call it by:</p>\n\n<pre><code>_resources\n .ParticularResources<LanguageEditorResource>()\n .Where(r => r.IsDirty)\n</code></pre>\n\n<p>This example would make more sense if the collection class didn't implement IEnumerable< T > against that same _dict.Values . The point is to understand IEnumerable < T > and generic typing.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267944",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1535/"
] |
Some background info;
* LanguageResource is the base class
* LanguageTranslatorResource and LanguageEditorResource inherit from LanguageResource
* LanguageEditorResource defines an IsDirty property
* LanguageResourceCollection is a collection of LanguageResource
* LanguageResourceCollection internally holds LanguageResources in `Dictionary<string, LanguageResource> _dict`
* LanguageResourceCollection.GetEnumerator() returns `_dict.Values.GetEnumerator()`
I have a LanguageResourceCollection \_resources that contains only LanguageEditorResource objects and want to use LINQ to enumerate those that are dirty so I have tried the following. My specific questions are in bold.
1. `_resources.Where(r => (r as LanguageEditorResource).IsDirty)`
neither Where not other LINQ methods are displayed by Intellisense but I code it anyway and am told "LanguageResourceCollection does not contain a definition for 'Where' and no extension method...".
**Why does the way that LanguageResourceCollection implements IEnumerable preclude it from supporting LINQ?**
2. If I change the query to
`(_resources as IEnumerable<LanguageEditorResource>).Where(r => r.IsDirty)`
Intellisense displays the LINQ methods and the solution compiles. But at runtime I get an ArgumentNullException "Value cannot be null. Parameter name: source".
**Is this a problem in my LINQ code?
Is it a problem with the general design of the classes?
How can I dig into what LINQ generates to try and see what the problem is?**
My aim with this question is not to get a solution for the specific problem, as I will have to solve it now using other (non LINQ) means, but rather to try and improve my understanding of LINQ and learn how I can improve the design of my classes to work better with LINQ.
|
It sounds like your collection implements `IEnumerable`, not `IEnumerable<T>`, hence you need:
```
_resources.Cast<LanguageEditorResource>().Where(r => r.IsDirty)
```
Note that `Enumerable.Where` is defined on `IEnumerable<T>`, not `IEnumerable` - if you have the non-generic type, you need to use `Cast<T>` (or `OfType<T>`) to get the right type. The difference being that `Cast<T>` will throw an exception if it finds something that isn't a `T`, where-as `OfType<T>` simply ignores anything that isn't a `T`. Since you've stated that your collection *only* contains `LanguageEditorResource`, it is reasonable to check that assumption using `Cast<T>`, rather than silently drop data.
Check also that you have "using System.Linq" (and are referencing System.Core (.NET 3.5; else LINQBridge with .NET 2.0) to get the `Where` extension method(s).
Actually, it would be worth having your collection implement `IEnumerable<LanguageResource>` - which you could do quite simply using either the `Cast<T>` method, or an iterator block (`yield return`).
[edit]
To build on Richard Poole's note - you could write your *own* generic container here, presumably with `T : LanguageResource` (and using that `T` in the `Dictionary<string,T>`, and implementing `IEnumerable<T>` or `ICollection<T>`). Just a thought.
|
267,949 |
<p>I'm working on a code base in which we have several configurable types. One of those types is 64 bit integer. When we compile for platforms that have no native 64 bit integer type, we simple represent 64 bit integers using a struct similar to</p>
<pre><code>typedef struct {
unsigned int hi, lo;
} int64;
</code></pre>
<p>In order to make this type useful, all common operations are defined as functions such as</p>
<pre><code>int64 int64_add(int64 x, int64 y);
</code></pre>
<p>On platforms where a native 64 bit integer type is available, these operations simply look like</p>
<pre><code>#define int64_add(x, y) ((x) + (y))
</code></pre>
<p>Anyway, on to the question. I am implementing some functionality regarding time and I want to represent my time using the 64 bit integer:</p>
<pre><code>typedef int64 mytime;
</code></pre>
<p>I also want all the common operations available to the int64 type to be available for my time type as well:</p>
<pre><code>#define mytime_add(x, y) (mytime) int64_add((int64) (x), (int64) (y))
</code></pre>
<p>The problem with this is that the casts between the types mytime and int64 isn't allowed in C (as far as I can tell anyhow). Is there any way to do this without having to reimplement all the add, sub, mul, div, etc functions for the mytime type?</p>
<p>One option is of course to never do the mytime typedef and simply use int64 everywhere I need to represent time. The problem with this is that I'm not sure if I always want to represent time as a 64 bit integer. Then there's the issue of readable code as well... :-)</p>
|
[
{
"answer_id": 267965,
"author": "Dan Fego",
"author_id": 34426,
"author_profile": "https://Stackoverflow.com/users/34426",
"pm_score": 1,
"selected": false,
"text": "<p>You could try:</p>\n\n<pre><code>#define mytime int64\n</code></pre>\n\n<p>Instead of the typedef.</p>\n\n<p>That looks like it will net you both the transparent conversion and the maintainability you're looking for.</p>\n"
},
{
"answer_id": 267989,
"author": "Drakosha",
"author_id": 19868,
"author_profile": "https://Stackoverflow.com/users/19868",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at stdint.h header file. It contains int64_t, uint64_t, etc'. This is standard and portable way, and you will avoid the need to implement math functions :).</p>\n"
},
{
"answer_id": 268065,
"author": "quinmars",
"author_id": 18687,
"author_profile": "https://Stackoverflow.com/users/18687",
"pm_score": 3,
"selected": true,
"text": "<p>Do you really need the cast? gcc is compiling the following example without any complains:</p>\n\n<pre><code>\ntypedef struct int64 int64;\n\nstruct int64\n{\n unsigned int hi, lo;\n};\n\ntypedef int64 mytime;\n\nint64\nadd_int64(int64 a, int64 b)\n{\n int64 c;\n /* I know that is wrong */\n c.hi = a.hi + b.hi;\n c.lo = a.lo + b.lo;\n\n return c;\n}\n\nint\nmain(void)\n{\n mytime a = {1, 2};\n mytime b = {3, 4};\n mytime c;\n\n c = add_int64(a, b);\n\n return 0;\n}\n</code></pre>\n"
},
{
"answer_id": 268309,
"author": "Walter Bright",
"author_id": 33949,
"author_profile": "https://Stackoverflow.com/users/33949",
"pm_score": 2,
"selected": false,
"text": "<p>Because you're using typedef's, you don't need the casts at all. Typedef's in C do not create a distinct type, only an alias to another type. The compiler does not distinguish between them. Just write the mytime_add function as:</p>\n\n<pre><code>#define mytime_add(x, y) int64_add((x), (y))\n</code></pre>\n\n<p>or if your C compiler is good enough to do inlining:</p>\n\n<pre><code>mytime mytime_add(mytime x, mytime y) { return int64_add(x, y); }\n</code></pre>\n"
},
{
"answer_id": 271671,
"author": "David Nordvall",
"author_id": 20398,
"author_profile": "https://Stackoverflow.com/users/20398",
"pm_score": 0,
"selected": false,
"text": "<p>Right, so I'm using typedefs and no casting. Works fine. Seems strange though that an explicit cast doesn't compile while an implicit one does. If the implicit cast really isn't a cast at all since the compiler sees the two types as being the same type, one would think the same reasoning would work when doing an explicit cast...</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20398/"
] |
I'm working on a code base in which we have several configurable types. One of those types is 64 bit integer. When we compile for platforms that have no native 64 bit integer type, we simple represent 64 bit integers using a struct similar to
```
typedef struct {
unsigned int hi, lo;
} int64;
```
In order to make this type useful, all common operations are defined as functions such as
```
int64 int64_add(int64 x, int64 y);
```
On platforms where a native 64 bit integer type is available, these operations simply look like
```
#define int64_add(x, y) ((x) + (y))
```
Anyway, on to the question. I am implementing some functionality regarding time and I want to represent my time using the 64 bit integer:
```
typedef int64 mytime;
```
I also want all the common operations available to the int64 type to be available for my time type as well:
```
#define mytime_add(x, y) (mytime) int64_add((int64) (x), (int64) (y))
```
The problem with this is that the casts between the types mytime and int64 isn't allowed in C (as far as I can tell anyhow). Is there any way to do this without having to reimplement all the add, sub, mul, div, etc functions for the mytime type?
One option is of course to never do the mytime typedef and simply use int64 everywhere I need to represent time. The problem with this is that I'm not sure if I always want to represent time as a 64 bit integer. Then there's the issue of readable code as well... :-)
|
Do you really need the cast? gcc is compiling the following example without any complains:
```
typedef struct int64 int64;
struct int64
{
unsigned int hi, lo;
};
typedef int64 mytime;
int64
add_int64(int64 a, int64 b)
{
int64 c;
/* I know that is wrong */
c.hi = a.hi + b.hi;
c.lo = a.lo + b.lo;
return c;
}
int
main(void)
{
mytime a = {1, 2};
mytime b = {3, 4};
mytime c;
c = add_int64(a, b);
return 0;
}
```
|
267,953 |
<p>I have two applications under <code>tomcat/webapps</code> folder. </p>
<pre><code>tomcat/webapps/App1
tomcat/webapps/App2
</code></pre>
<p>Both applications share the same libraries. Which are stored for example in <code>tomcat/webapps/App1/WEB-INF/lib</code>.</p>
<p>Are both libraries loaded twice in memory?</p>
<p>Should I put these shared libraries in <code>tomcat/server/lib</code>?</p>
|
[
{
"answer_id": 267959,
"author": "Romain Linsolas",
"author_id": 26457,
"author_profile": "https://Stackoverflow.com/users/26457",
"pm_score": 6,
"selected": true,
"text": "<p>As you can see <a href=\"http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html\" rel=\"noreferrer\">here</a>, Tomcat creates one class-loader per webapp on your server.\nThus, if you have webapp1 and webapp2 that share the same library, then this library will be indeed loaded twice.</p>\n\n<p>You can eventually place this library in the common directory (tomcat-dir/common/lib) if it is shared by <strong>all</strong> webapps that run on your Tomcat server.</p>\n"
},
{
"answer_id": 267976,
"author": "Ian",
"author_id": 4396,
"author_profile": "https://Stackoverflow.com/users/4396",
"pm_score": 3,
"selected": false,
"text": "<p>From experience: the two web-apps are entirely isolated from one another - the libraries for one are not utilised in another - thus to answer your initial question - yes they would be loaded twice.</p>\n\n<p>To answer you second question, whether you should deploy these libraries into Tomcat's shared directory - I would say no, and here's why:</p>\n\n<p>If you deploy a library Jar into the shared location (tomcat/server/lib), then that version of the library becomes the default for all web-applications running under that instance of Tomcat. As you can see from <a href=\"http://www.scribd.com/doc/2675284/Tomcat-Architecture-4x\" rel=\"noreferrer\">this overview of the tomcat architecture</a>, the class-loader works \"down the chain\", with an individual web-app's lib folder being the last place it will look before it throws a class-not-found exception. This is not true in Tomcat 6 and Tomcat 7: any classes in the web apps lib and classes folder <em>will</em> be resolved before those in common, and thus, this will not break other apps which deploy all of their jars in the war <a href=\"http://tomcat.apache.org/tomcat-7.0-doc/class-loader-howto.html\" rel=\"noreferrer\">2</a>.</p>\n\n<p>The problem therefore of deploying a shared library to that directory is that it breaks the architecture for individual applications being isolated from one-another. Fine in your initial example, but if you want to deploy a third-party application (e.g. if you a running an app that consumes Portlet's to handle specific content), you instantly run in to version dependency issues - your shared version of a library may not be correct for the third-party application, but because the package is already loaded, you'll throw exceptions left right and centre.</p>\n"
},
{
"answer_id": 268194,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 5,
"selected": false,
"text": "<p>I wouldn't recommend placing the jar files in the shared folder. Let's say for example that you need in the future to deploy a third party application, that has a newer version of a jar file in the WEB-INF folder. For this application the classes of the jar will be loaded twice (even if they have the same names), one from the shared folder and one from the web app folder. This situation may cause bugs very difficult to find.</p>\n\n<p>If the jar files are in the web app folders, then they are loaded by separate class loaders and don't interfere with each other.</p>\n"
},
{
"answer_id": 24514449,
"author": "Toni Bünter",
"author_id": 2729120,
"author_profile": "https://Stackoverflow.com/users/2729120",
"pm_score": 3,
"selected": false,
"text": "<p>We are using <strong>tomcat6</strong> and find a good way to have tomcat stuffed with common libraries all our webapps need.</p>\n\n<p>Edit in <strong>conf/catalina.properties</strong> the entry <strong>common.loader</strong>. E.g. append an additional folder with jars you like to share 'mylibs'</p>\n\n<pre><code>common.loader=${catalina.base}/lib,${catalina.base}/lib/*.jar,\n ${catalina.home}/lib,${catalina.home}/lib/*.jar,\n {catalina.home}/mylibs/*.jar\n</code></pre>\n\n<p>Then put all the common libraries there. Done.</p>\n\n<p>Why did we start using a <strong>mylibs</strong> folder instead of the WEB-INF/lib in all webapps (WAR files)? </p>\n\n<p>Deployment started to be a nightmare after the WAR crossed the 50MB line!</p>\n\n<p>When having a webapp with a never jar version you still can put it into <strong>WEB-INF/lib</strong> to overwrite what you have in <strong>mylibs</strong>.</p>\n"
},
{
"answer_id": 28270570,
"author": "Kevin Panko",
"author_id": 125389,
"author_profile": "https://Stackoverflow.com/users/125389",
"pm_score": 2,
"selected": false,
"text": "<p>If you do not want your libraries to load twice put them in: </p>\n\n<ul>\n<li>Tomcat 6: <code>$CATALINA_HOME/lib</code></li>\n<li>Tomcat 5: <code>$CATALINA_HOME/common/lib</code></li>\n</ul>\n\n<p><em>(removed from the question and copied here so it can be voted/commented on)</em></p>\n"
},
{
"answer_id": 34081588,
"author": "mayank agrawal",
"author_id": 5515739,
"author_profile": "https://Stackoverflow.com/users/5515739",
"pm_score": 0,
"selected": false,
"text": "<p>PermGen Space of heap is used to store classes and Meta data about classes in Java.</p>\n\n<p>Error java.lang.OutOfMemoryError: PermGen space can occurred frequently because we are loading lots of duplicate library in apache tomcat\ncan anyone share about it in details</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267953",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2138/"
] |
I have two applications under `tomcat/webapps` folder.
```
tomcat/webapps/App1
tomcat/webapps/App2
```
Both applications share the same libraries. Which are stored for example in `tomcat/webapps/App1/WEB-INF/lib`.
Are both libraries loaded twice in memory?
Should I put these shared libraries in `tomcat/server/lib`?
|
As you can see [here](http://tomcat.apache.org/tomcat-6.0-doc/class-loader-howto.html), Tomcat creates one class-loader per webapp on your server.
Thus, if you have webapp1 and webapp2 that share the same library, then this library will be indeed loaded twice.
You can eventually place this library in the common directory (tomcat-dir/common/lib) if it is shared by **all** webapps that run on your Tomcat server.
|
267,998 |
<p>I have a QGraphicsScene that I want to copy and append to the start of a list. What is the best method of doing this?</p>
<pre><code>QGraphicsScene* m_scene = new QGraphicsScene();
QGraphicsScene* m_DuplicateScene;
QList<QGraphicsScene *>m_list;
</code></pre>
|
[
{
"answer_id": 312047,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 4,
"selected": true,
"text": "<p>Doing this would be very complicated because you don't know anything about the children of <code>m_scene</code>. Even if you <code>dynamic_cast</code> and create a <code>clone()</code> function for each type of <code>QGraphicsItem</code>, you still need to remember that other people can subclass <code>QGraphicsItem</code> and create their own type of graphics item, making them unclonable by you.</p>\n\n<p>Basically, no, you can't duplicate a <code>QGraphicsScene</code> (cloning all items in the process). You can't even make references to the children of the original scene's children because a <code>QGraphicsItem</code> can only have one scene.</p>\n\n<p>Unless I'm missing a method call, of course. Searches for \"clone,\" \"copy,\" and \"duplicate\" produced no results, though.</p>\n\n<p>On your second question, use <code>QList<T *>::push_front</code>. Thus, <code>m_list.push_front</code>(<code>m_DuplicateScene</code>);</p>\n\n<p>(Side note: you prepend to the start of a list, and append to the end of a list.)</p>\n"
},
{
"answer_id": 52384499,
"author": "Mahdi",
"author_id": 9682880,
"author_profile": "https://Stackoverflow.com/users/9682880",
"pm_score": 1,
"selected": false,
"text": "<p>I make a copy of QGraphicsScene's items in my project. I'm using this way. may be helpful.<br/>\nI have a class like this:</p>\n\n<pre><code>class DiagramScene : public QGraphicsScene\n{\n[some datas]\n}\n</code></pre>\n\n<p>and another class in this like:</p>\n\n<pre><code>class DiagramItem : public QGraphicsItem\n{\n}\n</code></pre>\n\n<p>and in copy function, I use a code like this:</p>\n\n<pre><code>Diagram_Scene myScene;\n\nforeach (QGraphicsItem *item, diagram_scene1->items()) \n{\n if(item->type() == DiagramItem::Type)\n {\n DiagramItem *di = qgraphicsitem_cast<DiagramItem*>(item);\n myScene.addItem(di);\n }\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/267998",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24459/"
] |
I have a QGraphicsScene that I want to copy and append to the start of a list. What is the best method of doing this?
```
QGraphicsScene* m_scene = new QGraphicsScene();
QGraphicsScene* m_DuplicateScene;
QList<QGraphicsScene *>m_list;
```
|
Doing this would be very complicated because you don't know anything about the children of `m_scene`. Even if you `dynamic_cast` and create a `clone()` function for each type of `QGraphicsItem`, you still need to remember that other people can subclass `QGraphicsItem` and create their own type of graphics item, making them unclonable by you.
Basically, no, you can't duplicate a `QGraphicsScene` (cloning all items in the process). You can't even make references to the children of the original scene's children because a `QGraphicsItem` can only have one scene.
Unless I'm missing a method call, of course. Searches for "clone," "copy," and "duplicate" produced no results, though.
On your second question, use `QList<T *>::push_front`. Thus, `m_list.push_front`(`m_DuplicateScene`);
(Side note: you prepend to the start of a list, and append to the end of a list.)
|
268,013 |
<p>Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.</p>
<p>I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from <a href="http://forums.asp.net/t/1208353.aspx" rel="noreferrer">this source</a>, but I need to save the bitmap back into the SQL database, which I think I need to convert back into a byte[] format.</p>
<p>So how do I convert the bitmap to a byte[] format?</p>
<p>If I am going about this the wrong way I would be grateful it you could correct me.</p>
<p>Here is my code:</p>
<pre><code> // Find the fileUpload control
string filename = uplImage.FileName;
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(uplImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = sngRatio * newWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
PHJamesDataContext db = new PHJamesDataContext();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = data,
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
db.SubmitChanges();
</code></pre>
|
[
{
"answer_id": 268026,
"author": "Tamir",
"author_id": 30879,
"author_profile": "https://Stackoverflow.com/users/30879",
"pm_score": 3,
"selected": false,
"text": "<p>Assuming, that your bitmap is bmp</p>\n\n<pre><code>byte[] data;\nusing(System.IO.MemoryStream stream = new System.IO.MemoryStream()) {\n bmp.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\n stream.Position = 0;\n data = new byte[stream.Length];\n stream.Read(data, 0, stream.Length);\n stream.Close();\n}\n</code></pre>\n"
},
{
"answer_id": 268028,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>If you've got a <code>MemoryStream</code> already, just call <a href=\"http://msdn.microsoft.com/en-us/library/system.io.memorystream.toarray.aspx\" rel=\"noreferrer\"><code>MemoryStream.ToArray</code></a> to get the data out.</p>\n"
},
{
"answer_id": 268034,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 6,
"selected": true,
"text": "<p>You should be able to change this block to</p>\n\n<pre><code> System.IO.MemoryStream stream = new System.IO.MemoryStream();\n newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);\n\n PHJProjectPhoto myPhoto =\n new PHJProjectPhoto\n {\n ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]\n OrderDate = DateTime.Now,\n ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,\n ProjectId = selectedProjectId\n };\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32792/"
] |
Basically I am inserting an image using the listviews inserting event, trying to resize an image from the fileupload control, and then save it in a SQL database using LINQ.
I found some code to create a new bitmap of the content in the fileupload control, but this was to store it in a file on the server, from [this source](http://forums.asp.net/t/1208353.aspx), but I need to save the bitmap back into the SQL database, which I think I need to convert back into a byte[] format.
So how do I convert the bitmap to a byte[] format?
If I am going about this the wrong way I would be grateful it you could correct me.
Here is my code:
```
// Find the fileUpload control
string filename = uplImage.FileName;
// Create a bitmap in memory of the content of the fileUpload control
Bitmap originalBMP = new Bitmap(uplImage.FileContent);
// Calculate the new image dimensions
int origWidth = originalBMP.Width;
int origHeight = originalBMP.Height;
int sngRatio = origWidth / origHeight;
int newWidth = 100;
int newHeight = sngRatio * newWidth;
// Create a new bitmap which will hold the previous resized bitmap
Bitmap newBMP = new Bitmap(originalBMP, newWidth, newHeight);
// Create a graphic based on the new bitmap
Graphics oGraphics = Graphics.FromImage(newBMP);
// Set the properties for the new graphic file
oGraphics.SmoothingMode = SmoothingMode.AntiAlias;
oGraphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
// Draw the new graphic based on the resized bitmap
oGraphics.DrawImage(originalBMP, 0, 0, newWidth, newHeight);
PHJamesDataContext db = new PHJamesDataContext();
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
stream.Position = 0;
byte[] data = new byte[stream.Length];
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = data,
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
db.PHJProjectPhotos.InsertOnSubmit(myPhoto);
db.SubmitChanges();
```
|
You should be able to change this block to
```
System.IO.MemoryStream stream = new System.IO.MemoryStream();
newBMP.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
PHJProjectPhoto myPhoto =
new PHJProjectPhoto
{
ProjectPhoto = stream.ToArray(), // <<--- This will convert your stream to a byte[]
OrderDate = DateTime.Now,
ProjectPhotoCaption = ProjectPhotoCaptionTextBox.Text,
ProjectId = selectedProjectId
};
```
|
268,023 |
<p>I have read the answers for <a href="https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform">What's the best way to check if a file exists in C? (cross platform)</a>, but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all. </p>
<p>Both <code>stat</code> and <code>access</code> are pretty much ungoogleable. What should I <code>#include</code> to use these?</p>
|
[
{
"answer_id": 268031,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 4,
"selected": false,
"text": "<p>Use stat(), if it is cross-platform enough for your needs. It is not C++ standard though, but POSIX.</p>\n\n<p>On MS Windows there is _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64.</p>\n"
},
{
"answer_id": 268047,
"author": "Andreas Magnusson",
"author_id": 5811,
"author_profile": "https://Stackoverflow.com/users/5811",
"pm_score": 9,
"selected": true,
"text": "<p>Use <a href=\"http://www.boost.org/doc/libs/1_37_0/libs/filesystem/doc/index.htm\" rel=\"noreferrer\">boost::filesystem</a>:</p>\n\n<pre><code>#include <boost/filesystem.hpp>\n\nif ( !boost::filesystem::exists( \"myfile.txt\" ) )\n{\n std::cout << \"Can't find my file!\" << std::endl;\n}\n</code></pre>\n"
},
{
"answer_id": 268147,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 3,
"selected": false,
"text": "<p>How about <code>access</code>?</p>\n\n<pre><code>#include <io.h>\n\nif (_access(filename, 0) == -1)\n{\n // File does not exist\n}\n</code></pre>\n"
},
{
"answer_id": 268435,
"author": "fizzer",
"author_id": 18167,
"author_profile": "https://Stackoverflow.com/users/18167",
"pm_score": 3,
"selected": false,
"text": "<p>I would reconsider trying to find out if a file exists. Instead, you should try to open it (in Standard C or C++) in the same mode you intend to use it. What use is knowing that the file exists if, say, it isn't writable when you need to use it?</p>\n"
},
{
"answer_id": 268525,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": 5,
"selected": false,
"text": "<p>I am a happy boost user and would certainly use Andreas' solution. But if you didn't have access to the boost libs you can use the stream library:</p>\n\n<pre><code>ifstream file(argv[1]);\nif (!file)\n{\n // Can't open file\n}\n</code></pre>\n\n<p>It's not quite as nice as boost::filesystem::exists since the file will actually be opened...but then that's usually the next thing you want to do anyway.</p>\n"
},
{
"answer_id": 268598,
"author": "rlerallut",
"author_id": 20055,
"author_profile": "https://Stackoverflow.com/users/20055",
"pm_score": 5,
"selected": false,
"text": "<p>Be careful of race conditions: if the file disappears between the \"exists\" check and the time you open it, your program will fail unexpectedly.</p>\n\n<p>It's better to go and open the file, check for failure and if all is good then do something with the file. It's even more important with security-critical code.</p>\n\n<p>Details about security and race conditions:\n<a href=\"http://www.ibm.com/developerworks/library/l-sprace.html\" rel=\"noreferrer\">http://www.ibm.com/developerworks/library/l-sprace.html</a></p>\n"
},
{
"answer_id": 17195806,
"author": "Samer",
"author_id": 1707083,
"author_profile": "https://Stackoverflow.com/users/1707083",
"pm_score": 3,
"selected": false,
"text": "<p>Another possibility consists in using the <code>good()</code> function in the stream:</p>\n\n<pre><code>#include <fstream> \nbool checkExistence(const char* filename)\n{\n ifstream Infield(filename);\n return Infield.good();\n}\n</code></pre>\n"
},
{
"answer_id": 38628843,
"author": "gsamaras",
"author_id": 2411320,
"author_profile": "https://Stackoverflow.com/users/2411320",
"pm_score": 2,
"selected": false,
"text": "<p><strong>NO <a href=\"/questions/tagged/boost\" class=\"post-tag\" title=\"show questions tagged 'boost'\" rel=\"tag\">boost</a> REQUIRED</strong>, which would be an <em>overkill</em>.</p>\n\n<hr>\n\n<p>Use <a href=\"http://man7.org/linux/man-pages/man2/stat.2.html\" rel=\"nofollow noreferrer\">stat()</a> (not cross platform though as mentioned by pavon), like this:</p>\n\n<pre><code>#include <sys/stat.h>\n#include <iostream>\n\n// true if file exists\nbool fileExists(const std::string& file) {\n struct stat buf;\n return (stat(file.c_str(), &buf) == 0);\n}\n\nint main() {\n if(!fileExists(\"test.txt\")) {\n std::cerr << \"test.txt doesn't exist, exiting...\\n\";\n return -1;\n }\n return 0;\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt\nls: test.txt: No such file or directory\nC02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp\nC02QT2UBFVH6-lm:~ gsamaras$ ./a.out\ntest.txt doesn't exist, exiting...\n</code></pre>\n\n<p>Another version (and that) can be found <a href=\"https://techoverflow.net/blog/2013/08/21/how-to-check-if-file-exists-using-stat/\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 52527922,
"author": "Reza Saadati",
"author_id": 4641680,
"author_profile": "https://Stackoverflow.com/users/4641680",
"pm_score": 0,
"selected": false,
"text": "<p>If you are already using the input file stream class (<code>ifstream</code>), you could use its function <code>fail()</code>.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>ifstream myFile;\n\nmyFile.open(\"file.txt\");\n\n// Check for errors\nif (myFile.fail()) {\n cerr << \"Error: File could not be found\";\n exit(1);\n}\n</code></pre>\n"
},
{
"answer_id": 54992948,
"author": "AlbertM",
"author_id": 8469676,
"author_profile": "https://Stackoverflow.com/users/8469676",
"pm_score": 4,
"selected": false,
"text": "<p>If your compiler supports C++17 you don't need boost, you can simply use <a href=\"https://en.cppreference.com/w/cpp/filesystem/exists\" rel=\"noreferrer\"><code>std::filesystem::exists</code></a></p>\n\n<pre><code>#include <iostream> // only for std::cout\n#include <filesystem>\n\nif (!std::filesystem::exists(\"myfile.txt\"))\n{\n std::cout << \"File not found!\" << std::endl;\n}\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268023",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
] |
I have read the answers for [What's the best way to check if a file exists in C? (cross platform)](https://stackoverflow.com/questions/230062/whats-the-best-way-to-check-if-a-file-exists-in-c-cross-platform), but I'm wondering if there is a better way to do this using standard c++ libs? Preferably without trying to open the file at all.
Both `stat` and `access` are pretty much ungoogleable. What should I `#include` to use these?
|
Use [boost::filesystem](http://www.boost.org/doc/libs/1_37_0/libs/filesystem/doc/index.htm):
```
#include <boost/filesystem.hpp>
if ( !boost::filesystem::exists( "myfile.txt" ) )
{
std::cout << "Can't find my file!" << std::endl;
}
```
|
268,025 |
<p>The install instructions are:</p>
<pre><code>$ python setup.py build
$ sudo python setup.py install # or su first
</code></pre>
<p>This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 268054,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 2,
"selected": false,
"text": "<p>From the <a href=\"http://peak.telecommunity.com/DevCenter/EasyInstall#command-line-options\" rel=\"nofollow noreferrer\">EasyInstall</a> doc, command line options:</p>\n<blockquote>\n<p>--always-unzip, -Z</p>\n<p>Don't install any packages as zip files, even if the packages are marked as safe for running as a zipfile.</p>\n</blockquote>\n<p>Can you use <em>easyinstall</em> instead of calling setup.py ?</p>\n<p>calling <code>easy_install -Z mysql_python</code> from the command prompt, finds the egg on the net and installs it.</p>\n"
},
{
"answer_id": 268101,
"author": "monk.e.boy",
"author_id": 563932,
"author_profile": "https://Stackoverflow.com/users/563932",
"pm_score": 4,
"selected": true,
"text": "<p>OK, I hate to answer my own question, but:</p>\n\n<p>find your python site-packages (mine is /usr/local/lib/python2.5/site-packages )</p>\n\n<p>then:</p>\n\n<pre><code>$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg\n</code></pre>\n\n<p>This worked fine for me</p>\n"
},
{
"answer_id": 268111,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 1,
"selected": false,
"text": "<p>This will tell setuptools to not zip it up:</p>\n\n<pre><code>sudo python setup.py install --single-version-externally-managed\n</code></pre>\n"
},
{
"answer_id": 1460602,
"author": "jps",
"author_id": 98088,
"author_profile": "https://Stackoverflow.com/users/98088",
"pm_score": 2,
"selected": false,
"text": "<p>I'm a little late to this party, but here's a way to do it that seems to work great:</p>\n\n<pre><code>sudo python setup.py install --single-version-externally-managed --root=/\n</code></pre>\n\n<p>And then you don't use a .python-egg, any *.pth files etc.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268025",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/563932/"
] |
The install instructions are:
```
$ python setup.py build
$ sudo python setup.py install # or su first
```
This gives me an .egg file. How do I tell the install to dump the files as a normal, uncompressed library?
Thanks!
|
OK, I hate to answer my own question, but:
find your python site-packages (mine is /usr/local/lib/python2.5/site-packages )
then:
```
$ unzip MySQL_python-1.2.2-py2.5-linux-i686.egg
```
This worked fine for me
|
268,037 |
<p>I am working on creating a custom project template with Visual Studio 2008 Team System edition. I have also created a custom wizard for the custom template.</p>
<p>So I have to update the vstemplate file to tell the template to use my custom wizard. But the archive is corrupted!</p>
<p>7zip thinks folders within the archive are using non-standard zip compression. The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.</p>
<p>What am I doing wrong?</p>
<p>If I don't change the template zip file created by VS2008, it works just fine. But I need to be able to update the zip file. If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore. Files that are in folders within the zip file are inaccessible.</p>
<p>I do notice that the standard templates seem to keep a flat file structure. That is no nested folders or anything. But the vstemplate file has targetfilename attributes that recreate the original folder structure.</p>
<p>For example instead of...</p>
<pre><code><Folder Name="My Project" TargetFolderName="My Project">
<ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</Folder>
</code></pre>
<p>the standard vstemplate defines the following...</p>
<pre><code><ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</code></pre>
<p>I've just had a little think about the above. Are they actually the same thing?</p>
<p>Is the problem with the creation of the original zip file?</p>
<p>Is the folder structure within the zip file tripping everything up?</p>
<p>Should it have added all the files to the zip archive in as flat folder structure? If so is there a fix for VS2008 so that I do not have to manually fix the template archives?</p>
|
[
{
"answer_id": 603214,
"author": "penyaskito",
"author_id": 3008,
"author_profile": "https://Stackoverflow.com/users/3008",
"pm_score": 0,
"selected": false,
"text": "<p>Same problem here. I solved it by using <code><ProjectItem>MyFolder\\MyFile.cs</ProjectItem></code> instead of <code><Folder>...<Folder></code>.</p>\n\n<p>PS: TargetFileName doesn't work for me in VS2008 + Windows7.</p>\n"
},
{
"answer_id": 615154,
"author": "mackenir",
"author_id": 25457,
"author_profile": "https://Stackoverflow.com/users/25457",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like Visual Studio creates non-standard ZIP files. My solution was to unzip the template zip file generated by VS, and then re-zip the files with WinZip.</p>\n\n<p>You say VS2008 cant access all the files in the template when you do this, but here at least the resulting zip file didn't cause any problems for VS2008.</p>\n"
},
{
"answer_id": 3337528,
"author": "David Boike",
"author_id": 10039,
"author_profile": "https://Stackoverflow.com/users/10039",
"pm_score": 2,
"selected": false,
"text": "<p>You don't need to modify the contents of the archive to be flat.</p>\n\n<p>The trick is after editing the unzipped contents of the archive, instead of selecting the folder and zipping that, open the folder and select all the files (and folders if present), and zip those instead.</p>\n\n<p>This is what is preventing Visual Studio from recognizing the archive as a template. This should work with 7-Zip, WinRAR, or whatever you happen to prefer to the bloatware that is WinZip.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268037",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19377/"
] |
I am working on creating a custom project template with Visual Studio 2008 Team System edition. I have also created a custom wizard for the custom template.
So I have to update the vstemplate file to tell the template to use my custom wizard. But the archive is corrupted!
7zip thinks folders within the archive are using non-standard zip compression. The latest winzip thinks the CRC header on the folders doesn't match the main CRC header.
What am I doing wrong?
If I don't change the template zip file created by VS2008, it works just fine. But I need to be able to update the zip file. If I do, 7zip/winzip fixes the zip file structure and then VS2008 doesn't like the template anymore. Files that are in folders within the zip file are inaccessible.
I do notice that the standard templates seem to keep a flat file structure. That is no nested folders or anything. But the vstemplate file has targetfilename attributes that recreate the original folder structure.
For example instead of...
```
<Folder Name="My Project" TargetFolderName="My Project">
<ProjectItem ReplaceParameters="true" TargetFileName="AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
</Folder>
```
the standard vstemplate defines the following...
```
<ProjectItem ReplaceParameters="true" TargetFileName="My Project\AssemblyInfo.vb">AssemblyInfo.vb</ProjectItem>
```
I've just had a little think about the above. Are they actually the same thing?
Is the problem with the creation of the original zip file?
Is the folder structure within the zip file tripping everything up?
Should it have added all the files to the zip archive in as flat folder structure? If so is there a fix for VS2008 so that I do not have to manually fix the template archives?
|
You don't need to modify the contents of the archive to be flat.
The trick is after editing the unzipped contents of the archive, instead of selecting the folder and zipping that, open the folder and select all the files (and folders if present), and zip those instead.
This is what is preventing Visual Studio from recognizing the archive as a template. This should work with 7-Zip, WinRAR, or whatever you happen to prefer to the bloatware that is WinZip.
|
268,045 |
<p>I am looking for a tool to replace multiple lines through out a project. For example:</p>
<pre><code>#include "../DiscreteIO/Discrete.h"
#include "../PCI/pci.h"
#include "../Arinc429/ARINC429.h"
</code></pre>
<p>with</p>
<pre><code>#include "../PCI/pci.h"
#include "../DiscreteIO/DiscreteHW.h"
#include "../DiscreteIO/Discrete.h"
</code></pre>
<p>I have tried two tools that work for this type of search and replace. <a href="http://www.textpad.com/products/wildedit/index.html" rel="noreferrer">Wildedit</a> and <a href="http://www.divlocsoft.com/" rel="noreferrer">Actual search and replace</a> Both seem to be excellent tools but are shareware. Do anybody know of similar tools? Anything free or is it time to part with some money?</p>
<p><strong>Clarification:</strong> </p>
<p><strong>through out a project</strong> in this case means a thousand plus c files. The text editors can do this only one file at a time (Textpad, Programmers notepad) or in all open files(nodepad++). I haven't tried any of the other editors but I assume they will have similar problems. Please correct me if I am wrong.</p>
<p>Tools like sed & awk is a solution but present problems since I do not use them regularly and need to spend some time getting something to work since I am not a expert on the tools.</p>
<p><strong>The answer is:</strong> All of it...</p>
<p>Ultra edit can work but I already have an editor and the price is steep if I am just going to use it as a search and replace tool.</p>
<p>Sed, AWK and regular expression based tools can work but can be a pain in some cases.</p>
<p>Wild Edit can work and is not that expensive.</p>
<p>My decision in the end is to work my Regular expression skills.</p>
|
[
{
"answer_id": 268071,
"author": "Stephen Denne",
"author_id": 11721,
"author_profile": "https://Stackoverflow.com/users/11721",
"pm_score": 0,
"selected": false,
"text": "<p><a href=\"http://www.ultraedit.com/\" rel=\"nofollow noreferrer\">Ultraedit</a> can do that. I parted with money for it.</p>\n\n<p>There is <a href=\"http://www.ultraedit.com/support/tutorials_power_tips/ultraedit/multiline_find_replace.html\" rel=\"nofollow noreferrer\">a tutorial on multi-line find & replace</a> which you can use with \"<a href=\"http://www.ultraedit.com/support/tutorials_power_tips/ultraedit/find_replace.html\" rel=\"nofollow noreferrer\">replace in files</a>\" to apply over multiple files.</p>\n"
},
{
"answer_id": 268075,
"author": "Yann Semet",
"author_id": 5788,
"author_profile": "https://Stackoverflow.com/users/5788",
"pm_score": 0,
"selected": false,
"text": "<p>I'm pretty sure a combination of sed, awk and/or grep would do the job. They're free and come with any Linux distribution but Windows versions exist as well.</p>\n"
},
{
"answer_id": 268090,
"author": "The Archetypal Paul",
"author_id": 21755,
"author_profile": "https://Stackoverflow.com/users/21755",
"pm_score": 4,
"selected": true,
"text": "<p>sed will do what you want.</p>\n\n<p>See the FAQ entry about exactly this here <a href=\"http://sed.sourceforge.net/sedfaq4.html#s4.23.3\" rel=\"nofollow noreferrer\">http://sed.sourceforge.net/sedfaq4.html#s4.23.3</a></p>\n\n<blockquote>\n <p>If you need to match a static block of\n text (which may occur any number of\n times throughout a file), where the\n contents of the block are known in\n advance, then this script is easy to\n use</p>\n</blockquote>\n\n<p>Sed is available for Windows. See <a href=\"http://gnuwin32.sourceforge.net/packages/sed.htm\" rel=\"nofollow noreferrer\">http://gnuwin32.sourceforge.net/packages/sed.htm</a></p>\n"
},
{
"answer_id": 268415,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 0,
"selected": false,
"text": "<p>I am always perplex when people ask for tools without telling for which platform(s) they need them... In these cases, I suppose it is, by default, for Windows...</p>\n\n<p>There are a number of search/replace tools available for Windows, more or less powerful, lot of them free.<br>\nCurrently, I use the Search/Replace module of <a href=\"http://www.lopesoft.com/en/fmtools/info.html\" rel=\"nofollow noreferrer\" title=\"FileMenu Tools 5.4.1\">FileMenu Tools</a>, surprisingly powerful (you can use regular expressions), coming with lot of other goodies.<br>\nI have also RJL Soft's <a href=\"http://www.rjlsoftware.com/software/utility/search/\" rel=\"nofollow noreferrer\" title=\"Simple Search-Replace\">Simple Search-Replace</a> (no REs), TortoiseSVN author's <a href=\"http://tools.tortoisesvn.net/\" rel=\"nofollow noreferrer\" title=\"grepWin\">grepWin</a>, supporting regexes and a good number of options, and there are some others I used in the past.</p>\n\n<p>PS.: I forgot. Simple Search-Replace won't do multi-line replaces. Neither FileMenu Tools, apparently. grepWin can do (using \\r\\n for example).\nI do recall such free tools with multi-line search/replace fields, but I don't have their names at hand.</p>\n"
},
{
"answer_id": 268482,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://regexsearch.sourceforge.net/\" rel=\"nofollow noreferrer\">RegexSearch</a> is a bit ugly but a very useful tool for just this sort of thing.</p>\n"
},
{
"answer_id": 540781,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>The best tool I've found is a piece of freeware called <a href=\"http://www.snapfiles.com/get/bkreplace.html\" rel=\"nofollow noreferrer\">BK ReplaceEm</a>. The interface takes a bit of getting used to, but it's worth learning how to use it. The tool is very powerful and allows you to do multi-line replaces with or without regular expressions.</p>\n"
},
{
"answer_id": 596755,
"author": "Yordan Georgiev",
"author_id": 65706,
"author_profile": "https://Stackoverflow.com/users/65706",
"pm_score": 0,
"selected": false,
"text": "<pre><code>#see docs at the bottom \nuse strict;\nuse warnings;\nuse Cwd;\n\nuse File::Find;\n\nmy $search_patternFilePath=$ARGV[0] ;\nmy $replace_patternFilePath =$ARGV[1];\nmy $file_pattern = $ARGV[2];\n\n# Usage\n\n(@ARGV == 3 ) || die (\"Usage: FindAndReplace.pl pathToFileContaingTheMultiLineSearchText FullPathToFileContainingMultiLineReplaceText FilePattern . Example: perl MultiLineFindAndReplace.pl \\\"D:\\Opera\\New Folder\\search.txt\\\" \\\"D:\\Opera\\replace.txt\\\" bak\");\n\n\n\nfind(\\&d, cwd);\n\nsub d {\nmy $file = $File::Find::name;\n$file =~ s,/,\\\\,g;\n\nreturn unless -f $file;\nreturn unless $file =~ /$file_pattern/;\n\nmy $searchPatternString = &slurpFile ( $search_patternFilePath ) ; \nmy $replacePatternString = &slurpFile ( $replace_patternFilePath ) ; \nmy $fileStr = &slurpFile ( $file ) ; \n\n$fileStr =~ s/$searchPatternString/$replacePatternString/igo ; \nopen(FILEHANDLE,\">$file\") || die \"cannot open output file\";\nprint (FILEHANDLE \"$fileStr\");\nclose FILEHANDLE ;\n\n}\n\nsub slurpFile \n{\nmy $file = shift ;\nprint \"\\$file is $file\" ;\nlocal( $/, *FILE ) ; \nopen (FILE , $file) or \ndie \"Cannot find $file !!! \" ; \nmy $fileString = <FILE>; #slurp the whole file into one string !!! \nclose FILE ;\nreturn $fileString ;\n}\n#Purpose : performs recursive find and replace based on pеrl regexes from the current directory\n#the search and replace is case insensitive\n#Usage\n#perl MultiLineFindAndReplace.pl \"D:\\Opera\\New Folder\\search.txt\" \"D:\\Opera\\replace.txt\" bak\n</code></pre>\n"
},
{
"answer_id": 596781,
"author": "Zsolt Botykai",
"author_id": 11621,
"author_profile": "https://Stackoverflow.com/users/11621",
"pm_score": 2,
"selected": false,
"text": "<pre><code>cd $PROJECTDIR && find . -iname '*.*' -exec vim -c 's:^first line of text\\nsecond line of text\\n3rd line of text:new 1st line\\rnew 2nd\\rnew 3rd:' -c 'w!' -c 'q' {} \\;\n</code></pre>\n\n<p>HTH</p>\n"
},
{
"answer_id": 8277053,
"author": "Tyr Antilles",
"author_id": 1066686,
"author_profile": "https://Stackoverflow.com/users/1066686",
"pm_score": 2,
"selected": false,
"text": "<p>I successfully used Multiple Find And Replace 1.10, a freeware program that do just that: searches for multiple lines in a TXT or list of TXT's and replace them with other text at your wish or delete them. I found it here for download: <a href=\"http://www.softpedia.com/get/System/File-Management/Multiple-Find-And-Replace.shtml\" rel=\"nofollow\">http://www.softpedia.com/get/System/File-Management/Multiple-Find-And-Replace.shtml</a></p>\n"
},
{
"answer_id": 14839167,
"author": "Rich",
"author_id": 8261,
"author_profile": "https://Stackoverflow.com/users/8261",
"pm_score": 4,
"selected": false,
"text": "<p>The JetBrains family of IDEs: <a href=\"http://www.jetbrains.com/idea/\">IntelliJ</a>, <a href=\"http://www.jetbrains.com/ruby/\">RubyMine</a>, <a href=\"http://www.jetbrains.com/phpstorm/\">PHPStorm</a> etc. will do a multi-line search and replace.</p>\n\n<p>Select the text in question and press <code>ctrl-shift-F</code> -- this will open the replace dialog with the selected text as the find expression (using a regex with newlines escaped as <code>\\n</code>)</p>\n"
},
{
"answer_id": 39280154,
"author": "sporker",
"author_id": 435515,
"author_profile": "https://Stackoverflow.com/users/435515",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not allowed to comment, but the accepted solution cites an example that seems broken. Line 18 should be:</p>\n\n<pre><code>s,[/\\.*[],\\\\&,g\n</code></pre>\n\n<p>Not</p>\n\n<pre><code>s,[/\\[.*],\\\\&,g\n</code></pre>\n\n<p>The latter will complain with modern sed (or 'gsed' if you're in *BSD) about an unterminated expression on line 18.</p>\n"
},
{
"answer_id": 45141270,
"author": "Bruno Vincent",
"author_id": 5771893,
"author_profile": "https://Stackoverflow.com/users/5771893",
"pm_score": 2,
"selected": false,
"text": "<p>Only thing that works turnkey in one shot is dreamweaver....<a href=\"https://i.stack.imgur.com/wxLca.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/wxLca.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 56535387,
"author": "Kissaki",
"author_id": 392626,
"author_profile": "https://Stackoverflow.com/users/392626",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"https://code.visualstudio.com/\" rel=\"nofollow noreferrer\">Visual Studio Code</a> has an exceptionally good “global” search and replace. I just used it for multiple multi-line changes on numerous files, including some Regexp search with capture and replace.</p>\n\n<ul>\n<li>Open VS Code</li>\n<li>File → Open Folder, open the folder your files reside in</li>\n<li>Open a file and select the text you want to replace</li>\n<li>CTRL + SHIFT + H to open Search & Replace</li>\n<li>If you selected a text it will auto-fill, even multi line. Otherwise enter the text, use SHIFT + Enter to insert newlines, and optionally enable Regexp.</li>\n<li>Enter the replacement text</li>\n<li>Press Enter to start the search</li>\n<li>Click on change-items to preview the changes side by side</li>\n<li>Use the Replace All button (CTRL + ALT + Enter) to apply and save the changes</li>\n</ul>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268045",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34989/"
] |
I am looking for a tool to replace multiple lines through out a project. For example:
```
#include "../DiscreteIO/Discrete.h"
#include "../PCI/pci.h"
#include "../Arinc429/ARINC429.h"
```
with
```
#include "../PCI/pci.h"
#include "../DiscreteIO/DiscreteHW.h"
#include "../DiscreteIO/Discrete.h"
```
I have tried two tools that work for this type of search and replace. [Wildedit](http://www.textpad.com/products/wildedit/index.html) and [Actual search and replace](http://www.divlocsoft.com/) Both seem to be excellent tools but are shareware. Do anybody know of similar tools? Anything free or is it time to part with some money?
**Clarification:**
**through out a project** in this case means a thousand plus c files. The text editors can do this only one file at a time (Textpad, Programmers notepad) or in all open files(nodepad++). I haven't tried any of the other editors but I assume they will have similar problems. Please correct me if I am wrong.
Tools like sed & awk is a solution but present problems since I do not use them regularly and need to spend some time getting something to work since I am not a expert on the tools.
**The answer is:** All of it...
Ultra edit can work but I already have an editor and the price is steep if I am just going to use it as a search and replace tool.
Sed, AWK and regular expression based tools can work but can be a pain in some cases.
Wild Edit can work and is not that expensive.
My decision in the end is to work my Regular expression skills.
|
sed will do what you want.
See the FAQ entry about exactly this here <http://sed.sourceforge.net/sedfaq4.html#s4.23.3>
>
> If you need to match a static block of
> text (which may occur any number of
> times throughout a file), where the
> contents of the block are known in
> advance, then this script is easy to
> use
>
>
>
Sed is available for Windows. See <http://gnuwin32.sourceforge.net/packages/sed.htm>
|
268,048 |
<p>Take the following function:</p>
<pre><code>DataTable go() {
return someTableAdapter.getSomeData();
}
</code></pre>
<p>When I set a breakpoint in this function, is there a possibility to inspect the returned value? <code>go()</code> is directly coupled to a datagrid in an <code>.aspx</code> page.</p>
<p>The only way to inspect the returned datatable is to use a temporary variable. However, that's a bit inconvenient. Isn't there another way?</p>
|
[
{
"answer_id": 268052,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 9,
"selected": true,
"text": "<p>Not that I know of. Note that if you <em>do</em> add a variable, it will get removed by the compiler in release builds anyway...</p>\n\n<p><strong>Update:</strong>\n<a href=\"https://devblogs.microsoft.com/devops/seeing-function-return-values-in-the-visual-studio-2013-debugger/\" rel=\"noreferrer\">This functionality has been added to VS2013</a>.\nYou can see the return values in the autos windows or use <code>$ReturnValue</code> in the watch/immediate window.</p>\n\n<p>The value can only be seen directly after returning from the function, thus the easiest way to access it is by putting a breakpoint on the function call and step over (F10) the call.</p>\n\n<hr>\n\n<p>Update for VS2015: boo! unfortunately, it doesn't appear to be in VS2015 (devenv v14)<br>\nUpdate for VS2017: it's back. (devenv v15)</p>\n"
},
{
"answer_id": 268059,
"author": "Yann Semet",
"author_id": 5788,
"author_profile": "https://Stackoverflow.com/users/5788",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to select <code>\"someTableAdapter.getSomeData();\"</code>, right click on it, and go for <em>Quick Watch</em>.</p>\n"
},
{
"answer_id": 268095,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 1,
"selected": false,
"text": "<p>You can also ask to evaluate the value in the intermediate window as well, if it does not set flags or other variables, but only returns something.</p>\n"
},
{
"answer_id": 268122,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 4,
"selected": false,
"text": "<p>Step out of the go() method using Shift-F11, and then in the \"Autos\" debug window it will show the return value of the method call which just popped off the stack (in this case, the go() method which is what you want). This is the behaviour in Visual Studio 2005; I haven't used Visual Studio 2008 so I don't know if this behaves the same way in that version.</p>\n"
},
{
"answer_id": 268139,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 1,
"selected": false,
"text": "<p>Opening the Debug → Autos window gets you close. It won't show the actual return value, but it will show what was evaluated in the return statement.</p>\n"
},
{
"answer_id": 456659,
"author": "Sylvain Rodrigue",
"author_id": 54783,
"author_profile": "https://Stackoverflow.com/users/54783",
"pm_score": 2,
"selected": false,
"text": "<p>The only way I know is to place a breakpoint on the return line and then call the <em>Quick Watch</em> window and enter the returned expression:</p>\n\n<pre><code>someTableAdapter.getSomeData();\n</code></pre>\n\n<p>But this only works if the call does not change the state of any object (since there will be a second call to the same method when you will resume the execution).</p>\n"
},
{
"answer_id": 526853,
"author": "Pita.O",
"author_id": 40406,
"author_profile": "https://Stackoverflow.com/users/40406",
"pm_score": 0,
"selected": false,
"text": "<p>Drag and drop the return expression into a watch window.</p>\n\n<p>For example, in the statement</p>\n\n<pre><code>return someTableAdapter.getSomeData();\n</code></pre>\n\n<p>drag and drop</p>\n\n<pre><code>someTableAdapter.getSomeData()\n</code></pre>\n\n<p>into a watch window, and you'll see the value.</p>\n\n<p>You can do this for any expression.</p>\n"
},
{
"answer_id": 527408,
"author": "doekman",
"author_id": 56,
"author_profile": "https://Stackoverflow.com/users/56",
"pm_score": 3,
"selected": false,
"text": "<p>There are a lot of workarounds, but none seems satisfactory.</p>\n\n<p>To quote John Skeet below (comment on a now-deleted answer):</p>\n\n<blockquote>\n <p>Still looks inconvenient to me -\n especially if you don't know which\n return value you're going to need\n before you start debugging. I really\n don't want to have to have a temporary\n variable cluttering up my code every\n time I ever return anything.t</p>\n</blockquote>\n\n<p>In theory, the debugger could have a <code>return</code>-variable. After all: it's just a variable on the stack:</p>\n\n<pre><code>unsafe {\n int * sp = stackalloc int[1];\n try {\n return a+b;\n }\n finally {\n Trace.WriteLine(\"return is \" + *(sp+3));\n }\n}\n</code></pre>\n\n<p>So consider this a feature request for Visual Studio.</p>\n"
},
{
"answer_id": 3052614,
"author": "Sprintstar",
"author_id": 15233,
"author_profile": "https://Stackoverflow.com/users/15233",
"pm_score": 2,
"selected": false,
"text": "<p>Microsoft Visual C++ used to do this, but Visual Studio doesn't AFAIK.. :(</p>\n"
},
{
"answer_id": 3714884,
"author": "Alex Angas",
"author_id": 6651,
"author_profile": "https://Stackoverflow.com/users/6651",
"pm_score": 6,
"selected": false,
"text": "<p>This can be done in Visual Studio 2013 with CLR 4.5.1 <a href=\"http://visualstudio.uservoice.com/forums/121579-visual-studio/suggestions/2206747-function-return-value-in-debugger\" rel=\"nofollow noreferrer\">according to the customer feedback site</a>. It was not available in previous versions for C#.</p>\n\n<p>(Visual Studio 2008 and earlier supported it for VB.NET. It has always been available to C/C++ developers.)</p>\n"
},
{
"answer_id": 5473135,
"author": "Ross Buggins",
"author_id": 1310391,
"author_profile": "https://Stackoverflow.com/users/1310391",
"pm_score": 4,
"selected": false,
"text": "<p>If you go to menu <em>Tools</em> → <em>Options</em>, IntelliTrace, and change the setting to collect events and call information.</p>\n\n<p>You can go back to the previous call event (<kbd>Ctrl</kbd> + <kbd>Shift</kbd> + <kbd>F11</kbd>) and see the temporary value returned from the method call in the autos window as a child of the method name.</p>\n\n<p>This isn't showing you the return value for the method you are in. It just shows you the return value of the last method called in the current method.</p>\n\n<p>So, it's fine for</p>\n\n<pre><code>DataTable go(){return someTableAdapter.getSomeData();}\n</code></pre>\n\n<p>as it shows you the return value for <code>someTableAdapter.getSomeData()</code>.</p>\n\n<p>But not for:</p>\n\n<pre><code>int go(){return 100 * 99;}\n</code></pre>\n"
},
{
"answer_id": 8180530,
"author": "Omer Raviv",
"author_id": 292555,
"author_profile": "https://Stackoverflow.com/users/292555",
"pm_score": 5,
"selected": false,
"text": "<p>I agree that this is a very useful thing to have: not only seeing the return value of the method before stepping out of it, but also seeing the return value of methods I just stepped over. I implemented it as part of a commercial extension to Visual Studio called \"<a href=\"http://www.oz-code.com\" rel=\"noreferrer\">OzCode</a>\".</p>\n\n<p>With it, you can view method return values right on the code editor, as sort of a HUD-display:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Kw7mp.gif\" alt=\"Statement Visualization\"></p>\n\n<p>For more information, please see <a href=\"http://www.youtube.com/embed/u_1Lgzf3Y00?autoplay=1&rel=0\" rel=\"noreferrer\">this video</a>.</p>\n"
},
{
"answer_id": 11072070,
"author": "Dan Solovay",
"author_id": 402949,
"author_profile": "https://Stackoverflow.com/users/402949",
"pm_score": 5,
"selected": false,
"text": "<p>According to Microsoft, there is no way to implement this reliably with managed code. This is a problem they are aware of and are working on:</p>\n\n<blockquote>\n <p>For those out there who have experience debugging native C++ or VB6 code, you may have used a feature where function return values are provided for you in the Autos window. Unfortunately, this functionality does not exist for managed code. While you can work around this issue by assigning the return values to a local variable, this is not as convenient because it requires modifying your code.\n In managed code, it’s a lot trickier to determine what the return value of a function you’ve stepped over. We realized that we couldn’t do the right thing consistently here and so we removed the feature rather than give you incorrect results in the debugger. However, we want to bring this back for you and our CLR and Debugger teams are looking at a number potential solutions to this problem. Unfortunately this is will not be part of Visual Studio 11.</p>\n</blockquote>\n\n<p><a href=\"https://connect.microsoft.com/VisualStudio/feedback/details/597933/add-a-return-pseudo-variable-to-the-visual-studio-debugger-for-net-code\" rel=\"noreferrer\">https://connect.microsoft.com/VisualStudio/feedback/details/597933/add-a-return-pseudo-variable-to-the-visual-studio-debugger-for-net-code</a></p>\n"
},
{
"answer_id": 13132495,
"author": "ColinM",
"author_id": 1784519,
"author_profile": "https://Stackoverflow.com/users/1784519",
"pm_score": 4,
"selected": false,
"text": "<p>Old trick from the pre .NET days: Open the Registers window and look at the value of the EAX register. This contains the return value of the last function called.</p>\n"
},
{
"answer_id": 17603233,
"author": "Joe Rattz",
"author_id": 24665,
"author_profile": "https://Stackoverflow.com/users/24665",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can determine this by looking at the RAX register in the Registers window (Debug / Windows / Registers). After stepping out (SHIFT + F11) of the function, check the RAX register. I don't know for a fact, but once upon a moon you could check a register (pre .NET days) and see the return value there. It might even be a combination of RAX and RBX, etc.</p>\n"
},
{
"answer_id": 24835720,
"author": "Tom",
"author_id": 401246,
"author_profile": "https://Stackoverflow.com/users/401246",
"pm_score": 1,
"selected": false,
"text": "<p>Yeah, by switching to VB.NET. ;P (You did just say \"Visual Studio\". ;)</p>\n\n<p>For as long as I can remember (from Visual Basic through all versions of VB.NET), you can simply query the function name. It \"functions\" like a local variable that's implicitly declared at the start of the function and its current value is also used as the return value whenever the function exits via non-return statement means (i.e. <code>Exit Function</code> or just falling through) and of course, when the return statement is used.</p>\n\n<p>It is also set to the return statement's expression. Just like a local variable, its value can be inspected at any point of execution inside the function (including after the return statement is executed). C# doesn't have this and should.</p>\n\n<p>That little VB.NET feature (plus the <code>Exit Function</code> statement which it enables - another feature C# doesn't have and should) is very useful in a form of <a href=\"https://en.wikipedia.org/wiki/Defensive_programming\" rel=\"nofollow noreferrer\">defensive programming</a> I practice where I always initialize the function name to the failure/default value as the first statement. Then, at any failure point (which normally occurs much more often than success points), I can simply call the <code>Exit Function</code> statement (i.e. without having to duplicate the failure / default expression or even a constant/variable name).</p>\n"
},
{
"answer_id": 25644366,
"author": "Konrad Viltersten",
"author_id": 1525840,
"author_profile": "https://Stackoverflow.com/users/1525840",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, there is a very nice way. One significant drawback is that you'd have to wait for 5, maybe 6 years. Since I see that you posted in November 2008, I suggest that you waaaaaa...</p>\n\n<p>...aaaait. And voilà! Just for you, MS has released the latest <strong>Visual Studio 2013</strong> where it's a default feature accessible from the menus <strong>while running</strong> in debug mode (menu <em>Debug</em> → <em>Windows</em> → <em>Autos</em>).</p>\n"
},
{
"answer_id": 36081401,
"author": "PascalK",
"author_id": 942851,
"author_profile": "https://Stackoverflow.com/users/942851",
"pm_score": 5,
"selected": false,
"text": "<p><em>Regarding Visual Studio 2015:</em></p>\n\n<p>According to the currently accepted answer by Marc Gravell:</p>\n\n<blockquote>\n <p>This <a href=\"http://blogs.msdn.com/b/visualstudioalm/archive/2013/06/27/seeing-function-return-values-in-the-debugger-in-visual-studio-2013.aspx\" rel=\"noreferrer\">functionality has been added to Visual Studio 2013</a>. You can see the return\n values in the autos windows or use $ReturnValue in the watch/immediate\n window</p>\n</blockquote>\n\n<p>That answer also stated that this functionality does not work in Visual Studio 2015. This is not (entirely) true. On <em><a href=\"https://msdn.microsoft.com/en-us/library/dn323257.aspx\" rel=\"noreferrer\">Examine return values of method calls</a></em> there is the following note:</p>\n\n<blockquote>\n <p>You must have the legacy expression evaluators turned on for <strong>$ReturnValue</strong> to be recognized <strong>(Tools / Options / Debugging / Use the legacy C# and VB expression evaluators</strong>). Otherwise, you can use <strong>$ReturnValue1</strong>.</p>\n</blockquote>\n\n<p>I tested this in Visual Studio 2015 Enterprise:</p>\n\n<ul>\n<li>With legacy expression evaluators turned off: <em>only</em> <strong>$ReturnValue1</strong> works</li>\n<li>With legacy expression evaluators turned on: <em>both</em> <strong>$ReturnValue</strong> <em>and</em> <strong>$ReturnValue1</strong> work</li>\n</ul>\n"
},
{
"answer_id": 37556591,
"author": "splttingatms",
"author_id": 550608,
"author_profile": "https://Stackoverflow.com/users/550608",
"pm_score": 3,
"selected": false,
"text": "<p>I wanted to expand upon <a href=\"https://stackoverflow.com/questions/268048/can-i-find-out-the-return-value-before-returning-while-debugging-in-visual-studi/36081401#36081401\">PascalK's answer</a> for getting this to work in Visual Studio 2015, because there is a hidden feature which is not documented in <em><a href=\"https://msdn.microsoft.com/en-us/library/dn323257.aspx\" rel=\"nofollow noreferrer\">Examine return values of method calls</a></em>.</p>\n\n<p>If you have nested function calls, the pseudo-variables <code>$ResultValueX</code> are automatically created, where the X refers to the function call order. So if you have a call such as <code>Multiply(Five(), Six())</code>, the following pseudo-variables are created:</p>\n\n<pre><code>Five() | $ResultValue1 = 5\nSix() | $ResultValue2 = 6\nMultiply() | $ResultValue3 = 30\n</code></pre>\n"
},
{
"answer_id": 38458445,
"author": "Esben Skov Pedersen",
"author_id": 170196,
"author_profile": "https://Stackoverflow.com/users/170196",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://stackoverflow.com/questions/268048/can-i-find-out-the-return-value-before-returning-while-debugging-in-visual-studi/268052#268052\">The accepted answer</a> doesn't work properly with Visual Studio 2015, but by placing a break point on the last line of the method and pressing <kbd>F10</kbd>, it will put all expressions of the return value into the locals window.</p>\n"
},
{
"answer_id": 70519266,
"author": "Behzad",
"author_id": 809974,
"author_profile": "https://Stackoverflow.com/users/809974",
"pm_score": 2,
"selected": false,
"text": "<p>In VS2019, Just go to Debug->Windows->Autos window. There, you see concat return value as shown below:</p>\n<p><a href=\"https://i.stack.imgur.com/ENccs.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ENccs.png\" alt=\"enter image description here\" /></a></p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268048",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/56/"
] |
Take the following function:
```
DataTable go() {
return someTableAdapter.getSomeData();
}
```
When I set a breakpoint in this function, is there a possibility to inspect the returned value? `go()` is directly coupled to a datagrid in an `.aspx` page.
The only way to inspect the returned datatable is to use a temporary variable. However, that's a bit inconvenient. Isn't there another way?
|
Not that I know of. Note that if you *do* add a variable, it will get removed by the compiler in release builds anyway...
**Update:**
[This functionality has been added to VS2013](https://devblogs.microsoft.com/devops/seeing-function-return-values-in-the-visual-studio-2013-debugger/).
You can see the return values in the autos windows or use `$ReturnValue` in the watch/immediate window.
The value can only be seen directly after returning from the function, thus the easiest way to access it is by putting a breakpoint on the function call and step over (F10) the call.
---
Update for VS2015: boo! unfortunately, it doesn't appear to be in VS2015 (devenv v14)
Update for VS2017: it's back. (devenv v15)
|
268,064 |
<p>Looking at <code>System.Collections.Generic.Dictionary<TKey, TValue></code>, it clearly implements <code>ICollection<KeyValuePair<TKey, TValue>></code>, but doesn't have the required "<code>void Add(KeyValuePair<TKey, TValue> item)</code>" function.</p>
<p>This can also be seen when trying to initialize a <code>Dictionary</code> like this:</p>
<pre><code>private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
new KeyValuePair<string,int>("muh", 2)
};
</code></pre>
<p>which fails with </p>
<blockquote>
<p>No overload for method 'Add' takes '1' arguments</p>
</blockquote>
<p>Why is that so?</p>
|
[
{
"answer_id": 268083,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "<p>The expected API is to add via the two argument <code>Add(key,value)</code> method (or the <code>this[key]</code> indexer); as such, it uses explicit interface implementation to provide the <code>Add(KeyValuePair<,>)</code> method.</p>\n\n<p>If you use the <code>IDictionary<string, int></code> interface instead, you will have access to the missing method (since you can't hide anything on an interface).</p>\n\n<p>Also, with the collection initializer, note that you can use the alternative syntax:</p>\n\n<pre><code>Dictionary<string, int> PropertyIDs = new Dictionary<string, int> {\n {\"abc\",1}, {\"def\",2}, {\"ghi\",3}\n}\n</code></pre>\n\n<p>which uses the <code>Add(key,value)</code> method.</p>\n"
},
{
"answer_id": 268092,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 3,
"selected": false,
"text": "<p>Some interface methods are implemented <a href=\"http://msdn.microsoft.com/en-us/library/aa664591(VS.71).aspx\" rel=\"noreferrer\">explicitly</a>. If you use reflector you can see the explicitly implemented methods, which are:</p>\n\n<pre><code>void ICollection<KeyValuePair<TKey, TValue>>.Add(KeyValuePair<TKey, TValue> keyValuePair);\nbool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> keyValuePair);\nvoid ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int index);\nbool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> keyValuePair);\nIEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey, TValue>>.GetEnumerator();\nvoid ICollection.CopyTo(Array array, int index);\nvoid IDictionary.Add(object key, object value);\nbool IDictionary.Contains(object key);\nIDictionaryEnumerator IDictionary.GetEnumerator();\nvoid IDictionary.Remove(object key);\nIEnumerator IEnumerable.GetEnumerator();\n</code></pre>\n"
},
{
"answer_id": 268112,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "<p>It doesn't implement <code>ICollection<KeyValuePair<K,V>></code> directly. It implements <code>IDictionary<K,V></code>.</p>\n\n<p><code>IDictionary<K,V></code> derives from <code>ICollection<KeyValuePair<K,V>></code>.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
Looking at `System.Collections.Generic.Dictionary<TKey, TValue>`, it clearly implements `ICollection<KeyValuePair<TKey, TValue>>`, but doesn't have the required "`void Add(KeyValuePair<TKey, TValue> item)`" function.
This can also be seen when trying to initialize a `Dictionary` like this:
```
private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
new KeyValuePair<string,int>("muh", 2)
};
```
which fails with
>
> No overload for method 'Add' takes '1' arguments
>
>
>
Why is that so?
|
The expected API is to add via the two argument `Add(key,value)` method (or the `this[key]` indexer); as such, it uses explicit interface implementation to provide the `Add(KeyValuePair<,>)` method.
If you use the `IDictionary<string, int>` interface instead, you will have access to the missing method (since you can't hide anything on an interface).
Also, with the collection initializer, note that you can use the alternative syntax:
```
Dictionary<string, int> PropertyIDs = new Dictionary<string, int> {
{"abc",1}, {"def",2}, {"ghi",3}
}
```
which uses the `Add(key,value)` method.
|
268,069 |
<p>I have been trying to include a file in a included file e.g</p>
<p><strong>main.cpp file</strong></p>
<pre><code>#include <includedfile.cpp>
int main(){
cout<<name<<endl;
}
</code></pre>
<p><strong>includedfile.cpp</strong></p>
<pre><code>#include <iostream>
using namespace std;
string name;
name = "jim";
</code></pre>
<p>this code does not work, the debuger says that name is not defined.</p>
|
[
{
"answer_id": 268085,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 3,
"selected": false,
"text": "<p>You cannot have statements exist outside of a method!</p>\n\n<pre><code>name = \"jim\"; // This is outside of any method, so it is an error.\n</code></pre>\n\n<p>You could refactor your code so the variable declaration is also an initial assignment, which should be valid (my C++ is a bit rusty, so I might be wrong on this point).</p>\n\n<pre><code>string name = \"jim\";\n</code></pre>\n"
},
{
"answer_id": 268102,
"author": "Carl Seleborg",
"author_id": 2095,
"author_profile": "https://Stackoverflow.com/users/2095",
"pm_score": 0,
"selected": false,
"text": "<p>You have to have a very good reason to include a .cpp file, however. It happens, but it's rare! What exactly are you trying to achieve? Or are you just experimenting?</p>\n"
},
{
"answer_id": 268339,
"author": "tragomaskhalos",
"author_id": 31140,
"author_profile": "https://Stackoverflow.com/users/31140",
"pm_score": 0,
"selected": false,
"text": "<p>Changing <strong>includedfile.cpp</strong> to say</p>\n\n<pre><code>string name = \"jim\";\n</code></pre>\n\n<p>should work (confirmed by Comeau online).\nYou should really also explicitly do</p>\n\n<pre><code>#include <string>\n</code></pre>\n\n<p>as otherwise you're relying on the fact that this is done by iostream.</p>\n"
},
{
"answer_id": 1226093,
"author": "bgee",
"author_id": 7003,
"author_profile": "https://Stackoverflow.com/users/7003",
"pm_score": 0,
"selected": false,
"text": "<p>Well, of course it doesn't working because namespace defined works only in included.cpp. Simple solution here is to to write \"using\" once more in main.\nMany things in C\\C++ defined at a \"file scope\" and when you are inserting one in another, it's not exactly clear how to define such scope.</p>\n\n<p>Besides, it's indeed not good practice to include cpps. You should include h\\hpp files (headers), because it makes troubles in growing projects (cohesion) and makes problems like discussed here. </p>\n\n<pre><code>#include <includedfile.h>\n#include <iostream>\nint main()\n{ \n std::cout << name << endl;\n}\n\n//includedfile.cpp\nvoid DoSomething()\n{\n std::string name;\n name = \"jim\";\n}\n\n//includedfile.h\nvoid DoSomething();\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268069",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I have been trying to include a file in a included file e.g
**main.cpp file**
```
#include <includedfile.cpp>
int main(){
cout<<name<<endl;
}
```
**includedfile.cpp**
```
#include <iostream>
using namespace std;
string name;
name = "jim";
```
this code does not work, the debuger says that name is not defined.
|
You cannot have statements exist outside of a method!
```
name = "jim"; // This is outside of any method, so it is an error.
```
You could refactor your code so the variable declaration is also an initial assignment, which should be valid (my C++ is a bit rusty, so I might be wrong on this point).
```
string name = "jim";
```
|
268,079 |
<p>I have 3 lists, I will make them simple here. </p>
<p>list of letters<br>
A<br>
B<br>
C </p>
<p>list of numbers<br>
1<br>
2<br>
3 </p>
<p>Mixed<br>
A,1<br>
A,2<br>
B,2<br>
B,3<br>
C,1<br>
C,3</p>
<p>I need to know what is missing:<br>
A,3<br>
B,1<br>
C,2</p>
<p>The list of letters has about 85 entries<br>
and the list of numbers has about 500 entries.</p>
<p>The mixed list has about 75,000 entries.</p>
<p>I can use either a database query (mysql 5.0) or Turbo Delphi 2006 to process text files. What would be the best way to find what is missing?</p>
<p>Thanks,<br>
Dave</p>
|
[
{
"answer_id": 268099,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "<p>A cross join would produce every combination there is, given that you have both of your lists in SQL tables:</p>\n\n<pre><code>SELECT\n Letter + ',' + Number AS Combination\nFROM\n NumberList,\n LetterList\n</code></pre>\n\n<p>Using the combined result (maybe save it into a temporary table), you can use a NOT EXISTS query to find what is missing:</p>\n\n<pre><code>SELECT\n Combination\nFROM\n AllCombinations AS a\nWHERE\n NOT EXISTS \n (SELECT 1 FROM MyCombitations AS m WHERE m.Combination = a.Combination)\n</code></pre>\n\n<p>This would require a table <code>MyCombitations</code>, which lists all of the combinations you actually have and want to check against the full list.</p>\n\n<p>If you want to speed things up, you should use a permanent table of combinations and an index on the <code>MyCombitations.Combination</code> field. For repeated querying this is definitely advisable.</p>\n"
},
{
"answer_id": 268126,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 1,
"selected": false,
"text": "<p>75.000 is not much. Load list of letters and list of numbers into two separate TStringLists. Create dynamic array (indices would be indexes into those two string lists) with the appropriate dimensions. Fill it up. Load the data and mark each line in the array. Output all elements that were not marked.</p>\n\n<p>In pseudocode (untested):</p>\n\n<pre><code>var\n i1, i2: integer;\n sl1, sl2: TStringList;\n cross: array of array of boolean;\nbegin\n // load data into sl1, sl2\n SetLength(cross, sl1.Count, sl2.Count);\n for i1 := 0 to sl1.Count - 1 do\n for i2 := 0 to sl2.Count - 1 do\n cross[i1, i2] := false;\n // for each element in 'combined' list\n // split it into elements s1, s2\n i1 := sl1.IndexOf(s1);\n i2 := sl2.IndexOf(s2);\n if (i1 < 0) or (i2 < 0) then\n // report error\n else\n cross[i1, i2] := true;\n for i1 := 0 to sl1.Count - 1 do\n for i2 := 0 to sl2.Count - 1 do\n if not cross[i1, i2] then\n // output sl1[i1], sl2[i2]\nend;\n</code></pre>\n"
},
{
"answer_id": 268183,
"author": "Yann Semet",
"author_id": 5788,
"author_profile": "https://Stackoverflow.com/users/5788",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT letter,number FROM lettersTable l , numbersTable n WHERE\n(\n SELECT count(*) \n FROM \n (\n SELECT * \n FROM combinationsTable \n WHERE l.letter=combinationsTable.letter AND n.number = combinationsTable .number\n ) AS temp\n) = 0;\n</code></pre>\n\n<p>This relies on SELECT * FROM A,B testing all combinations (implicit cross-join).</p>\n"
},
{
"answer_id": 269225,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 1,
"selected": false,
"text": "<p>If you can sort the data (<a href=\"http://sourceforge.net/projects/tpsystools\" rel=\"nofollow noreferrer\">Turbo powers SysTools</a> has a good sort routine which works well) then you can do this in code fairly quickly with two input lists and an output list. The concept behind this is simple:</p>\n\n<ol>\n<li>Take two lists, sorted in the same manner</li>\n<li>If the left side is less than the right side, then the right side is missing that value so add it to your \"missing list\" and increment the cursor for the left side. </li>\n<li>If they are equal, then increment both, </li>\n<li>If the right side is less than the left side, then only increment the right side (optionally add to the \"must delete\" list).</li>\n</ol>\n\n<p>This process is sometimes refered to as the \"Old Master/New Master\" process and is extremely fast as your only walking both lists once.</p>\n\n<p>Simple example:</p>\n\n<pre><code>var\n ListL : tStringList; // the left list\n ListR : tSTringList; // the right list\n ListA : tSTringList; // the Add List (should start empty)\n ListD : tStringList; // the Delete list (should start empty)\n iCurL : integer; // Left Cursor\n iCurR : integer; // Right Cursor\n iRes : integer; // result of compare\nbegin\n iCurL := 0;\n iCurR := 0;\n ListL := tStringList.create;\n ListR := tSTringList.create;\n ListA := tSTringList.create;\n ListD := tStringList.create;\n InitAndLoadLists(ListL,ListR,ListA,ListD);\n while (iCurL <= ListL.Count-1) and (iCurR <= ListR.Count-1) do\n begin\n iRes := CompareStr(ListL.Strings[iCurL],ListR.Strings[iCurR]);\n if iRes = 0 then\n begin\n inc(iCurL);\n inc(iCurR);\n end;\n if iRes < 0 then\n begin\n ListA.Add(ListL.Strings[iCurL]);\n inc(iCurL);\n end;\n if iRes > 0 then\n begin\n listD.Add(ListR.Strings[iCurR]);\n inc(iCurR);\n end;\n end;\n while (iCurL <= ListL.Count-1) do\n begin\n listA.Add(ListL.Strings[iCurL]);\n inc(iCurL);\n end;\n while (iCurR <= ListR.Count-1) do\n begin\n listD.Add(ListR.Strings[iCurR]);\n inc(iCurR);\n end;\n ShowMessage( 'ADDS' + ^M+^J + ListA.Text);\n ShowMessage( 'DELS' + ^M+^J + ListD.Text);\nend;\n</code></pre>\n\n<p>The following code is what I used for testing. This is just an example, but in a real world situation I would build my keys so that they would sort properly, right padding numbers, and forcing case where appropriate. If your using the turbo power sort routines, you can use TWO sorts instead of two lists, but the end effect is the same.</p>\n\n<pre><code>procedure InitAndLoadLists(ListL, ListR, ListA, ListD: TStringList);\nbegin\n ListL.Add('A,1');\n ListL.Add('B,3');\n ListL.Add('C,2');\n ListR.Add('A,2');\n ListR.Add('B,3');\n ListR.Add('C,4');\nend;\n</code></pre>\n\n<p><strong>Edit:</strong> Code tested in Delphi 2009 and behaves properly.</p>\n"
},
{
"answer_id": 269732,
"author": "user34850",
"author_id": 34850,
"author_profile": "https://Stackoverflow.com/users/34850",
"pm_score": 3,
"selected": true,
"text": "<p>There's no need to create extra tables. The following query would work just as well:</p>\n\n<pre><code>SELECT c.chr, n.num\nFROM chars c, nums n\n WHERE NOT EXISTS (SELECT 1\n FROM mix m\n WHERE m.chr = c.chr AND m.num = n.num)\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268079",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35003/"
] |
I have 3 lists, I will make them simple here.
list of letters
A
B
C
list of numbers
1
2
3
Mixed
A,1
A,2
B,2
B,3
C,1
C,3
I need to know what is missing:
A,3
B,1
C,2
The list of letters has about 85 entries
and the list of numbers has about 500 entries.
The mixed list has about 75,000 entries.
I can use either a database query (mysql 5.0) or Turbo Delphi 2006 to process text files. What would be the best way to find what is missing?
Thanks,
Dave
|
There's no need to create extra tables. The following query would work just as well:
```
SELECT c.chr, n.num
FROM chars c, nums n
WHERE NOT EXISTS (SELECT 1
FROM mix m
WHERE m.chr = c.chr AND m.num = n.num)
```
|
268,084 |
<p>What is the most efficient way to create a <strong>constant</strong> (never changes at runtime) mapping of <code>string</code>s to <code>int</code>s? </p>
<p>I've tried using a <a href="https://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke">const Dictionary</a>, but that didn't work out. </p>
<p>I could implement a <a href="https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary">immutable wrapper</a> with appropriate semantics, but that still doesn't seem totally right.</p>
<hr>
<p>For those who have asked, I'm implementing <a href="https://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.110).aspx" rel="noreferrer">IDataErrorInfo</a> in a generated class and am looking for a way to make the columnName lookup into my array of descriptors. </p>
<p>I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!</p>
|
[
{
"answer_id": 268097,
"author": "Sander",
"author_id": 2928,
"author_profile": "https://Stackoverflow.com/users/2928",
"pm_score": 1,
"selected": false,
"text": "<p>There does not seem to be any standard immutable interface for dictionaries, so creating a wrapper seems like the only reasonable option, unfortunately.</p>\n\n<p><strong>Edit</strong>: Marc Gravell found the ILookup that I missed - that will allow you to at least avoid creating a new wrapper, although you still need to transform the Dictionary with .ToLookup().</p>\n\n<p>If this is a need constrained to a specific scenario, you might be better off with a more business-logic-oriented interface:</p>\n\n<pre><code>interface IActiveUserCountProvider\n{\n int GetMaxForServer(string serverName);\n}\n</code></pre>\n"
},
{
"answer_id": 268103,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": false,
"text": "<p>There are precious few immutable collections in the current framework. I can think of one relatively pain-free option in .NET 3.5:</p>\n\n<p>Use <code>Enumerable.ToLookup()</code> - the <a href=\"http://msdn.microsoft.com/en-us/library/bb460184.aspx\" rel=\"noreferrer\"><code>Lookup<,></code></a> class is immutable (but multi-valued on the rhs); you can do this from a <code>Dictionary<,></code> quite easily:</p>\n\n<pre><code> Dictionary<string, int> ids = new Dictionary<string, int> {\n {\"abc\",1}, {\"def\",2}, {\"ghi\",3}\n };\n ILookup<string, int> lookup = ids.ToLookup(x => x.Key, x => x.Value);\n int i = lookup[\"def\"].Single();\n</code></pre>\n"
},
{
"answer_id": 268138,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 4,
"selected": false,
"text": "<pre><code>enum Constants\n{\n Abc = 1,\n Def = 2,\n Ghi = 3\n}\n\n...\n\nint i = (int)Enum.Parse(typeof(Constants), \"Def\");\n</code></pre>\n"
},
{
"answer_id": 268223,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 9,
"selected": true,
"text": "<p>Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.</p>\n\n<p>There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:</p>\n\n<pre><code>switch (myString)\n{\n case \"cat\": return 0;\n case \"dog\": return 1;\n case \"elephant\": return 3;\n}\n</code></pre>\n\n<p>This is exactly what you want. And yes, I know, it's ugly.</p>\n"
},
{
"answer_id": 268249,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": false,
"text": "<p>This is the closest thing you can get to a \"CONST Dictionary\":</p>\n\n<pre><code>public static int GetValueByName(string name)\n{\n switch (name)\n {\n case \"bob\": return 1;\n case \"billy\": return 2;\n default: return -1;\n }\n}\n</code></pre>\n\n<p>The compiler will be smart enough to build the code as clean as possible.</p>\n"
},
{
"answer_id": 3343754,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Why not:</p>\n\n<pre><code>public class MyClass\n{\n private Dictionary<string, int> _myCollection = new Dictionary<string, int>() { { \"A\", 1 }, { \"B\", 2 }, { \"C\", 3 } };\n\n public IEnumerable<KeyValuePair<string,int>> MyCollection\n {\n get { return _myCollection.AsEnumerable<KeyValuePair<string, int>>(); }\n }\n}</code></pre>\n"
},
{
"answer_id": 49759219,
"author": "Joshua",
"author_id": 3470291,
"author_profile": "https://Stackoverflow.com/users/3470291",
"pm_score": 2,
"selected": false,
"text": "<p>Why not use namespaces or classes to nest your values? It may be imperfect, but it is very clean.</p>\n\n<pre><code>public static class ParentClass\n{\n // here is the \"dictionary\" class\n public static class FooDictionary\n {\n public const string Key1 = \"somevalue\";\n public const string Foobar = \"fubar\";\n }\n}\n</code></pre>\n\n<p>Now you can access .ParentClass.FooDictionary.Key1, etc.</p>\n"
},
{
"answer_id": 53072313,
"author": "Kram",
"author_id": 7346935,
"author_profile": "https://Stackoverflow.com/users/7346935",
"pm_score": 3,
"selected": false,
"text": "<p>If using 4.5+ Framework I would use ReadOnlyDictionary (also ReadOnly Collection for lists) to do readonly mappings/constants. It's implemented in the following way.</p>\n\n<pre><code>static class SomeClass\n{\n static readonly ReadOnlyDictionary<string,int> SOME_MAPPING \n = new ReadOnlyDictionary<string,int>(\n new Dictionary<string,int>()\n {\n { \"One\", 1 },\n { \"Two\", 2 }\n }\n )\n} \n</code></pre>\n"
},
{
"answer_id": 57414953,
"author": "Suleman",
"author_id": 7116068,
"author_profile": "https://Stackoverflow.com/users/7116068",
"pm_score": 4,
"selected": false,
"text": "<p>I am not sure why no one mentioned this but in C# for things that I cannot assign const, I use static read-only properties.</p>\n\n<p>Example:</p>\n\n<pre><code>public static readonly Dictionary<string, string[]> NewDictionary = new Dictionary<string, string[]>()\n {\n { \"Reference1\", Array1 },\n { \"Reference2\", Array2 },\n { \"Reference3\", Array3 },\n { \"Reference4\", Array4 },\n { \"Reference5\", Array5 }\n };\n</code></pre>\n"
},
{
"answer_id": 58547393,
"author": "Gina Marano",
"author_id": 1301310,
"author_profile": "https://Stackoverflow.com/users/1301310",
"pm_score": 2,
"selected": false,
"text": "<p>Just another idea since I am binding to a winforms combobox:</p>\n\n<pre><code>public enum DateRange {\n [Display(Name = \"None\")]\n None = 0,\n [Display(Name = \"Today\")]\n Today = 1,\n [Display(Name = \"Tomorrow\")]\n Tomorrow = 2,\n [Display(Name = \"Yesterday\")]\n Yesterday = 3,\n [Display(Name = \"Last 7 Days\")]\n LastSeven = 4,\n [Display(Name = \"Custom\")]\n Custom = 99\n };\n\nint something = (int)DateRange.None;\n</code></pre>\n\n<p>To get the int value from the display name <a href=\"https://stackoverflow.com/questions/33225729/enum-value-from-display-name\">from</a>:</p>\n\n<pre><code>public static class EnumHelper<T>\n{\n public static T GetValueFromName(string name)\n {\n var type = typeof(T);\n if (!type.IsEnum) throw new InvalidOperationException();\n\n foreach (var field in type.GetFields())\n {\n var attribute = Attribute.GetCustomAttribute(field,\n typeof(DisplayAttribute)) as DisplayAttribute;\n if (attribute != null)\n {\n if (attribute.Name == name)\n {\n return (T)field.GetValue(null);\n }\n }\n else\n {\n if (field.Name == name)\n return (T)field.GetValue(null);\n }\n }\n\n throw new ArgumentOutOfRangeException(\"name\");\n }\n}\n</code></pre>\n\n<p>usage:</p>\n\n<pre><code>var z = (int)EnumHelper<DateRange>.GetValueFromName(\"Last 7 Days\");\n</code></pre>\n"
},
{
"answer_id": 69175477,
"author": "PawZaw",
"author_id": 12417800,
"author_profile": "https://Stackoverflow.com/users/12417800",
"pm_score": 1,
"selected": false,
"text": "<p>As of C# 8, the <a href=\"https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/switch-expression\" rel=\"nofollow noreferrer\">new switch expression</a> is the cleanest way to achieve the result:</p>\n<pre><code>int value = inputString switch {\n "one" => 1,\n "two" => 2,\n _ => -1\n};\n</code></pre>\n<p>or as a function</p>\n<pre><code>int GetValue(string inputString) => inputString switch {\n "one" => 1,\n "two" => 2,\n _ => -1\n};\n</code></pre>\n<p>It is more concise that the "old" one:</p>\n<pre><code>int value = -1;\nswitch (inputString){\n case "one": value=1; break;\n case "two": value=2; break;\n}\n</code></pre>\n<p>The difference in performance of the old and new one can vary across different compilers</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268084",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4918/"
] |
What is the most efficient way to create a **constant** (never changes at runtime) mapping of `string`s to `int`s?
I've tried using a [const Dictionary](https://stackoverflow.com/questions/268064/c-how-can-dictionarykv-implement-icollectionkeyvaluepairkv-without-having-addke), but that didn't work out.
I could implement a [immutable wrapper](https://stackoverflow.com/questions/35002/does-c-have-a-way-of-giving-me-an-immutable-dictionary) with appropriate semantics, but that still doesn't seem totally right.
---
For those who have asked, I'm implementing [IDataErrorInfo](https://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo(v=vs.110).aspx) in a generated class and am looking for a way to make the columnName lookup into my array of descriptors.
I wasn't aware (typo when testing! d'oh!) that switch accepts strings, so that's what I'm gonna use. Thanks!
|
Creating a truly compile-time generated constant dictionary in C# is not really a straightforward task. Actually, none of the answers here really achieve that.
There is one solution though which meets your requirements, although not necessarily a nice one; remember that according to the C# specification, switch-case tables are compiled to constant hash jump tables. That is, they are constant dictionaries, not a series of if-else statements. So consider a switch-case statement like this:
```
switch (myString)
{
case "cat": return 0;
case "dog": return 1;
case "elephant": return 3;
}
```
This is exactly what you want. And yes, I know, it's ugly.
|
268,088 |
<p>After I open something with emacsclient, when I kill that buffer (C-x k) I get a confirmation dialog:</p>
<pre><code>Buffer `blah' still has clients; kill it? (yes or no)
</code></pre>
<p>But when I kill buffers opened directly from Emacs I don't. Is there a way not to get them when emacsclient opened them?</p>
|
[
{
"answer_id": 268205,
"author": "Touko",
"author_id": 28482,
"author_profile": "https://Stackoverflow.com/users/28482",
"pm_score": 5,
"selected": true,
"text": "<p>This worked for me:</p>\n\n<pre><code>(remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)\n</code></pre>\n\n<p>There's more information on <a href=\"http://shreevatsa.wordpress.com/2007/01/06/using-emacsclient\" rel=\"noreferrer\">Using Emacsclient blog entry</a>.</p>\n"
},
{
"answer_id": 268859,
"author": "David Webb",
"author_id": 3171,
"author_profile": "https://Stackoverflow.com/users/3171",
"pm_score": 5,
"selected": false,
"text": "<p>The other option is to use the <code>-n</code> option with <code>emacsclient</code> so that it doesn't wait for the file to be edited before exiting.</p>\n\n<p>For example:</p>\n\n<pre><code>emacsclient -n myfile.txt\n</code></pre>\n"
},
{
"answer_id": 16782311,
"author": "RussellStewart",
"author_id": 2237635,
"author_profile": "https://Stackoverflow.com/users/2237635",
"pm_score": 0,
"selected": false,
"text": "<p>For whatever reason, I have to manually launch the remove-hook solution on emacs23, perhaps because certain parts of the server are loaded after the .emacs is loaded. Adding a dummy (server-start) line to my .emacs before the (remove-hook ...) did not help. So I have opted for the following, less principled solution:</p>\n\n<pre><code>(defalias 'server-kill-buffer-query-function '(lambda () t))\n</code></pre>\n"
},
{
"answer_id": 28002666,
"author": "mzuther",
"author_id": 161979,
"author_profile": "https://Stackoverflow.com/users/161979",
"pm_score": 1,
"selected": false,
"text": "<p>You may set the keyboard command <strong>C-x k</strong> so that it marks <em>client buffers</em> as done and kills <em>normal buffers</em>.</p>\n\n<p>I shamelessly stole this code snippet from the <a href=\"http://www.emacswiki.org/emacs/EmacsClient#toc36\" rel=\"nofollow\">Emacs Client</a> entry in the Emacs Wiki:</p>\n\n\n\n<pre class=\"lang-lisp prettyprint-override\"><code>(add-hook 'server-switch-hook\n (lambda ()\n (when (current-local-map)\n (use-local-map (copy-keymap (current-local-map))))\n (when server-buffer-clients\n (local-set-key (kbd \"C-x k\") 'server-edit))))\n</code></pre>\n\n<p>While this does not help with other ways of killing buffers (such as <code>M-x list-buffers</code>), it should be on the safe side by respecting the Emacs client behavior that some shell scripts expect.</p>\n\n<p>Here is an excerpt from the file <em>server.el</em> in your Emacs distribution that might shed a little light on what I mean:</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>;; When you finish editing a Server buffer, again call server-edit\n;; to mark that buffer as done for the client and switch to the next\n;; Server buffer. When all the buffers for a client have been edited\n;; and exited with server-edit, the client \"editor\" will return\n;; to the program that invoked it.\n</code></pre>\n\n<p>Later on, there is an explicit warning that a buffer shouldn't be killed, but released (at least this is how I interpret it):</p>\n\n<pre class=\"lang-lisp prettyprint-override\"><code>;; Ask before killing a server buffer.\n;; It was suggested to release its client instead,\n;; but I think that is dangerous--the client would proceed\n;; using whatever is on disk in that file. -- rms.\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6068/"
] |
After I open something with emacsclient, when I kill that buffer (C-x k) I get a confirmation dialog:
```
Buffer `blah' still has clients; kill it? (yes or no)
```
But when I kill buffers opened directly from Emacs I don't. Is there a way not to get them when emacsclient opened them?
|
This worked for me:
```
(remove-hook 'kill-buffer-query-functions 'server-kill-buffer-query-function)
```
There's more information on [Using Emacsclient blog entry](http://shreevatsa.wordpress.com/2007/01/06/using-emacsclient).
|
268,089 |
<p>From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.</p>
<p>Can anyone please tell me how one can achieve multiple database connections in Django.</p>
<p>Does anyone have any idea by when Django will fully/officially support Multiple database connections.</p>
|
[
{
"answer_id": 268369,
"author": "Jonny Buchanan",
"author_id": 6760,
"author_profile": "https://Stackoverflow.com/users/6760",
"pm_score": 2,
"selected": false,
"text": "<p>The most recent discussion I've seen on it was in the <a href=\"http://groups.google.com/group/django-developers/browse_thread/thread/9f0353fe0682b73\" rel=\"nofollow noreferrer\">Proposal: user-friendly API for multi-database support</a> django-developers thread, which also has an example of one way to use multiple databases using Managers in the original message.</p>\n"
},
{
"answer_id": 271220,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 0,
"selected": false,
"text": "<p>I think you will have to resort to \"raw sql\" .. kinda thing .. <br>\nlook here: <a href=\"http://docs.djangoproject.com/en/dev/topics/db/sql/\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/sql/</a></p>\n\n<p>you need a \"connection\" to your other database, \nif you look at <code>django/db/__init__.py</code> around line 39 (in my version ..)</p>\n\n<p><code>connection = backend.DatabaseWrapper(**settings.DATABASE_OPTIONS)</code></p>\n\n<p>try to take it from there ..<br>\nP.S. I haven't really tried this or anything .. just trying to point in the general direction of what I think might solve your problem.</p>\n"
},
{
"answer_id": 272522,
"author": "Peter Rowell",
"author_id": 17017,
"author_profile": "https://Stackoverflow.com/users/17017",
"pm_score": 2,
"selected": false,
"text": "<p>If you read a few of the many (<em>many</em>) threads on this subject in django-dev, you will see that what <em>looks</em> straightforward, isn't. If you pick a single use case, then it looks easy, but as soon as you start to generalize in any way you start to run into trouble.</p>\n\n<p>To use the above-referenced thread as an example, when you say \"multiple databases\", which of the following are you talking about?</p>\n\n<ul>\n<li>All DB on the same machine under the same engine.</li>\n<li>All DB on same machine, different engines (E.g. MySQL + PostgreSQL)</li>\n<li>One Master DB with N read-only slaves on different machines.</li>\n<li>Sharding of tables across multiple DB servers.</li>\n</ul>\n\n<p>Will you need:</p>\n\n<ul>\n<li>Foreign keys across DBs</li>\n<li>JOINs across machines and/or engines</li>\n<li>etc. etc.</li>\n</ul>\n\n<p>One of the problems with a slick ORM like Django's is that it hides all of those messy details under a nice paint job. To continue to do that, but to then add in any of the above, is Not Easy (tm).</p>\n"
},
{
"answer_id": 997136,
"author": "Corey Oordt",
"author_id": 113081,
"author_profile": "https://Stackoverflow.com/users/113081",
"pm_score": 2,
"selected": false,
"text": "<p>Eric Florenzano wrote a very good blog post that allows you some multiple database support at: <a href=\"http://www.eflorenzano.com/blog/post/easy-multi-database-support-django/\" rel=\"nofollow noreferrer\">Easy MultipleDatabase Support for Django</a>.</p>\n\n<p>It starts by creating a new custom manager that allows you to specify the database settings.</p>\n"
},
{
"answer_id": 1287729,
"author": "washeck",
"author_id": 151678,
"author_profile": "https://Stackoverflow.com/users/151678",
"pm_score": 0,
"selected": false,
"text": "<p>Eric Florenzano's approach works well if all your databases use the same engine. If you have different engines (Postgres and MSSQL in my case) you will run into many issues deep in the ORM code (such as models/sql/where.py using the default connection's SQL syntax).</p>\n\n<p>If you need this to work, you should wait for Alex Gaynor's MultiDB project which is planned for <a href=\"http://code.djangoproject.com/wiki/Version1.2Features\" rel=\"nofollow noreferrer\">Django 1.2</a></p>\n"
},
{
"answer_id": 1836058,
"author": "Dave Aaron Smith",
"author_id": 223268,
"author_profile": "https://Stackoverflow.com/users/223268",
"pm_score": 3,
"selected": false,
"text": "<p>If you simply need multiple connections, you can do something like this:</p>\n\n<pre><code>from django.db import load_backend\nmyBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle'\nmyConnection = myBackend.DatabaseWrapper({\n 'DATABASE_HOST': '192.168.1.1',\n 'DATABASE_NAME': 'my_database',\n 'DATABASE_OPTIONS': {},\n 'DATABASE_PASSWORD': \"\",\n 'DATABASE_PORT': \"\",\n 'DATABASE_USER': \"my_user\",\n 'TIME_ZONE': \"America/New_York\",})\n# Now we can do all the standard raw sql stuff with myConnection.\nmyCursor = myConnection.cursor()\nmyCursor.execute(\"SELECT COUNT(1) FROM my_table;\")\nmyCursor.fetchone()\n</code></pre>\n"
},
{
"answer_id": 2277593,
"author": "blueyed",
"author_id": 15690,
"author_profile": "https://Stackoverflow.com/users/15690",
"pm_score": 3,
"selected": false,
"text": "<p>This will be in Django 1.2.</p>\n\n<p>See <a href=\"http://docs.djangoproject.com/en/dev/topics/db/multi-db/\" rel=\"noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a></p>\n"
},
{
"answer_id": 2583949,
"author": "Jack Ha",
"author_id": 80500,
"author_profile": "https://Stackoverflow.com/users/80500",
"pm_score": 0,
"selected": false,
"text": "<p>From Django 1.2, it will support multiple databases. See: <a href=\"http://docs.djangoproject.com/en/dev/topics/db/multi-db/\" rel=\"nofollow noreferrer\">http://docs.djangoproject.com/en/dev/topics/db/multi-db/</a>\nVersion 1.2 is now in beta</p>\n"
},
{
"answer_id": 8539232,
"author": "joshjdevl",
"author_id": 20641,
"author_profile": "https://Stackoverflow.com/users/20641",
"pm_score": 1,
"selected": false,
"text": "<p>There is a \"using\" directive for queries,saves, and deletes</p>\n\n<p><a href=\"https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database\" rel=\"nofollow\">https://docs.djangoproject.com/en/dev/topics/db/multi-db/#manually-selecting-a-database</a></p>\n"
},
{
"answer_id": 14604432,
"author": "Aventador",
"author_id": 1822871,
"author_profile": "https://Stackoverflow.com/users/1822871",
"pm_score": 2,
"selected": false,
"text": "<p>Multiple database to choose from </p>\n\n<p>We always need one named default, the names of the rest are up to you.</p>\n\n<pre><code>DATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'mupltiple_datab_app1', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST': \"\", \n 'PORT': \"\", \n },\n 'user1':{\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': 'mupltiple_datab_app2', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST': \"\", \n 'PORT': \"\", \n\n },\n 'user2':{\n 'ENGINE': 'django.db.backends.mysql', \n 'NAME': 'mupltiple_datab_app3', \n 'USER': 'root', \n 'PASSWORD': 'admin', \n 'HOST':\"\" , \n 'PORT': \"\" , \n\n }\n}\n</code></pre>\n\n<p>for sync to one particular database</p>\n\n<pre><code>manage.py syncdb --database=user1\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268089",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35009/"
] |
From some forum I came to know that Multiple database support is added in Django at lower level, but the higher level apis are not added yet.
Can anyone please tell me how one can achieve multiple database connections in Django.
Does anyone have any idea by when Django will fully/officially support Multiple database connections.
|
If you simply need multiple connections, you can do something like this:
```
from django.db import load_backend
myBackend = load_backend('postgresql_psycopg2') # or 'mysql', 'sqlite3', 'oracle'
myConnection = myBackend.DatabaseWrapper({
'DATABASE_HOST': '192.168.1.1',
'DATABASE_NAME': 'my_database',
'DATABASE_OPTIONS': {},
'DATABASE_PASSWORD': "",
'DATABASE_PORT': "",
'DATABASE_USER': "my_user",
'TIME_ZONE': "America/New_York",})
# Now we can do all the standard raw sql stuff with myConnection.
myCursor = myConnection.cursor()
myCursor.execute("SELECT COUNT(1) FROM my_table;")
myCursor.fetchone()
```
|
268,093 |
<p>I'd like to create a webpage layout with the sidebar to the right and the main content flowing around the sidebar.</p>
<p>Requirements:</p>
<ol>
<li>Content below the sidebar should occupy all of the available width</li>
<li>Content below the sidebar should not wrap when it hits the left of the sidebar</li>
<li>Main content should <em>precede</em> the sidebar in the markup</li>
<li>Sidebar has fixed width but unknown/variable height</li>
<li>CSS-only - no JavaScript solutions</li>
</ol>
<p>This could be achieved without the third requirement: if the sidebar is before the main content in the markup and is within the same containing element, a simple right float does the job. A sidebar before the main content in the markup is not an option here. The sidebar will contain supplemental information and adverts. If this is before the main content in the markup it will be annoying to CSSless browsers and screenreader users (even with 'skip to ...' links).</p>
<p>This could be achieved without the fourth requirement. If the sidebar had a fixed height I could put a containing element before the main content, float it right and give it a suitable width and height and then use absolute positioning to put the sidebar on top of the pre-made space.</p>
<p>Example markup (without CSS, relevant bits only):</p>
<pre><code><body>
<div id="content">
<p>
Lorem ipsum ....
</p>
<p>
Pellentesque ....
</p>
<div id="sidebar">
/* has some form of fixed width */
</div>
</div>
</body>
</code></pre>
<p>Example layout:</p>
<p><a href="http://webignition.net/images/layoutexample.png">alt text http://webignition.net/images/layoutexample.png</a></p>
<p>I'm not sure if this is possible. I'm happy to accept an authoritative answer stating that this cannot be achieved. If this can't be achieved I'd appreciate an explanation - knowing why it can't be achieved is much more valuable than just being told it can't.</p>
<p><strong>Update</strong>: I'm happy to see answers that don't meet all of the five requirements, so long as an answer states which requirement is being ignored plus the consequences (pros and cons) of ignoring the requirement. I can then make an informed compromise.</p>
<p><strong>Update 2</strong>: I can't ignore requirement 3 - the sidebar cannot precede the content.</p>
|
[
{
"answer_id": 268135,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 2,
"selected": false,
"text": "<p>I believe you're gonna have to change the order for this, putting the sidebar first. Then, use CSS's <code>float</code> property (without changing order, <code>div#sidebar</code> would end up below the paragraphs vs next to them). <code>div#sidebar</code> should stretch as needed for height.</p>\n\n<p>CSS:</p>\n\n<pre><code>#sidebar {\n float: right;\n width: 50px;\n}\n</code></pre>\n\n<p>HTML:</p>\n\n<pre><code><body>\n <div id=\"content\">\n <div id=\"sidebar\">\n /* has some form of fixed width */\n </div>\n\n <!-- paragraphs -->\n </div>\n</body>\n</code></pre>\n\n<hr>\n\n<p>@Jon Cram [comment]</p>\n\n<p>Ok...nvm. You stated your own answer and rejected it at the same time.</p>\n\n<p>You can't float an element around other elements that are defined before it. The browser has to be able to answer \"float around what?\" And it looks to the next element to start, continuing as far as necessary.</p>\n"
},
{
"answer_id": 268155,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "<p>If you can rearrange your HTML so the sidebar is before the content, then this is easy:</p>\n\n<pre><code>#sidebar { float: right; width: 150px; }\n</code></pre>\n\n<p>.. and then just make sure to clear it afterwards (at the end of the <code>#content</code> div).</p>\n\n<p>I know your intentions are in the right place, serving the content in the right order, but unless you're expecting a lot of traffic from visually impaired users, then I think you might need to reconsider your priorities.</p>\n"
},
{
"answer_id": 268178,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 2,
"selected": false,
"text": "<p>Ok, here's another answer then, since we can ignore one of the requirements, skip out the first requirement where the content wraps underneath the sidebar.</p>\n\n<pre><code>#sidebar {\n float: left;\n width: 100px;\n}\n#actualContent {\n width: 700px;\n float: left;\n}\n</code></pre>\n\n<p>The only change to your code is that you have to put your <em>actual content</em> in another wrapper.</p>\n\n<pre><code><div id=\"content\">\n <div id=\"actualContent\">\n <p>...</p>\n <p>...</p>\n </div>\n <div id=\"sidebar\">\n <p>...</p>\n </div>\n</div>\n</code></pre>\n"
},
{
"answer_id": 268181,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 0,
"selected": false,
"text": "<p>To my knowledge, the only way of getting the sidebar where you want (without the obvious markup reordering) is to set <code>#content { position: relative; }</code> and <code>#sidebar { position: absolute; right: 0; top: 0; }</code></p>\n\n<p>Unfortunately, absolute positioning will take the sidebar out of the flowing layout and the content of <code>#content</code> will not avoid <code>#sidebar</code> as you desire.</p>\n"
},
{
"answer_id": 268268,
"author": "Gabe",
"author_id": 9835,
"author_profile": "https://Stackoverflow.com/users/9835",
"pm_score": 0,
"selected": false,
"text": "<p>I don't have anywhere to test it right now, and I'm not sure if it will work, but have you tried displaying the sidebar div as <strong>inline</strong> and going from there?</p>\n"
},
{
"answer_id": 268828,
"author": "Steve Clay",
"author_id": 3779,
"author_profile": "https://Stackoverflow.com/users/3779",
"pm_score": 3,
"selected": true,
"text": "<p>Simple floating w/ opposite source order just can't be done (w/o CSS3 draft specs). The pragmatic approach is to first build a nice layout that supports your desired source order. HTML:</p>\n\n<pre><code><div id=\"content\" class=\"noJs\">\n <div id=\"floatSpace\"></div>\n <p>Lorem ipsum ....</p>\n <p>Pellentesque ....</p>\n <div id=\"sidebar\">content</div>\n</div>\n</code></pre>\n\n<p>CSS:</p>\n\n<pre><code>#content {position:relative;}\n#sidebar {width:150px; position:absolute; top:0; right:0;}\n.noJs {padding-right:150px;}\n.noJs #floatSpace {display:none;}\n.js #floatSpace {float:right; width:150px;}\n</code></pre>\n\n<p>This satisfies all but 1 and 2. Now, we add the JS:</p>\n\n<pre><code>$(function () {\n // make floatSpace the same height as sidebar\n $('#floatSpace').height($('#sidebar').height());\n // trigger alternate layout\n $('#content')[0].className = 'js';\n});\n</code></pre>\n\n<p>This will make the contents float around #floatSpace, and #sidebar will remain positioned on top of it. This is better than moving #sidebar because source order remains the same (for screenreaders that support Javascript, etc.).</p>\n\n<p>Here's a <a href=\"http://jsfiddle.net/wh6oLjy0/\" rel=\"nofollow noreferrer\">JSFiddle of this in action</a>. This layout does come with the unfortunate requirement of keeping the floatSpace height in sync with the sidebar height. If the sidebar is dynamic or has lazy-loading content, you must re-sync. </p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268093",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5343/"
] |
I'd like to create a webpage layout with the sidebar to the right and the main content flowing around the sidebar.
Requirements:
1. Content below the sidebar should occupy all of the available width
2. Content below the sidebar should not wrap when it hits the left of the sidebar
3. Main content should *precede* the sidebar in the markup
4. Sidebar has fixed width but unknown/variable height
5. CSS-only - no JavaScript solutions
This could be achieved without the third requirement: if the sidebar is before the main content in the markup and is within the same containing element, a simple right float does the job. A sidebar before the main content in the markup is not an option here. The sidebar will contain supplemental information and adverts. If this is before the main content in the markup it will be annoying to CSSless browsers and screenreader users (even with 'skip to ...' links).
This could be achieved without the fourth requirement. If the sidebar had a fixed height I could put a containing element before the main content, float it right and give it a suitable width and height and then use absolute positioning to put the sidebar on top of the pre-made space.
Example markup (without CSS, relevant bits only):
```
<body>
<div id="content">
<p>
Lorem ipsum ....
</p>
<p>
Pellentesque ....
</p>
<div id="sidebar">
/* has some form of fixed width */
</div>
</div>
</body>
```
Example layout:
[alt text http://webignition.net/images/layoutexample.png](http://webignition.net/images/layoutexample.png)
I'm not sure if this is possible. I'm happy to accept an authoritative answer stating that this cannot be achieved. If this can't be achieved I'd appreciate an explanation - knowing why it can't be achieved is much more valuable than just being told it can't.
**Update**: I'm happy to see answers that don't meet all of the five requirements, so long as an answer states which requirement is being ignored plus the consequences (pros and cons) of ignoring the requirement. I can then make an informed compromise.
**Update 2**: I can't ignore requirement 3 - the sidebar cannot precede the content.
|
Simple floating w/ opposite source order just can't be done (w/o CSS3 draft specs). The pragmatic approach is to first build a nice layout that supports your desired source order. HTML:
```
<div id="content" class="noJs">
<div id="floatSpace"></div>
<p>Lorem ipsum ....</p>
<p>Pellentesque ....</p>
<div id="sidebar">content</div>
</div>
```
CSS:
```
#content {position:relative;}
#sidebar {width:150px; position:absolute; top:0; right:0;}
.noJs {padding-right:150px;}
.noJs #floatSpace {display:none;}
.js #floatSpace {float:right; width:150px;}
```
This satisfies all but 1 and 2. Now, we add the JS:
```
$(function () {
// make floatSpace the same height as sidebar
$('#floatSpace').height($('#sidebar').height());
// trigger alternate layout
$('#content')[0].className = 'js';
});
```
This will make the contents float around #floatSpace, and #sidebar will remain positioned on top of it. This is better than moving #sidebar because source order remains the same (for screenreaders that support Javascript, etc.).
Here's a [JSFiddle of this in action](http://jsfiddle.net/wh6oLjy0/). This layout does come with the unfortunate requirement of keeping the floatSpace height in sync with the sidebar height. If the sidebar is dynamic or has lazy-loading content, you must re-sync.
|
268,105 |
<p>In a table I have the following schema</p>
<pre><code>table1:
playerID int primary key,
nationalities nvarchar
table2:
playerID int,
pubVisited nvarchar
</code></pre>
<p>Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this? </p>
|
[
{
"answer_id": 268127,
"author": "pilsetnieks",
"author_id": 6615,
"author_profile": "https://Stackoverflow.com/users/6615",
"pm_score": 2,
"selected": false,
"text": "<p>Judging by the <em>nvarchar</em> type, you're using MSSQL. Now, in MySQL you could use a subselect in the update .. where clause but MSSQL has its own update .. from clause:</p>\n\n<pre><code>UPDATE table2\nSET\n table2.pubVisited = null\nFROM table1\nWHERE\n table2.playerID = table1.playerID and table1.nationalities = 'England'\n</code></pre>\n\n<p>Haven't tested it though, so it might not work.</p>\n"
},
{
"answer_id": 268128,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "<p>Syntax in Oracle would be:</p>\n\n<pre><code>update table2\nset playedvisited = NULL\nwhere playerID in (select playerID \n from table1 \n where nationalities = 'England')\n</code></pre>\n"
},
{
"answer_id": 268136,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 3,
"selected": true,
"text": "<p>Tested on SQL Server 2005</p>\n\n<pre><code>update table2 set pubVisited = NULL \nfrom \n table1 t1 \n inner join \n table2 t2 \n on (t1.playerID = t2.playerID and t1.nationalities = 'England')\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268105",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3834/"
] |
In a table I have the following schema
```
table1:
playerID int primary key,
nationalities nvarchar
table2:
playerID int,
pubVisited nvarchar
```
Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this?
|
Tested on SQL Server 2005
```
update table2 set pubVisited = NULL
from
table1 t1
inner join
table2 t2
on (t1.playerID = t2.playerID and t1.nationalities = 'England')
```
|
268,107 |
<pre>
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
</pre>
<p>I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.</p>
<p>I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer <code>count</code> to be 0 (or NULL) if there are no rows, and the name still returns.</p>
<p><em>Edit:</em> I'd like to be able to sort by the <code>count</code> descending. (or <code>name</code> ASC) is that possible?</p>
|
[
{
"answer_id": 268118,
"author": "Dheer",
"author_id": 17266,
"author_profile": "https://Stackoverflow.com/users/17266",
"pm_score": 0,
"selected": false,
"text": "<p>Do a union to get the other set</p>\n\n<pre><code>SELECT `name` , COUNT(*) AS `count`\nFROM `t1`, `t2`\nWHERE `t2`.`id` = `t1`.`id`\nGROUP BY `t2`.`id`\nUNION\nSelect name, 0 as count\nfrom t1\nwhere NOT EXISTS (select 1 from t2 where `t2`.`id` = `t1`.`id`)\n</code></pre>\n"
},
{
"answer_id": 268158,
"author": "Incidently",
"author_id": 34187,
"author_profile": "https://Stackoverflow.com/users/34187",
"pm_score": 3,
"selected": true,
"text": "<p>This should work for you:</p>\n\n<pre><code>SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`\nFROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`\nGROUP BY `t1`.`id`\n</code></pre>\n\n<p>Left join ensures you have all rows from t1, and COUNT(<code>t2</code>.<code>id</code>) makes it count only records where t2.id is not null (that is - those that really exist in t2)</p>\n"
},
{
"answer_id": 268204,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>This sorts descending by COUNT, and within same counts ascending by <code>name</code>. Names with no rows in <code>t2</code> will return with a count of 0.</p>\n\n<pre><code>SELECT \n `t1`.`name`, \n COUNT(`t2`.`id`) AS `count`\nFROM \n `t1` \n LEFT JOIN `t2` ON`t2`.`id` = `t1`.`id`\nGROUP BY\n `t1`.`name`\nORDER BY\n COUNT(`t2`.`id`) DESC,\n `t1`.`name`\n</code></pre>\n\n<p>Modify the ORDER BY to your needs.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21559/"
] |
```
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
```
I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.
I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer `count` to be 0 (or NULL) if there are no rows, and the name still returns.
*Edit:* I'd like to be able to sort by the `count` descending. (or `name` ASC) is that possible?
|
This should work for you:
```
SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`
FROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`
GROUP BY `t1`.`id`
```
Left join ensures you have all rows from t1, and COUNT(`t2`.`id`) makes it count only records where t2.id is not null (that is - those that really exist in t2)
|
268,109 |
<p>I have a VB.NET application which needs to generate reports (invoices) which contains optional images. The images are going to be loaded into 1 of 6 places on the report, but will reside on the client PC (deployed with the application). I've been trying to access the ICROleObject object, which is what's placed onto the report, but I can't locate this interface in the object browser, even. As this is the object's interface, I figured that it would let me access it if only I could cast it:
<pre> CType(r.ReportDefinition.ReportObjects("picTL"), ICROleObject)</pre>
Any ideas where I would find this, or if I'm even approaching this correctly?<br>
I've tried following the directions at <a href="http://www.idautomation.com/crystal/streaming_crystal.html" rel="nofollow noreferrer"><a href="http://www.idautomation.com/crystal/streaming_crystal.html" rel="nofollow noreferrer">http://www.idautomation.com/crystal/streaming_crystal.html</a></a>, and that won't work with the version of Crystal which is embedded in .NET 2008. Neither will the solution found at <a href="http://www.a1vbcode.com/a1vbcode/vbforums/Topic25620-3-1.aspx#bm25974" rel="nofollow noreferrer"><a href="http://www.a1vbcode.com/a1vbcode/vbforums/Topic25620-3-1.aspx#bm25974" rel="nofollow noreferrer">http://www.a1vbcode.com/a1vbcode/vbforums/Topic25620-3-1.aspx#bm25974</a></a>, although that one looks a bit more promising, and is the one I'm trying to model after.<br>
If I have to use a dataset & a series of subreports, I suppose could ... but that method just doesn't seem as straightforward as this one.</p>
|
[
{
"answer_id": 268481,
"author": "Louis Gerbarg",
"author_id": 30506,
"author_profile": "https://Stackoverflow.com/users/30506",
"pm_score": 2,
"selected": false,
"text": "<p>There is no reliable way to do this using the current iPhone SDK. You should file a <a href=\"http://bugreporter.apple.com\" rel=\"nofollow noreferrer\">bug</a> with Apple to try to get them to add more control over the camera.</p>\n"
},
{
"answer_id": 269374,
"author": "Airsource Ltd",
"author_id": 18017,
"author_profile": "https://Stackoverflow.com/users/18017",
"pm_score": 2,
"selected": false,
"text": "<p>I ran into a blog on this last night, that discussed how to stripp out the overlay view.</p>\n\n<p><a href=\"http://blogs.oreilly.com/iphone/2008/10/creating-a-full-screen-camera.html\" rel=\"nofollow noreferrer\">http://blogs.oreilly.com/iphone/2008/10/creating-a-full-screen-camera.html</a></p>\n\n<p>It's not clear whether this would pass testing, though Phanfare do customize their view.</p>\n"
},
{
"answer_id": 526275,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I've been trying to do this for quite some time. </p>\n\n<p>Aswell as the link in the post above mine. I've stumbled across this page - <a href=\"http://blog.airsource.co.uk/index.php/2008/11/11/views-of-uiimagepickercontroller/\" rel=\"nofollow noreferrer\">http://blog.airsource.co.uk/index.php/2008/11/11/views-of-uiimagepickercontroller/</a> </p>\n\n<p>While the article itself is not spectacular, the comments provide some great insight and suggestions. Also, some users provided links to some external sites. If you happen to get it working, please email me.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6850/"
] |
I have a VB.NET application which needs to generate reports (invoices) which contains optional images. The images are going to be loaded into 1 of 6 places on the report, but will reside on the client PC (deployed with the application). I've been trying to access the ICROleObject object, which is what's placed onto the report, but I can't locate this interface in the object browser, even. As this is the object's interface, I figured that it would let me access it if only I could cast it:
```
CType(r.ReportDefinition.ReportObjects("picTL"), ICROleObject)
```
Any ideas where I would find this, or if I'm even approaching this correctly?
I've tried following the directions at [<http://www.idautomation.com/crystal/streaming_crystal.html>](http://www.idautomation.com/crystal/streaming_crystal.html), and that won't work with the version of Crystal which is embedded in .NET 2008. Neither will the solution found at [<http://www.a1vbcode.com/a1vbcode/vbforums/Topic25620-3-1.aspx#bm25974>](http://www.a1vbcode.com/a1vbcode/vbforums/Topic25620-3-1.aspx#bm25974), although that one looks a bit more promising, and is the one I'm trying to model after.
If I have to use a dataset & a series of subreports, I suppose could ... but that method just doesn't seem as straightforward as this one.
|
There is no reliable way to do this using the current iPhone SDK. You should file a [bug](http://bugreporter.apple.com) with Apple to try to get them to add more control over the camera.
|
268,116 |
<p>I have the following code block in my xslt;</p>
<pre><code> <xsl:when test="StatusData/Status/Temperature > 27">
<td bgcolor="#ffaaaa">
<xsl:value-of select="StatusData/Status/Temperature" />
</td>
</xsl:when>
</code></pre>
<p>But as you might guess when the value is 34,5 instead of 34.5 it is recognised as a string which makes integer comparison not possible. I thought replacing , with . would be solution that needs a char replace. My question is how I can do this
or
It would be great to know more about string operations in XSLT...</p>
|
[
{
"answer_id": 268140,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 4,
"selected": true,
"text": "<p>There is a <code>translate()</code> function in XPath:</p>\n\n<pre><code>test=\"translate(StatusData/Status/Temperature, \",\", \".\") > 27\"\n</code></pre>\n\n<p>Additionally you should make use of the number function, which converts it's argument to a number (or NaN, if that fails):</p>\n\n<pre><code>test=\"number(translate(StatusData/Status/Temperature, \",\", \".\")) > 27.0\"\n</code></pre>\n\n<p>See the <a href=\"http://www.w3.org/TR/xpath#function-translate\" rel=\"noreferrer\">documentation for <code>translate()</code></a> and the <a href=\"http://www.w3.org/TR/xpath#function-number\" rel=\"noreferrer\">documentation for <code>number()</code></a> at w3.org.</p>\n"
},
{
"answer_id": 268171,
"author": "yusuf",
"author_id": 35012,
"author_profile": "https://Stackoverflow.com/users/35012",
"pm_score": 0,
"selected": false,
"text": "<p>Thanx a lot.</p>\n\n<p>it works but with one simple modification:</p>\n\n<pre><code>test=\"number(translate(StatusData/Status/Temperature, ',', '.')) > 27.0\"\n</code></pre>\n\n<p>by the way it is not about XSLT it is about XPath :) good to learn...</p>\n"
},
{
"answer_id": 433238,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>In XSL 2 you can also use the full-fledged <code>replace()</code> which even supports regex patterns.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35012/"
] |
I have the following code block in my xslt;
```
<xsl:when test="StatusData/Status/Temperature > 27">
<td bgcolor="#ffaaaa">
<xsl:value-of select="StatusData/Status/Temperature" />
</td>
</xsl:when>
```
But as you might guess when the value is 34,5 instead of 34.5 it is recognised as a string which makes integer comparison not possible. I thought replacing , with . would be solution that needs a char replace. My question is how I can do this
or
It would be great to know more about string operations in XSLT...
|
There is a `translate()` function in XPath:
```
test="translate(StatusData/Status/Temperature, ",", ".") > 27"
```
Additionally you should make use of the number function, which converts it's argument to a number (or NaN, if that fails):
```
test="number(translate(StatusData/Status/Temperature, ",", ".")) > 27.0"
```
See the [documentation for `translate()`](http://www.w3.org/TR/xpath#function-translate) and the [documentation for `number()`](http://www.w3.org/TR/xpath#function-number) at w3.org.
|
268,120 |
<p>I am having an string like this</p>
<p>string str = "dfdsfdsf8fdfdfd9dfdfd4"</p>
<p>I need to check whether the string contains number by looping through the array.</p>
|
[
{
"answer_id": 268148,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 6,
"selected": true,
"text": "<p>What about a regular expression:</p>\n\n<pre><code>bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @\"\\d\");\n</code></pre>\n"
},
{
"answer_id": 268151,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": "<p>If you are looking for an integer value you could use <strong><a href=\"http://msdn.microsoft.com/en-us/library/f02979c7.aspx\" rel=\"noreferrer\">int.TryParse</a></strong>:</p>\n\n<pre><code>int result;\nif (int.TryParse(\"123\", out result))\n{\n Debug.WriteLine(\"Valid integer: \" + result);\n}\nelse\n{\n Debug.WriteLine(\"Not a valid integer\");\n}\n</code></pre>\n\n<p>For checking a decimal number, replace int.TryParse with <a href=\"http://msdn.microsoft.com/en-us/library/ew0seb73.aspx\" rel=\"noreferrer\"><strong>Decimal.TryParse</strong></a>. Check out this blog post and comments <a href=\"http://fatagnus.com/why-you-should-use-tryparse-in-c/\" rel=\"noreferrer\">\"Why you should use TryParse() in C#\"</a> for details.</p>\n\n<p>If you need decimal numbers, you could alternatively use this regular expression:</p>\n\n<pre><code>return System.Text.RegularExpressions.Regex.IsMatch(\n TextValue, @\"^-?\\d+([\\.]{1}\\d*)?$\");\n</code></pre>\n\n<p>And finally another alternative (if you are not religiously <em>against VB.NET</em>), you could use the method in the Microsoft.VisualBasic namespace:</p>\n\n<pre><code>Microsoft.VisualBasic.Information.IsNumeric(\"abc\"); \n</code></pre>\n"
},
{
"answer_id": 268168,
"author": "GeekyMonkey",
"author_id": 29900,
"author_profile": "https://Stackoverflow.com/users/29900",
"pm_score": 0,
"selected": false,
"text": "<p>If you're a linq junkie like me, you'd do it this way</p>\n\n<pre><code>string s = \"abc1def2ghi\";\nbool HasNumber = (from a in s.ToCharArray() where a >= '0' && a <= '9' select a).Count() > 0;\n</code></pre>\n"
},
{
"answer_id": 268186,
"author": "Arief",
"author_id": 34096,
"author_profile": "https://Stackoverflow.com/users/34096",
"pm_score": 0,
"selected": false,
"text": "<p>in C# 2.0, try this:</p>\n\n<pre><code> string str = \"dfdsfdsf8fdfdfd9dfdfd4\";\n\n for (int i = 0; i < str.Length; i++)\n {\n int result;\n if (int.TryParse(str[i].ToString(), out result))\n {\n //element is a number \n }\n else\n {\n // not a number\n }\n }\n</code></pre>\n"
},
{
"answer_id": 268234,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 3,
"selected": false,
"text": "<p>If you're going to loop through the string, DON'T use int.TryParse... that's way too heavy. Instead, use char.IsNumber();</p>\n\n<p>example:</p>\n\n<pre><code>foreach (char c in myString)\n if (char.IsNumber(c))\n return true;\n</code></pre>\n"
},
{
"answer_id": 11145727,
"author": "Kamal",
"author_id": 906340,
"author_profile": "https://Stackoverflow.com/users/906340",
"pm_score": 2,
"selected": false,
"text": "<pre><code>str.ToCharArray().Any(x => char.IsNumber(x));\n</code></pre>\n"
},
{
"answer_id": 12015197,
"author": "TriStar",
"author_id": 510161,
"author_profile": "https://Stackoverflow.com/users/510161",
"pm_score": 0,
"selected": false,
"text": "<pre><code>str.ToCharArray().Any(char.IsNumber)\n</code></pre>\n"
},
{
"answer_id": 44905588,
"author": "andrewtatham",
"author_id": 352059,
"author_profile": "https://Stackoverflow.com/users/352059",
"pm_score": 1,
"selected": false,
"text": "<p>Combining parts of Kamals answer and Tristars answers give...</p>\n\n<pre><code>str.Any(char.IsNumber)\n</code></pre>\n\n<p>which I think is the most succinct and readable way, instead of a regex</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22162/"
] |
I am having an string like this
string str = "dfdsfdsf8fdfdfd9dfdfd4"
I need to check whether the string contains number by looping through the array.
|
What about a regular expression:
```
bool val = System.Text.RegularExpressions.Regex.IsMatch(str, @"\d");
```
|
268,123 |
<p>Is there a single shortcut to start inserting in the new line at end of the file?</p>
<p>I'm aware of <kbd>G</kbd> + <kbd>o</kbd> combo.</p>
|
[
{
"answer_id": 268134,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 4,
"selected": false,
"text": "<p>Not that I know of - <kbd>G</kbd>+<kbd>o</kbd> is what I would have suggested too, but that is 2 steps :)</p>\n\n<p>You could always create a macro which does <kbd>G</kbd>+<kbd>o</kbd>, and then you can invoke the macro which will be 1 step.</p>\n"
},
{
"answer_id": 268143,
"author": "Ignacio Vazquez-Abrams",
"author_id": 20862,
"author_profile": "https://Stackoverflow.com/users/20862",
"pm_score": 4,
"selected": false,
"text": "<p>Adding the following into ~/.vimrc will create one for you:</p>\n\n<pre><code>:nmap ^A Go\n</code></pre>\n\n<p>To type the \"^A\" first press Ctrl-V, then press Ctrl-A. You can then use Ctrl-A to append at the end of the file when not in insert or visual mode.</p>\n"
},
{
"answer_id": 268157,
"author": "Rob Wells",
"author_id": 2974,
"author_profile": "https://Stackoverflow.com/users/2974",
"pm_score": 1,
"selected": false,
"text": "<p>You could stick the map definition in your .vimrc and then invoke it when the you open the file.</p>\n\n<p>Or, if you only want to do this for a particular file, you could create an autocmd for that file type that does it automatically. See <a href=\"http://vimdoc.sourceforge.net/htmldoc/autocmd.html#autocommand\" rel=\"nofollow noreferrer\">autocommand</a> in the vim doc's.</p>\n"
},
{
"answer_id": 379012,
"author": "Cyber Oliveira",
"author_id": 9793,
"author_profile": "https://Stackoverflow.com/users/9793",
"pm_score": 7,
"selected": true,
"text": "<p>There's also the command line option \"+\":</p>\n\n<pre>\nvim + myfile.txt\n</pre>\n\n<p>Will open myfile.txt and do an automatic G for you.</p>\n"
},
{
"answer_id": 27207461,
"author": "gautam",
"author_id": 4307380,
"author_profile": "https://Stackoverflow.com/users/4307380",
"pm_score": 2,
"selected": false,
"text": "<pre><code>echo >> myfile.txt && vim -c 'startinsert' + myfile.txt\n</code></pre>\n\n<p>You can also save the above command in a script and then use $1 instead of myfile.txt, name your script myvim ( or whatever you like ) and always open your files and start writing away instantly.</p>\n\n<pre><code>myvim myfile.txt\n</code></pre>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268123",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11439/"
] |
Is there a single shortcut to start inserting in the new line at end of the file?
I'm aware of `G` + `o` combo.
|
There's also the command line option "+":
```
vim + myfile.txt
```
Will open myfile.txt and do an automatic G for you.
|
268,132 |
<p>When I ran <a href="http://en.wikipedia.org/wiki/ReSharper" rel="noreferrer">ReSharper</a> on my code, for example:</p>
<pre><code> if (some condition)
{
Some code...
}
</code></pre>
<p>ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:</p>
<pre><code> if (!some condition) return;
Some code...
</code></pre>
<p>I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".</p>
|
[
{
"answer_id": 268145,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "<p>That is simply controversial. There is no \"agreement among programmers\" on the question of early return. It's always subjective, as far as I know.</p>\n\n<p>It's possible to make a performance argument, since it's better to have conditions that are written so they are most often true; it can also be argued that it is clearer. It does, on the other hand, create nested tests.</p>\n\n<p>I don't think you will get a conclusive answer to this question.</p>\n"
},
{
"answer_id": 268149,
"author": "Colin Pickard",
"author_id": 12744,
"author_profile": "https://Stackoverflow.com/users/12744",
"pm_score": 2,
"selected": false,
"text": "<p>It's a matter of opinion.</p>\n\n<p>My normal approach would be to avoid single line ifs, and returns in the middle of a method.</p>\n\n<p>You wouldn't want lines like it suggests everywhere in your method but there is something to be said for checking a bunch of assumptions at the top of your method, and only doing your actual work if they all pass.</p>\n"
},
{
"answer_id": 268154,
"author": "LeopardSkinPillBoxHat",
"author_id": 22489,
"author_profile": "https://Stackoverflow.com/users/22489",
"pm_score": 7,
"selected": false,
"text": "<p>This is a bit of a religious argument, but I agree with ReSharper that you should prefer less nesting. I believe that this outweighs the negatives of having multiple return paths from a function.</p>\n\n<p>The key reason for having less nesting is to improve <strong>code readability and maintainability</strong>. Remember that many other developers will need to read your code in the future, and code with less indentation is generally much easier to read.</p>\n\n<p><strong>Preconditions</strong> are a great example of where it is okay to return early at the start of the function. Why should the readability of the rest of the function be affected by the presence of a precondition check?</p>\n\n<p>As for the negatives about returning multiple times from a method - debuggers are pretty powerful now, and it's very easy to find out exactly where and when a particular function is returning.</p>\n\n<p><em>Having multiple returns in a function is not going to affect the maintainance programmer's job.</em></p>\n\n<p><em>Poor code readability will.</em></p>\n"
},
{
"answer_id": 268161,
"author": "Bluenuance",
"author_id": 33111,
"author_profile": "https://Stackoverflow.com/users/33111",
"pm_score": 0,
"selected": false,
"text": "<p>I think it depends on what you prefer, as mentioned, theres no general agreement afaik.\nTo reduce annoyment, you may reduce this kind of warning to \"Hint\"</p>\n"
},
{
"answer_id": 268166,
"author": "Deestan",
"author_id": 6848,
"author_profile": "https://Stackoverflow.com/users/6848",
"pm_score": 4,
"selected": false,
"text": "<p>This is of course subjective, but I think it strongly improves on two points:</p>\n\n<ul>\n<li>It is now immediately obvious that your function has nothing left to do if <code>condition</code> holds.</li>\n<li>It keeps the nesting level down. Nesting hurts readability more than you'd think.</li>\n</ul>\n"
},
{
"answer_id": 268170,
"author": "Oli",
"author_id": 12870,
"author_profile": "https://Stackoverflow.com/users/12870",
"pm_score": 4,
"selected": false,
"text": "<p>Guard clauses or pre-conditions (as you can probably see) check to see if a certain condition is met and then breaks the flow of the program. They're great for places where you're really only interested in one outcome of an <code>if</code> statement. So rather than say:</p>\n\n<pre><code>if (something) {\n // a lot of indented code\n}\n</code></pre>\n\n<p>You reverse the condition and break if that reversed condition is fulfilled</p>\n\n<pre><code>if (!something) return false; // or another value to show your other code the function did not execute\n\n// all the code from before, save a lot of tabs\n</code></pre>\n\n<p><code>return</code> is nowhere near as dirty as <code>goto</code>. It allows you to pass a value to show the rest of your code that the function couldn't run.</p>\n\n<p>You'll see the best examples of where this can be applied in nested conditions:</p>\n\n<pre><code>if (something) {\n do-something();\n if (something-else) {\n do-another-thing();\n } else {\n do-something-else();\n }\n}\n</code></pre>\n\n<p>vs:</p>\n\n<pre><code>if (!something) return;\ndo-something();\n\nif (!something-else) return do-something-else();\ndo-another-thing();\n</code></pre>\n\n<p>You'll find few people arguing the first is cleaner but of course, it's completely subjective. Some programmers like to know what conditions something is operating under by indentation, while I'd much rather keep method flow linear.</p>\n\n<p>I won't suggest for one moment that precons will change your life or get you laid but you might find your code just that little bit easier to read.</p>\n"
},
{
"answer_id": 268175,
"author": "Joshi Spawnbrood",
"author_id": 15392,
"author_profile": "https://Stackoverflow.com/users/15392",
"pm_score": 0,
"selected": false,
"text": "<p>My idea is that the return \"in the middle of a function\" shouldn't be so \"subjective\".\nThe reason is quite simple, take this code:</p>\n\n<pre>\n function do_something( data ){\n\n if (!is_valid_data( data )) \n return false;\n\n\n do_something_that_take_an_hour( data );\n\n istance = new object_with_very_painful_constructor( data );\n\n if ( istance is not valid ) {\n error_message( );\n return ;\n\n }\n connect_to_database ( );\n get_some_other_data( );\n return;\n }\n</pre>\n\n<p>Maybe the first \"return\" it's not SO intuitive, but that's really saving.\nThere are too many \"ideas\" about clean codes, that simply need more practise to lose their \"subjective\" bad ideas.</p>\n"
},
{
"answer_id": 268187,
"author": "jop",
"author_id": 11830,
"author_profile": "https://Stackoverflow.com/users/11830",
"pm_score": 9,
"selected": true,
"text": "<p>A return in the middle of the method is not necessarily bad. It might be better to return immediately if it makes the intent of the code clearer. For example:</p>\n\n<pre><code>double getPayAmount() {\n double result;\n if (_isDead) result = deadAmount();\n else {\n if (_isSeparated) result = separatedAmount();\n else {\n if (_isRetired) result = retiredAmount();\n else result = normalPayAmount();\n };\n }\n return result;\n};\n</code></pre>\n\n<p>In this case, if <code>_isDead</code> is true, we can immediately get out of the method. It might be better to structure it this way instead:</p>\n\n<pre><code>double getPayAmount() {\n if (_isDead) return deadAmount();\n if (_isSeparated) return separatedAmount();\n if (_isRetired) return retiredAmount();\n\n return normalPayAmount();\n}; \n</code></pre>\n\n<p>I've picked this code from the <a href=\"http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html\" rel=\"noreferrer\">refactoring catalog</a>. This specific refactoring is called: Replace Nested Conditional with Guard Clauses.</p>\n"
},
{
"answer_id": 268200,
"author": "Scott Langham",
"author_id": 11898,
"author_profile": "https://Stackoverflow.com/users/11898",
"pm_score": 6,
"selected": false,
"text": "<p>The idea of only returning at the end of a function came back from the days before languages had support for exceptions. It enabled programs to rely on being able to put clean-up code at the end of a method, and then being sure it would be called and some other programmer wouldn't hide a return in the method that caused the cleanup code to be skipped. Skipped cleanup code could result in a memory or resource leak.</p>\n\n<p>However, in a language that supports exceptions, it provides no such guarantees. In a language that supports exceptions, the execution of any statement or expression can cause a control flow that causes the method to end. This means clean-up must be done through using the finally or using keywords.</p>\n\n<p>Anyway, I'm saying I think a lot of people quote the 'only return at the end of a method' guideline without understanding why it was ever a good thing to do, and that reducing nesting to improve readability is probably a better aim.</p>\n"
},
{
"answer_id": 268218,
"author": "Richard Poole",
"author_id": 26003,
"author_profile": "https://Stackoverflow.com/users/26003",
"pm_score": 4,
"selected": false,
"text": "<p>Multiple return points were a problem in C (and to a lesser extent C++) because they forced you to duplicate clean-up code before each of the return points. With garbage collection, the <code>try</code> | <code>finally</code> construct and <code>using</code> blocks, there's really no reason why you should be afraid of them.</p>\n\n<p>Ultimately it comes down to what you and your colleagues find easier to read.</p>\n"
},
{
"answer_id": 268228,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 3,
"selected": false,
"text": "<p>There are several good points made here, but multiple return points <em>can be unreadable</em> as well, if the method is very lengthy. That being said, if you're going to use multiple return points just make sure that your method is short, otherwise the readability bonus of multiple return points may be lost.</p>\n"
},
{
"answer_id": 268252,
"author": "David Allan Finch",
"author_id": 27417,
"author_profile": "https://Stackoverflow.com/users/27417",
"pm_score": 0,
"selected": false,
"text": "<p>There are several advantages to this sort of coding but for me the big win is, if you can return quick you can improve the speed of your application. IE I know that because of Precondition X that I can return quickly with an error. This gets rid of the error cases first and reduces the complexity of your code. In a lot of cases because the cpu pipeline can be now be cleaner it can stop pipeline crashes or switches. Secondly if you are in a loop, breaking or returning out quickly can save you a lots of cpu. Some programmers use loop invariants to do this sort of quick exit but in this you can broke your cpu pipeline and even create memory seek problem and mean the the cpu needs to load from outside cache. But basically I think you should do what you intended, that is end the loop or function not create a complex code path just to implement some abstract notion of correct code. If the only tool you have is a hammer then everything looks like a nail.</p>\n"
},
{
"answer_id": 268304,
"author": "JohnIdol",
"author_id": 1311500,
"author_profile": "https://Stackoverflow.com/users/1311500",
"pm_score": 2,
"selected": false,
"text": "<p>In my opinion early return is fine if you are just returning void (or some useless return code you're never gonna check) and it might improve readability because you avoid nesting and at the same time you make explicit that your function is done.</p>\n\n<p>If you are actually returning a returnValue - nesting is usually a better way to go cause you return your returnValue just in one place (at the end - duh), and it might make your code more maintainable in a whole lot of cases.</p>\n"
},
{
"answer_id": 268318,
"author": "graffic",
"author_id": 15987,
"author_profile": "https://Stackoverflow.com/users/15987",
"pm_score": 3,
"selected": false,
"text": "<p>Many good reasons about <em>how the code looks like</em>. But what about <em>results</em>?</p>\n<p>Let's take a look to some C# code and its IL compiled form:</p>\n<pre><code>using System;\n\npublic class Test {\n public static void Main(string[] args) {\n if (args.Length == 0) return;\n if ((args.Length+2)/3 == 5) return;\n Console.WriteLine("hey!!!");\n }\n}\n</code></pre>\n<p>This simple snippet can be compiled. You can open the generated <code>.exe</code> file with <code>ildasm</code> and check what is the result. I won't post all the assembler thing but I'll describe the results.</p>\n<p>The generated IL code does the following:</p>\n<ol>\n<li>If the first condition is <code>false</code>, jumps to the code where the second is.</li>\n<li>If it's <code>true</code> jumps to the last instruction. (Note: the last instruction is a return).</li>\n<li>In the second condition the same happens after the result is calculated. Compare and: got to the <code>Console.WriteLine</code> if <code>false</code> or to the end if this is <code>true</code>.</li>\n<li>Print the message and return.</li>\n</ol>\n<p>So it seems that the code will jump to the end. What if we do a normal if with nested code?</p>\n<pre><code>using System;\n\npublic class Test {\n public static void Main(string[] args) {\n if (args.Length != 0 && (args.Length+2)/3 != 5) \n {\n Console.WriteLine("hey!!!");\n }\n }\n}\n</code></pre>\n<p>The results are quite similar in IL instructions. The difference is that before there were two jumps per condition: if <code>false</code> go to next piece of code, if <code>true</code> go to the end. And now the IL code flows better and has 3 jumps (the compiler optimized this a bit):</p>\n<ol>\n<li>First jump: when Length is 0 to a part where the code jumps again (Third jump) to the end.</li>\n<li>Second: in the middle of the second condition to avoid one instruction.</li>\n<li>Third: if the second condition is <code>false</code>, jump to the end.</li>\n</ol>\n<p>Anyway, the program counter will always jump.</p>\n"
},
{
"answer_id": 271465,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 3,
"selected": false,
"text": "<p>Personally I prefer only 1 exit point. It's easy to accomplish if you keep your methods short and to the point, and it provides a predictable pattern for the next person who works on your code.</p>\n\n<p>eg.</p>\n\n<pre><code> bool PerformDefaultOperation()\n {\n bool succeeded = false;\n\n DataStructure defaultParameters;\n if ((defaultParameters = this.GetApplicationDefaults()) != null)\n {\n succeeded = this.DoSomething(defaultParameters);\n }\n\n return succeeded;\n }\n</code></pre>\n\n<p>This is also very useful if you just want to check the values of certain local variables within a function before it exits. All you need to do is place a breakpoint on the final return and you are guaranteed to hit it (unless an exception is thrown).</p>\n"
},
{
"answer_id": 6342924,
"author": "Ingo Schalk-Schupp",
"author_id": 797551,
"author_profile": "https://Stackoverflow.com/users/797551",
"pm_score": 2,
"selected": false,
"text": "<p>There are a lot of insightful answers there already, but still, I would to direct to a slightly different situation: Instead of precondition, that should be put on top of a function indeed, think of a step-by-step initialization, where you have to check for each step to succeed and then continue with the next. In this case, you cannot check everything at the top.</p>\n\n<p>I found my code really unreadable when writing an ASIO host application with Steinberg's ASIOSDK, as I followed the nesting paradigm. It went like eight levels deep, and I cannot see a design flaw there, as mentioned by Andrew Bullock above. Of course, I could have packed some inner code to another function, and then nested the remaining levels there to make it more readable, but this seems rather random to me.</p>\n\n<p>By replacing nesting with guard clauses, I even discovered a misconception of mine regarding a portion of cleanup-code that should have occurred much earlier within the function instead of at the end. With nested branches, I would never have seen that, you could even say they led to my misconception.</p>\n\n<p>So this might be another situation where inverted ifs can contribute to a clearer code.</p>\n"
},
{
"answer_id": 8437318,
"author": "Jon",
"author_id": 50079,
"author_profile": "https://Stackoverflow.com/users/50079",
"pm_score": 8,
"selected": false,
"text": "<p><strong>It is not only aesthetic</strong>, but it also reduces the <a href=\"http://codebetter.com/patricksmacchia/2008/03/07/a-simple-trick-to-code-better-and-to-increase-testability/\" rel=\"noreferrer\">maximum nesting level</a> inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, <a href=\"http://www.ndepend.com/Metrics.aspx#ILNestingDepth\" rel=\"noreferrer\">many</a> <a href=\"http://www.scitools.com/documents/metricsList.php?metricGroup=complex#MaxNesting\" rel=\"noreferrer\">static</a> <a href=\"http://www.aivosto.com/project/help/pm-complexity.html\" rel=\"noreferrer\">analysis</a> <a href=\"http://www.semdesigns.com/products/metrics/CSharpMetrics.html\" rel=\"noreferrer\">tools</a> provide a measure of this as one of the indicators of code quality).</p>\n\n<p>On the other hand, it also makes your method have multiple exit points, something that another group of people believes is a no-no.</p>\n\n<p>Personally, I agree with ReSharper and the first group (in a language that has exceptions I find it silly to discuss \"multiple exit points\"; almost anything can throw, so there are numerous potential exit points in all methods).</p>\n\n<p><strong>Regarding performance</strong>: both versions <em>should</em> be equivalent (if not at the IL level, then certainly after the jitter is through with the code) in every language. Theoretically this depends on the compiler, but practically any widely used compiler of today is capable of handling much more advanced cases of code optimization than this.</p>\n"
},
{
"answer_id": 8437339,
"author": "Rion Williams",
"author_id": 557445,
"author_profile": "https://Stackoverflow.com/users/557445",
"pm_score": 4,
"selected": false,
"text": "<p>It doesn't only affect aesthetics, but it also prevents code nesting. </p>\n\n<p>It can actually function as a precondition to ensure that your data is valid as well.</p>\n"
},
{
"answer_id": 8437570,
"author": "Jeffrey Sax",
"author_id": 923873,
"author_profile": "https://Stackoverflow.com/users/923873",
"pm_score": 4,
"selected": false,
"text": "<p>Performance-wise, there will be no noticeable difference between the two approaches.</p>\n\n<p>But coding is about more than performance. Clarity and maintainability are also very important. And, in cases like this where it doesn't affect performance, it is the only thing that matters.</p>\n\n<p>There are competing schools of thought as to which approach is preferable.</p>\n\n<p>One view is the one others have mentioned: the second approach reduces the nesting level, which improves code clarity. This is natural in an imperative style: when you have nothing left to do, you might as well return early.</p>\n\n<p>Another view, from the perspective of a more functional style, is that a method should have only one exit point. Everything in a functional language is an expression. So if statements must always have an else clauses. Otherwise the if expression wouldn't always have a value. So in the functional style, the first approach is more natural.</p>\n"
},
{
"answer_id": 8437941,
"author": "Ryan Ternier",
"author_id": 324516,
"author_profile": "https://Stackoverflow.com/users/324516",
"pm_score": 3,
"selected": false,
"text": "<p>Performance is in two parts. You have performance when the software is in production, but you also want to have performance while developing and debugging. The last thing a developer wants is to \"wait\" for something trivial. In the end, compiling this with optimization enabled will result in similar code. So it's good to know these little tricks that pay off in both scenarios.</p>\n\n<p>The case in the question is clear, ReSharper is correct. Rather than nesting <code>if</code> statements, and creating new scope in code, you're setting a clear rule at the start of your method. It increases readability, it will be easier to maintain, and it reduces the amount of rules one has to sift through to find where they want to go.</p>\n"
},
{
"answer_id": 8438213,
"author": "Michael McGowan",
"author_id": 387852,
"author_profile": "https://Stackoverflow.com/users/387852",
"pm_score": 6,
"selected": false,
"text": "<p>As others have mentioned, there shouldn't be a performance hit, but there are other considerations. Aside from those valid concerns, this also can open you up to gotchas in some circumstances. Suppose you were dealing with a <code>double</code> instead:</p>\n\n<pre><code>public void myfunction(double exampleParam){\n if(exampleParam > 0){\n //Body will *not* be executed if Double.IsNan(exampleParam)\n }\n}\n</code></pre>\n\n<p>Contrast that with the <em>seemingly</em> equivalent inversion: </p>\n\n<pre><code>public void myfunction(double exampleParam){\n if(exampleParam <= 0)\n return;\n //Body *will* be executed if Double.IsNan(exampleParam)\n}\n</code></pre>\n\n<p>So in certain circumstances what appears to be a a correctly inverted <code>if</code> might not be.</p>\n"
},
{
"answer_id": 8493256,
"author": "Piotr Perak",
"author_id": 679340,
"author_profile": "https://Stackoverflow.com/users/679340",
"pm_score": 5,
"selected": false,
"text": "<p>I'd like to add that there is name for those inverted if's - Guard Clause. I use it whenever I can.</p>\n\n<p>I hate reading code where there is if at the beginning, two screens of code and no else. Just invert if and return. That way nobody will waste time scrolling.</p>\n\n<p><a href=\"http://c2.com/cgi/wiki?GuardClause\" rel=\"noreferrer\">http://c2.com/cgi/wiki?GuardClause</a></p>\n"
},
{
"answer_id": 8509008,
"author": "shibumi",
"author_id": 895131,
"author_profile": "https://Stackoverflow.com/users/895131",
"pm_score": 3,
"selected": false,
"text": "<p>Avoiding multiple exit points <strong>can</strong> lead to performance gains. I am not sure about C# but in C++ the Named Return Value Optimization (Copy Elision, ISO C++ '03 12.8/15) depends on having a single exit point. This optimization avoids copy constructing your return value (in your specific example it doesn't matter). This could lead to considerable gains in performance in tight loops, as you are saving a constructor and a destructor each time the function is invoked.</p>\n\n<p>But for 99% of the cases saving the additional constructor and destructor calls is not worth the loss of readability nested <code>if</code> blocks introduce (as others have pointed out). </p>\n"
},
{
"answer_id": 8624570,
"author": "jfg956",
"author_id": 851677,
"author_profile": "https://Stackoverflow.com/users/851677",
"pm_score": 3,
"selected": false,
"text": "<p>In theory, inverting <code>if</code> could lead to better performance if it increases branch prediction hit rate. In practice, I think it is very hard to know exactly how branch prediction will behave, especially after compiling, so I would not do it in my day-to-day development, except if I am writing assembly code.</p>\n\n<p>More on branch prediction <a href=\"http://en.wikipedia.org/wiki/Branch_predictor\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 56245111,
"author": "Marcin Gołembiewski",
"author_id": 11535752,
"author_profile": "https://Stackoverflow.com/users/11535752",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure, but I think, that R# tries to avoid far jumps. When You have IF-ELSE, compiler does something like this:</p>\n\n<p>Condition false -> far jump to false_condition_label</p>\n\n<p>true_condition_label:\ninstruction1\n...\ninstruction_n</p>\n\n<p>false_condition_label:\ninstruction1\n...\ninstruction_n</p>\n\n<p>end block</p>\n\n<p>If condition is true there is no jump and no rollout L1 cache, but jump to false_condition_label can be very far and processor must rollout his own cache. Synchronising cache is expensive. R# tries replace far jumps into short jumps and in this case there is bigger probability, that all instructions are already in cache.</p>\n"
}
] |
2008/11/06
|
[
"https://Stackoverflow.com/questions/268132",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/278/"
] |
When I ran [ReSharper](http://en.wikipedia.org/wiki/ReSharper) on my code, for example:
```
if (some condition)
{
Some code...
}
```
ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:
```
if (!some condition) return;
Some code...
```
I would like to understand why that's better. I always thought that using "return" in the middle of a method problematic, somewhat like "goto".
|
A return in the middle of the method is not necessarily bad. It might be better to return immediately if it makes the intent of the code clearer. For example:
```
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
else {
if (_isRetired) result = retiredAmount();
else result = normalPayAmount();
};
}
return result;
};
```
In this case, if `_isDead` is true, we can immediately get out of the method. It might be better to structure it this way instead:
```
double getPayAmount() {
if (_isDead) return deadAmount();
if (_isSeparated) return separatedAmount();
if (_isRetired) return retiredAmount();
return normalPayAmount();
};
```
I've picked this code from the [refactoring catalog](http://www.refactoring.com/catalog/replaceNestedConditionalWithGuardClauses.html). This specific refactoring is called: Replace Nested Conditional with Guard Clauses.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.