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
|
---|---|---|---|---|---|---|
232,933 |
<p>How do I multiply the values of a multi-dimensional array with weights and sum up the results into a new array in PHP or in general?</p>
<p>The boring way looks like this:</p>
<pre><code>$weights = array(0.25, 0.4, 0.2, 0.15);
$values = array
(
array(5,10,15),
array(20,25,30),
array(35,40,45),
array(50,55,60)
);
$result = array();
for($i = 0; $i < count($values[0]); ++$i) {
$result[$i] = 0;
foreach($weights as $index => $thisWeight)
$result[$i] += $thisWeight * $values[$index][$i];
}
</code></pre>
<p>Is there a more elegant solution?</p>
|
[
{
"answer_id": 232963,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 0,
"selected": false,
"text": "<p>Hm...</p>\n\n<pre><code>foreach($values as $index => $ary )\n $result[$index] = array_sum($ary) * $weights[$index];\n</code></pre>\n"
},
{
"answer_id": 233018,
"author": "Vinko Vrsalovic",
"author_id": 5190,
"author_profile": "https://Stackoverflow.com/users/5190",
"pm_score": 0,
"selected": false,
"text": "<p>I had also misunderstood the question at first. </p>\n\n<p>I guess that with that data representation any other choice would be less clear than what you have. </p>\n\n<p>If we could change it to something else, for instance if we were to transpose the matrix and multiply the other way around, then it would be very easy to get a more succint and probably elegant way.</p>\n\n<pre><code><?php\n\n$weights = array(0.2,0.3,0.4,0.5);\n$values = array(array(1,2,0.5), array(1,1,1), array(1,1,1), array(1,1,1));\n$result = array();\n\nfor($i = 0; $i < count($values[0]); ++$i) {\n $result[$i] = 0;\n foreach($weights as $index => $thisWeight) {\n $result[$i] += $thisWeight * $values[$index][$i];\n }\n}\nprint_r($result);\n\n\n$result = call_user_func_array(\"array_map\",array_merge(array(\"weightedSum\"),$values));\n\nfunction weightedSum() {\n global $weights;\n $args = func_get_args();\n return array_sum(array_map(\"weight\",$weights,$args));\n}\n\nfunction weight($w,$a) {\n return $w*$a;\n}\n\nprint_r($result);\n\n?>\n</code></pre>\n"
},
{
"answer_id": 233022,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 2,
"selected": true,
"text": "<p>Depends on what you mean by elegant, of course.</p>\n\n<pre><code>function weigh(&$vals, $key, $weights) {\n $sum = 0;\n foreach($vals as $v)\n $sum += $v*$weights[$key];\n $vals = $sum;\n}\n\n$result = $values;\narray_walk($result, \"weigh\", $weights);\n</code></pre>\n\n<p>EDIT: Sorry for not reading your example better.\nI make result a copy of values, since array_walk works by reference.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6260/"
] |
How do I multiply the values of a multi-dimensional array with weights and sum up the results into a new array in PHP or in general?
The boring way looks like this:
```
$weights = array(0.25, 0.4, 0.2, 0.15);
$values = array
(
array(5,10,15),
array(20,25,30),
array(35,40,45),
array(50,55,60)
);
$result = array();
for($i = 0; $i < count($values[0]); ++$i) {
$result[$i] = 0;
foreach($weights as $index => $thisWeight)
$result[$i] += $thisWeight * $values[$index][$i];
}
```
Is there a more elegant solution?
|
Depends on what you mean by elegant, of course.
```
function weigh(&$vals, $key, $weights) {
$sum = 0;
foreach($vals as $v)
$sum += $v*$weights[$key];
$vals = $sum;
}
$result = $values;
array_walk($result, "weigh", $weights);
```
EDIT: Sorry for not reading your example better.
I make result a copy of values, since array\_walk works by reference.
|
232,934 |
<p>I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it doesn't expose the internal DropDownList (logically, I guess). I've googled for the answer but can't find anything. </p>
<p>I've come as far as writing the actual class, and it's possible to subclass from DropDownList but I'm unable to register the file in my ASP.NET page and use it in the source view. Maybe I'm missing some properties in my class?</p>
<p>Any ideas?</p>
|
[
{
"answer_id": 232972,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 5,
"selected": true,
"text": "<p>You want to extend DropDownList in a Custom Control... not in a usercontrol.</p>\n\n<p>Create a new Class Library Project called MyLibrary.</p>\n\n<p>Add a class called MyDropDownList.cs</p>\n\n<pre><code>namespace My.Namespace.Controls\n{\n[ToolboxData(\"<{0}:MyDropDownList runat=\\\"server\\\"></{0}:MyDropDownList>\")]\npublic class MyDropDownList: DropDownList\n{\n // your custom code goes here\n // e.g.\n protected override void RenderContents(HtmlTextWriter writer)\n {\n //Your own render code\n }\n}\n}\n</code></pre>\n\n<p>Once you compile your library, you can add a reference to it in your web application.</p>\n\n<p>And a tagprefix in your web.config</p>\n\n<pre><code> <add tagPrefix=\"my\" namespace=\"My.Namespace.Controls\" assembly=\"MyLibrary\" />\n</code></pre>\n\n<p>That should allow you to add this to your aspx/ascx's</p>\n\n<pre><code><my:MyDropDownList ID=\"myDDl\" runat=\"server\">\n ...\n</my:MyDropDownList>\n</code></pre>\n"
},
{
"answer_id": 233440,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "<p>In a comment, you clarify your goal: \"The only thing I want to do with it is add an InitialValue property that defines the first value that is always present in the DDL.\"</p>\n\n<p>I don't think you need to create a special user control or custom control to accomplish that.</p>\n\n<p>I often use this code throughout my web apps to populate list controls. You pass in a boolean indicating whether an additional ListItem is to be added at the top of the list, and the text for that item.</p>\n\n<pre><code> public static void BindListControl (ListControl ctl, SqlDataReader dr,\n String textColumn, String valueColumn, bool addBlankRow, string blankRowText)\n {\n ctl.Items.Clear();\n ctl.DataSource = dr;\n ctl.DataTextField = textColumn;\n ctl.DataValueField = valueColumn;\n ctl.DataBind();\n\n if (addBlankRow == true) ctl.Items.Insert(0, blankRowText);\n }\n</code></pre>\n\n<p>This is useful, for example, if you want every DropDownList to have as its initial value a blank, or text such as \"Select a city\". </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] |
I want to subclass the built-in DropDownList in ASP.NET so that I can add functionality to it and use it in my pages. I tried doing this with a UserControl but found that it doesn't expose the internal DropDownList (logically, I guess). I've googled for the answer but can't find anything.
I've come as far as writing the actual class, and it's possible to subclass from DropDownList but I'm unable to register the file in my ASP.NET page and use it in the source view. Maybe I'm missing some properties in my class?
Any ideas?
|
You want to extend DropDownList in a Custom Control... not in a usercontrol.
Create a new Class Library Project called MyLibrary.
Add a class called MyDropDownList.cs
```
namespace My.Namespace.Controls
{
[ToolboxData("<{0}:MyDropDownList runat=\"server\"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
// your custom code goes here
// e.g.
protected override void RenderContents(HtmlTextWriter writer)
{
//Your own render code
}
}
}
```
Once you compile your library, you can add a reference to it in your web application.
And a tagprefix in your web.config
```
<add tagPrefix="my" namespace="My.Namespace.Controls" assembly="MyLibrary" />
```
That should allow you to add this to your aspx/ascx's
```
<my:MyDropDownList ID="myDDl" runat="server">
...
</my:MyDropDownList>
```
|
232,935 |
<p>I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?</p>
|
[
{
"answer_id": 232942,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 5,
"selected": false,
"text": "<p><code>SELECT * FROM table WHERE field1 NOT LIKE '%$x%';</code> (Make sure you escape $x properly beforehand to avoid SQL injection)</p>\n\n<p>Edit: <code>NOT IN</code> does something a bit different - your question isn't totally clear so pick which one to use. <code>LIKE 'xxx%'</code> can use an index. <code>LIKE '%xxx'</code> or <code>LIKE '%xxx%'</code> can't.</p>\n"
},
{
"answer_id": 232951,
"author": "Vegard Larsen",
"author_id": 1606,
"author_profile": "https://Stackoverflow.com/users/1606",
"pm_score": 10,
"selected": true,
"text": "<p>What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:</p>\n\n<pre><code>-- subquery\nSELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);\n-- predefined list\nSELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);\n</code></pre>\n\n<p>If you are searching a string, go for the LIKE operator (but this will be slow):</p>\n\n<pre><code>-- Finds all rows where a does not contain \"text\"\nSELECT * FROM x WHERE x.a NOT LIKE '%text%';\n</code></pre>\n\n<p>If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:</p>\n\n<pre><code>-- Finds all rows where a does not start with \"text\"\nSELECT * FROM x WHERE x.a NOT LIKE 'text%';\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232935",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I want to find an SQL query to find rows where field1 does not contain $x. How can I do this?
|
What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:
```
-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);
```
If you are searching a string, go for the LIKE operator (but this will be slow):
```
-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';
```
If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:
```
-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';
```
|
232,938 |
<p>I have a .rc file which is used to include some text data in my executable, like this:</p>
<pre><code>1234 RCDATA myfile.txt
</code></pre>
<p>This works fine: the content of the 'myfile.txt' is included in my executable.
The problem is that no 0-terminator is added to the string, and I cannot add it to the file. Is there any way of adding a 0-terminator from within the .rc file? Something like this:</p>
<pre><code>1234 RCDATA { myfile.txt, "\0" } // error RC2104
</code></pre>
<p>Note that I already found this solution, but I am looking for something more elegant.</p>
<pre><code>1234 RCDATA myfile.txt
1235 RCDATA { "\0" }
</code></pre>
<p>Thanks alot,
eli</p>
|
[
{
"answer_id": 232992,
"author": "eugensk",
"author_id": 17495,
"author_profile": "https://Stackoverflow.com/users/17495",
"pm_score": 3,
"selected": true,
"text": "<p>I don't think so, unless you write your own resource compiler.<br>\nI have not meet one which allowed to build one resource from several sources.<br>\nYou may write a small utility to add a trailing '\\0' to a file, say makeZ.exe,<br>\nand set an additional build step: </p>\n\n<pre><code>makeZ myfile.txt myfileZ.txt\n</code></pre>\n\n<p>In you .rc there will be </p>\n\n<pre><code> 1234 RCDATA myfileZ.txt\n</code></pre>\n"
},
{
"answer_id": 239279,
"author": "bugmagnet",
"author_id": 426,
"author_profile": "https://Stackoverflow.com/users/426",
"pm_score": 0,
"selected": false,
"text": "<p>Alternatively, you could look at embedding the data in the RC itself, as per this slice out of the <a href=\"http://www.jorgon.freeserve.co.uk/Resource.htm#raw\" rel=\"nofollow noreferrer\">GORC manual</a>:</p>\n\n<pre><code>0x3333 RCDATA\nBEGIN\n \"Hello world\"\n \"Hello world (zero terminated)\\0\"\n L\"A Unicode version of the above\\0\"\n 0x9999 ;hex number stored as a word\nEND\n\nMyRes RCDATA\nBEGIN\n 1034 ;decimal number stored as a word\nEND\n\nMyRes MyResType\nBEGIN\n 10456L ;decimal number stored as a dword\n 1234L,56666L,99999L ;decimal numbers stored as dwords\nEND\n\n34h 100h\nBEGIN\n 33hL,34hL,35hL,36hL ;hex numbers stored as dwords\n 0x37L,0x38L,0x39L,0x40L ;C-style hex numbers stored as dwords\nEND \n</code></pre>\n"
},
{
"answer_id": 239304,
"author": "Windows programmer",
"author_id": 23705,
"author_profile": "https://Stackoverflow.com/users/23705",
"pm_score": 0,
"selected": false,
"text": "<p>You'd better put the trailing character in the file itself. If myfile.txt is stored in ANSI you need one trailing byte, if myfile.txt is stored in Unicode you need two trailing bytes, and your RCDATA statement can't switch on it.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232938",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12893/"
] |
I have a .rc file which is used to include some text data in my executable, like this:
```
1234 RCDATA myfile.txt
```
This works fine: the content of the 'myfile.txt' is included in my executable.
The problem is that no 0-terminator is added to the string, and I cannot add it to the file. Is there any way of adding a 0-terminator from within the .rc file? Something like this:
```
1234 RCDATA { myfile.txt, "\0" } // error RC2104
```
Note that I already found this solution, but I am looking for something more elegant.
```
1234 RCDATA myfile.txt
1235 RCDATA { "\0" }
```
Thanks alot,
eli
|
I don't think so, unless you write your own resource compiler.
I have not meet one which allowed to build one resource from several sources.
You may write a small utility to add a trailing '\0' to a file, say makeZ.exe,
and set an additional build step:
```
makeZ myfile.txt myfileZ.txt
```
In you .rc there will be
```
1234 RCDATA myfileZ.txt
```
|
232,945 |
<p>I have an XML document which looks like this:</p>
<pre><code><xconnect>
<type>OK</type>
<response/>
<report>
<id>suppressionlist_get</id>
<name>Suppression List Get</name>
<timestamp>24 Oct 08 @ 10:16AM</timestamp>
<records type=\"user\"/>
<records type=\"client\"/>
<records type=\"group\">
<record>
<email>[email protected]</email>
<type>RECIPSELF</type>
<long_type>Recipient self suppressed</long_type>
<created>23 Oct 08 @ 8:53PM</created>
<user>facm</user>
</record>
</code></pre>
<p>I have omitted the closing of the document for clarity and to keep this post short.</p>
<p>Anyway, I have a GridView and I want to bind this XML to the GridView so I get table, like:</p>
<pre><code>email | type | long | created | user
------------------------------------
data data data data data
</code></pre>
<p>And so forth.</p>
<p>I was playing with DataSets and XMLDataDocuments and when stepping through, each attribute seemed to be represented as its own table in a data collection table.</p>
<p>Any ideas on how to achieve the above? I thought it was as simple as just adding a GridView, and XML data source with the data file specified.</p>
<p>Thanks</p>
|
[
{
"answer_id": 232954,
"author": "benPearce",
"author_id": 4490,
"author_profile": "https://Stackoverflow.com/users/4490",
"pm_score": 0,
"selected": false,
"text": "<p>Create a test DataSet and write it out to Xml to get a feel for the Xml format used by a dataset, then either convert the Xml format to match this and then load it in to the Dataset using <code>DataSet.LoadXml()</code>. </p>\n\n<p>Or you could build a DataSet on the fly from your existing Xml format.</p>\n"
},
{
"answer_id": 7355097,
"author": "jon3laze",
"author_id": 399770,
"author_profile": "https://Stackoverflow.com/users/399770",
"pm_score": 1,
"selected": false,
"text": "<p>Try: </p>\n\n<pre><code>DataSet dataSet = new DataSet();\ndataSet.ReadXML(\"Path to XML\");\nthis.GridView1.DataMember = \"record\";\nthis.GridView1.DataSource = dataSet;\nthis.GridView1.DataBind();\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232945",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30004/"
] |
I have an XML document which looks like this:
```
<xconnect>
<type>OK</type>
<response/>
<report>
<id>suppressionlist_get</id>
<name>Suppression List Get</name>
<timestamp>24 Oct 08 @ 10:16AM</timestamp>
<records type=\"user\"/>
<records type=\"client\"/>
<records type=\"group\">
<record>
<email>[email protected]</email>
<type>RECIPSELF</type>
<long_type>Recipient self suppressed</long_type>
<created>23 Oct 08 @ 8:53PM</created>
<user>facm</user>
</record>
```
I have omitted the closing of the document for clarity and to keep this post short.
Anyway, I have a GridView and I want to bind this XML to the GridView so I get table, like:
```
email | type | long | created | user
------------------------------------
data data data data data
```
And so forth.
I was playing with DataSets and XMLDataDocuments and when stepping through, each attribute seemed to be represented as its own table in a data collection table.
Any ideas on how to achieve the above? I thought it was as simple as just adding a GridView, and XML data source with the data file specified.
Thanks
|
Try:
```
DataSet dataSet = new DataSet();
dataSet.ReadXML("Path to XML");
this.GridView1.DataMember = "record";
this.GridView1.DataSource = dataSet;
this.GridView1.DataBind();
```
|
232,979 |
<p>I'm looking to get data such as Size/Capacity, Serial No, Model No, Heads Sectors, Manufacturer and possibly SMART data.</p>
|
[
{
"answer_id": 232991,
"author": "jmcd",
"author_id": 2285,
"author_profile": "https://Stackoverflow.com/users/2285",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://www.csharphelp.com/archives2/archive334.html\" rel=\"nofollow noreferrer\">WMI</a> to get most of the information you want, and there's an introduction to WMI <a href=\"http://www.geekpedia.com/tutorial73_An-introduction-in-retrieving-WMI-in-Csharp.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 232995,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 4,
"selected": true,
"text": "<p>You can use WMI Calls to access info about the hard disks.</p>\n\n<p>//Requires using System.Management; & System.Management.dll Reference</p>\n\n<pre><code>ManagementObject disk = new ManagementObject(\"win32_logicaldisk.deviceid=\\\"c:\\\"\"); \ndisk.Get(); \nConsole.WriteLine(\"Logical Disk Size = \" + disk[\"Size\"] + \" bytes\"); \nConsole.WriteLine(\"Logical Disk FreeSpace = \" + disk[\"FreeSpace\"] + \"bytes\");\n</code></pre>\n"
},
{
"answer_id": 232999,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 2,
"selected": false,
"text": "<p>You should use the <a href=\"http://msdn.microsoft.com/en-us/library/system.management.aspx\" rel=\"nofollow noreferrer\">System.Management</a> namespace:</p>\n\n<pre><code>System.Management.ManagementObjectSearcher ms =\n new System.Management.ManagementObjectSearcher(\"SELECT * FROM Win32_DiskDrive\");\nforeach (ManagementObject mo in ms.Get())\n{\n System.Console.Write(mo[\"Model\");\n}\n</code></pre>\n\n<p>For details on the members of the Win32_DiskDrive class, check out:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx</a></p>\n"
},
{
"answer_id": 233025,
"author": "Stu Mackellar",
"author_id": 28591,
"author_profile": "https://Stackoverflow.com/users/28591",
"pm_score": 2,
"selected": false,
"text": "<p>The easiest way is to use WMI to get the required information. Take at look at the documentation for <a href=\"http://msdn.microsoft.com/en-us/library/aa394132(VS.85).aspx\" rel=\"nofollow noreferrer\">Win32___DiskDrive</a> in MSDN, which contains a variety of standard drive properties. You can also try using the MSStorageDriver_ATAPISmartData WMI class, which I can't find any docs for at the moment, but should have all of the SMART data that you're looking for. Here's some basic sample code to enumerate all drives and get their properties:</p>\n\n<pre><code>ManagementClass driveClass = new ManagementClass(\"Win32_DiskDrive\");\nManagementObjectCollection drives = driveClass.GetInstances();\nforeach (ManagementObject drive in drives) \n{ \n foreach (PropertyData property in drive.Properties)\n {\n Console.WriteLine(\"Property: {0}, Value: {1}\", property.Name, property.Value); \n }\n Console.WriteLine();\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11538/"
] |
I'm looking to get data such as Size/Capacity, Serial No, Model No, Heads Sectors, Manufacturer and possibly SMART data.
|
You can use WMI Calls to access info about the hard disks.
//Requires using System.Management; & System.Management.dll Reference
```
ManagementObject disk = new ManagementObject("win32_logicaldisk.deviceid=\"c:\"");
disk.Get();
Console.WriteLine("Logical Disk Size = " + disk["Size"] + " bytes");
Console.WriteLine("Logical Disk FreeSpace = " + disk["FreeSpace"] + "bytes");
```
|
232,986 |
<p>I am attempting to bind a WPF textbox's Maxlength property to a known constant deep within a class. I am using c#.</p>
<p>The class has a structure not too dissimilar to the following:</p>
<pre><code>namespace Blah
{
public partial class One
{
public partial class Two
{
public string MyBindingValue { get; set; }
public static class MetaData
{
public static class Sizes
{
public const int Length1 = 10;
public const int Length2 = 20;
}
}
}
}
}
</code></pre>
<p>Yes it is deeply nested, but unfortunately in this instance I can't move things round very much without huge rewrites required.</p>
<p>I was hoping I'd be able to bind the textbox MaxLength to the Length1 or Length2 values but I can't get it to work.</p>
<p>I was expecting the binding to be something like the following:</p>
<pre><code><Textbox Text="{Binding Path=MyBindingValue}" MaxLength="{Binding Path=Blah.One.Two.MetaData.Sizes.Length1}" />
</code></pre>
<p>Any help is appreciated.</p>
<p>Many thanks</p>
|
[
{
"answer_id": 232996,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 0,
"selected": false,
"text": "<p>try to bind with x:Static. add a xmlns:local namespace with the namespace of Sizes to your xaml header and then bind with something like this:</p>\n\n<pre><code>{x:Static local:Sizes.Length1}\n</code></pre>\n"
},
{
"answer_id": 233017,
"author": "Ash",
"author_id": 31128,
"author_profile": "https://Stackoverflow.com/users/31128",
"pm_score": 0,
"selected": false,
"text": "<p>Unfortunately, with the following I get the error <code>Type 'One.Two.MetaData.Sizes' not found</code>. I cannot create a local namespace deeper than \"Blah\" (well according to VS2008 anyway)</p>\n\n<pre><code>xmlns:local=\"clr-namespace:Blah\"\n</code></pre>\n\n<p>and</p>\n\n<pre><code>MaxLength=\"{x:Static local:One.Two.MetaData.Sizes.Length1}\"\n</code></pre>\n"
},
{
"answer_id": 233034,
"author": "Joachim Kerschbaumer",
"author_id": 20227,
"author_profile": "https://Stackoverflow.com/users/20227",
"pm_score": 0,
"selected": false,
"text": "<p>if One is not a static class you cannot bind to it with x:Static. why using inner classes? if metadata is outside of two, and Sizes is a property, you can easily access it with x:Static.\nyou cannot bind to types in this case, only to existing objects. but One and Two are types, not objects.</p>\n"
},
{
"answer_id": 233061,
"author": "stusmith",
"author_id": 6604,
"author_profile": "https://Stackoverflow.com/users/6604",
"pm_score": 5,
"selected": false,
"text": "<pre><code>MaxLength=\"{x:Static local:One+Two+MetaData+Sizes.Length1}\"\n</code></pre>\n\n<p>Periods reference properties. Plus signs refer to inner classes.</p>\n"
},
{
"answer_id": 233355,
"author": "Ash",
"author_id": 31128,
"author_profile": "https://Stackoverflow.com/users/31128",
"pm_score": 4,
"selected": true,
"text": "<p>Fixed!</p>\n\n<p>Initially I tried doing this:</p>\n\n<pre><code>{Binding Path=MetaData+Sizes.Length1}\n</code></pre>\n\n<p>which compiled ok, however the binding failed at runtime, despite the Class 'Two' being the datacontext the path couldn't resolve into the inner static classes (could I have done something like : {Binding Path={x:Static MetaData+Size.Length1}} ?)</p>\n\n<p>I had to fiddle with the layout of my classes a little but the binding is now working.</p>\n\n<p>New class structure:</p>\n\n<pre><code>namespace Blah\n{\n public static class One\n {\n // This metadata class is moved outside of class 'Two', but in this instance\n // this doesn't matter as it relates to class 'One' more specifically than class 'Two'\n public static class MetaData\n {\n public static class Sizes\n {\n public static int Length1 { get { return 10; } }\n public static int Length2 { get { return 20; } }\n }\n }\n\n public partial class Two\n {\n public string MyBindingValue { get; set; }\n }\n }\n}\n</code></pre>\n\n<p>Then my binding statement is as follows:</p>\n\n<pre><code>xmlns:local=\"clr-namespace:Blah\"\n</code></pre>\n\n<p>and</p>\n\n<pre><code>MaxLength=\"{x:Static local:MetaData+Sizes.Length1}\"\n</code></pre>\n\n<p>Which appears to work ok. I'm not sure whether or not the constants needed to be converted into properties, but there doesn't appear to be any harm in doing so.</p>\n\n<p>Thankyou everyone for your help!</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232986",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31128/"
] |
I am attempting to bind a WPF textbox's Maxlength property to a known constant deep within a class. I am using c#.
The class has a structure not too dissimilar to the following:
```
namespace Blah
{
public partial class One
{
public partial class Two
{
public string MyBindingValue { get; set; }
public static class MetaData
{
public static class Sizes
{
public const int Length1 = 10;
public const int Length2 = 20;
}
}
}
}
}
```
Yes it is deeply nested, but unfortunately in this instance I can't move things round very much without huge rewrites required.
I was hoping I'd be able to bind the textbox MaxLength to the Length1 or Length2 values but I can't get it to work.
I was expecting the binding to be something like the following:
```
<Textbox Text="{Binding Path=MyBindingValue}" MaxLength="{Binding Path=Blah.One.Two.MetaData.Sizes.Length1}" />
```
Any help is appreciated.
Many thanks
|
Fixed!
Initially I tried doing this:
```
{Binding Path=MetaData+Sizes.Length1}
```
which compiled ok, however the binding failed at runtime, despite the Class 'Two' being the datacontext the path couldn't resolve into the inner static classes (could I have done something like : {Binding Path={x:Static MetaData+Size.Length1}} ?)
I had to fiddle with the layout of my classes a little but the binding is now working.
New class structure:
```
namespace Blah
{
public static class One
{
// This metadata class is moved outside of class 'Two', but in this instance
// this doesn't matter as it relates to class 'One' more specifically than class 'Two'
public static class MetaData
{
public static class Sizes
{
public static int Length1 { get { return 10; } }
public static int Length2 { get { return 20; } }
}
}
public partial class Two
{
public string MyBindingValue { get; set; }
}
}
}
```
Then my binding statement is as follows:
```
xmlns:local="clr-namespace:Blah"
```
and
```
MaxLength="{x:Static local:MetaData+Sizes.Length1}"
```
Which appears to work ok. I'm not sure whether or not the constants needed to be converted into properties, but there doesn't appear to be any harm in doing so.
Thankyou everyone for your help!
|
232,997 |
<p>I have what is essentially a jagged array of name value pairs - i need to generate a set of unique name values from this. the jagged array is approx 86,000 x 11 values.
It does not matter to me what way I have to store a name value pair (a single string "name=value" or a specialised class for example KeyValuePair).<br>
<strong>Additional Info:</strong> There are 40 distinct names and a larger number of distinct values - probably in the region 10,000 values.</p>
<p>I am using C# and .NET 2.0 (and the performance is so poor I am thinking that it may be better to push my entire jagged array into a sql database and do a select distinct from there).</p>
<p>Below is the current code Im using:</p>
<pre><code>List<List<KeyValuePair<string,string>>> vehicleList = retriever.GetVehicles();
this.statsLabel.Text = "Unique Vehicles: " + vehicleList.Count;
Dictionary<KeyValuePair<string, string>, int> uniqueProperties = new Dictionary<KeyValuePair<string, string>, int>();
foreach (List<KeyValuePair<string, string>> vehicle in vehicleList)
{
foreach (KeyValuePair<string, string> property in vehicle)
{
if (!uniqueProperties.ContainsKey(property))
{
uniqueProperties.Add(property, 0);
}
}
}
this.statsLabel.Text += "\rUnique Properties: " + uniqueProperties.Count;
</code></pre>
|
[
{
"answer_id": 233005,
"author": "Eoin Campbell",
"author_id": 30155,
"author_profile": "https://Stackoverflow.com/users/30155",
"pm_score": 0,
"selected": false,
"text": "<p>if you don't need any specific correlation between each key/value pair and the unique values you're generating, you could just use a GUID? I'm assuming the problem is that your current 'Key' isn't unique in this jagged array.</p>\n\n<pre><code>Dictionary<System.Guid, KeyValuePair<string, string>> myDict \n = new Dictionary<Guid, KeyValuePair<string, string>>();\n\n\nforeach of your key values in their current format\n myDict.Add(System.Guid.NewGuid(), new KeyValuePair<string, string>(yourKey, yourvalue))\n</code></pre>\n\n<p>Sounds like it would store what you need but I don't know how you would pull data back from this as there would be no semantic relationship between the generate Guid & what you originally had...</p>\n\n<p>Can you provide any more info in your question?</p>\n"
},
{
"answer_id": 233024,
"author": "Mats Fredriksson",
"author_id": 2973,
"author_profile": "https://Stackoverflow.com/users/2973",
"pm_score": 0,
"selected": false,
"text": "<p>Use KeyValuePair as a wrapper class and then create a dictionary with to create a set perhaps? Or implement your own wrapper that overrides the Equals and GetHashCode.</p>\n\n<pre><code>Dictionary<KeyValuePair, bool> mySet;\n\nfor(int i = 0; i < keys.length; ++i)\n{\n KeyValuePair kvp = new KeyValuePair(keys[i], values[i]);\n mySet[kvp] = true;\n}\n</code></pre>\n"
},
{
"answer_id": 233110,
"author": "Leandro López",
"author_id": 22695,
"author_profile": "https://Stackoverflow.com/users/22695",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of using a <code>Dictionary</code> why not extend <a href=\"http://msdn.microsoft.com/en-us/library/ms132438.aspx\" rel=\"nofollow noreferrer\"><code>KeyedCollection<TKey, TItem></code></a>? According to the documentation:</p>\n\n<p>Provides the abstract base class for a collection whose keys are embedded in the values.</p>\n\n<p>You then need to override the <a href=\"http://msdn.microsoft.com/en-us/library/ms132454.aspx\" rel=\"nofollow noreferrer\"><code>protected TKey GetKeyForItem(TItem item)</code></a> function. As it is an hybrid between <a href=\"http://msdn.microsoft.com/en-us/library/5y536ey6.aspx\" rel=\"nofollow noreferrer\"><code>IList<T></code></a> and <a href=\"http://msdn.microsoft.com/en-us/library/s4ys34ea.aspx\" rel=\"nofollow noreferrer\"><code>IDictionary<TKey, TValue></code></a> I think it's likely to be quite fast.</p>\n"
},
{
"answer_id": 233139,
"author": "Eric Smith",
"author_id": 26054,
"author_profile": "https://Stackoverflow.com/users/26054",
"pm_score": 0,
"selected": false,
"text": "<p>How about:</p>\n\n<pre><code>Dictionary<NameValuePair,int> hs = new Dictionary<NameValuePair,int>();\nforeach (i in jaggedArray)\n{\n foreach (j in i)\n {\n if (!hs.ContainsKey(j))\n {\n hs.Add(j, 0);\n }\n }\n}\nIEnumerable<NameValuePair> unique = hs.Keys;\n</code></pre>\n\n<p>of course, if you were using C# 3.0, .NET 3.5:</p>\n\n<pre><code>var hs = new HashSet<NameValuePair>();\nhs.UnionWith(jaggedArray.SelectMany(item => item));\n</code></pre>\n\n<p>would do the trick.</p>\n"
},
{
"answer_id": 237037,
"author": "Thomas Eyde",
"author_id": 3282,
"author_profile": "https://Stackoverflow.com/users/3282",
"pm_score": 0,
"selected": false,
"text": "<p>Have you profiled your code? You are certain that the foreach loops are the bottleneck, and not retriever.GetVehicles()?</p>\n\n<p>I did create a small test project where I fake the retriever and let it return 86.000 X 11 values. My first attempt ran at 5 seconds, creating the data included.</p>\n\n<p>I used the same value for both the key and value where the first key was \"0#0\" and the last \"85999#10\".</p>\n\n<p>Then I switched to guids. Same result.</p>\n\n<p>Then I made the key longer, like this:</p>\n\n<pre><code> var s = Guid.NewGuid().ToString();\n return s + s + s + s + s + s + s+ s + s + s;\n</code></pre>\n\n<p>Now it took almost 10 seconds.</p>\n\n<p>Then I made the keys insanely long and got an out of memory exception. I don't have a swap file on my computer, so I got this exception immediately.</p>\n\n<p>How long are your keys? Are your virtual memory consumption the reason for your poor performance?</p>\n"
},
{
"answer_id": 251619,
"author": "Binary Worrier",
"author_id": 18797,
"author_profile": "https://Stackoverflow.com/users/18797",
"pm_score": 5,
"selected": true,
"text": "<p><strong>I have it running in 0.34 seconds</strong> down from 9+ minutes</p>\n\n<p>The problem is when comparing the KeyValuePair structs.\nI worked around it by writing a comparer object, and passing an instance of it to the Dictionary.</p>\n\n<p>From what I can determine, the KeyValuePair.GetHashCode() returns the hashcode of it's <code>Key</code> object (in this example the least unique object).</p>\n\n<p>As the dictionary adds (and checks existence of) each item, it uses both Equals and GetHashCode functions, but has to rely on the Equals function when the hashcode is less unique.</p>\n\n<p>By providing a more unique GetHashCode function, it excerises the Equals function far less often. I also optimised the Equals function to compare the more unique Values before the less unqiue Keys.</p>\n\n<p>86,000 * 11 items with 10,000 unique properties runs in 0.34 seconds using the comparer object below (without the comparer object it takes 9 minutes 22 seconds)</p>\n\n<p>Hope this helps :)</p>\n\n<pre><code> class StringPairComparer\n : IEqualityComparer<KeyValuePair<string, string>>\n {\n public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)\n {\n return x.Value == y.Value && x.Key == y.Key;\n }\n public int GetHashCode(KeyValuePair<string, string> obj)\n {\n return (obj.Key + obj.Value).GetHashCode();\n }\n }\n</code></pre>\n\n<p><strong>EDIT</strong>: If it was just one string (instead of a KeyValuePair, where string = Name+Value) it would be approx twice as fast. It's a nice intresting problem, and I have spent <em>faaaaaar too much time on it</em> (I learned quiet a bit though)</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/232997",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22100/"
] |
I have what is essentially a jagged array of name value pairs - i need to generate a set of unique name values from this. the jagged array is approx 86,000 x 11 values.
It does not matter to me what way I have to store a name value pair (a single string "name=value" or a specialised class for example KeyValuePair).
**Additional Info:** There are 40 distinct names and a larger number of distinct values - probably in the region 10,000 values.
I am using C# and .NET 2.0 (and the performance is so poor I am thinking that it may be better to push my entire jagged array into a sql database and do a select distinct from there).
Below is the current code Im using:
```
List<List<KeyValuePair<string,string>>> vehicleList = retriever.GetVehicles();
this.statsLabel.Text = "Unique Vehicles: " + vehicleList.Count;
Dictionary<KeyValuePair<string, string>, int> uniqueProperties = new Dictionary<KeyValuePair<string, string>, int>();
foreach (List<KeyValuePair<string, string>> vehicle in vehicleList)
{
foreach (KeyValuePair<string, string> property in vehicle)
{
if (!uniqueProperties.ContainsKey(property))
{
uniqueProperties.Add(property, 0);
}
}
}
this.statsLabel.Text += "\rUnique Properties: " + uniqueProperties.Count;
```
|
**I have it running in 0.34 seconds** down from 9+ minutes
The problem is when comparing the KeyValuePair structs.
I worked around it by writing a comparer object, and passing an instance of it to the Dictionary.
From what I can determine, the KeyValuePair.GetHashCode() returns the hashcode of it's `Key` object (in this example the least unique object).
As the dictionary adds (and checks existence of) each item, it uses both Equals and GetHashCode functions, but has to rely on the Equals function when the hashcode is less unique.
By providing a more unique GetHashCode function, it excerises the Equals function far less often. I also optimised the Equals function to compare the more unique Values before the less unqiue Keys.
86,000 \* 11 items with 10,000 unique properties runs in 0.34 seconds using the comparer object below (without the comparer object it takes 9 minutes 22 seconds)
Hope this helps :)
```
class StringPairComparer
: IEqualityComparer<KeyValuePair<string, string>>
{
public bool Equals(KeyValuePair<string, string> x, KeyValuePair<string, string> y)
{
return x.Value == y.Value && x.Key == y.Key;
}
public int GetHashCode(KeyValuePair<string, string> obj)
{
return (obj.Key + obj.Value).GetHashCode();
}
}
```
**EDIT**: If it was just one string (instead of a KeyValuePair, where string = Name+Value) it would be approx twice as fast. It's a nice intresting problem, and I have spent *faaaaaar too much time on it* (I learned quiet a bit though)
|
233,009 |
<p>Ok: This is some of my table structure that matters here</p>
<pre><code>CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)
</code></pre>
<p>Part of my procedure</p>
<pre><code>Declare @Temp table(CaseStudyID int,
Title nvarchar(50))
Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title
Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going
Select * From @Temp
</code></pre>
<p>Can anyone help?</p>
|
[
{
"answer_id": 233039,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 1,
"selected": false,
"text": "<p>You could achieve it without using tempory table this way:</p>\n\n<pre><code>SELECT \n MIN(CaseStudyID) AS CaseStudyID, \n CASE WHEN count(*) = 1 THEN \n MIN(Title) \n ELSE\n MIN(OverrideTitle) \n END AS Title\nFROM CaseStudy\nGROUP BY Title\nORDER BY Title\n</code></pre>\n"
},
{
"answer_id": 233080,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure whether you need every single row of the orginal table. So here is my alternative solution which gives you every row:</p>\n\n<pre><code>SELECT CaseStudyID, Title \nFROM CaseStudy c1\nWHERE NOT EXISTS (\n SELECT * FROM CaseStudy c2 \n WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title\n)\n\nUNION ALL\n\nSELECT CaseStudyID, OverrideTitle\nFROM CaseStudy c1\nWHERE exists (\n SELECT * FROM CaseStudy c2\n WHERE c2.CaseStudyID <> c1.CaseStudyID and c2.Title = c1.Title\n)\n\nORDER BY Title\n</code></pre>\n"
},
{
"answer_id": 233091,
"author": "kristof",
"author_id": 3241,
"author_profile": "https://Stackoverflow.com/users/3241",
"pm_score": 2,
"selected": true,
"text": "<p>That would replace every title that appears multiple times with the corresponding overrideTitle value. </p>\n\n<p>It will keep the first occurrence of it, e.g if you have 3 titles like a,a,a only the second and third one will be replaced</p>\n\n<pre><code>select distinct\n cs1.CaseStudyID,\n case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title\nfrom \n CaseStudy cs1\n left join CaseStudy cs2 \n on cs1.title = cs2.title\n and cs1.CaseStudyID > cs2.CaseStudyID\n</code></pre>\n\n<p>If you want to replace all of them just change > to <> as below</p>\n\n<pre><code>select distinct\n cs1.CaseStudyID,\n case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title\nfrom \n CaseStudy cs1\n left join CaseStudy cs2 \n on cs1.title = cs2.title\n and cs1.CaseStudyID <> cs2.CaseStudyID\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11394/"
] |
Ok: This is some of my table structure that matters here
```
CaseStudyID int
Title nvarchar(50)
OverrideTitle nvarchar(50)
```
Part of my procedure
```
Declare @Temp table(CaseStudyID int,
Title nvarchar(50))
Insert Into @Temp
SELECT CaseStudyID,Title
FROM CaseStudy
WHERE Visible = 1 AND DisplayOnHomePage = 1
ORDER BY Title
Update @Temp Set Title = TitleOverride
--Here is where im lost if the title occurs more than once
--I need to replace it with the override
--Schoolboy error or leaking brain I cant get it going
Select * From @Temp
```
Can anyone help?
|
That would replace every title that appears multiple times with the corresponding overrideTitle value.
It will keep the first occurrence of it, e.g if you have 3 titles like a,a,a only the second and third one will be replaced
```
select distinct
cs1.CaseStudyID,
case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title
from
CaseStudy cs1
left join CaseStudy cs2
on cs1.title = cs2.title
and cs1.CaseStudyID > cs2.CaseStudyID
```
If you want to replace all of them just change > to <> as below
```
select distinct
cs1.CaseStudyID,
case when cs2.CaseStudyID is null then cs1.Title else cs1.overrideTitle end as title
from
CaseStudy cs1
left join CaseStudy cs2
on cs1.title = cs2.title
and cs1.CaseStudyID <> cs2.CaseStudyID
```
|
233,013 |
<p>I recently started learning Python and I was rather surprised to find a 1000 deep recursion limit (by default). If you set it high enough, about 30000, it crashes with a segmentation fault just like C. Although, C seems to go quite a lot higher.</p>
<p>(The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster. That's 100% true. It's not really what my question is about though.)</p>
<p>I tried the same experiment in Perl and somewhere around 10 million recursions it consumed all of my 4 gigs of ram and I used ^C to stop trying. Clearly Perl doesn't use the C stack, but it does use a ridiculous amount of memory when it recurses -- not terribly shocking considering how much work it has to do to call functions.</p>
<p>I tried in Pike and was completely surprised to get 100,000,000 recursions in about 2 seconds. I have no idea how it did that, but I suspect it flattened the recursion to an iterative process -- it doesn't seem to consume any extra memory while it does it. [Note: Pike does flatten trivial cases, but segfaults on more complicated ones, or so I'm told.]</p>
<p>I used these otherwise useless functions:</p>
<pre><code>int f(int i, int l) { if(i<l) return f(i+1,l); return i; }
sub f { return f($_[0]+1, $_[1]) if $_[0]<$_[1]; return $_[0] };
def f(i,l):
if i<l:
return f(i+1,l)
return i
</code></pre>
<p>I'm very curious how other languages (e.g., PHP, Ruby, Java, Lua, Ocaml, Haskell) handle recursion and why they handle it that way. Additionally, please note whether it makes a difference if the function is "tail-recursive" (see comment).</p>
|
[
{
"answer_id": 233028,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "<p>PHP has a default limit of 100 before it dies:</p>\n\n<p><code>Fatal error: Maximum function nesting level of '100' reached, aborting!</code></p>\n\n<p>Edit: You can change the limit with <code>ini_set('xdebug.max_nesting_level', 100000);</code>, but if you go above about 1150 iterations PHP crashes:</p>\n\n<p><code>[Fri Oct 24 11:39:41 2008] [notice] Parent: child process exited with status 3221225477 -- Restarting.</code></p>\n"
},
{
"answer_id": 233029,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "<p>According to this thread, <a href=\"http://www.velocityreviews.com/forums/showpost.php?p=652300&postcount=7\" rel=\"nofollow noreferrer\">around 5,000,000</a> with java, 1Gb RAM. (and that, with the 'client' version of the hotspot)</p>\n\n<p>That was with a <a href=\"http://mindprod.com/jgloss/javaexe.html\" rel=\"nofollow noreferrer\">stack (-Xss)</a> of 300Mo.</p>\n\n<p>With a <a href=\"https://stackoverflow.com/questions/198577/real-differences-between-java-server-and-java-client#198651\">-server option</a>, that could be increased.</p>\n\n<p>Also one can try to optimize the compiler (<a href=\"http://mindprod.com/jgloss/jet.html\" rel=\"nofollow noreferrer\">with JET</a> for instance) to reduce the stack overhead at each layer.</p>\n"
},
{
"answer_id": 233031,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "<p>C#/.NET will use tail recursion in a particular set of circumstances. (The C# compiler doesn't emit a tailcall opcode, but the <a href=\"http://blogs.msdn.com/davbr/pages/tail-call-jit-conditions.aspx\" rel=\"nofollow noreferrer\">JIT will implement tail recursion in some cases</a>.</p>\n\n<p>Shri Borde <a href=\"http://blogs.msdn.com/shrib/archive/2005/01/25/360370.aspx\" rel=\"nofollow noreferrer\">also has a post on this topic</a>. Of course, the CLR is continually changing, and with .NET 3.5 and 3.5SP1 it may have changed again with respect to tail calls.</p>\n"
},
{
"answer_id": 233052,
"author": "Ola Eldøy",
"author_id": 18651,
"author_profile": "https://Stackoverflow.com/users/18651",
"pm_score": 1,
"selected": false,
"text": "<p>Visual Dataflex will stack overflow.</p>\n"
},
{
"answer_id": 233163,
"author": "Steve Jessop",
"author_id": 13005,
"author_profile": "https://Stackoverflow.com/users/13005",
"pm_score": 6,
"selected": true,
"text": "<p>\"The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster\"</p>\n\n<p>This is true, but if it's really as easy as all that, why doesn't Python do it for me, so that my code can look as simple as possible? (I say this not to slam Python implementers, but because the answer explains the problem).</p>\n\n<p>Recursion optimisations have been present in functional languages since, like, the 14th century or something. Haskell, CAML, Lisp implementations all typically convert at least tail recursive functions to iterations: you basically do this by spotting that it's possible, i.e. that the function can be rearranged such that no local variables other than the return value are used after the recursive call. One trick to make it possible if there's some work done to the recursed return value before return, is to introduce an additional \"accumulator\" parameter. In simple terms this means the work can effectively be done on the way \"down\" instead of on the way \"up\": search around for 'how to make a function tail-recursive' for details.</p>\n\n<p>The actual details of turning a tail recursive function into a loop is basically to jigger with your call convention such you can \"perform the call\" simply by setting up the parameters and jumping back to the start of the function, without bothering to save all that stuff in scope that you know you won't ever use. In assembler terms, you don't have to preserve caller-saves registers if data-flow analysis tells you they're unused beyond the call, and the same goes for anything on the stack: you don't have to move the stack pointer on a call if you don't mind \"your\" bit of stack being scribbled over by the next recursion/iteration.</p>\n\n<p>Contrary to how you paraphrased the Python folks, converting a general recursive function to an iteration is not trivial: for example if it's multiply-recursive then in a simple approach you'd still need a stack. </p>\n\n<p>Memoization is a useful technique, though, for arbitrarily recursive functions, that you might like to look up if you're interested in the possible approaches. What it means is that each time a function is evaluated, you stick the result in a cache. To use this to optimize recursion, basically, if your recursive function counts \"down\", and you memoize it, then you can evaluate it iteratively by adding a loop that counts \"up\" calculating each value of the function in turn until you reach the target. This uses very little stack space provided that the memo cache is big enough to hold all the values you'll need: for instance if f(n) depends on f(n-1), f(n-2) and f(n-3) you only need space for 3 values in the cache: as you go up you can kick the ladder away. If f(n) depends on f(n-1) and f(n/2), you need lots of space in the cache, but still less than you'd use for stack in an unoptimised recursion.</p>\n"
},
{
"answer_id": 233190,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 2,
"selected": false,
"text": "<p>In some non pathological cases (like your), (latest) Lua will use <a href=\"http://en.wikipedia.org/wiki/Tail_recursion\" rel=\"nofollow noreferrer\" title=\"Tail recursion - Wikipedia, the free encyclopedia\">tail call recursion</a>, ie. it will just jump without pushing data in stack. So the number of recursion loops can be almost unlimited.</p>\n\n<p>Tested with:</p>\n\n<pre><code>function f(i, l)\n if i < l then\n return f(i+1, l)\n end\n return i\nend\n\nlocal val1 = arg[1] or 1\nlocal val2 = arg[2] or 100000000\nprint(f(val1 + 0, val2 + 0))\n</code></pre>\n\n<p>Also with:</p>\n\n<pre><code>function g(i, l)\n if i >= l then\n return i\n end\n return g(i+1, l)\nend\n</code></pre>\n\n<p>and even tried cross-recursion (f calling g and g calling f...).</p>\n\n<p>On Windows, Lua 5.1 uses around 1.1MB (constant) to run this, finishes in a few seconds.</p>\n"
},
{
"answer_id": 233359,
"author": "Thedric Walker",
"author_id": 26166,
"author_profile": "https://Stackoverflow.com/users/26166",
"pm_score": 2,
"selected": false,
"text": "<p>Using the following in the F# interactive console, it ran in less than a second:</p>\n\n<pre><code>let rec f i l = \n match i with \n | i when i < l -> f (i+1) l\n | _ -> l\n\nf 0 100000000;;\n</code></pre>\n\n<p>I then tried a straight translation i.e.</p>\n\n<pre><code>let rec g i l = if i < l then g (i+1) l else l\n\ng 0 100000000;;\n</code></pre>\n\n<p>Same outcome but different compilation. </p>\n\n<p>This is what <em>f</em> looks like in when translated to C#:</p>\n\n<pre><code>int f(int i, int l)\n{\n while(true)\n {\n int num = i;\n if(num >= l)\n return l;\n int i = num;\n l = l;\n i = i + 1;\n }\n}\n</code></pre>\n\n<p><em>g</em>, however is translated to this:</p>\n\n<pre><code>int g(int i, int l)\n{\n while(i < l)\n {\n l = l;\n i++;\n }\n return l;\n}\n</code></pre>\n\n<p>It is interesting that two functions that are fundamentally the same are rendered differently by the F# compiler. It also shows that the F# compiler has tail-recursive optimization. Thus this should loop until i reaches the limit for 32-bit integers.</p>\n"
},
{
"answer_id": 233574,
"author": "T.E.D.",
"author_id": 29639,
"author_profile": "https://Stackoverflow.com/users/29639",
"pm_score": 3,
"selected": false,
"text": "<p>This is more of an implementation question than a language question. There's nothing stopping some (stoopid) C compiler implementor from also limiting their call stack to 1000. There are a lot of small processors out there that wouldn't have stack space for even that many.</p>\n\n<blockquote>\n <p>(The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster. That's 100% true. It's not really what my question is about though.)</p>\n</blockquote>\n\n<p>Perhaps they do say that, but this isn't quite correct. Recursion can always be converted to iteration, but sometimes it also requires manual use of a <em>stack</em> too. In those circumstances, I could see the recursive version being faster (assuming you are smart enough to make simple optimizations, like pulling unneeded declarations outside of the recursive routine). After all, the stack pushes surrounding procedure calls are a well bounded problem that your compiler should know how to optimize very well. Manual stack operations, on the other hand, are not going to have specialized optimization code in your compiler, and are liable to have all sorts of user-interface sanity checks that will take up extra cycles.</p>\n\n<p>It may be the case that the iterative/stack solution is always faster <em>in Python</em>. If so, that's a failing of Python, not of recursion.</p>\n"
},
{
"answer_id": 234173,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 1,
"selected": false,
"text": "<p>There is a way to improve upon the <code>Perl</code> code, to make it use a constant size stack. You do this by using a special form of <code>goto</code>.</p>\n\n<pre><code>sub f{\n if( $_[0] < $_[1] ){\n\n # return f( $_[0]+1, $_[1] );\n\n @_ = ( $_[0]+1, $_[1] );\n goto &f;\n\n } else {\n return $_[0]\n }\n}\n</code></pre>\n\n<p>When first called it will allocate space on the stack. Then it will change its arguments, and restart the subroutine, without adding anything more to the stack. It will therefore pretend that it never called its self, changing it into an iterative process.</p>\n\n<hr>\n\n<p>You could also use the <a href=\"http://search.cpan.org/perldoc/Sub::Call::Recur\" rel=\"nofollow noreferrer\">Sub::Call::Recur</a> module. Which makes the code easier to understand, and shorter.</p>\n\n<pre><code>use Sub::Call::Recur;\nsub f{\n recur( $_[0]+1, $_[1] ) if $_[0] < $_[1];\n return $_[0];\n}\n</code></pre>\n\n\n"
},
{
"answer_id": 234208,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>I'm quite a fan of functional programming, and since most of those langauges implement tail call optimization, you can recurse as much as you like :-P</p>\n\n<p>However, practically, I have to use a lot of Java and use Python a lot too. No idea what limit Java has, but for Python I had actually planned (but have not yet done it) to implement a decorator which would tail call optimize the decorated function.\nI was planning this not to optimize recursion, but mainly as an exercise in dynamically patching Python bytecode and learning more about Pythons internals.\nHeres some itneresting links: <a href=\"http://lambda-the-ultimate.org/node/1331\" rel=\"nofollow noreferrer\">http://lambda-the-ultimate.org/node/1331</a> and <a href=\"http://www.rowehl.com/blog/?p=626\" rel=\"nofollow noreferrer\">http://www.rowehl.com/blog/?p=626</a></p>\n"
},
{
"answer_id": 4229575,
"author": "ordnungswidrig",
"author_id": 9069,
"author_profile": "https://Stackoverflow.com/users/9069",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://clojure.org/\" rel=\"nofollow\">clojure</a> provides a special form for tail recursion \"recur\" this can only be used in tail places of the ast. Otherwise it behaves like java and will likely throw a StackverflowException.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233013",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/388466/"
] |
I recently started learning Python and I was rather surprised to find a 1000 deep recursion limit (by default). If you set it high enough, about 30000, it crashes with a segmentation fault just like C. Although, C seems to go quite a lot higher.
(The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster. That's 100% true. It's not really what my question is about though.)
I tried the same experiment in Perl and somewhere around 10 million recursions it consumed all of my 4 gigs of ram and I used ^C to stop trying. Clearly Perl doesn't use the C stack, but it does use a ridiculous amount of memory when it recurses -- not terribly shocking considering how much work it has to do to call functions.
I tried in Pike and was completely surprised to get 100,000,000 recursions in about 2 seconds. I have no idea how it did that, but I suspect it flattened the recursion to an iterative process -- it doesn't seem to consume any extra memory while it does it. [Note: Pike does flatten trivial cases, but segfaults on more complicated ones, or so I'm told.]
I used these otherwise useless functions:
```
int f(int i, int l) { if(i<l) return f(i+1,l); return i; }
sub f { return f($_[0]+1, $_[1]) if $_[0]<$_[1]; return $_[0] };
def f(i,l):
if i<l:
return f(i+1,l)
return i
```
I'm very curious how other languages (e.g., PHP, Ruby, Java, Lua, Ocaml, Haskell) handle recursion and why they handle it that way. Additionally, please note whether it makes a difference if the function is "tail-recursive" (see comment).
|
"The Python folks are quick to point out that you can always convert recursive functions to iterative ones and that they're always faster"
This is true, but if it's really as easy as all that, why doesn't Python do it for me, so that my code can look as simple as possible? (I say this not to slam Python implementers, but because the answer explains the problem).
Recursion optimisations have been present in functional languages since, like, the 14th century or something. Haskell, CAML, Lisp implementations all typically convert at least tail recursive functions to iterations: you basically do this by spotting that it's possible, i.e. that the function can be rearranged such that no local variables other than the return value are used after the recursive call. One trick to make it possible if there's some work done to the recursed return value before return, is to introduce an additional "accumulator" parameter. In simple terms this means the work can effectively be done on the way "down" instead of on the way "up": search around for 'how to make a function tail-recursive' for details.
The actual details of turning a tail recursive function into a loop is basically to jigger with your call convention such you can "perform the call" simply by setting up the parameters and jumping back to the start of the function, without bothering to save all that stuff in scope that you know you won't ever use. In assembler terms, you don't have to preserve caller-saves registers if data-flow analysis tells you they're unused beyond the call, and the same goes for anything on the stack: you don't have to move the stack pointer on a call if you don't mind "your" bit of stack being scribbled over by the next recursion/iteration.
Contrary to how you paraphrased the Python folks, converting a general recursive function to an iteration is not trivial: for example if it's multiply-recursive then in a simple approach you'd still need a stack.
Memoization is a useful technique, though, for arbitrarily recursive functions, that you might like to look up if you're interested in the possible approaches. What it means is that each time a function is evaluated, you stick the result in a cache. To use this to optimize recursion, basically, if your recursive function counts "down", and you memoize it, then you can evaluate it iteratively by adding a loop that counts "up" calculating each value of the function in turn until you reach the target. This uses very little stack space provided that the memo cache is big enough to hold all the values you'll need: for instance if f(n) depends on f(n-1), f(n-2) and f(n-3) you only need space for 3 values in the cache: as you go up you can kick the ladder away. If f(n) depends on f(n-1) and f(n/2), you need lots of space in the cache, but still less than you'd use for stack in an unoptimised recursion.
|
233,026 |
<p>I have a database with a table which is full of conditions and error messages for checking another database.</p>
<p>I want to run a loop such that each of these conditions is checked against all the tables in the second database and generae a report which gives the errors.</p>
<p>Is this possible in ms access.</p>
<p>For example,</p>
<p>querycrit table</p>
<pre><code>id query error
1 speed<25 and speed>56 speed above limit
2 dist<56 or dist >78 dist within limit
</code></pre>
<p>I have more than 400 queries like this of different variables.</p>
<p>THe table against which I am running the queries is</p>
<p>records table</p>
<pre><code>id speed dist accce decele aaa bbb ccc
1 33 34 44 33 33 33 33
2 45 44 55 55 55 22 23
</code></pre>
<p>regards
ttk</p>
|
[
{
"answer_id": 233086,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": "<p>When you say \"report\", do you mean an Access Report, or would writing to a file or Access Form work?</p>\n\n<p>You can create a function or sub in a Module to do this. Open a recordset on your querycrit table and spin through the records dynamically building and running the SQL for the records table. You can write the results of these dynamic queries to a file, or a form, or insert the results into a temp table and drive the Access Report from there.</p>\n"
},
{
"answer_id": 233136,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<p>Here is some sample code, it is typed, not tested.</p>\n\n<pre><code>Dim rs AS DAO.Recordset\nDim rs2 AS DAO.Recordset\n\nSet rs=CurrentDB.OpenRecordset(\"querycrit\")\n\nstrSQL=\"SELECT * From Records WHERE \"\nDo While Not rs.EOF\n Set rs2=CurrentDB.OpenRecordset(strSQL & rs![Query])\n If Not rs2.EOF Then\n Debug.Print rs![Error]\n Debug.Print rs2.Fields(1)\n End If\n\n rs.MoveNext\nLoop\n</code></pre>\n"
},
{
"answer_id": 233244,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 0,
"selected": false,
"text": "<blockquote>\n <p>\"actually there are many record tables\n to be checked and not all queries can\n be run on all tables, for eg in one\n table speed may not be there and in\n next table distance may not be there.\"</p>\n</blockquote>\n\n<p>The correct think to do, I think, would be to create a table of tables and a query-table junction table that shows which queries are to be run on which table, for example:</p>\n\n<pre><code>TableID QueryID\n1 4\n2 1\n2 3\n3 1\n</code></pre>\n\n<p>This can the be used to run the correct set of queries on each table.</p>\n"
},
{
"answer_id": 233470,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 3,
"selected": true,
"text": "<p>Here is some more sample code. It illustrates the use of two different types of recordsets. You may wish to read <a href=\"http://allenbrowne.com/ser-29.html\" rel=\"nofollow noreferrer\">VBA Traps: Working with Recordsets</a> by Allen Browne and <a href=\"http://support.microsoft.com/kb/286335\" rel=\"nofollow noreferrer\">List of reserved words in Access 2002 and in later versions of Access \n</a>.</p>\n\n<pre><code>Dim rs As DAO.Recordset\nDim rs2 As ADODB.Recordset\n\nSet rs = CurrentDb.OpenRecordset(\"querycrit\")\nSet rs2 = CreateObject(\"ADODB.Recordset\")\nrs2.ActiveConnection = CurrentProject.Connection\nFor Each tdf In CurrentDb.TableDefs\n'EDIT: TableDefs includes Microsoft System tables and '\n'these should never be tampered with. They all begin with Msys '\n'so we can leave them out of the loop here. '\n If Left(tdf.Name, 4) <> \"msys\" And tdf.Name <> \"querycrit\" Then\n rs.MoveFirst\n strSQL = \"SELECT * From [\" & tdf.Name & \"] WHERE \"\n\n Do While Not rs.EOF\n On Error Resume Next\n Debug.Print tdf.Name\n rs2.Open strSQL & \" \" & rs![query]\n If Err.Number = 0 Then\n On Error GoTo 0\n If Not rs2.EOF Then\n Debug.Print rs![Error]\n Debug.Print rs2.GetString\n End If\n End If\n Err.Clear\n rs2.Close\n rs.MoveNext\n\n Loop\n End If\nNext\nEnd Sub\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233026",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31132/"
] |
I have a database with a table which is full of conditions and error messages for checking another database.
I want to run a loop such that each of these conditions is checked against all the tables in the second database and generae a report which gives the errors.
Is this possible in ms access.
For example,
querycrit table
```
id query error
1 speed<25 and speed>56 speed above limit
2 dist<56 or dist >78 dist within limit
```
I have more than 400 queries like this of different variables.
THe table against which I am running the queries is
records table
```
id speed dist accce decele aaa bbb ccc
1 33 34 44 33 33 33 33
2 45 44 55 55 55 22 23
```
regards
ttk
|
Here is some more sample code. It illustrates the use of two different types of recordsets. You may wish to read [VBA Traps: Working with Recordsets](http://allenbrowne.com/ser-29.html) by Allen Browne and [List of reserved words in Access 2002 and in later versions of Access](http://support.microsoft.com/kb/286335).
```
Dim rs As DAO.Recordset
Dim rs2 As ADODB.Recordset
Set rs = CurrentDb.OpenRecordset("querycrit")
Set rs2 = CreateObject("ADODB.Recordset")
rs2.ActiveConnection = CurrentProject.Connection
For Each tdf In CurrentDb.TableDefs
'EDIT: TableDefs includes Microsoft System tables and '
'these should never be tampered with. They all begin with Msys '
'so we can leave them out of the loop here. '
If Left(tdf.Name, 4) <> "msys" And tdf.Name <> "querycrit" Then
rs.MoveFirst
strSQL = "SELECT * From [" & tdf.Name & "] WHERE "
Do While Not rs.EOF
On Error Resume Next
Debug.Print tdf.Name
rs2.Open strSQL & " " & rs![query]
If Err.Number = 0 Then
On Error GoTo 0
If Not rs2.EOF Then
Debug.Print rs![Error]
Debug.Print rs2.GetString
End If
End If
Err.Clear
rs2.Close
rs.MoveNext
Loop
End If
Next
End Sub
```
|
233,027 |
<p>How to set the turbo c path in windows globally so that i can compile and run my C programs (which are in other drives) using command prompt in windows XP?
Can any one tell me how to get commands at every drive in the command prompt just by typing in </p>
<pre><code>c:\tcc
</code></pre>
<p>in command prompt in windows and turbo c environment?</p>
|
[
{
"answer_id": 233036,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 4,
"selected": true,
"text": "<ul>\n<li>Go to the Start Menu, then Control Panel. </li>\n<li>Choose the \"System\" applet.</li>\n<li>Click on the \"Advanced\" tab.</li>\n<li>Click on \"Environment Variables\"</li>\n<li>Find the \"Path\" variable, and press \"Edit\"</li>\n<li>Append a semicolon, then the path to Turbo C</li>\n</ul>\n\n<p>For setting the include and library paths, go to the same place, but instead of editing the \"Path\" variable, create a new variable called \"INCLUDE\", and set it to the location of your turboc \"\\include\" directory; and create one called \"LIB\" and one called \"CLASSPATH\", and set them to your turboc \"\\lib\" directory.</p>\n"
},
{
"answer_id": 233130,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>Is there some reason why you're using such an old compiler? Turbo C was last released in the early 1990s, if I remember correctly.</p>\n\n<p>I might suggest downloading the free <a href=\"http://www.microsoft.com/Express/\" rel=\"nofollow noreferrer\">Visual Studio Express Edition</a> which is a much more modern compiler and you will find many more people here who are willing to help. It also comes with good documentation and it's easier to search the net for articles and help for it.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
How to set the turbo c path in windows globally so that i can compile and run my C programs (which are in other drives) using command prompt in windows XP?
Can any one tell me how to get commands at every drive in the command prompt just by typing in
```
c:\tcc
```
in command prompt in windows and turbo c environment?
|
* Go to the Start Menu, then Control Panel.
* Choose the "System" applet.
* Click on the "Advanced" tab.
* Click on "Environment Variables"
* Find the "Path" variable, and press "Edit"
* Append a semicolon, then the path to Turbo C
For setting the include and library paths, go to the same place, but instead of editing the "Path" variable, create a new variable called "INCLUDE", and set it to the location of your turboc "\include" directory; and create one called "LIB" and one called "CLASSPATH", and set them to your turboc "\lib" directory.
|
233,072 |
<p><p>How to include any assembly code lines into my C program ?
<p>In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?</p>
|
[
{
"answer_id": 233090,
"author": "xsl",
"author_id": 11387,
"author_profile": "https://Stackoverflow.com/users/11387",
"pm_score": 3,
"selected": true,
"text": "<p>One way to include assembly code is to add a wrapper function and write the assembly code in the asm block, as shown in the example below:</p>\n\n<pre><code>void wrapper_function()\n{\n asm\n {\n /* your assembly code */\n }\n}\n</code></pre>\n"
},
{
"answer_id": 233122,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 0,
"selected": false,
"text": "<p>You can also link in the object files. But inline assembler is much easier to maintain.</p>\n"
},
{
"answer_id": 233131,
"author": "Ray",
"author_id": 13327,
"author_profile": "https://Stackoverflow.com/users/13327",
"pm_score": 1,
"selected": false,
"text": "<p>You can use your makefile to define actions for different target types. For C types (e.g. foo.c) have the C compiler invoked. For ASM files, invoke the assembler. The output from either should be an object file (e.g. .o) which can all be compiled together by the linker.</p>\n\n<p>If you have a little bit of assembly, go ahead an inline. Otherwise, I recommend separate modules and functional decomposition as the best way to manage everything. Especially if you need to support different targets (i.e. cross platform development).</p>\n"
},
{
"answer_id": 4147512,
"author": "Rishav Ambasta",
"author_id": 503584,
"author_profile": "https://Stackoverflow.com/users/503584",
"pm_score": 0,
"selected": false,
"text": "<pre><code>void func()\n{\nasm://assembly statements...\nasm://assembly statements...\n...\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233072",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31116/"
] |
How to include any assembly code lines into my C program ?
In turbo c is there a possibility to add an assembly code file (.asm) to a project of few .c files?
|
One way to include assembly code is to add a wrapper function and write the assembly code in the asm block, as shown in the example below:
```
void wrapper_function()
{
asm
{
/* your assembly code */
}
}
```
|
233,073 |
<p>How can I group by two different fields in a Crystal Report?</p>
<p>Foe example :</p>
<pre><code>val1|val2|val3|val6
val1|val12|val3|val7
val11|val2|val3|val8
val11|val12|val3|val9
</code></pre>
<p>I want the report to look like </p>
<pre><code>val1 :
=======
val2
----
val3|val6
val12
-------
val3|val7
val11 :
=========
val2
-----
val3|val8
val12 :
------
val3|val9
</code></pre>
|
[
{
"answer_id": 233463,
"author": "thismat",
"author_id": 14045,
"author_profile": "https://Stackoverflow.com/users/14045",
"pm_score": 0,
"selected": false,
"text": "<p>Not sure on best practices, but what I've used to do similar in the past was a sub report with it's own grouping, within the first group.</p>\n\n<p>So it would look something like this:</p>\n\n<p>MainReportHeader\n SubReport(?)\n SubreportHeader\n Values\n SubReportFooter\nMainReportFooter</p>\n\n<p>Again, not a crystal expert, just an idea and something I've used before. There is probably a much easier way.</p>\n"
},
{
"answer_id": 234433,
"author": "smbarbour",
"author_id": 29115,
"author_profile": "https://Stackoverflow.com/users/29115",
"pm_score": 3,
"selected": false,
"text": "<p>The generic data provided is rather vague, so I will provide my own to demonstrate (with field names on the first line)</p>\n\n<pre>\"EmployeeName\",\"WeekNumber\",\"DayOfWeek\",\"HoursWorked\"\n\"John Doe\",20,\"Monday\",8\n\"John Doe\",20,\"Tuesday\",8\n\"John Doe\",20,\"Wednesday\",8\n\"John Doe\",21,\"Thursday\",8\n\"John Doe\",21,\"Friday\",8\n\"Jane Doe\",20,\"Monday\",8\n\"Jane Doe\",20,\"Tuesday\",8\n\"Jane Doe\",21,\"Wednesday\",8\n\"Jane Doe\",21,\"Thursday\",8\n\"Jane Doe\",21,\"Friday\",8\n</pre>\n\n<p>Assuming that I read the question correctly, you would want the report to look like this:</p>\n\n<pre>John Doe\n Week: 20\n Monday 8 hours\n Tuesday 8 hours\n Wednesday 8 hours\n Week: 21\n Thursday 8 hours\n Friday 8 hours\n\nJane Doe\n Week: 20\n Monday 8 hours\n Tuesday 8 hours\n Week: 21\n Wednesday 8 hours\n Thursday 8 hours\n Friday 8 hours</pre>\n\n<p>If this is the case, you would group by the \"EmployeeName\" field first, and then simply add another group for \"WeekNumber\" via the Insert menu using the Group option. This is pretty straightforward, and you can do summaries on the fields at various levels. The only thing that would get \"hairy\" with multiple tier of grouping would be if you were calculating fields within the group and wanted to return those calculations to a higher level of grouping for summation, which would require declaring global variables within the report.</p>\n\n<p>For what it's worth, I've been using Crystal Reports heavily for the past 7 years.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233073",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
How can I group by two different fields in a Crystal Report?
Foe example :
```
val1|val2|val3|val6
val1|val12|val3|val7
val11|val2|val3|val8
val11|val12|val3|val9
```
I want the report to look like
```
val1 :
=======
val2
----
val3|val6
val12
-------
val3|val7
val11 :
=========
val2
-----
val3|val8
val12 :
------
val3|val9
```
|
The generic data provided is rather vague, so I will provide my own to demonstrate (with field names on the first line)
```
"EmployeeName","WeekNumber","DayOfWeek","HoursWorked"
"John Doe",20,"Monday",8
"John Doe",20,"Tuesday",8
"John Doe",20,"Wednesday",8
"John Doe",21,"Thursday",8
"John Doe",21,"Friday",8
"Jane Doe",20,"Monday",8
"Jane Doe",20,"Tuesday",8
"Jane Doe",21,"Wednesday",8
"Jane Doe",21,"Thursday",8
"Jane Doe",21,"Friday",8
```
Assuming that I read the question correctly, you would want the report to look like this:
```
John Doe
Week: 20
Monday 8 hours
Tuesday 8 hours
Wednesday 8 hours
Week: 21
Thursday 8 hours
Friday 8 hours
Jane Doe
Week: 20
Monday 8 hours
Tuesday 8 hours
Week: 21
Wednesday 8 hours
Thursday 8 hours
Friday 8 hours
```
If this is the case, you would group by the "EmployeeName" field first, and then simply add another group for "WeekNumber" via the Insert menu using the Group option. This is pretty straightforward, and you can do summaries on the fields at various levels. The only thing that would get "hairy" with multiple tier of grouping would be if you were calculating fields within the group and wanted to return those calculations to a higher level of grouping for summation, which would require declaring global variables within the report.
For what it's worth, I've been using Crystal Reports heavily for the past 7 years.
|
233,074 |
<p>Please could someone help me with writing a regex expression to replace 0044 token which will be at the start of the string with a 0. Please note that I do not want to replace all 0044 tokens with 0, only those that appear at the start of the string.</p>
<p>Thanks a lot</p>
|
[
{
"answer_id": 233076,
"author": "Graeme Perrow",
"author_id": 1821,
"author_profile": "https://Stackoverflow.com/users/1821",
"pm_score": 1,
"selected": false,
"text": "<p>In perl: </p>\n\n<pre><code>s/^0044/0/;\n</code></pre>\n\n<p>The <code>^</code> means that the match will only happen at the beginning of the string.</p>\n"
},
{
"answer_id": 233442,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": 0,
"selected": false,
"text": "<p>Then why you dont put an space at the begining in the search and replace boxes, i mean:</p>\n\n<pre><code>Search: \" 0044\"\nReplace \" 0\"\n</code></pre>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 233464,
"author": "Timbo",
"author_id": 4310,
"author_profile": "https://Stackoverflow.com/users/4310",
"pm_score": 0,
"selected": false,
"text": "<p>The ^ works in notepad++ to match the beginning of the line.</p>\n"
},
{
"answer_id": 233480,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 1,
"selected": false,
"text": "<p>If you really want to use regex its already answered above. i.e</p>\n\n<p>Find What: <code>^0044</code></p>\n\n<p>Replace With: <code>0</code></p>\n\n<p>But here is a crude way to do it:</p>\n\n<p>Press ALT, then select all the '<code>044</code>'s vertically using mouse and delete them. Keep ALT pressed while making the selection. </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233074",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Please could someone help me with writing a regex expression to replace 0044 token which will be at the start of the string with a 0. Please note that I do not want to replace all 0044 tokens with 0, only those that appear at the start of the string.
Thanks a lot
|
In perl:
```
s/^0044/0/;
```
The `^` means that the match will only happen at the beginning of the string.
|
233,088 |
<p>The fundamental equation of weight loss/gain is:</p>
<pre><code>weight_change = convert_to_weight_diff(calories_consumed - calories_burnt);
</code></pre>
<p>I'm going on a health kick, and like a good nerd I thought I'd start keeping track of these things and write some software to process my data. I'm not attentive and disciplined enough to count calories in food, so I thought I'd work backwards:</p>
<ul>
<li>I can weigh myself every day</li>
<li>I can calculate my BMR and hence how many calories I burn doing nothing all day</li>
<li>I can use my heart-rate monitor to figure out how many calories I burn doing exercise</li>
</ul>
<p>That way I can generate an approximate "calories consumed" graph based on my exercise and weight records, and use that to motivate myself when I'm tempted to have a donut.</p>
<p>The thing I'm stuck on is the function:</p>
<pre><code>int convert_to_weight_diff(int calorie_diff);
</code></pre>
<p>Anybody know the pseudo-code for that function? If you've got some details, make sure you specify if we're talking calories, Calories, kilojoules, pounds, kilograms, etc.</p>
<p>Thanks! </p>
|
[
{
"answer_id": 233096,
"author": "Ken",
"author_id": 20074,
"author_profile": "https://Stackoverflow.com/users/20074",
"pm_score": 4,
"selected": true,
"text": "<p>Look at <a href=\"http://www.fourmilab.ch/hackdiet/www/hackdiet.html\" rel=\"nofollow noreferrer\">The Hacker's Diet</a> and <a href=\"http://www.physicsdiet.com/\" rel=\"nofollow noreferrer\">physicsdiet.com</a> - this wheel has already been invented.</p>\n"
},
{
"answer_id": 233099,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I dunno how accurate this is because it's Wikipedia but it looks like a good basis for a rule-of-thumb-o-meter.</p>\n\n<p><a href=\"http://en.wikipedia.org/wiki/Food_energy\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Food_energy</a></p>\n"
},
{
"answer_id": 233101,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "<p>I think the conversion factor is about 3500 calories per pound. Google search (not the calculator!) seems to agree: <a href=\"http://www.google.com/search?q=calories+per+pound\" rel=\"nofollow noreferrer\">http://www.google.com/search?q=calories+per+pound</a></p>\n"
},
{
"answer_id": 233115,
"author": "Markus",
"author_id": 18597,
"author_profile": "https://Stackoverflow.com/users/18597",
"pm_score": 0,
"selected": false,
"text": "<p>As you will only burn fat, the conversation is as follows:</p>\n\n<p>To burn 1g of fat you'll have to work out 9kcal.</p>\n\n<p>Source: <a href=\"http://en.wikipedia.org/wiki/Food_energy\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Food_energy</a></p>\n"
},
{
"answer_id": 233239,
"author": "Nic Wise",
"author_id": 2947,
"author_profile": "https://Stackoverflow.com/users/2947",
"pm_score": 0,
"selected": false,
"text": "<p>I think everyone else has summed it up well, however there is something (maybe more) that you have forgotten:</p>\n\n<p>water and stimulants (your a developer right, so caffeine is a standard drug, like Spice is in dune)</p>\n\n<p>For example, if I have 2000cal of food in a day, and thru metabolism and exercise I burn 1750 (I get stuff all exercise at the moment, should be 2500 or so), I have 350cal left, which goes as fat, so I'm about +50 grams (were 3500 cals == about 500g of fat. Not sure if thats right, but lets go with it for the moment)</p>\n\n<p>If I do the exact same thing tomorrow, but I have 2 cups of coffee (keep in mind my coffee of choice is Espresso with nothing else in it, so close to zero cals), I have to take two things into account:</p>\n\n<ul>\n<li>caffeine ups my metabolism, so I burn more - so my burn may be +100cals </li>\n<li>caffeine is a diuretic, so I'll lose more water - so my WEIGHT will be down maybe -200g, depending on my bodys reaction to it.</li>\n</ul>\n\n<p>So, I think for a basic idea, your proposal is a good one, but once you start getting more specific, it gets NASTY complex.</p>\n\n<p>Another example: If you are doing exercise, and burn 500cals during a RUN, you will continue to burn cals for a number of hours after. If you burn 200 cals thru weight training, you'll do the same post-exercise burn (maybe more), and your baseline metabolic burn (how much you burn if you just sit on your backside) will be higher until that muscle atrophies back to whatever it was before.</p>\n\n<p>I think you are right tho - not really a SO question, but fun none the less.</p>\n"
},
{
"answer_id": 233254,
"author": "Dan",
"author_id": 8040,
"author_profile": "https://Stackoverflow.com/users/8040",
"pm_score": 0,
"selected": false,
"text": "<p>I would add that you find a different measurement than BMI into your considerations because it doesn't take body composition into consideration. For example, I remember seeing an article about Evander Holyfield being considered \"dangerously obese\" based on his high BMI. He looked like he had barely an ounce of fat on him. Anyway, just a consideration.</p>\n"
},
{
"answer_id": 9695826,
"author": "hetelek",
"author_id": 877651,
"author_profile": "https://Stackoverflow.com/users/877651",
"pm_score": 1,
"selected": false,
"text": "<p>I mean, if this is what you're looking for, you should be set.</p>\n\n<p>Supposely, in Einstein's Theory of Relativity he states that a calorie does have an exact weight(0.000000000000046 grams).</p>\n\n<p>With this said, something like this should work:</p>\n\n<pre><code>int convert_to_weight_diff(int calories)\n{\n return 0.000000000000046 * calories;\n}\n</code></pre>\n\n<p>That would return, in grams, how much weight was lost. To make it more reasonable, I would do something like find out how many calories are in like half a pound or whatever.</p>\n\n<p>From what I read, that is what you are trying to do. Tell me if not.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233088",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6408/"
] |
The fundamental equation of weight loss/gain is:
```
weight_change = convert_to_weight_diff(calories_consumed - calories_burnt);
```
I'm going on a health kick, and like a good nerd I thought I'd start keeping track of these things and write some software to process my data. I'm not attentive and disciplined enough to count calories in food, so I thought I'd work backwards:
* I can weigh myself every day
* I can calculate my BMR and hence how many calories I burn doing nothing all day
* I can use my heart-rate monitor to figure out how many calories I burn doing exercise
That way I can generate an approximate "calories consumed" graph based on my exercise and weight records, and use that to motivate myself when I'm tempted to have a donut.
The thing I'm stuck on is the function:
```
int convert_to_weight_diff(int calorie_diff);
```
Anybody know the pseudo-code for that function? If you've got some details, make sure you specify if we're talking calories, Calories, kilojoules, pounds, kilograms, etc.
Thanks!
|
Look at [The Hacker's Diet](http://www.fourmilab.ch/hackdiet/www/hackdiet.html) and [physicsdiet.com](http://www.physicsdiet.com/) - this wheel has already been invented.
|
233,113 |
<p>How do I get the type of a generic typed class within the class?</p>
<p>An example:</p>
<p>I build a generic typed collection implementing <em>ICollection< T></em>. Within I have methods like </p>
<pre><code> public void Add(T item){
...
}
public void Add(IEnumerable<T> enumItems){
...
}
</code></pre>
<p>How can I ask within the method for the given type <em>T</em>?</p>
<p>The reason for my question is: If <em>object</em> is used as <em>T</em> the collection uses Add(object item) instead of Add(IEnumerable<object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.</p>
<p>So i need something like </p>
<pre><code>if (T is object) {
// Check for IEnumerable
}
</code></pre>
<p>but of course that cannot work in C#. Suggestions?</p>
<p>Thank you very much!</p>
<p>Michael</p>
|
[
{
"answer_id": 233120,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "<p>You can use: <code>typeof(T)</code></p>\n\n<pre><code>if (typeof(T) == typeof(object) ) {\n // Check for IEnumerable\n}\n</code></pre>\n"
},
{
"answer_id": 233146,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 6,
"selected": true,
"text": "<p>Personally, I would side step the issue by renaming the <code>IEnumerable<T></code> method to <code>AddRange</code>. This avoids such issues, and is consistent with existing APIs such as <a href=\"http://msdn.microsoft.com/en-us/library/z883w3dc.aspx\" rel=\"noreferrer\"><code>List<T>.AddRange</code></a>.</p>\n\n<p>It also keeps things clean when the <code>T</code> you want to add implements <code>IEnumerable<T></code> (rare, I'll admit).</p>\n"
},
{
"answer_id": 233155,
"author": "Isak Savo",
"author_id": 8521,
"author_profile": "https://Stackoverflow.com/users/8521",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to use the <code>is</code> operator in a generic class/method you have to limit <code>T</code> to a reference type:</p>\n\n<pre><code>public void MyMethod<T>(T theItem) where T : class\n{\n if (theItem is IEnumerable) { DoStuff(); }\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233113",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9470/"
] |
How do I get the type of a generic typed class within the class?
An example:
I build a generic typed collection implementing *ICollection< T>*. Within I have methods like
```
public void Add(T item){
...
}
public void Add(IEnumerable<T> enumItems){
...
}
```
How can I ask within the method for the given type *T*?
The reason for my question is: If *object* is used as *T* the collection uses Add(object item) instead of Add(IEnumerable<object> enumItems) even if the parameter is IEnumerable. So in the first case it would add the whole enumerable collection as one object instead of multiple objects of the enumerable collection.
So i need something like
```
if (T is object) {
// Check for IEnumerable
}
```
but of course that cannot work in C#. Suggestions?
Thank you very much!
Michael
|
Personally, I would side step the issue by renaming the `IEnumerable<T>` method to `AddRange`. This avoids such issues, and is consistent with existing APIs such as [`List<T>.AddRange`](http://msdn.microsoft.com/en-us/library/z883w3dc.aspx).
It also keeps things clean when the `T` you want to add implements `IEnumerable<T>` (rare, I'll admit).
|
233,127 |
<p>We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread.</p>
<p>The result is that the caller can use the function naively, and internally it'll make use of multiple cores.</p>
<p><em>All good so far..</em></p>
<p>The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there.</p>
<p><strong><em>How can we do this?</em></strong></p>
<p>The best I can think of is:</p>
<ol>
<li>Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones).</li>
<li>Record the type and message of the exception.</li>
<li>Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread.</li>
</ol>
<p>This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.</p>
|
[
{
"answer_id": 233180,
"author": "PierreBdR",
"author_id": 7136,
"author_profile": "https://Stackoverflow.com/users/7136",
"pm_score": 2,
"selected": false,
"text": "<p>There is, indeed, no good and generic way to transmit exceptions from one thread to the next.</p>\n\n<p>If, as it should, all your exceptions derive from std::exception, then you can have a top-level general exception catch that will somehow send the exception to the main thread where it will be thrown again. The problem being you loose the throwing point of the exception. You can probably write compiler-dependent code to get this information and transmit it though.</p>\n\n<p>If not all your exception inherit std::exception, then you are in trouble and have to write a lot of top-level catch in your thread ... but the solution still hold.</p>\n"
},
{
"answer_id": 233191,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 2,
"selected": false,
"text": "<p>Could you serialize the exception in the worker thread, transmit that back to the main thread, deserialize, and throw it again? I expect that for this to work the exceptions would all have to derive from the same class (or at least a small set of classes with the switch statement thing again). Also, I'm not sure that they would be serializable, I'm just thinking out loud.</p>\n"
},
{
"answer_id": 233194,
"author": "anon6439",
"author_id": 15477,
"author_profile": "https://Stackoverflow.com/users/15477",
"pm_score": 1,
"selected": false,
"text": "<p>You will need to do a generic catch for all exceptions in the worker (including non-std exceptions, like access violations), and send a message from the worker thread (i suppose you have some kind of messaging in place?) to the controlling thread, containing a live pointer to the exception, and rethrow there by creating a copy of the exception.\nThen the worker can free the original object and exit.</p>\n"
},
{
"answer_id": 233196,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 3,
"selected": false,
"text": "<p>You problem is that you could receive multiple exceptions, from multiple threads, as each could fail, perhaps from different reasons.</p>\n<p>I am assuming the main thread is somehow waiting for the threads to end to retrieve the results, or checking regularly the other threads' progress, and that access to shared data is synchronized.</p>\n<h2>Simple solution</h2>\n<p>The simple solution would be to catch all exceptions in each thread, record them in a shared variable (in the main thread).</p>\n<p>Once all threads finished, decide what to do with the exceptions. This means that all other threads continued their processing, which perhaps, is not what you want.</p>\n<h2>Complex solution</h2>\n<p>The more complex solution is have each of your threads check at strategic points of their execution, if an exception was thrown from another thread.</p>\n<p>If a thread throws an exception, it is caught before exiting the thread, the exception object is copied into some container in the main thread (as in the simple solution), and some shared boolean variable is set to true.</p>\n<p>And when another thread tests this boolean, it sees the execution is to be aborted, and aborts in a graceful way.</p>\n<p>When all thread did abort, the main thread can handle the exception as needed.</p>\n"
},
{
"answer_id": 233206,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 2,
"selected": false,
"text": "<p>An exception thrown from a thread will not be catchable in the parent thread. Threads have different contexts and stacks, and generally the parent thread is not required to stay there and wait for the children to finish, so that it could catch their exceptions. There is simply no place in code for that catch:</p>\n\n<pre><code>try\n{\n start thread();\n wait_finish( thread );\n}\ncatch(...)\n{\n // will catch exceptions generated within start and wait, \n // but not from the thread itself\n}\n</code></pre>\n\n<p>You will need to catch exceptions inside each thread and interpret exit status from threads in the main thread to re-throw any exceptions you might need.</p>\n\n<p>BTW, in the absents of a catch in a thread it is implementation specific if stack unwinding will be done at all, i.e. your automatic variables' destructors may not even be called before terminate is called. Some compilers do that, but it's not required.</p>\n"
},
{
"answer_id": 233588,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 6,
"selected": false,
"text": "<p>Currently, the only <strong>portable</strong> way is to write catch clauses for all the types of exceptions that you might like to transfer between threads, store the information somewhere from that catch clause and then use it later to rethrow an exception. This is the approach taken by <a href=\"http://www.boost.org/doc/libs/1_36_0/libs/exception/doc/boost-exception.html\" rel=\"noreferrer\">Boost.Exception</a>.</p>\n\n<p>In C++0x, you will be able to catch an exception with <code>catch(...)</code> and then store it in an instance of <code>std::exception_ptr</code> using <code>std::current_exception()</code>. You can then rethrow it later from the same or a different thread with <code>std::rethrow_exception()</code>.</p>\n\n<p>If you are using Microsoft Visual Studio 2005 or later, then the <a href=\"http://www.stdthread.co.uk\" rel=\"noreferrer\">just::thread C++0x thread library</a> supports <code>std::exception_ptr</code>. (Disclaimer: this is my product).</p>\n"
},
{
"answer_id": 2062829,
"author": "Emil",
"author_id": 250383,
"author_profile": "https://Stackoverflow.com/users/250383",
"pm_score": 1,
"selected": false,
"text": "<p>See <a href=\"http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html\" rel=\"nofollow noreferrer\">http://www.boost.org/doc/libs/release/libs/exception/doc/tutorial_exception_ptr.html</a>. It is also possible to write a wrapper function of whatever function you call to join a child thread, which automatically re-throws (using boost::rethrow_exception) any exception emitted by a child thread.</p>\n"
},
{
"answer_id": 14513824,
"author": "Quuxplusone",
"author_id": 1424877,
"author_profile": "https://Stackoverflow.com/users/1424877",
"pm_score": 4,
"selected": false,
"text": "<p>If you're using C++11, then <code>std::future</code> might do exactly what you're looking for: it can automagically trap exceptions that make it to the top of the worker thread, and pass them through to the parent thread at the point that <code>std::future::get</code> is called. (Behind the scenes, this happens exactly as in @AnthonyWilliams' answer; it's just been implemented for you already.)</p>\n\n<p>The down side is that there's no standard way to \"stop caring about\" a <code>std::future</code>; even its destructor will simply block until the task is done. <strong>[EDIT, 2017: The blocking-destructor behavior is a misfeature <em>only</em> of the pseudo-futures returned from <code>std::async</code>, which you should never use anyway. Normal futures don't block in their destructor. But you still can't \"cancel\" tasks if you're using <code>std::future</code>: the promise-fulfilling task(s) will continue running behind the scenes even if nobody is listening for the answer anymore.]</strong> Here's a toy example that might clarify what I mean:</p>\n\n<pre><code>#include <atomic>\n#include <chrono>\n#include <exception>\n#include <future>\n#include <thread>\n#include <vector>\n#include <stdio.h>\n\nbool is_prime(int n)\n{\n if (n == 1010) {\n puts(\"is_prime(1010) throws an exception\");\n throw std::logic_error(\"1010\");\n }\n /* We actually want this loop to run slowly, for demonstration purposes. */\n std::this_thread::sleep_for(std::chrono::milliseconds(100));\n for (int i=2; i < n; ++i) { if (n % i == 0) return false; }\n return (n >= 2);\n}\n\nint worker()\n{\n static std::atomic<int> hundreds(0);\n const int start = 100 * hundreds++;\n const int end = start + 100;\n int sum = 0;\n for (int i=start; i < end; ++i) {\n if (is_prime(i)) { printf(\"%d is prime\\n\", i); sum += i; }\n }\n return sum;\n}\n\nint spawn_workers(int N)\n{\n std::vector<std::future<int>> waitables;\n for (int i=0; i < N; ++i) {\n std::future<int> f = std::async(std::launch::async, worker);\n waitables.emplace_back(std::move(f));\n }\n\n int sum = 0;\n for (std::future<int> &f : waitables) {\n sum += f.get(); /* may throw an exception */\n }\n return sum;\n /* But watch out! When f.get() throws an exception, we still need\n * to unwind the stack, which means destructing \"waitables\" and each\n * of its elements. The destructor of each std::future will block\n * as if calling this->wait(). So in fact this may not do what you\n * really want. */\n}\n\nint main()\n{\n try {\n int sum = spawn_workers(100);\n printf(\"sum is %d\\n\", sum);\n } catch (std::exception &e) {\n /* This line will be printed after all the prime-number output. */\n printf(\"Caught %s\\n\", e.what());\n }\n}\n</code></pre>\n\n<p>I just tried to write a work-alike example using <code>std::thread</code> and <code>std::exception_ptr</code>, but something's going wrong with <code>std::exception_ptr</code> (using libc++) so I haven't gotten it to actually work yet. :(</p>\n\n<p><strong>[EDIT, 2017:</strong></p>\n\n<pre><code>int main() {\n std::exception_ptr e;\n std::thread t1([&e](){\n try {\n ::operator new(-1);\n } catch (...) {\n e = std::current_exception();\n }\n });\n t1.join();\n try {\n std::rethrow_exception(e);\n } catch (const std::bad_alloc&) {\n puts(\"Success!\");\n }\n}\n</code></pre>\n\n<p><strong>I have no idea what I was doing wrong in 2013, but I'm sure it was my fault.]</strong></p>\n"
},
{
"answer_id": 32428427,
"author": "Gerardo Hernandez",
"author_id": 653991,
"author_profile": "https://Stackoverflow.com/users/653991",
"pm_score": 8,
"selected": true,
"text": "<p>C++11 introduced the <code>exception_ptr</code> type that allows to transport exceptions between threads:</p>\n\n<pre><code>#include<iostream>\n#include<thread>\n#include<exception>\n#include<stdexcept>\n\nstatic std::exception_ptr teptr = nullptr;\n\nvoid f()\n{\n try\n {\n std::this_thread::sleep_for(std::chrono::seconds(1));\n throw std::runtime_error(\"To be passed between threads\");\n }\n catch(...)\n {\n teptr = std::current_exception();\n }\n}\n\nint main(int argc, char **argv)\n{\n std::thread mythread(f);\n mythread.join();\n\n if (teptr) {\n try{\n std::rethrow_exception(teptr);\n }\n catch(const std::exception &ex)\n {\n std::cerr << \"Thread exited with exception: \" << ex.what() << \"\\n\";\n }\n }\n\n return 0;\n}\n</code></pre>\n\n<p>Because in your case you have multiple worker threads, you will need to keep one <code>exception_ptr</code> for each of them.</p>\n\n<p>Note that <code>exception_ptr</code> is a shared ptr-like pointer, so you will need to keep at least one <code>exception_ptr</code> pointing to each exception or they will be released.</p>\n\n<p>Microsoft specific: if you use SEH Exceptions (<code>/EHa</code>), the example code will also transport SEH exceptions like access violations, which may not be what you want.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233127",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] |
We have a function which a single thread calls into (we name this the main thread). Within the body of the function we spawn multiple worker threads to do CPU intensive work, wait for all threads to finish, then return the result on the main thread.
The result is that the caller can use the function naively, and internally it'll make use of multiple cores.
*All good so far..*
The problem we have is dealing with exceptions. We don't want exceptions on the worker threads to crash the application. We want the caller to the function to be able to catch them on the main thread. We must catch exceptions on the worker threads and propagate them across to the main thread to have them continue unwinding from there.
***How can we do this?***
The best I can think of is:
1. Catch a whole variety of exceptions on our worker threads (std::exception and a few of our own ones).
2. Record the type and message of the exception.
3. Have a corresponding switch statement on the main thread which rethrows exceptions of whatever type was recorded on the worker thread.
This has the obvious disadvantage of only supporting a limited set of exception types, and would need modification whenever new exception types were added.
|
C++11 introduced the `exception_ptr` type that allows to transport exceptions between threads:
```
#include<iostream>
#include<thread>
#include<exception>
#include<stdexcept>
static std::exception_ptr teptr = nullptr;
void f()
{
try
{
std::this_thread::sleep_for(std::chrono::seconds(1));
throw std::runtime_error("To be passed between threads");
}
catch(...)
{
teptr = std::current_exception();
}
}
int main(int argc, char **argv)
{
std::thread mythread(f);
mythread.join();
if (teptr) {
try{
std::rethrow_exception(teptr);
}
catch(const std::exception &ex)
{
std::cerr << "Thread exited with exception: " << ex.what() << "\n";
}
}
return 0;
}
```
Because in your case you have multiple worker threads, you will need to keep one `exception_ptr` for each of them.
Note that `exception_ptr` is a shared ptr-like pointer, so you will need to keep at least one `exception_ptr` pointing to each exception or they will be released.
Microsoft specific: if you use SEH Exceptions (`/EHa`), the example code will also transport SEH exceptions like access violations, which may not be what you want.
|
233,141 |
<p>I have a comma separated list of strings like the one below.</p>
<pre><code>a,b ,c ,d, , , , ,e, f,g,h .
</code></pre>
<p>I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be</p>
<pre><code>a,b ,c ,d,NA,NA,NA,NA,e, f,g,h .
</code></pre>
<p>I tried using ",\s+," to search but it skips the alternate empty strings and results in</p>
<pre><code>a,b ,c ,d,NA, ,NA, ,e, f,g,h .
</code></pre>
<p>What's the correct regex to use here ?</p>
|
[
{
"answer_id": 233160,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "<p><code>(?<=,)\\s+(?=,)</code></p>\n\n<p>This is a lookbehind for a comma, then whitespace, then a lookahead for a comma</p>\n"
},
{
"answer_id": 233227,
"author": "MrM",
"author_id": 319803,
"author_profile": "https://Stackoverflow.com/users/319803",
"pm_score": 0,
"selected": false,
"text": "<p>Here you are:</p>\n<p><code>echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +[^a-z|A-Z]/,Na/g'</code></p>\n<p>Or:</p>\n<p><code>echo a,b ,c ,d, , , , ,e, f,g,h . | perl -p -e 's/, +\\S/,Na/g'</code></p>\n<p>if you want to make it work with non <code>a-Z</code> characters also (thanks for the comment :)</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233141",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24424/"
] |
I have a comma separated list of strings like the one below.
```
a,b ,c ,d, , , , ,e, f,g,h .
```
I want to write a regular expression that will replace the empty values i.e., strings that contain only white spaces to 'NA'. So the result should be
```
a,b ,c ,d,NA,NA,NA,NA,e, f,g,h .
```
I tried using ",\s+," to search but it skips the alternate empty strings and results in
```
a,b ,c ,d,NA, ,NA, ,e, f,g,h .
```
What's the correct regex to use here ?
|
`(?<=,)\s+(?=,)`
This is a lookbehind for a comma, then whitespace, then a lookahead for a comma
|
233,148 |
<p>I keep reading that, in C, using pointer arithmetic is generally faster than subscripting for array access. Is this true even with modern (supposedly-optimizing) compilers?</p>
<p>If so, is this still the case as I begin to move away from learning C into Objective-C and <a href="http://en.wikipedia.org/wiki/Cocoa_%28API%29" rel="noreferrer">Cocoa</a> on Macs?</p>
<p>Which is the preferred coding style for array access, in both C and Objective-C? Which is considered (by professionals of their respective languages) more legible, more "correct" (for lack of a better term)?</p>
|
[
{
"answer_id": 233166,
"author": "Mecki",
"author_id": 15809,
"author_profile": "https://Stackoverflow.com/users/15809",
"pm_score": 7,
"selected": true,
"text": "<p>You need to understand the reason behind this claim. Have you ever questioned yourself why it is faster? Let's compare some code:</p>\n<pre><code>int i;\nint a[20];\n\n// Init all values to zero\nmemset(a, 0, sizeof(a));\nfor (i = 0; i < 20; i++) {\n printf("Value of %d is %d\\n", i, a[i]);\n}\n</code></pre>\n<p>They are all zero, what a surprise :-P The question is, what means <code>a[i]</code> actually in low level machine code? It means</p>\n<ol>\n<li><p>Take the address of <code>a</code> in memory.</p>\n</li>\n<li><p>Add <code>i</code> times the size of a single item of <code>a</code> to that address (int usually is four bytes).</p>\n</li>\n<li><p>Fetch the value from that address.</p>\n</li>\n</ol>\n<p>So each time you fetch a value from <code>a</code>, the base address of <code>a</code> is added to the result of the multiplication of <code>i</code> by four. If you just dereference a pointer, step 1. and 2. don't need to be performed, only step 3.</p>\n<p>Consider the code below.</p>\n<pre><code>int i;\nint a[20];\nint * b;\n\nmemset(a, 0, sizeof(a));\nb = a;\nfor (i = 0; i < 20; i++) {\n printf("Value of %d is %d\\n", i, *b);\n b++;\n}\n</code></pre>\n<p>This code <strong>might</strong> be faster... but even if it is, the difference is tiny. Why might it be faster? "*b" is the same as step 3. of above. However, "b++" is not the same as step 1. and step 2. "b++" will increase the pointer by 4.</p>\n<blockquote>\n<p>(<strong>important for newbies</strong>: running <code>++</code>\non a pointer will not increase the\npointer one byte in memory! It will\nincrease the pointer by as many bytes\nin memory as the data it points to is\nin size. It points to an <code>int</code> and the\n<code>int</code> is four bytes on my machine, so b++\nincreases b by four!)</p>\n</blockquote>\n<p>Okay, but why might it be faster? Because adding four to a pointer is faster than multiplying <code>i</code> by four and adding that to a pointer. You have an addition in either case, but in the second one, you have no multiplication (you avoid the CPU time needed for one multiplication). Considering the speed of modern CPUs, even if the array was 1 mio elements, I wonder if you could really benchmark a difference, though.</p>\n<p>That a modern compiler can optimize either one to be equally fast is something you can check by looking at the assembly output it produces. You do so by passing the "-S" option (capital S) to GCC.</p>\n<p>Here's the code of first C code (optimization level <code>-Os</code> has been used, which means optimize for code size and speed, but don't do speed optimizations that will increase code size noticeably, unlike <code>-O2</code> and much unlike <code>-O3</code>):</p>\n<pre><code>_main:\n pushl %ebp\n movl %esp, %ebp\n pushl %edi\n pushl %esi\n pushl %ebx\n subl $108, %esp\n call ___i686.get_pc_thunk.bx\n"L00000000001$pb":\n leal -104(%ebp), %eax\n movl $80, 8(%esp)\n movl $0, 4(%esp)\n movl %eax, (%esp)\n call L_memset$stub\n xorl %esi, %esi\n leal LC0-"L00000000001$pb"(%ebx), %edi\nL2:\n movl -104(%ebp,%esi,4), %eax\n movl %eax, 8(%esp)\n movl %esi, 4(%esp)\n movl %edi, (%esp)\n call L_printf$stub\n addl $1, %esi\n cmpl $20, %esi\n jne L2\n addl $108, %esp\n popl %ebx\n popl %esi\n popl %edi\n popl %ebp\n ret\n</code></pre>\n<p>Same with the second code:</p>\n<pre><code>_main:\n pushl %ebp\n movl %esp, %ebp\n pushl %edi\n pushl %esi\n pushl %ebx\n subl $124, %esp\n call ___i686.get_pc_thunk.bx\n"L00000000001$pb":\n leal -104(%ebp), %eax\n movl %eax, -108(%ebp)\n movl $80, 8(%esp)\n movl $0, 4(%esp)\n movl %eax, (%esp)\n call L_memset$stub\n xorl %esi, %esi\n leal LC0-"L00000000001$pb"(%ebx), %edi\nL2:\n movl -108(%ebp), %edx\n movl (%edx,%esi,4), %eax\n movl %eax, 8(%esp)\n movl %esi, 4(%esp)\n movl %edi, (%esp)\n call L_printf$stub\n addl $1, %esi\n cmpl $20, %esi\n jne L2\n addl $124, %esp\n popl %ebx\n popl %esi\n popl %edi\n popl %ebp\n ret\n</code></pre>\n<p>Well, it's different, that's for sure. The 104 and 108 number difference comes of the variable <code>b</code> (in the first code there was one variable less on stack, now we have one more, changing stack addresses). The real code difference in the <code>for</code> loop is</p>\n<pre><code>movl -104(%ebp,%esi,4), %eax\n</code></pre>\n<p>compared to</p>\n<pre><code>movl -108(%ebp), %edx\nmovl (%edx,%esi,4), %eax\n</code></pre>\n<p>Actually to me it rather looks like the first approach is faster(!), since it issues one CPU machine code to perform all the work (the CPU does it all for us), instead of having two machine codes. On the other hand, the two assembly commands below might have a lower runtime altogether than the one above.</p>\n<p>As a closing word, I'd say depending on your compiler and the CPU capabilities (what commands CPUs offer to access memory in what way), the result might be either way. Either one might be faster/slower. You cannot say for sure unless you limit yourself exactly to one compiler (meaning also one version) and one specific CPU. As CPUs can do more and more in a single assembly command (ages ago, a compiler really had to manually fetch the address, multiply <code>i</code> by four and add both together before fetching the value), statements that used to be an absolute truth ages ago are nowadays more and more questionable. Also who knows how CPUs work internally? Above I compare one assembly instructions to two other ones.</p>\n<p>I can see that the number of instructions is different and the time such an instruction needs can be different as well. Also how much memory these instructions needs in their machine presentation (they need to be transferred from memory to CPU cache after all) is different. However modern CPUs don't execute instructions the way you feed them. They split big instructions (often referred to as CISC) into small sub-instructions (often referred to as RISC), which also allows them to better optimize program flow for speed internally. In fact, the first, single instruction and the two other instructions below might result in the <em>same set of sub-instructions</em>, in which case there is no measurable speed difference whatsoever.</p>\n<p>Regarding Objective-C, it is just C with extensions. So everything that holds true for C will hold true for Objective-C as well in terms of pointers and arrays. If you use Objects on the other hand (for example, an <code>NSArray</code> or <code>NSMutableArray</code>), this is a completely different beast. However in that case you must access these arrays with methods anyway, there is no pointer/array access to choose from.</p>\n"
},
{
"answer_id": 233169,
"author": "Bob Somers",
"author_id": 1384,
"author_profile": "https://Stackoverflow.com/users/1384",
"pm_score": 2,
"selected": false,
"text": "<p>If you're dealing with array-type data, I'd say using subscripts makes the code more readable. On today's machines (especially for something simple like this), readable code is more important.</p>\n\n<p>Now if you're dealing explicitly with a chunk of data you malloc()'d and you want to get a pointer inside that data, say 20 bytes inside a audio file header, then I think address arithmetic more clearly expresses what you're trying to do.</p>\n\n<p><strike>I'm not sure about compiler optimizations in this regard, but even if subscripting is slower it's only slower by maybe a few clock cycles at the most. That's hardly anything when you can gain so much more from the clarity of your train of thought.</strike></p>\n\n<p>EDIT: According to some of these other responses, subscripting is just a syntacitic element and has no effect on performance like I figured. In that case, definitely go with whatever context you're trying to express through access data inside the block pointed to by the pointer.</p>\n"
},
{
"answer_id": 233170,
"author": "moonshadow",
"author_id": 11834,
"author_profile": "https://Stackoverflow.com/users/11834",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>\"using pointer arithmetic is generally\n faster than subscripting for array\n access\"</p>\n</blockquote>\n\n<p>Nah. It's the same operation either way. Subscripting is syntactic sugar for adding (element size * index) to the array's start address.</p>\n\n<p>That said, when iterating over the elements in an array, taking a pointer to the first element and increasing it each time through the loop will usually be slightly faster than calculating the current element's position from the loop variable each time. (Though it is unusual for this to matter much in a real life application. Examine your algorithm first, premature optimisation is the root of all evil, etc etc)</p>\n"
},
{
"answer_id": 233172,
"author": "JtR",
"author_id": 30958,
"author_profile": "https://Stackoverflow.com/users/30958",
"pm_score": 1,
"selected": false,
"text": "<p>It's not true. It's exactly as fast as with subscript operators. In Objective-C, you can use arrays like in C and in object-oriented style where object-oriented style is a lot slower, because it makes some operations in every call due to dynamic nature of calling.</p>\n"
},
{
"answer_id": 233173,
"author": "Zebra North",
"author_id": 17440,
"author_profile": "https://Stackoverflow.com/users/17440",
"pm_score": 0,
"selected": false,
"text": "<p>It's unlikely that there will be any difference in speed.</p>\n\n<p>Using the array operator [] is probably preferred, as in C++ you can use the same syntax with other containers (e.g. vector).</p>\n"
},
{
"answer_id": 233186,
"author": "n-alexander",
"author_id": 23420,
"author_profile": "https://Stackoverflow.com/users/23420",
"pm_score": 1,
"selected": false,
"text": "<pre><code>char p1[ ] = \"12345\";\nchar* p2 = \"12345\";\n\nchar *ch = p1[ 3 ]; /* 4 */\nch = *(p2 + 3); /* 4 */\n</code></pre>\n\n<p>The C standard doesn't say which is faster. On the observable behavior is same and it is up to compiler to implement it in any way it wants. More often than not it won't even read memory at all.</p>\n\n<p>In general, you have no way to say which is \"faster\" unless you specify a compiler, version, architecture, and compile options. Even then, optimization will depend on the surrounding context.</p>\n\n<p>So the general advice is to use whatever gives clearer and simpler code. Using array[ i ] gives some tools ability to try and find index-out-of-bound conditions, so if you are using arrays, it's better to just treat them as such.</p>\n\n<p>If it is critical - look into assembler that you compiler generates. But keep in mind it may change as you change the code that surrounds it.</p>\n"
},
{
"answer_id": 233225,
"author": "TheMarko",
"author_id": 31099,
"author_profile": "https://Stackoverflow.com/users/31099",
"pm_score": 3,
"selected": false,
"text": "<p>This might be a bit off topic (sorry) because it doesn't answer your question regarding execution speed, but you should consider that <em>premature optimization is the root of all evil</em> (Knuth). In my opinion, specially when still (re)learning the language, by all means write it the way it is easiest to read first. \nThen, if your program runs <strong>correct</strong>, consider optimizing speed. \nMost of the time you code will be fast enough anyway.</p>\n"
},
{
"answer_id": 233260,
"author": "TheMarko",
"author_id": 31099,
"author_profile": "https://Stackoverflow.com/users/31099",
"pm_score": 2,
"selected": false,
"text": "<p>Please keep in mind that execution speed is hard to predict even when looking at the machine code with superscalar cpus and the like with</p>\n\n<ul>\n<li>out of order exection</li>\n<li>pipelining</li>\n<li>branch prediction</li>\n<li>hyperthreading</li>\n<li>...</li>\n</ul>\n\n<p>It's not just counting machine instructions and not even only counting clock cylces. \nSeems easier just to measure in cases where really necessary. Even if it's not impossible to calculate the correct cycle count for a given program (we had to do it in university) but it's hardly fun and hard to get right.\nSidenote: Measuring correctly is also hard in multithreaded / mulit-processor environments.</p>\n"
},
{
"answer_id": 233293,
"author": "Mr Fooz",
"author_id": 25050,
"author_profile": "https://Stackoverflow.com/users/25050",
"pm_score": 2,
"selected": false,
"text": "<p>Mecki has a great explanation. From my experience, one of the things that often matters with indexing vs. pointers is what other code sits in the loop. Example:</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n#include <iostream>\n\nusing namespace std;\n\ntypedef int64_t int64;\nstatic int64 nsTime() {\n struct timespec tp;\n clock_gettime(CLOCK_REALTIME, &tp);\n return tp.tv_sec*(int64)1000000000 + tp.tv_nsec;\n}\n\ntypedef int T;\nsize_t const N = 1024*1024*128;\nT data[N];\n\nint main(int, char**) {\n cout << \"starting\\n\";\n\n {\n int64 const a = nsTime();\n int sum = 0;\n for (size_t i=0; i<N; i++) {\n sum += data[i];\n }\n int64 const b = nsTime();\n cout << \"Simple loop (indexed): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n T *d = data;\n for (size_t i=0; i<N; i++) {\n sum += *d++;\n }\n int64 const b = nsTime();\n cout << \"Simple loop (pointer): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n for (size_t i=0; i<N; i++) {\n int a = sum+3;\n int b = 4-sum;\n int c = sum+5;\n sum += data[i] + a - b + c;\n }\n int64 const b = nsTime();\n cout << \"Loop that uses more ALUs (indexed): \" << (b-a)/1e9 << \"\\n\";\n }\n\n {\n int64 const a = nsTime();\n int sum = 0;\n T *d = data;\n for (size_t i=0; i<N; i++) {\n int a = sum+3;\n int b = 4-sum;\n int c = sum+5;\n sum += *d++ + a - b + c;\n }\n int64 const b = nsTime();\n cout << \"Loop that uses more ALUs (pointer): \" << (b-a)/1e9 << \"\\n\";\n }\n}\n</code></pre>\n\n<p>On a fast Core 2-based system (g++ 4.1.2, x64), here's the timing:</p>\n\n<pre>\n Simple loop (indexed): 0.400842\n Simple loop (pointer): 0.380633\n Loop that uses more ALUs (indexed): 0.768398\n Loop that uses more ALUs (pointer): 0.777886\n</pre>\n\n<p>Sometimes indexing is faster, sometimes pointer arithmetic is. It depends on the how the CPU and compiler are able to pipeline the loop execution.</p>\n"
},
{
"answer_id": 233314,
"author": "Malkocoglu",
"author_id": 31152,
"author_profile": "https://Stackoverflow.com/users/31152",
"pm_score": 1,
"selected": false,
"text": "<p>No, using pointer arithmetic is not faster and most probably slower, because an optimizing compiler may use instructions like LEA (Load Effective Address) on Intel processors or similar on other processors for pointer arithmetic which is faster than add or add/mul. It has the advantage of doing several things at once and NOT effecting the flags, and it also takes one cycle to compute. BTW, the below is from the GCC manual. So <code>-Os</code> does not optimize primarily for speed.</p>\n\n<p>I also completely agree with themarko. First try to write clean, readable and reusable code and then think about optimization and use some profiling tools to find the bottleneck. Most of the time the performance problem is I/O related or some bad algorithm or some bug that you have to hunt down. <a href=\"http://en.wikipedia.org/wiki/Donald_Knuth\" rel=\"nofollow noreferrer\">Knuth</a> is the man ;-)</p>\n\n<p>It just occurred to me that what will you do it with a structure array. If you want to do pointer arithmetic, then you definitely should do it for each member of the struct. Does it sound like overkill? Yes, of course it is overkill and also it opens a wide door to obscure bugs.</p>\n\n<blockquote>\n <p><code>-Os</code> Optimize for size. <code>Os</code> enables all O2 optimizations that do not typically increase code size. It also performs further optimizations designed to reduce code size.</p>\n</blockquote>\n"
},
{
"answer_id": 35734643,
"author": "Code Herder",
"author_id": 2400811,
"author_profile": "https://Stackoverflow.com/users/2400811",
"pm_score": 0,
"selected": false,
"text": "<p>I've worked on C++/assembly optimization for several <a href=\"https://en.wikipedia.org/wiki/AAA_(video_game_industry)\" rel=\"nofollow noreferrer\">AAA</a> titles for 10 years and I can say that on the <strong>particular platforms/compiler</strong> I've worked on, <em>pointer arithmetic</em> made a quite measurable difference.</p>\n\n<p>As an example to put things in perspective, I was able to make a really tight loop in our particle generator 40% faster by replacing all array access by pointer arithmetic to the complete disbelief of my coworkers. I'd heard of it from one of my teachers as a good trick back in the day, but I assumed there would be no way it'd make a difference with the compilers/CPU we have today. I was wrong ;)</p>\n\n<p>It must be pointed out that many of the console <a href=\"https://en.wikipedia.org/wiki/ARM_architecture\" rel=\"nofollow noreferrer\">ARM</a> processors don't have all the cute features of modern <a href=\"https://en.wikipedia.org/wiki/Complex_instruction_set_computer\" rel=\"nofollow noreferrer\">CISC</a> CPUs and the compiler were a bit shaky sometimes.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233148",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14048/"
] |
I keep reading that, in C, using pointer arithmetic is generally faster than subscripting for array access. Is this true even with modern (supposedly-optimizing) compilers?
If so, is this still the case as I begin to move away from learning C into Objective-C and [Cocoa](http://en.wikipedia.org/wiki/Cocoa_%28API%29) on Macs?
Which is the preferred coding style for array access, in both C and Objective-C? Which is considered (by professionals of their respective languages) more legible, more "correct" (for lack of a better term)?
|
You need to understand the reason behind this claim. Have you ever questioned yourself why it is faster? Let's compare some code:
```
int i;
int a[20];
// Init all values to zero
memset(a, 0, sizeof(a));
for (i = 0; i < 20; i++) {
printf("Value of %d is %d\n", i, a[i]);
}
```
They are all zero, what a surprise :-P The question is, what means `a[i]` actually in low level machine code? It means
1. Take the address of `a` in memory.
2. Add `i` times the size of a single item of `a` to that address (int usually is four bytes).
3. Fetch the value from that address.
So each time you fetch a value from `a`, the base address of `a` is added to the result of the multiplication of `i` by four. If you just dereference a pointer, step 1. and 2. don't need to be performed, only step 3.
Consider the code below.
```
int i;
int a[20];
int * b;
memset(a, 0, sizeof(a));
b = a;
for (i = 0; i < 20; i++) {
printf("Value of %d is %d\n", i, *b);
b++;
}
```
This code **might** be faster... but even if it is, the difference is tiny. Why might it be faster? "\*b" is the same as step 3. of above. However, "b++" is not the same as step 1. and step 2. "b++" will increase the pointer by 4.
>
> (**important for newbies**: running `++`
> on a pointer will not increase the
> pointer one byte in memory! It will
> increase the pointer by as many bytes
> in memory as the data it points to is
> in size. It points to an `int` and the
> `int` is four bytes on my machine, so b++
> increases b by four!)
>
>
>
Okay, but why might it be faster? Because adding four to a pointer is faster than multiplying `i` by four and adding that to a pointer. You have an addition in either case, but in the second one, you have no multiplication (you avoid the CPU time needed for one multiplication). Considering the speed of modern CPUs, even if the array was 1 mio elements, I wonder if you could really benchmark a difference, though.
That a modern compiler can optimize either one to be equally fast is something you can check by looking at the assembly output it produces. You do so by passing the "-S" option (capital S) to GCC.
Here's the code of first C code (optimization level `-Os` has been used, which means optimize for code size and speed, but don't do speed optimizations that will increase code size noticeably, unlike `-O2` and much unlike `-O3`):
```
_main:
pushl %ebp
movl %esp, %ebp
pushl %edi
pushl %esi
pushl %ebx
subl $108, %esp
call ___i686.get_pc_thunk.bx
"L00000000001$pb":
leal -104(%ebp), %eax
movl $80, 8(%esp)
movl $0, 4(%esp)
movl %eax, (%esp)
call L_memset$stub
xorl %esi, %esi
leal LC0-"L00000000001$pb"(%ebx), %edi
L2:
movl -104(%ebp,%esi,4), %eax
movl %eax, 8(%esp)
movl %esi, 4(%esp)
movl %edi, (%esp)
call L_printf$stub
addl $1, %esi
cmpl $20, %esi
jne L2
addl $108, %esp
popl %ebx
popl %esi
popl %edi
popl %ebp
ret
```
Same with the second code:
```
_main:
pushl %ebp
movl %esp, %ebp
pushl %edi
pushl %esi
pushl %ebx
subl $124, %esp
call ___i686.get_pc_thunk.bx
"L00000000001$pb":
leal -104(%ebp), %eax
movl %eax, -108(%ebp)
movl $80, 8(%esp)
movl $0, 4(%esp)
movl %eax, (%esp)
call L_memset$stub
xorl %esi, %esi
leal LC0-"L00000000001$pb"(%ebx), %edi
L2:
movl -108(%ebp), %edx
movl (%edx,%esi,4), %eax
movl %eax, 8(%esp)
movl %esi, 4(%esp)
movl %edi, (%esp)
call L_printf$stub
addl $1, %esi
cmpl $20, %esi
jne L2
addl $124, %esp
popl %ebx
popl %esi
popl %edi
popl %ebp
ret
```
Well, it's different, that's for sure. The 104 and 108 number difference comes of the variable `b` (in the first code there was one variable less on stack, now we have one more, changing stack addresses). The real code difference in the `for` loop is
```
movl -104(%ebp,%esi,4), %eax
```
compared to
```
movl -108(%ebp), %edx
movl (%edx,%esi,4), %eax
```
Actually to me it rather looks like the first approach is faster(!), since it issues one CPU machine code to perform all the work (the CPU does it all for us), instead of having two machine codes. On the other hand, the two assembly commands below might have a lower runtime altogether than the one above.
As a closing word, I'd say depending on your compiler and the CPU capabilities (what commands CPUs offer to access memory in what way), the result might be either way. Either one might be faster/slower. You cannot say for sure unless you limit yourself exactly to one compiler (meaning also one version) and one specific CPU. As CPUs can do more and more in a single assembly command (ages ago, a compiler really had to manually fetch the address, multiply `i` by four and add both together before fetching the value), statements that used to be an absolute truth ages ago are nowadays more and more questionable. Also who knows how CPUs work internally? Above I compare one assembly instructions to two other ones.
I can see that the number of instructions is different and the time such an instruction needs can be different as well. Also how much memory these instructions needs in their machine presentation (they need to be transferred from memory to CPU cache after all) is different. However modern CPUs don't execute instructions the way you feed them. They split big instructions (often referred to as CISC) into small sub-instructions (often referred to as RISC), which also allows them to better optimize program flow for speed internally. In fact, the first, single instruction and the two other instructions below might result in the *same set of sub-instructions*, in which case there is no measurable speed difference whatsoever.
Regarding Objective-C, it is just C with extensions. So everything that holds true for C will hold true for Objective-C as well in terms of pointers and arrays. If you use Objects on the other hand (for example, an `NSArray` or `NSMutableArray`), this is a completely different beast. However in that case you must access these arrays with methods anyway, there is no pointer/array access to choose from.
|
233,171 |
<p>What is the best way to do GUIs in <a href="http://en.wikipedia.org/wiki/Clojure" rel="noreferrer">Clojure</a>?</p>
<p>Is there an example of some functional <a href="http://en.wikipedia.org/wiki/Swing_%28Java%29" rel="noreferrer">Swing</a> or <a href="http://en.wikipedia.org/wiki/Standard_Widget_Toolkit" rel="noreferrer">SWT</a> wrapper?
Or some integration with <a href="http://en.wikipedia.org/wiki/JavaFX" rel="noreferrer">JavaFX</a> declarative GUI description which could be easily wrapped to <a href="http://en.wikipedia.org/wiki/S-expression" rel="noreferrer">s-expressions</a> using some macrology?</p>
<p>Any tutorials?</p>
|
[
{
"answer_id": 233271,
"author": "dsm",
"author_id": 7780,
"author_profile": "https://Stackoverflow.com/users/7780",
"pm_score": 4,
"selected": false,
"text": "<p>From this <a href=\"http://blog.thinkrelevance.com/2008/8/12/java-next-2-java-interop\" rel=\"noreferrer\">page</a>:</p>\n\n<pre><code>(import '(javax.swing JFrame JButton JOptionPane)) ;'\n(import '(java.awt.event ActionListener)) ;'\n\n(let [frame (JFrame. \"Hello Swing\")\n button (JButton. \"Click Me\")]\n (.addActionListener button\n (proxy [ActionListener] []\n (actionPerformed [evt]\n (JOptionPane/showMessageDialog nil,\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand evt) \" clicked.\")))))\n\n (.. frame getContentPane (add button))\n\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)\n .pack\n (.setVisible true)))\n\nprint(\"code sample\");\n</code></pre>\n\n<p>And, of course, it would be worth looking at the <a href=\"http://clojure.org/java_interop\" rel=\"noreferrer\">interoperability</a> section of clojure's website.</p>\n"
},
{
"answer_id": 236313,
"author": "pupeno",
"author_id": 6068,
"author_profile": "https://Stackoverflow.com/users/6068",
"pm_score": 4,
"selected": false,
"text": "<p>If you want to do GUI programming I'd point to <a href=\"http://en.wikibooks.org/wiki/Clojure_Programming#Simple_GUI_:_Temperature_Converter\" rel=\"noreferrer\">Temperature Converter</a> or <a href=\"http://clojure.googlegroups.com/web/ants.clj\" rel=\"noreferrer\">the ants colony</a>.</p>\n\n<p>Many things in Swing are done by sub-classing, particularly if you are creating custom components. For that there are two essential functions/macros: <a href=\"http://clojure.org/api#toc383\" rel=\"noreferrer\">proxy</a> and <a href=\"http://clojure.org/api#toc234\" rel=\"noreferrer\">gen-class</a>.</p>\n\n<p>Now I understand where you are going with the more Lispy way. I don't think there's anything like that yet. I would strongly advise against trying to build a grandiose GUI-building framework a-la <a href=\"http://www.cliki.net/CLIM\" rel=\"noreferrer\">CLIM</a>, but to do something more Lispy: start writing your Swing application and abstract out your common patterns with macros. When doing that you may end up with a language to write your kind of GUIs, or maybe some very generic stuff that can be shared and grow.</p>\n\n<p>One thing you lose when writing the GUIs in Clojure is the use of tools like Matisse. That can be a strong pointing to write some parts in Java (the GUI) and some parts in Clojure (the logic). Which actually makes sense as in the logic you'll be able to build a language for your kind of logic using macros and I think there's more to gain there than with the GUI. Obviously, it depends on your application.</p>\n"
},
{
"answer_id": 483875,
"author": "Berlin Brown",
"author_id": 10522,
"author_profile": "https://Stackoverflow.com/users/10522",
"pm_score": 1,
"selected": false,
"text": "<p>Clojure and SWT is the best approach for doing GUI(s). Essentially, SWT is a plug and play style approach for developing software.</p>\n"
},
{
"answer_id": 553526,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>I've been developing a Java applet in which everything is written in Clojure except the applet code, which is written in Java. The applet invokes the Clojure code's callbacks of init, paint, etc from java's hooks for those methods that are defined by the applet model. So the code ends up being 99.999 percent Clojure and you don't have to think about the tiny Java piece at all for the most part. </p>\n\n<p>There are some drawbacks to this approach, which I hope to discuss in more detail on the Clojure Google Group. I think the Clojure developers should include a native way of building applications. Presently you can do whatever GUI stuff you like from the REPL, but if you want a deliverable GUI application, it is necessary to write some Java to call the Clojure code. Also, it seems like the architecture of a Java Applet kind of forces you outside of Clojure's more idiomatic best practices, requiring you to use mutable state, etc.</p>\n\n<p>But also, I am not very far along with Clojure yet and it might be the case that it is possible and I just haven't discovered how to do it correctly yet.</p>\n"
},
{
"answer_id": 610548,
"author": "Joe W.",
"author_id": 3459,
"author_profile": "https://Stackoverflow.com/users/3459",
"pm_score": 3,
"selected": false,
"text": "<p>There's been <a href=\"http://groups.google.com/group/clojure/browse_thread/thread/cd88c3d948ff6b4a\" rel=\"noreferrer\">talk on the mailing list</a> about a few Cells (a la <a href=\"http://smuglispweeny.blogspot.com/2008/02/cells-manifesto.html\" rel=\"noreferrer\">Kenny Tilton's Cells</a>) implementations. It's a pretty neat way to do GUI programming.</p>\n"
},
{
"answer_id": 1505404,
"author": "Jeroen Dirks",
"author_id": 7743,
"author_profile": "https://Stackoverflow.com/users/7743",
"pm_score": 2,
"selected": false,
"text": "<p>Here is another very basic swing wrapping example:</p>\n\n<pre><code>; time for some swing\n(import '(javax.swing JFrame JTable JScrollPane))\n(import '(javax.swing.table DefaultTableModel))\n\n(let \n [frame (JFrame. \"Hello Swing\")\n dm (DefaultTableModel.)\n table (JTable. dm)\n scroll (JScrollPane. table)]\n (doto dm\n (.setNumRows 30)\n (.setColumnCount 5))\n (.. frame getContentPane (add scroll))\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE) \n (.pack)\n (.setVisible true)))\n</code></pre>\n"
},
{
"answer_id": 1505842,
"author": "tomjen",
"author_id": 21133,
"author_profile": "https://Stackoverflow.com/users/21133",
"pm_score": 2,
"selected": false,
"text": "<p>I don't think there is an official one, but personally I would take advantage of the fact that I am using one of the most powerful language in the world and just imagine what the perfect gui code would look like:</p>\n\n<pre><code>(form {:title :on-close dispose :x-size 500 :y-size 450}\n [(button {:text \"Close\" :id 5 :on-click #(System/exit 0) :align :bottom})\n (text-field {:text \"\" :on-change #(.println System/out (:value %)) :align :center})\n (combo-box {:text \"Chose background colour\" :on-change background-update-function\n :items valid-colours})])\n</code></pre>\n\n<p>Your idea would differ but this should hopefully the above gives you some idea.</p>\n"
},
{
"answer_id": 1914910,
"author": "Abhijith",
"author_id": 68963,
"author_profile": "https://Stackoverflow.com/users/68963",
"pm_score": 3,
"selected": false,
"text": "<p>There is a wrapper for MigLayout in clojure contrib. You can also take a look at <a href=\"http://gist.github.com/261140\" rel=\"nofollow noreferrer\">this gist</a>. I am basically putting up whatever code I am writing as I am learning swing/miglayout.</p>\n\n<p>dsm's example re-written in a lispy way using contrib.swing-utils</p>\n\n<pre><code>(ns test\n (:import (javax.swing JButton JFrame))\n (:use (clojure.contrib\n [swing-utils :only (add-action-listener)])))\n\n (defn handler\n [event]\n (JOptionPane/showMessageDialog nil,\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand event) \" clicked.\")))\n\n (let [ frame (JFrame. \"Hello Swing\") \n button (JButton. \"Click Me\") ]\n (add-action-listener button handler)\n (doto frame\n (.setDefaultCloseOperation JFrame/EXIT_ON_CLOSE)\n (.add button)\n (.pack)\n (.setVisible true)))\n</code></pre>\n"
},
{
"answer_id": 1964524,
"author": "Anders Rune Jensen",
"author_id": 13995,
"author_profile": "https://Stackoverflow.com/users/13995",
"pm_score": 1,
"selected": false,
"text": "<p>I know that you are hinting for classical desktop solutions, but web fits quite well with clojure. I've written a complete audio application where everything is hooked up so that if you add music to the audio folder it is reflected in the web UI. Just saying that Desktop application isn't the only way :)</p>\n"
},
{
"answer_id": 2171623,
"author": "steglig",
"author_id": 91272,
"author_profile": "https://Stackoverflow.com/users/91272",
"pm_score": 5,
"selected": false,
"text": "<p>Stuart Sierra recently published a series of blog posts on GUI-development with clojure (and swing). Start off here: <a href=\"http://stuartsierra.com/2010/01/02/first-steps-with-clojure-swing\" rel=\"nofollow noreferrer\">http://stuartsierra.com/2010/01/02/first-steps-with-clojure-swing</a></p>\n"
},
{
"answer_id": 5944667,
"author": "Dave Ray",
"author_id": 40310,
"author_profile": "https://Stackoverflow.com/users/40310",
"pm_score": 8,
"selected": true,
"text": "<p>I will humbly suggest <a href=\"https://github.com/daveray/seesaw\">Seesaw</a>. </p>\n\n<p><a href=\"https://gist.github.com/1441520\">Here's a REPL-based tutorial</a> that assumes no Java or Swing knowledge.</p>\n\n<hr>\n\n<p>Seesaw's a lot like what @tomjen suggests. Here's \"Hello, World\":</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(use 'seesaw.core)\n\n(-> (frame :title \"Hello\"\n :content \"Hello, Seesaw\"\n :on-close :exit)\n pack!\n show!)\n</code></pre>\n\n<p>and here's @Abhijith and @dsm's example, translated pretty literally:</p>\n\n<pre class=\"lang-clj prettyprint-override\"><code>(ns seesaw-test.core\n (:use seesaw.core))\n\n(defn handler\n [event]\n (alert event\n (str \"<html>Hello from <b>Clojure</b>. Button \"\n (.getActionCommand event) \" clicked.\")))\n\n(-> (frame :title \"Hello Swing\" :on-close :exit\n :content (button :text \"Click Me\" :listen [:action handler]))\n pack!\n show!)\n</code></pre>\n"
},
{
"answer_id": 16546943,
"author": "Matthew Gilliard",
"author_id": 268619,
"author_profile": "https://Stackoverflow.com/users/268619",
"pm_score": 4,
"selected": false,
"text": "<p>Nobody yet suggested it, so I will: Browser as UI platform. You could write your app in Clojure, including an HTTP server and then develop the UI using anything from HTML to <a href=\"https://github.com/weavejester/hiccup\">hiccup</a>, ClojureScript and any of the billions of JS libaries you need. If you wanted consistent browser behaviour and \"desktop app look'n'feel\" you could <a href=\"http://developer.chrome.com/trunk/apps/about_apps.html\">bundle chrome with your app</a>.</p>\n\n<p>This seems to be how <a href=\"http://www.lighttable.com/\">Light Table</a> is distributed.</p>\n"
},
{
"answer_id": 27296601,
"author": "Efrain Bergillos",
"author_id": 346898,
"author_profile": "https://Stackoverflow.com/users/346898",
"pm_score": 3,
"selected": false,
"text": "<p>I would rather go for clojurefx, it is a bit premature, but it does work and saves you time.</p>\n\n<p>I started my GUI with seesaw and then tried another component in clojurefx.</p>\n\n<p>I have finished both, and I am convinced that I am going to refactor the seesaw one to clojurefx.</p>\n\n<p>After all, JavaFX is the way to go forward.</p>\n\n<p>It feels lighter than seesaw. Or at least, writing it..</p>\n\n<p>Bindings work, listeners work, most of the component work, otherwise, just use one of the macros to create a constructor for that particular case and job done. Or, if you find it difficult, write some methods in Java and ask for help to improve clojurefx.</p>\n\n<p>The guy who wrote clojurefx is busy at the moment, but you can fork the project and do some fixes.</p>\n"
},
{
"answer_id": 27921649,
"author": "Rulle",
"author_id": 1008794,
"author_profile": "https://Stackoverflow.com/users/1008794",
"pm_score": 2,
"selected": false,
"text": "<p>I asked myself the same question of writing a GUI in Clojure with Swing and came up with the library <a href=\"https://github.com/jonasseglare/signe\" rel=\"nofollow noreferrer\">signe</a></p>\n\n<p>It lets you use represent your domain model as a single Clojure data structure wrapped inside an atom.</p>\n\n<p>See the examples <a href=\"https://github.com/jonasseglare/signe/blob/master/src/signe/examples.clj\" rel=\"nofollow noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 32381539,
"author": "T.W.R. Cole",
"author_id": 1536280,
"author_profile": "https://Stackoverflow.com/users/1536280",
"pm_score": 2,
"selected": false,
"text": "<p>My preferred Clojure UI environment uses <a href=\"https://iojs.org/en/\" rel=\"nofollow\">IO.js (Node for ES6)</a> + <a href=\"http://electron.atom.io/\" rel=\"nofollow\">Electron (Container)</a> + <a href=\"https://github.com/levand/quiescent\" rel=\"nofollow\">Quiescent (ReactJS wrapper)</a>.</p>\n"
},
{
"answer_id": 44462960,
"author": "Bill Barnhill",
"author_id": 204343,
"author_profile": "https://Stackoverflow.com/users/204343",
"pm_score": 2,
"selected": false,
"text": "<p>So I didn't see Fn-Fx on this list, from Timothy Baldridge (halgiri). This is a Clojure library providing a functional abstraction over JavaFX. </p>\n\n<p>It can be found on Github at <a href=\"https://github.com/halgari/fn-fx\" rel=\"nofollow noreferrer\">https://github.com/halgari/fn-fx</a>.</p>\n\n<p>To use, make sure you are using a recent version of Java (1.8 90+) and add a dependency to the github repo by adding the following to your project.clj:</p>\n\n<pre><code>:plugins [[lein-git-deps \"0.0.1-SNAPSHOT\"]]\n:git-dependencies [[\"https://github.com/halgari/fn-fx.git\"]]\n</code></pre>\n\n<p>I have tried it, and it works out of the box.</p>\n"
},
{
"answer_id": 67114315,
"author": "Micah Elliott",
"author_id": 326516,
"author_profile": "https://Stackoverflow.com/users/326516",
"pm_score": 1,
"selected": false,
"text": "<p><strong><a href=\"https://openjfx.io/\" rel=\"nofollow noreferrer\">cljfx</a></strong> is described as a</p>\n<blockquote>\n<p>Declarative, functional and extensible wrapper of JavaFX inspired by better parts of react and re-frame</p>\n</blockquote>\n<p>and <a href=\"https://openjfx.io/\" rel=\"nofollow noreferrer\">JavaFx</a> as</p>\n<blockquote>\n<p>... an open source, next generation client application platform for desktop, mobile and embedded systems built on Java. It is a collaborative effort by many individuals and companies with the goal of producing a modern, efficient, and fully featured toolkit for developing rich client applications.</p>\n</blockquote>\n<p>Its creator uses it to build <a href=\"https://vlaaad.github.io/reveal/\" rel=\"nofollow noreferrer\">reveal</a>, and a <a href=\"https://github.com/cljfx/hn\" rel=\"nofollow noreferrer\">hackernews demo</a> that features various capabilities and some bundling for multiple OSs via <a href=\"https://openjdk.java.net/jeps/343\" rel=\"nofollow noreferrer\">jpackage</a>.</p>\n<p>You can get Clojure REPL-driven development with this by leveraging JavaFX to build UIs for desktop, mobile, and web.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233171",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31141/"
] |
What is the best way to do GUIs in [Clojure](http://en.wikipedia.org/wiki/Clojure)?
Is there an example of some functional [Swing](http://en.wikipedia.org/wiki/Swing_%28Java%29) or [SWT](http://en.wikipedia.org/wiki/Standard_Widget_Toolkit) wrapper?
Or some integration with [JavaFX](http://en.wikipedia.org/wiki/JavaFX) declarative GUI description which could be easily wrapped to [s-expressions](http://en.wikipedia.org/wiki/S-expression) using some macrology?
Any tutorials?
|
I will humbly suggest [Seesaw](https://github.com/daveray/seesaw).
[Here's a REPL-based tutorial](https://gist.github.com/1441520) that assumes no Java or Swing knowledge.
---
Seesaw's a lot like what @tomjen suggests. Here's "Hello, World":
```clj
(use 'seesaw.core)
(-> (frame :title "Hello"
:content "Hello, Seesaw"
:on-close :exit)
pack!
show!)
```
and here's @Abhijith and @dsm's example, translated pretty literally:
```clj
(ns seesaw-test.core
(:use seesaw.core))
(defn handler
[event]
(alert event
(str "<html>Hello from <b>Clojure</b>. Button "
(.getActionCommand event) " clicked.")))
(-> (frame :title "Hello Swing" :on-close :exit
:content (button :text "Click Me" :listen [:action handler]))
pack!
show!)
```
|
233,188 |
<p>I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes the div as expected, but firefox seems to make it too wide, such that the scrollbar begins to disappear when the window client width reaches about 800px. I'm using the following methods to set the position and size: </p>
<pre><code>function getWindowWidth() {
var windowWidth = 0;
if (typeof(window.innerWidth) == 'number') {
windowWidth=window.innerWidth;
}
else {
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth=document.documentElement.clientWidth ;
}
else {
if (document.body && document.body.clientWidth) {
windowWidth=document.body.clientWidth;
}
}
}
return windowWidth;
}
function findLPos(obj) {
var curleft = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
}
}
return curleft;
}
var bdydiv;
var coldiv;
document.body.style.overflow="hidden";
window.onload=resizeDivs;
window.onresize=resizeDivs;
function resizeDivs(){
bdydiv=document.getElementById('bdydiv');
coldiv=document.getElementById('coldiv');
var winWdth=getWindowWidth();
var rghtMarg = 0;
var colHdrTbl=document.getElementById('colHdrTbl');
rghtMarg = parseInt((winWdth - 766) / 2) - 8;
rghtMarg = (rghtMarg > 0 ? rghtMarg : 0);
coldiv.style.paddingLeft = rghtMarg + "px";
bdydiv.style.paddingLeft = rghtMarg + "px";
var bdydivLft=findLPos(bdydiv);
if ((winWdth - bdydivLft) >= 1){
bdydiv.style.width = winWdth - bdydivLft;
coldiv.style.width = bdydiv.style.width;
}
syncScroll();
}
function syncScroll(){
if(coldiv.scrollLeft>=0){
coldiv.scrollLeft=bdydiv.scrollLeft;
}
}
</code></pre>
<p>Note that I've cut out other code which sets height, and other non-relevant parts. The full page can be seen <a href="http://site1.funddata.com/mozilladivresize.html" rel="nofollow noreferrer">here</a>. If you go to the link in both IE and firefox, resize width until "800" is displayed in the green box top-right, and resize height until the scrollbar at the right is enabled, you can see the problem. If you then resize the IE width, the scrollbar stays, but if you resize the firefox width wider, the scrollbar begins to disappear. I'm at a loss as to why this is happening....</p>
<p>Note that AFAIK, getWindowWidth() should be cross-browser-compatible, but I'm not so sure about findLPos().... perhaps there's an extra object in Firefox's DOM or something, which is changing the result??</p>
|
[
{
"answer_id": 233195,
"author": "Michael Madsen",
"author_id": 27528,
"author_profile": "https://Stackoverflow.com/users/27528",
"pm_score": 0,
"selected": false,
"text": "<p>As long as you don't include a valid doctype, you can't expect consistent results, due to Quirks Mode. Go add one (HTML 4.01 Transitional is fine), then let us know if it still occurs.</p>\n\n<p>Also see <a href=\"http://en.wikipedia.org/wiki/Quirks_mode\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Quirks_mode</a>.</p>\n"
},
{
"answer_id": 233204,
"author": "Bob Somers",
"author_id": 1384,
"author_profile": "https://Stackoverflow.com/users/1384",
"pm_score": 0,
"selected": false,
"text": "<p>In your getWindowWidth() function, whenever you grab the width of something, instead of this:</p>\n\n<pre><code>windowWidth = document.documentElement.clientWidth;\n</code></pre>\n\n<p>try this</p>\n\n<pre><code>windowWidth = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth);\n</code></pre>\n"
},
{
"answer_id": 233577,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>A detail to help optimize some of your code:</p>\n\n<pre><code>function getPos(elm) {//jumper\n for(var zx=zy=0;elm!=null;zx+=elm.offsetLeft,zy+=elm.offsetTop,elm=elm.offsetParent);\n return {x:zx,y:zy}\n}\n</code></pre>\n\n<p>(jumper is a user who posted this code in Eksperten.dk)</p>\n"
},
{
"answer_id": 233998,
"author": "Graza",
"author_id": 11820,
"author_profile": "https://Stackoverflow.com/users/11820",
"pm_score": 1,
"selected": false,
"text": "<p>Ok, I found the problem. Seems to be that firefox does not include the style.paddingLeft value in its style.width setting, whereas IE does, thus the div was ending up exactly style.paddingLeft too wide. That is, if for example style.paddingLeft is 8, IE's style.width value would be 8 more than FireFox's - and thus the inverse when setting the value, for FireFox I needed to subtract the style.paddingLeft value</p>\n\n<p>Modified code with:</p>\n\n<pre><code> if (__isFireFox){\n bdydiv.style.width = winWdth - bdydivLft - rghtMarg;\n } else {\n bdydiv.style.width = winWdth - bdydivLft;\n }\n</code></pre>\n"
},
{
"answer_id": 234122,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 3,
"selected": true,
"text": "<p>You are dealing with \"<a href=\"http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug\" rel=\"nofollow noreferrer\">one of the best-known software bugs in a popular implementation of Cascading Style Sheets (CSS)</a>\" according to Wikipedia. I recommend the <a href=\"http://www.quirksmode.org/viewport/elementdimensions.html\" rel=\"nofollow noreferrer\">Element dimensions</a> and <a href=\"http://www.quirksmode.org/dom/w3c_cssom.html\" rel=\"nofollow noreferrer\">CSS Object Model View</a> pages on <a href=\"http://www.quirksmode.org/\" rel=\"nofollow noreferrer\">Quirksmode.org</a>.</p>\n\n<p>Also: I think you'll find that Safari and Opera behave like Firefox in most circumstances. A more compatible approach to working around these problems is testing for, and making exceptions for, MSIE instead of the other way around.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11820/"
] |
I have a web page that uses a scrolling div to display table information. When the window is resized (and also on page load), the display is centered and the div's scrollbar positioned to the right of the page by setting its width. For some reason, the behaviour is different under firefox than IE. IE positions/sizes the div as expected, but firefox seems to make it too wide, such that the scrollbar begins to disappear when the window client width reaches about 800px. I'm using the following methods to set the position and size:
```
function getWindowWidth() {
var windowWidth = 0;
if (typeof(window.innerWidth) == 'number') {
windowWidth=window.innerWidth;
}
else {
if (document.documentElement && document.documentElement.clientWidth) {
windowWidth=document.documentElement.clientWidth ;
}
else {
if (document.body && document.body.clientWidth) {
windowWidth=document.body.clientWidth;
}
}
}
return windowWidth;
}
function findLPos(obj) {
var curleft = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft
while (obj = obj.offsetParent) {
curleft += obj.offsetLeft
}
}
return curleft;
}
var bdydiv;
var coldiv;
document.body.style.overflow="hidden";
window.onload=resizeDivs;
window.onresize=resizeDivs;
function resizeDivs(){
bdydiv=document.getElementById('bdydiv');
coldiv=document.getElementById('coldiv');
var winWdth=getWindowWidth();
var rghtMarg = 0;
var colHdrTbl=document.getElementById('colHdrTbl');
rghtMarg = parseInt((winWdth - 766) / 2) - 8;
rghtMarg = (rghtMarg > 0 ? rghtMarg : 0);
coldiv.style.paddingLeft = rghtMarg + "px";
bdydiv.style.paddingLeft = rghtMarg + "px";
var bdydivLft=findLPos(bdydiv);
if ((winWdth - bdydivLft) >= 1){
bdydiv.style.width = winWdth - bdydivLft;
coldiv.style.width = bdydiv.style.width;
}
syncScroll();
}
function syncScroll(){
if(coldiv.scrollLeft>=0){
coldiv.scrollLeft=bdydiv.scrollLeft;
}
}
```
Note that I've cut out other code which sets height, and other non-relevant parts. The full page can be seen [here](http://site1.funddata.com/mozilladivresize.html). If you go to the link in both IE and firefox, resize width until "800" is displayed in the green box top-right, and resize height until the scrollbar at the right is enabled, you can see the problem. If you then resize the IE width, the scrollbar stays, but if you resize the firefox width wider, the scrollbar begins to disappear. I'm at a loss as to why this is happening....
Note that AFAIK, getWindowWidth() should be cross-browser-compatible, but I'm not so sure about findLPos().... perhaps there's an extra object in Firefox's DOM or something, which is changing the result??
|
You are dealing with "[one of the best-known software bugs in a popular implementation of Cascading Style Sheets (CSS)](http://en.wikipedia.org/wiki/Internet_Explorer_box_model_bug)" according to Wikipedia. I recommend the [Element dimensions](http://www.quirksmode.org/viewport/elementdimensions.html) and [CSS Object Model View](http://www.quirksmode.org/dom/w3c_cssom.html) pages on [Quirksmode.org](http://www.quirksmode.org/).
Also: I think you'll find that Safari and Opera behave like Firefox in most circumstances. A more compatible approach to working around these problems is testing for, and making exceptions for, MSIE instead of the other way around.
|
233,192 |
<p><em>What options are there to detect web-crawlers that do not want to be detected?</em></p>
<p>(I know that listing detection techniques will allow the smart stealth-crawler programmer to make a better spider, but I do not think that we will ever be able to block smart stealth-crawlers anyway, only the ones that make mistakes.)</p>
<p>I'm not talking about the nice crawlers such as Googlebot and Yahoo! Slurp.
I consider a bot nice if it:</p>
<ol>
<li>identifies itself as a bot in the user agent string</li>
<li>reads <code>robots.txt</code> (and obeys it)</li>
</ol>
<p>I'm talking about the <em>bad</em> crawlers, hiding behind common user agents, using my bandwidth and never giving me anything in return.</p>
<p>There are some trapdoors that can be constructed <em>updated list (thanks Chris, gs)</em>:</p>
<ol>
<li>Adding a directory only listed (marked as disallow) in the <code>robots.txt</code>,</li>
<li>Adding invisible links (possibly marked as rel="nofollow"?),
<ul>
<li>style="display: none;" on link or parent container</li>
<li>placed underneath another element with higher z-index</li>
</ul>
</li>
<li>detect who doesn't understand CaPiTaLiSaTioN,</li>
<li>detect who tries to post replies but always fail the Captcha.</li>
<li>detect GET requests to POST-only resources</li>
<li>detect interval between requests</li>
<li>detect order of pages requested</li>
<li>detect who (consistently) requests HTTPS resources over HTTP</li>
<li>detect who does not request image file (this in combination with a list of user-agents of known image capable browsers works surprisingly nice)</li>
</ol>
<p>Some traps would be triggered by both 'good' and 'bad' bots.
you could combine those with a whitelist:</p>
<ol>
<li>It trigger a trap</li>
<li>It request <code>robots.txt</code>?</li>
<li>It doest not trigger another trap because it obeyed <code>robots.txt</code></li>
</ol>
<p><em>One other important thing here is:</em>
Please consider blind people using a screen readers: give people a way to contact you, or solve a (non-image) Captcha to continue browsing.</p>
<p><strong>What methods are there to automatically detect the web crawlers trying to mask themselves as normal human visitors.</strong></p>
<p>The question is not: <em>How do I catch every crawler.</em> The question is: <em>How can I maximize the chance of detecting a crawler.</em></p>
<p>Some spiders are really good, and actually parse and understand HTML, xhtml, CSS JavaScript, VBScript etc...
I have no illusions: I won't be able to beat them.</p>
<p>You would however be surprised how stupid some crawlers are. With the best example of stupidity (in my opinion) being: cast all URLs to lower case before requesting them.</p>
<p>And then there is a whole bunch of crawlers that are just 'not good enough' to avoid the various trapdoors.</p>
|
[
{
"answer_id": 233465,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 3,
"selected": false,
"text": "<p>One thing you didn't list, that are used commonly to detect bad crawlers.</p>\n\n<p>Hit speed, good web crawlers will break their hits up so they don't deluge a site with requests. Bad ones will do one of three things:</p>\n\n<ol>\n<li>hit sequential links one after the other</li>\n<li>hit sequential links in some paralell sequence (2 or more at a time.)</li>\n<li>hit sequential links at a fixed interval</li>\n</ol>\n\n<p>Also, some offline browsing programs will slurp up a number of pages, I'm not sure what kind of threshold you'd want to use, to start blocking by IP address.</p>\n\n<p>This method will also catch mirroring programs like fmirror or wget.</p>\n\n<p>If the bot randomizes the time interval, you could check to see if the links are traversed in a sequential or depth-first manner, or you can see if the bot is traversing a huge amount of text (as in words to read) in a too-short period of time. Some sites limit the number of requests per hour, also.</p>\n\n<p>Actually, I heard an idea somewhere, I don't remember where, that if a user gets too much data, in terms of kilobytes, they can be presented with a captcha asking them to prove they aren't a bot. I've never seen that implemented though.</p>\n\nUpdate on Hiding Links\n\n<p>As far as hiding links goes, you can put a div under another, with CSS (placing it first in the draw order) and possibly setting the z-order. A bot could not ignore that, without parsing all your javascript to see if it is a menu. To some extent, links inside invisible DIV elements also can't be ignored without the bot parsing all the javascript.</p>\n\n<p>Taking that idea to completion, uncalled javascript which could potentially show the hidden elements would possilby fool a subset of javascript parsing bots. And, it is not a lot of work to implement.</p>\n"
},
{
"answer_id": 233541,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 3,
"selected": false,
"text": "<p>An easy solution is to create a link and make it invisible</p>\n\n<pre><code><a href=\"iamabot.script\" style=\"display:none;\">Don't click me!</a>\n</code></pre>\n\n<p>Of course you should expect that some people who look at the source code follow that link just to see where it leads. But you could present those users with a captcha...</p>\n\n<p>Valid crawlers would, of course, also follow the link. But you should not implement a rel=nofollow, but look for the sign of a valid crawler. (like the user agent)</p>\n"
},
{
"answer_id": 233898,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 2,
"selected": false,
"text": "<p>It's not actually that easy to keep up with the good user agent strings. Browser versions come and go. Making a statistic about user agent strings by different behaviors can reveal interesting things.</p>\n\n<p>I don't know how far this could be automated, but at least it is one differentiating thing.</p>\n"
},
{
"answer_id": 310343,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"http://www.projecthoneypot.org/\" rel=\"noreferrer\">Project Honeypot</a> - they're setting up bot traps on large scale (and have DNSRBL with their IPs).</p>\n\n<p>Use tricky URLs and HTML:</p>\n\n<pre><code><a href=\"//example.com/\"> = http://example.com/ on http pages.\n<a href=\"page&amp;&#x23;hash\"> = page& + #hash\n</code></pre>\n\n<p>In HTML you can use plenty of tricks with comments, CDATA elements, entities, etc:</p>\n\n<pre><code><a href=\"foo<!--bar-->\"> (comment should not be removed)\n<script>var haha = '<a href=\"bot\">'</script>\n<script>// <!-- </script> <!--><a href=\"bot\"> <!-->\n</code></pre>\n"
},
{
"answer_id": 311628,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 4,
"selected": false,
"text": "<p>A while back, I worked with a smallish hosting company to help them implement a solution to this. The system I developed examined web server logs for excessive activity from any given IP address and issued firewall rules to block offenders. It included whitelists of IP addresses/ranges based on <a href=\"http://www.iplists.com/\" rel=\"noreferrer\">http://www.iplists.com/</a>, which were then updated automatically as needed by checking claimed user-agent strings and, if the client claimed to be a legitimate spider but not on the whitelist, it performed DNS/reverse-DNS lookups to verify that the source IP address corresponds to the claimed owner of the bot. As a failsafe, these actions were reported to the admin by email, along with links to black/whitelist the address in case of an incorrect assessment.</p>\n\n<p>I haven't talked to that client in 6 months or so, but, last I heard, the system was performing quite effectively.</p>\n\n<p>Side point: If you're thinking about doing a similar detection system based on hit-rate-limiting, be sure to use at least one-minute (and preferably at least five-minute) totals. I see a lot of people talking about these kinds of schemes who want to block anyone who tops 5-10 hits in a second, which may generate false positives on image-heavy pages (unless images are excluded from the tally) and <em>will</em> generate false positives when someone like me finds an interesting site that he wants to read all of, so he opens up all the links in tabs to load in the background while he reads the first one.</p>\n"
},
{
"answer_id": 727362,
"author": "Agile Noob",
"author_id": 42987,
"author_profile": "https://Stackoverflow.com/users/42987",
"pm_score": 2,
"selected": false,
"text": "<p>One simple bot detection method I've heard of for forms is the hidden input technique. If you are trying to secure a form put a input in the form with an id that looks completely legit. Then use css in an external file to hide it. Or if you are really paranoid, setup something like jquery to hide the input box on page load. If you do this right I imagine it would be very hard for a bot to figure out. You know those bots have it in there nature to fill out everything on a page especially if you give your hidden input an id of something like id=\"fname\", etc.</p>\n"
},
{
"answer_id": 3121529,
"author": "Brian Armstrong",
"author_id": 76486,
"author_profile": "https://Stackoverflow.com/users/76486",
"pm_score": 2,
"selected": false,
"text": "<p>Untested, but here is a nice list of user-agents you could make a regular expression out of. Could get you most of the way there:</p>\n\n<pre><code>ADSARobot|ah-ha|almaden|aktuelles|Anarchie|amzn_assoc|ASPSeek|ASSORT|ATHENS|Atomz|attach|attache|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|bmclient|Boston\\ Project|BravoBrian\\ SpiderEngine\\ MarcoPolo|Bot\\ mailto:[email protected]|Buddy|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|Collector|Copier|Crescent|Crescent\\ Internet\\ ToolPak|Custo|cyberalert|DA$|Deweb|diagem|Digger|Digimarc|DIIbot|DISCo|DISCo\\ Pump|DISCoFinder|Download\\ Demon|Download\\ Wonder|Downloader|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|ecollector|efp@gmx\\.net|Email\\ Extractor|EirGrabber|email|EmailCollector|EmailSiphon|EmailWolf|Express\\ WebPictures|ExtractorPro|EyeNetIE|FavOrg|fastlwspider|Favorites\\ Sweeper|Fetch|FEZhead|FileHound|FlashGet\\ WebWasher|FlickBot|fluffy|FrontPage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go\\!Zilla|Go!Zilla|Go-Ahead-Got-It|GornKer|gotit|Grabber|GrabNet|Grafula|Green\\ Research|grub-client|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|http\\ generic|HTTrack|httpdown|httrack|ia_archiver|IBM_Planetwide|Image\\ Stripper|Image\\ Sucker|imagefetch|IncyWincy|Indy*Library|Indy\\ Library|informant|Ingelin|InterGET|Internet\\ Ninja|InternetLinkagent|Internet\\ Ninja|InternetSeer\\.com|Iria|Irvine|JBH*agent|JetCar|JOC|JOC\\ Web\\ Spider|JustView|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|libwww|likse|Link|Link*Sleuth|LINKS\\ ARoMATIZED|LinkWalker|LWP|lwp-trivial|Mag-Net|Magnet|Mac\\ Finder|Mag-Net|Mass\\ Downloader|MCspider|Memo|Microsoft.URL|MIDown\\ tool|Mirror|Missigua\\ Locator|Mister\\ PiX|MMMtoCrawl\\/UrlDispatcherLLL|^Mozilla$|Mozilla.*Indy|Mozilla.*NEWT|Mozilla*MSIECrawler|MS\\ FrontPage*|MSFrontPage|MSIECrawler|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|Net\\ Vampire|NetZIP|NetZip\\ Downloader|NetZippy|NEWT|NICErsPRO|Ninja|NPBot|Octopus|Offline\\ Explorer|Offline\\ Navigator|OpaL|Openfind|OpenTextSiteCrawler|OrangeBot|PageGrabber|Papa\\ Foto|PackRat|pavuk|pcBrowser|PersonaPilot|Ping|PingALink|Pockey|Proxy|psbot|PSurf|puf|Pump|PushSite|QRVA|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|Robozilla|Rover|RPT-HTTPClient|Rsync|Scooter|SearchExpress|searchhippo|searchterms\\.it|Second\\ Street\\ Research|Seeker|Shai|Siphon|sitecheck|sitecheck.internetseer.com|SiteSnagger|SlySearch|SmartDownload|snagger|Snake|SpaceBison|Spegla|SpiderBot|sproose|SqWorm|Stripper|Sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|Szukacz|tAkeOut|tarspider|Teleport\\ Pro|Templeton|TrueRobot|TV33_Mercator|UIowaCrawler|UtilMind|URLSpiderPro|URL_Spider_Pro|Vacuum|vagabondo|vayala|visibilitygap|VoidEYE|vspider|Web\\ Downloader|w3mir|Web\\ Data\\ Extractor|Web\\ Image\\ Collector|Web\\ Sucker|Wweb|WebAuto|WebBandit|web\\.by\\.mail|Webclipping|webcollage|webcollector|WebCopier|webcraft@bea|webdevil|webdownloader|Webdup|WebEMailExtrac|WebFetch|WebGo\\ IS|WebHook|Webinator|WebLeacher|WEBMASTERS|WebMiner|WebMirror|webmole|WebReaper|WebSauger|Website|Website\\ eXtractor|Website\\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Wget|Whacker|whizbang|WhosTalking|Widow|WISEbot|WWWOFFLE|x-Tractor|^Xaldon\\ WebSpider|WUMPUS|Xenu|XGET|Zeus.*Webster|Zeus [NC]\n</code></pre>\n\n<p>Taken from:\n<a href=\"http://perishablepress.com/press/2007/10/15/ultimate-htaccess-blacklist-2-compressed-version/\" rel=\"nofollow noreferrer\">http://perishablepress.com/press/2007/10/15/ultimate-htaccess-blacklist-2-compressed-version/</a></p>\n"
},
{
"answer_id": 3121691,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 1,
"selected": false,
"text": "<p>I currently work for a company that scans web sites in order to classify them. We also check sites for malware.</p>\n\n<p>In my experience the number one blockers of our web crawler (which of course uses a IE or Firefox UA and does not obey robots.txt. Duh.) are sites intentionally hosting malware. It's a pain because the site then falls back to a human who has to manually load the site, classify it and check it for malware.</p>\n\n<p>I'm just saying, <a href=\"http://www.darkreading.com/applications/google-report-how-web-attackers-evade-ma/231500264\" rel=\"nofollow noreferrer\">by blocking web crawlers you're putting yourself in some bad company.</a></p>\n\n<p>Of course, if they are horribly rude and suck up tons of your bandwidth it's a different story because then you've got a good reason.</p>\n"
},
{
"answer_id": 4886720,
"author": "Danubian Sailor",
"author_id": 531954,
"author_profile": "https://Stackoverflow.com/users/531954",
"pm_score": 1,
"selected": false,
"text": "<p>You can also check referrals. No referral could raise bot suspition. Bad referral means certainly it is not browser.</p>\n\n<blockquote>\n <p>Adding invisible links (possibly marked as rel=\"nofollow\"?),</p>\n</blockquote>\n\n<pre><code>* style=\"display: none;\" on link or parent container\n* placed underneath another element with higher z-index\n</code></pre>\n\n<p>I would'nt do that. You can end up blacklisted by google for black hat SEO :)</p>\n"
},
{
"answer_id": 52328537,
"author": "Granitosaurus",
"author_id": 3737009,
"author_profile": "https://Stackoverflow.com/users/3737009",
"pm_score": 1,
"selected": false,
"text": "<p>People keep addressing broad crawlers but not crawlers that are specialized for your website.</p>\n\n<p>I write stealth crawlers and if they are individually built no amount of honey pots or hidden links will have any effect whatsoever - the only real way to detect specialised crawlers is by inspecting connection patterns. </p>\n\n<p>The best systems use AI (e.g. Linkedin) use AI to address this.<br>\nThe easiest solution is write log parsers that analyze IP connections and simply blacklist those IPs or serve captcha, at least temporary. </p>\n\n<p>e.g.<br>\nif IP X is seen every 2 seconds connecting to <code>foo.com/cars/*.html</code> but not any other pages - it's most likely a bot or a hungry power user.</p>\n\n<p>Alternatively there are various javascript challenges that act as protection (e.g. Cloudflare's anti-bot system), but those are easily solvable, you can write something custom and that might be enough deterrent to make it not worth the effort for the crawler.</p>\n\n<p>However you must ask a question are you willing to false-positive legit users and introduce inconvenience for them to prevent bot traffic. Protecting public data is an impossible paradox.</p>\n"
},
{
"answer_id": 54911774,
"author": "Alex MAN",
"author_id": 7540270,
"author_profile": "https://Stackoverflow.com/users/7540270",
"pm_score": -1,
"selected": false,
"text": "<p>short answer: if a mid level programmer knows what he's doing you won't be able to detect a crawler without affecting the real user. Having your information publicly you won't be able to defend it against a crawler... it's like the 1st amendment right :)</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233192",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22674/"
] |
*What options are there to detect web-crawlers that do not want to be detected?*
(I know that listing detection techniques will allow the smart stealth-crawler programmer to make a better spider, but I do not think that we will ever be able to block smart stealth-crawlers anyway, only the ones that make mistakes.)
I'm not talking about the nice crawlers such as Googlebot and Yahoo! Slurp.
I consider a bot nice if it:
1. identifies itself as a bot in the user agent string
2. reads `robots.txt` (and obeys it)
I'm talking about the *bad* crawlers, hiding behind common user agents, using my bandwidth and never giving me anything in return.
There are some trapdoors that can be constructed *updated list (thanks Chris, gs)*:
1. Adding a directory only listed (marked as disallow) in the `robots.txt`,
2. Adding invisible links (possibly marked as rel="nofollow"?),
* style="display: none;" on link or parent container
* placed underneath another element with higher z-index
3. detect who doesn't understand CaPiTaLiSaTioN,
4. detect who tries to post replies but always fail the Captcha.
5. detect GET requests to POST-only resources
6. detect interval between requests
7. detect order of pages requested
8. detect who (consistently) requests HTTPS resources over HTTP
9. detect who does not request image file (this in combination with a list of user-agents of known image capable browsers works surprisingly nice)
Some traps would be triggered by both 'good' and 'bad' bots.
you could combine those with a whitelist:
1. It trigger a trap
2. It request `robots.txt`?
3. It doest not trigger another trap because it obeyed `robots.txt`
*One other important thing here is:*
Please consider blind people using a screen readers: give people a way to contact you, or solve a (non-image) Captcha to continue browsing.
**What methods are there to automatically detect the web crawlers trying to mask themselves as normal human visitors.**
The question is not: *How do I catch every crawler.* The question is: *How can I maximize the chance of detecting a crawler.*
Some spiders are really good, and actually parse and understand HTML, xhtml, CSS JavaScript, VBScript etc...
I have no illusions: I won't be able to beat them.
You would however be surprised how stupid some crawlers are. With the best example of stupidity (in my opinion) being: cast all URLs to lower case before requesting them.
And then there is a whole bunch of crawlers that are just 'not good enough' to avoid the various trapdoors.
|
See [Project Honeypot](http://www.projecthoneypot.org/) - they're setting up bot traps on large scale (and have DNSRBL with their IPs).
Use tricky URLs and HTML:
```
<a href="//example.com/"> = http://example.com/ on http pages.
<a href="page&#hash"> = page& + #hash
```
In HTML you can use plenty of tricks with comments, CDATA elements, entities, etc:
```
<a href="foo<!--bar-->"> (comment should not be removed)
<script>var haha = '<a href="bot">'</script>
<script>// <!-- </script> <!--><a href="bot"> <!-->
```
|
233,199 |
<p>I am trying to get data from my server, used RemoteObject to accomplish it.
When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).</p>
<p>On the server side logs there is a mention about cross domain .
77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501</p>
<p>Any one encountered the same problem ? any idea ?</p>
|
[
{
"answer_id": 233465,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 3,
"selected": false,
"text": "<p>One thing you didn't list, that are used commonly to detect bad crawlers.</p>\n\n<p>Hit speed, good web crawlers will break their hits up so they don't deluge a site with requests. Bad ones will do one of three things:</p>\n\n<ol>\n<li>hit sequential links one after the other</li>\n<li>hit sequential links in some paralell sequence (2 or more at a time.)</li>\n<li>hit sequential links at a fixed interval</li>\n</ol>\n\n<p>Also, some offline browsing programs will slurp up a number of pages, I'm not sure what kind of threshold you'd want to use, to start blocking by IP address.</p>\n\n<p>This method will also catch mirroring programs like fmirror or wget.</p>\n\n<p>If the bot randomizes the time interval, you could check to see if the links are traversed in a sequential or depth-first manner, or you can see if the bot is traversing a huge amount of text (as in words to read) in a too-short period of time. Some sites limit the number of requests per hour, also.</p>\n\n<p>Actually, I heard an idea somewhere, I don't remember where, that if a user gets too much data, in terms of kilobytes, they can be presented with a captcha asking them to prove they aren't a bot. I've never seen that implemented though.</p>\n\nUpdate on Hiding Links\n\n<p>As far as hiding links goes, you can put a div under another, with CSS (placing it first in the draw order) and possibly setting the z-order. A bot could not ignore that, without parsing all your javascript to see if it is a menu. To some extent, links inside invisible DIV elements also can't be ignored without the bot parsing all the javascript.</p>\n\n<p>Taking that idea to completion, uncalled javascript which could potentially show the hidden elements would possilby fool a subset of javascript parsing bots. And, it is not a lot of work to implement.</p>\n"
},
{
"answer_id": 233541,
"author": "Georg Schölly",
"author_id": 24587,
"author_profile": "https://Stackoverflow.com/users/24587",
"pm_score": 3,
"selected": false,
"text": "<p>An easy solution is to create a link and make it invisible</p>\n\n<pre><code><a href=\"iamabot.script\" style=\"display:none;\">Don't click me!</a>\n</code></pre>\n\n<p>Of course you should expect that some people who look at the source code follow that link just to see where it leads. But you could present those users with a captcha...</p>\n\n<p>Valid crawlers would, of course, also follow the link. But you should not implement a rel=nofollow, but look for the sign of a valid crawler. (like the user agent)</p>\n"
},
{
"answer_id": 233898,
"author": "iny",
"author_id": 27067,
"author_profile": "https://Stackoverflow.com/users/27067",
"pm_score": 2,
"selected": false,
"text": "<p>It's not actually that easy to keep up with the good user agent strings. Browser versions come and go. Making a statistic about user agent strings by different behaviors can reveal interesting things.</p>\n\n<p>I don't know how far this could be automated, but at least it is one differentiating thing.</p>\n"
},
{
"answer_id": 310343,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 4,
"selected": false,
"text": "<p>See <a href=\"http://www.projecthoneypot.org/\" rel=\"noreferrer\">Project Honeypot</a> - they're setting up bot traps on large scale (and have DNSRBL with their IPs).</p>\n\n<p>Use tricky URLs and HTML:</p>\n\n<pre><code><a href=\"//example.com/\"> = http://example.com/ on http pages.\n<a href=\"page&amp;&#x23;hash\"> = page& + #hash\n</code></pre>\n\n<p>In HTML you can use plenty of tricks with comments, CDATA elements, entities, etc:</p>\n\n<pre><code><a href=\"foo<!--bar-->\"> (comment should not be removed)\n<script>var haha = '<a href=\"bot\">'</script>\n<script>// <!-- </script> <!--><a href=\"bot\"> <!-->\n</code></pre>\n"
},
{
"answer_id": 311628,
"author": "Dave Sherohman",
"author_id": 18914,
"author_profile": "https://Stackoverflow.com/users/18914",
"pm_score": 4,
"selected": false,
"text": "<p>A while back, I worked with a smallish hosting company to help them implement a solution to this. The system I developed examined web server logs for excessive activity from any given IP address and issued firewall rules to block offenders. It included whitelists of IP addresses/ranges based on <a href=\"http://www.iplists.com/\" rel=\"noreferrer\">http://www.iplists.com/</a>, which were then updated automatically as needed by checking claimed user-agent strings and, if the client claimed to be a legitimate spider but not on the whitelist, it performed DNS/reverse-DNS lookups to verify that the source IP address corresponds to the claimed owner of the bot. As a failsafe, these actions were reported to the admin by email, along with links to black/whitelist the address in case of an incorrect assessment.</p>\n\n<p>I haven't talked to that client in 6 months or so, but, last I heard, the system was performing quite effectively.</p>\n\n<p>Side point: If you're thinking about doing a similar detection system based on hit-rate-limiting, be sure to use at least one-minute (and preferably at least five-minute) totals. I see a lot of people talking about these kinds of schemes who want to block anyone who tops 5-10 hits in a second, which may generate false positives on image-heavy pages (unless images are excluded from the tally) and <em>will</em> generate false positives when someone like me finds an interesting site that he wants to read all of, so he opens up all the links in tabs to load in the background while he reads the first one.</p>\n"
},
{
"answer_id": 727362,
"author": "Agile Noob",
"author_id": 42987,
"author_profile": "https://Stackoverflow.com/users/42987",
"pm_score": 2,
"selected": false,
"text": "<p>One simple bot detection method I've heard of for forms is the hidden input technique. If you are trying to secure a form put a input in the form with an id that looks completely legit. Then use css in an external file to hide it. Or if you are really paranoid, setup something like jquery to hide the input box on page load. If you do this right I imagine it would be very hard for a bot to figure out. You know those bots have it in there nature to fill out everything on a page especially if you give your hidden input an id of something like id=\"fname\", etc.</p>\n"
},
{
"answer_id": 3121529,
"author": "Brian Armstrong",
"author_id": 76486,
"author_profile": "https://Stackoverflow.com/users/76486",
"pm_score": 2,
"selected": false,
"text": "<p>Untested, but here is a nice list of user-agents you could make a regular expression out of. Could get you most of the way there:</p>\n\n<pre><code>ADSARobot|ah-ha|almaden|aktuelles|Anarchie|amzn_assoc|ASPSeek|ASSORT|ATHENS|Atomz|attach|attache|autoemailspider|BackWeb|Bandit|BatchFTP|bdfetch|big.brother|BlackWidow|bmclient|Boston\\ Project|BravoBrian\\ SpiderEngine\\ MarcoPolo|Bot\\ mailto:[email protected]|Buddy|Bullseye|bumblebee|capture|CherryPicker|ChinaClaw|CICC|clipping|Collector|Copier|Crescent|Crescent\\ Internet\\ ToolPak|Custo|cyberalert|DA$|Deweb|diagem|Digger|Digimarc|DIIbot|DISCo|DISCo\\ Pump|DISCoFinder|Download\\ Demon|Download\\ Wonder|Downloader|Drip|DSurf15a|DTS.Agent|EasyDL|eCatch|ecollector|efp@gmx\\.net|Email\\ Extractor|EirGrabber|email|EmailCollector|EmailSiphon|EmailWolf|Express\\ WebPictures|ExtractorPro|EyeNetIE|FavOrg|fastlwspider|Favorites\\ Sweeper|Fetch|FEZhead|FileHound|FlashGet\\ WebWasher|FlickBot|fluffy|FrontPage|GalaxyBot|Generic|Getleft|GetRight|GetSmart|GetWeb!|GetWebPage|gigabaz|Girafabot|Go\\!Zilla|Go!Zilla|Go-Ahead-Got-It|GornKer|gotit|Grabber|GrabNet|Grafula|Green\\ Research|grub-client|Harvest|hhjhj@yahoo|hloader|HMView|HomePageSearch|http\\ generic|HTTrack|httpdown|httrack|ia_archiver|IBM_Planetwide|Image\\ Stripper|Image\\ Sucker|imagefetch|IncyWincy|Indy*Library|Indy\\ Library|informant|Ingelin|InterGET|Internet\\ Ninja|InternetLinkagent|Internet\\ Ninja|InternetSeer\\.com|Iria|Irvine|JBH*agent|JetCar|JOC|JOC\\ Web\\ Spider|JustView|KWebGet|Lachesis|larbin|LeechFTP|LexiBot|lftp|libwww|likse|Link|Link*Sleuth|LINKS\\ ARoMATIZED|LinkWalker|LWP|lwp-trivial|Mag-Net|Magnet|Mac\\ Finder|Mag-Net|Mass\\ Downloader|MCspider|Memo|Microsoft.URL|MIDown\\ tool|Mirror|Missigua\\ Locator|Mister\\ PiX|MMMtoCrawl\\/UrlDispatcherLLL|^Mozilla$|Mozilla.*Indy|Mozilla.*NEWT|Mozilla*MSIECrawler|MS\\ FrontPage*|MSFrontPage|MSIECrawler|MSProxy|multithreaddb|nationaldirectory|Navroad|NearSite|NetAnts|NetCarta|NetMechanic|netprospector|NetResearchServer|NetSpider|Net\\ Vampire|NetZIP|NetZip\\ Downloader|NetZippy|NEWT|NICErsPRO|Ninja|NPBot|Octopus|Offline\\ Explorer|Offline\\ Navigator|OpaL|Openfind|OpenTextSiteCrawler|OrangeBot|PageGrabber|Papa\\ Foto|PackRat|pavuk|pcBrowser|PersonaPilot|Ping|PingALink|Pockey|Proxy|psbot|PSurf|puf|Pump|PushSite|QRVA|RealDownload|Reaper|Recorder|ReGet|replacer|RepoMonkey|Robozilla|Rover|RPT-HTTPClient|Rsync|Scooter|SearchExpress|searchhippo|searchterms\\.it|Second\\ Street\\ Research|Seeker|Shai|Siphon|sitecheck|sitecheck.internetseer.com|SiteSnagger|SlySearch|SmartDownload|snagger|Snake|SpaceBison|Spegla|SpiderBot|sproose|SqWorm|Stripper|Sucker|SuperBot|SuperHTTP|Surfbot|SurfWalker|Szukacz|tAkeOut|tarspider|Teleport\\ Pro|Templeton|TrueRobot|TV33_Mercator|UIowaCrawler|UtilMind|URLSpiderPro|URL_Spider_Pro|Vacuum|vagabondo|vayala|visibilitygap|VoidEYE|vspider|Web\\ Downloader|w3mir|Web\\ Data\\ Extractor|Web\\ Image\\ Collector|Web\\ Sucker|Wweb|WebAuto|WebBandit|web\\.by\\.mail|Webclipping|webcollage|webcollector|WebCopier|webcraft@bea|webdevil|webdownloader|Webdup|WebEMailExtrac|WebFetch|WebGo\\ IS|WebHook|Webinator|WebLeacher|WEBMASTERS|WebMiner|WebMirror|webmole|WebReaper|WebSauger|Website|Website\\ eXtractor|Website\\ Quester|WebSnake|Webster|WebStripper|websucker|webvac|webwalk|webweasel|WebWhacker|WebZIP|Wget|Whacker|whizbang|WhosTalking|Widow|WISEbot|WWWOFFLE|x-Tractor|^Xaldon\\ WebSpider|WUMPUS|Xenu|XGET|Zeus.*Webster|Zeus [NC]\n</code></pre>\n\n<p>Taken from:\n<a href=\"http://perishablepress.com/press/2007/10/15/ultimate-htaccess-blacklist-2-compressed-version/\" rel=\"nofollow noreferrer\">http://perishablepress.com/press/2007/10/15/ultimate-htaccess-blacklist-2-compressed-version/</a></p>\n"
},
{
"answer_id": 3121691,
"author": "Zan Lynx",
"author_id": 13422,
"author_profile": "https://Stackoverflow.com/users/13422",
"pm_score": 1,
"selected": false,
"text": "<p>I currently work for a company that scans web sites in order to classify them. We also check sites for malware.</p>\n\n<p>In my experience the number one blockers of our web crawler (which of course uses a IE or Firefox UA and does not obey robots.txt. Duh.) are sites intentionally hosting malware. It's a pain because the site then falls back to a human who has to manually load the site, classify it and check it for malware.</p>\n\n<p>I'm just saying, <a href=\"http://www.darkreading.com/applications/google-report-how-web-attackers-evade-ma/231500264\" rel=\"nofollow noreferrer\">by blocking web crawlers you're putting yourself in some bad company.</a></p>\n\n<p>Of course, if they are horribly rude and suck up tons of your bandwidth it's a different story because then you've got a good reason.</p>\n"
},
{
"answer_id": 4886720,
"author": "Danubian Sailor",
"author_id": 531954,
"author_profile": "https://Stackoverflow.com/users/531954",
"pm_score": 1,
"selected": false,
"text": "<p>You can also check referrals. No referral could raise bot suspition. Bad referral means certainly it is not browser.</p>\n\n<blockquote>\n <p>Adding invisible links (possibly marked as rel=\"nofollow\"?),</p>\n</blockquote>\n\n<pre><code>* style=\"display: none;\" on link or parent container\n* placed underneath another element with higher z-index\n</code></pre>\n\n<p>I would'nt do that. You can end up blacklisted by google for black hat SEO :)</p>\n"
},
{
"answer_id": 52328537,
"author": "Granitosaurus",
"author_id": 3737009,
"author_profile": "https://Stackoverflow.com/users/3737009",
"pm_score": 1,
"selected": false,
"text": "<p>People keep addressing broad crawlers but not crawlers that are specialized for your website.</p>\n\n<p>I write stealth crawlers and if they are individually built no amount of honey pots or hidden links will have any effect whatsoever - the only real way to detect specialised crawlers is by inspecting connection patterns. </p>\n\n<p>The best systems use AI (e.g. Linkedin) use AI to address this.<br>\nThe easiest solution is write log parsers that analyze IP connections and simply blacklist those IPs or serve captcha, at least temporary. </p>\n\n<p>e.g.<br>\nif IP X is seen every 2 seconds connecting to <code>foo.com/cars/*.html</code> but not any other pages - it's most likely a bot or a hungry power user.</p>\n\n<p>Alternatively there are various javascript challenges that act as protection (e.g. Cloudflare's anti-bot system), but those are easily solvable, you can write something custom and that might be enough deterrent to make it not worth the effort for the crawler.</p>\n\n<p>However you must ask a question are you willing to false-positive legit users and introduce inconvenience for them to prevent bot traffic. Protecting public data is an impossible paradox.</p>\n"
},
{
"answer_id": 54911774,
"author": "Alex MAN",
"author_id": 7540270,
"author_profile": "https://Stackoverflow.com/users/7540270",
"pm_score": -1,
"selected": false,
"text": "<p>short answer: if a mid level programmer knows what he's doing you won't be able to detect a crawler without affecting the real user. Having your information publicly you won't be able to defend it against a crawler... it's like the 1st amendment right :)</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233199",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20955/"
] |
I am trying to get data from my server, used RemoteObject to accomplish it.
When I run the application on my localhost it works great but when iam using it on my server i get a Channel.Security.Error(Security Error accessing URL).
On the server side logs there is a mention about cross domain .
77.127.194.4 - - [23/Oct/2008 21:15:11] "GET /crossdomain.xml HTTP/1.1" 501
Any one encountered the same problem ? any idea ?
|
See [Project Honeypot](http://www.projecthoneypot.org/) - they're setting up bot traps on large scale (and have DNSRBL with their IPs).
Use tricky URLs and HTML:
```
<a href="//example.com/"> = http://example.com/ on http pages.
<a href="page&#hash"> = page& + #hash
```
In HTML you can use plenty of tricks with comments, CDATA elements, entities, etc:
```
<a href="foo<!--bar-->"> (comment should not be removed)
<script>var haha = '<a href="bot">'</script>
<script>// <!-- </script> <!--><a href="bot"> <!-->
```
|
233,216 |
<p>I have an abstract generic class <code>BLL<T> where T : BusinessObject</code>. I need to open an assembly that contains a set of concrete BLL classes, and return the tuples (businessObjectType, concreteBLLType) inside a Dictionary. There is the part of the method I could do until now, but I'm having problems to discover T.</p>
<pre><code>protected override Dictionary<Type, Type> DefineBLLs()
{
string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];
Type[] types = LoadAssembly(bllsAssembly);
Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();
foreach (Type type in types)
{
if (type.IsSubclassOf(typeof(BLL<>)))
/* how to know T in the situation below? */
bllsTypes.Add(??businessObjectType (T)??, type);
}
return bllsTypes;
}
</code></pre>
|
[
{
"answer_id": 233236,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": true,
"text": "<p>So the concrete classes will be closed rather than generic? Here's a short program which demonstrates what I <em>think</em> you're after...</p>\n\n<pre><code>using System;\nusing System.Reflection;\n\npublic abstract class Base<T>\n{\n}\n\npublic class Concrete : Base<string>\n{\n}\n\nclass Test\n{\n static void Main()\n {\n Type type = typeof(Concrete);\n Type baseType = type.BaseType;\n Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg\n Console.WriteLine(typeOfT.Name); // Prints String\n }\n}\n</code></pre>\n\n<p>Note that here I'm <em>assuming</em> that we only need to go up one level to get to the appropriate base type, and that the concrete class <em>will</em> be closed. You'd want to put more checks into your real code, of course, but I suspect it was the call to <a href=\"http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx\" rel=\"nofollow noreferrer\">GetGenericArguments</a> that you were missing.</p>\n"
},
{
"answer_id": 233267,
"author": "Victor Rodrigues",
"author_id": 21668,
"author_profile": "https://Stackoverflow.com/users/21668",
"pm_score": 0,
"selected": false,
"text": "<p>Jon, that is exactly what I was looking for. I use the basics of reflection and generics, so when it is needed a more profound knowledge of the API to confront both, I miss things like this one, thanks for answering.</p>\n\n<p>Your assumptions are right, the concrete classes are closed, and T is defined on the base class (BLL).</p>\n\n<p>The code became into this:</p>\n\n<pre><code>protected override Dictionary<Type, Type> DefineBLLs()\n{\n string bllsAssembly = ConfigurationManager.AppSettings[\"BLLsAssembly\"];\n\n Type[] types = LoadAssembly(bllsAssembly);\n\n Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();\n\n foreach (Type bllType in types)\n {\n if (bllType.IsSubclassOf(typeof(BLL<>)))\n {\n Type baseType = bllType.BaseType;\n Type businessObjectType = baseType.GetGenericArguments()[0];\n bllsTypes.Add(businessObjectType, bllType);\n }\n }\n\n return bllsTypes;\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233216",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
I have an abstract generic class `BLL<T> where T : BusinessObject`. I need to open an assembly that contains a set of concrete BLL classes, and return the tuples (businessObjectType, concreteBLLType) inside a Dictionary. There is the part of the method I could do until now, but I'm having problems to discover T.
```
protected override Dictionary<Type, Type> DefineBLLs()
{
string bllsAssembly = ConfigurationManager.AppSettings["BLLsAssembly"];
Type[] types = LoadAssembly(bllsAssembly);
Dictionary<Type, Type> bllsTypes = new Dictionary<Type, Type>();
foreach (Type type in types)
{
if (type.IsSubclassOf(typeof(BLL<>)))
/* how to know T in the situation below? */
bllsTypes.Add(??businessObjectType (T)??, type);
}
return bllsTypes;
}
```
|
So the concrete classes will be closed rather than generic? Here's a short program which demonstrates what I *think* you're after...
```
using System;
using System.Reflection;
public abstract class Base<T>
{
}
public class Concrete : Base<string>
{
}
class Test
{
static void Main()
{
Type type = typeof(Concrete);
Type baseType = type.BaseType;
Type typeOfT = baseType.GetGenericArguments()[0]; // Only one arg
Console.WriteLine(typeOfT.Name); // Prints String
}
}
```
Note that here I'm *assuming* that we only need to go up one level to get to the appropriate base type, and that the concrete class *will* be closed. You'd want to put more checks into your real code, of course, but I suspect it was the call to [GetGenericArguments](http://msdn.microsoft.com/en-us/library/system.type.getgenericarguments.aspx) that you were missing.
|
233,217 |
<p>I'm writing a C Shell program that will be doing <code>su</code> or <code>sudo</code> or <code>ssh</code>. They all want their passwords in console input (the TTY) rather than stdin or the command line.</p>
<p>Does anybody know a solution?</p>
<p>Setting up password-less <code>sudo</code> is not an option.</p>
<p><a href="/questions/tagged/expect" class="post-tag" title="show questions tagged 'expect'" rel="tag">expect</a> could be an option, but it's not present on my stripped-down system.</p>
|
[
{
"answer_id": 233224,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": 3,
"selected": false,
"text": "<p>Take a look at <code>expect</code> linux utility.</p>\n\n<p>It allows you to send output to stdio based on simple pattern matching on stdin.</p>\n"
},
{
"answer_id": 233234,
"author": "diciu",
"author_id": 2811,
"author_profile": "https://Stackoverflow.com/users/2811",
"pm_score": 4,
"selected": false,
"text": "<p>The usual solution to this problem is setuiding a helper app that performs the task requiring superuser access:\n<a href=\"http://en.wikipedia.org/wiki/Setuid\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Setuid</a></p>\n\n<p>Sudo is not meant to be used offline.</p>\n\n<p>Later edit: SSH can be used with private-public key authentication. If the private key does not have a passphrase, ssh can be used without prompting for a password.</p>\n"
},
{
"answer_id": 233235,
"author": "Marko",
"author_id": 31141,
"author_profile": "https://Stackoverflow.com/users/31141",
"pm_score": -1,
"selected": false,
"text": "<p>You can provide password as parameter to expect script.</p>\n"
},
{
"answer_id": 240402,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>Set SSH up for Public Key Authentication, with no pasphrase on the Key. Loads of guides on the net. You won't need a password to login then. You can then limit connections for a key based on client hostname. Provides reasonable security and is great for automated logins.</p>\n"
},
{
"answer_id": 351916,
"author": "mlambie",
"author_id": 17453,
"author_profile": "https://Stackoverflow.com/users/17453",
"pm_score": 5,
"selected": false,
"text": "<p>I wrote some Applescript which prompts for a password via a dialog box and then builds a custom bash command, like this:</p>\n\n<pre><code>echo <password> | sudo -S <command>\n</code></pre>\n\n<p>I'm not sure if this helps.</p>\n\n<p>It'd be nice if sudo accepted a pre-encrypted password, so I could encrypt it within my script and not worry about echoing clear text passwords around. However this works for me and my situation.</p>\n"
},
{
"answer_id": 1607458,
"author": "Shankar",
"author_id": 194613,
"author_profile": "https://Stackoverflow.com/users/194613",
"pm_score": -1,
"selected": false,
"text": "<pre><code>su -c \"Command\" < \"Password\"\n</code></pre>\n\n<p><em>Hope it is helpful.</em></p>\n"
},
{
"answer_id": 3959957,
"author": "DevOz",
"author_id": 479370,
"author_profile": "https://Stackoverflow.com/users/479370",
"pm_score": 1,
"selected": false,
"text": "<pre><code>echo <password> | su -c <command> <user> \n</code></pre>\n\n<p>This is working.</p>\n"
},
{
"answer_id": 4327123,
"author": "Jesse Webb",
"author_id": 346561,
"author_profile": "https://Stackoverflow.com/users/346561",
"pm_score": 9,
"selected": true,
"text": "<p>For sudo there is a -S option for accepting the password from standard input. Here is the man entry:</p>\n\n<pre><code> -S The -S (stdin) option causes sudo to read the password from\n the standard input instead of the terminal device.\n</code></pre>\n\n<p>This will allow you to run a command like:</p>\n\n<pre><code>echo myPassword | sudo -S ls /tmp\n</code></pre>\n\n<p>As for ssh, I have made many attempts to automate/script it's usage with no success. There doesn't seem to be any build-in way to pass the password into the command without prompting. As others have mentioned, the \"<a href=\"http://en.wikipedia.org/wiki/Expect\" rel=\"noreferrer\">expect</a>\" utility seems like it is aimed at addressing this dilemma but ultimately, setting up the correct private-key authorization is the correct way to go when attempting to automate this.</p>\n"
},
{
"answer_id": 4627834,
"author": "David Dawson",
"author_id": 490129,
"author_profile": "https://Stackoverflow.com/users/490129",
"pm_score": 4,
"selected": false,
"text": "<p>I've got:</p>\n\n<pre><code>ssh user@host bash -c \"echo mypass | sudo -S mycommand\"\n</code></pre>\n\n<p>Works for me.</p>\n"
},
{
"answer_id": 7437667,
"author": "Martin Dorey",
"author_id": 18096,
"author_profile": "https://Stackoverflow.com/users/18096",
"pm_score": 3,
"selected": false,
"text": "<p>When there's no better choice (as suggested by others), then man socat can help:</p>\n\n<pre><code> (sleep 5; echo PASSWORD; sleep 5; echo ls; sleep 1) |\n socat - EXEC:'ssh -l user server',pty,setsid,ctty\n\n EXEC’utes an ssh session to server. Uses a pty for communication\n between socat and ssh, makes it ssh’s controlling tty (ctty),\n and makes this pty the owner of a new process group (setsid), so\n ssh accepts the password from socat.\n</code></pre>\n\n<p>All of the pty,setsid,ctty complexity is necessary and, while you might not need to sleep as long, you will need to sleep. The echo=0 option is worth a look too, as is passing the remote command on ssh's command line.</p>\n"
},
{
"answer_id": 8850586,
"author": "Edward",
"author_id": 1147674,
"author_profile": "https://Stackoverflow.com/users/1147674",
"pm_score": 5,
"selected": false,
"text": "<p>For <code>ssh</code> you can use <code>sshpass</code>: <code>sshpass -p yourpassphrase ssh user@host</code>.</p>\n\n<p>You just need to download sshpass first :)</p>\n\n<pre><code>$ apt-get install sshpass\n$ sshpass -p 'password' ssh username@server\n</code></pre>\n"
},
{
"answer_id": 10492509,
"author": "adhown",
"author_id": 1369159,
"author_profile": "https://Stackoverflow.com/users/1369159",
"pm_score": 4,
"selected": false,
"text": "<p>Maybe you can use an <code>expect</code> command?:</p>\n\n<pre><code>expect -c 'spawn ssh [email protected];expect password;send \"your-password\\n\";interact\n</code></pre>\n\n<p>That command gives the password automatically.</p>\n"
},
{
"answer_id": 11722033,
"author": "Byob ",
"author_id": 1555487,
"author_profile": "https://Stackoverflow.com/users/1555487",
"pm_score": 3,
"selected": false,
"text": "<p>This can be done by setting up public/private keys on the target hosts you will be connecting to.\nThe first step would be to generate an ssh key for the user running the script on the local host, by executing:</p>\n\n<pre><code>ssh-keygen\nEnter file in which to save the key (/home/myuser/.ssh/id_rsa): <Hit enter for default>\nOverwrite (y/n)? y\n</code></pre>\n\n<p>Then enter a blank password. After that, copy your ssh key onto the target host which you will be connecting to.</p>\n\n<pre><code>ssh-copy-id <remote_user>@<other_host>\nremote_user@other_host's password: <Enter remote user's password here>\n</code></pre>\n\n<p>After registering the ssh keys, you would be able to perform a silent <code>ssh remote_user@other_host</code> from you local host.</p>\n"
},
{
"answer_id": 15015379,
"author": "Avi",
"author_id": 2097715,
"author_profile": "https://Stackoverflow.com/users/2097715",
"pm_score": -1,
"selected": false,
"text": "<p>One way would be to use read -s option .. this way the password characters are not echoed back to the screen. I wrote a small script for some use cases and you can see it in my blog:\n<a href=\"http://www.datauniv.com/blogs/2013/02/21/a-quick-little-expect-script/\" rel=\"nofollow\">http://www.datauniv.com/blogs/2013/02/21/a-quick-little-expect-script/</a></p>\n"
},
{
"answer_id": 15586177,
"author": "titus",
"author_id": 2202105,
"author_profile": "https://Stackoverflow.com/users/2202105",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem. dialog script to create directory on remote pc.\ndialog with ssh is easy. I use sshpass (previously installed).</p>\n\n<pre><code> dialog --inputbox \"Enter IP\" 8 78 2> /tmp/ip\n\n IP=$(cat /tmp/ip)\n\n\n dialog --inputbox \"Please enter username\" 8 78 2> /tmp/user\n\n US=$(cat /tmp/user)\n\n\n dialog --passwordbox \"enter password for \\\"$US\\\" 8 78 2> /tmp/pass\n\n PASSWORD = $(cat /tmp/pass)\n\n\n sshpass -p \"$PASSWORD\" ssh $US@$IP mkdir -p /home/$US/TARGET-FOLDER\n\n\n rm /tmp/ip\n\n rm /tmp/user\n\n rm /tmp/pass\n</code></pre>\n\n<p>greetings from germany</p>\n\n<p>titus</p>\n"
},
{
"answer_id": 30734581,
"author": "Jahid",
"author_id": 3744681,
"author_profile": "https://Stackoverflow.com/users/3744681",
"pm_score": 4,
"selected": false,
"text": "<p>For sudo you can do this too:</p>\n\n<pre><code>sudo -S <<< \"password\" command\n</code></pre>\n"
},
{
"answer_id": 42299931,
"author": "Ed Bishop",
"author_id": 184383,
"author_profile": "https://Stackoverflow.com/users/184383",
"pm_score": 2,
"selected": false,
"text": "<pre><code>ssh -t -t [email protected] << EOF\necho SOMEPASSWORD | sudo -S do something\nsudo do something else\nexit\nEOF\n</code></pre>\n"
},
{
"answer_id": 42970257,
"author": "Sarat Chandra",
"author_id": 7121889,
"author_profile": "https://Stackoverflow.com/users/7121889",
"pm_score": -1,
"selected": false,
"text": "<p>USE:</p>\n\n<pre><code>echo password | sudo command\n</code></pre>\n\n<p>Example: </p>\n\n<pre><code>echo password | sudo apt-get update; whoami\n</code></pre>\n\n<p>Hope It Helps..</p>\n"
},
{
"answer_id": 47105629,
"author": "JS.",
"author_id": 310399,
"author_profile": "https://Stackoverflow.com/users/310399",
"pm_score": 0,
"selected": false,
"text": "<p>Building on @Jahid's answer, this worked for me on macOS 10.13:</p>\n\n<pre><code>ssh <remote_username>@<remote_server> sudo -S <<< <remote_password> cat /etc/sudoers\n</code></pre>\n"
},
{
"answer_id": 59699659,
"author": "Badr Elmers",
"author_id": 3020379,
"author_profile": "https://Stackoverflow.com/users/3020379",
"pm_score": 1,
"selected": false,
"text": "<p>a better <code>sshpass</code> alternative is: <code>passh</code>\n<a href=\"https://github.com/clarkwang/passh\" rel=\"nofollow noreferrer\">https://github.com/clarkwang/passh</a></p>\n<p>Login to a remote server</p>\n<pre><code> $ passh -p password ssh user@host\n</code></pre>\n<p>Run a command on remote server</p>\n<pre><code> $ passh -p password ssh user@host date\n</code></pre>\n<p>other methods to pass the password</p>\n<blockquote>\n<p>-p The password (Default: `password')</p>\n<p>-p env: Read password from env var</p>\n<p>-p file: Read password from file</p>\n</blockquote>\n<p><a href=\"https://serverfault.com/a/998599/364860\">here</a> I explained why it is better than sshpass, and other solutions.</p>\n"
},
{
"answer_id": 68749025,
"author": "nivalderramas",
"author_id": 10605742,
"author_profile": "https://Stackoverflow.com/users/10605742",
"pm_score": 1,
"selected": false,
"text": "<p>You can also pass various parameters as follows:</p>\n<p><code>echo password | echo y | sudo -S pacman -Syu</code></p>\n<p>(Although that's a bad idea, it's just an example)</p>\n"
},
{
"answer_id": 70407908,
"author": "Affes Salem",
"author_id": 13541620,
"author_profile": "https://Stackoverflow.com/users/13541620",
"pm_score": 0,
"selected": false,
"text": "<p>I once had a use case where I needed to run Sudo and ssh in the same command without <code>stdin</code> specifying all the variables needed.</p>\n<p>This is the command I used</p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo sudopassword | sudo -S -u username sshpass -p extsshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@ipaddress " CMD on external machine"\n</code></pre>\n<p>Breaking that command into pieces!</p>\n<p>This will allow you to run commands through your machine using Superuser:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>echo password | sudo -S -u username\n</code></pre>\n<p>This will allow you to pass ssh password and execute commands on external machines:</p>\n<pre class=\"lang-sh prettyprint-override\"><code>sshpass -p sshpassword ssh -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no username@ipaddress " CMD on external machine"\n</code></pre>\n<blockquote>\n<blockquote>\n<p>make sure you install the sudo and openssh packages on your machine.</p>\n</blockquote>\n</blockquote>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23420/"
] |
I'm writing a C Shell program that will be doing `su` or `sudo` or `ssh`. They all want their passwords in console input (the TTY) rather than stdin or the command line.
Does anybody know a solution?
Setting up password-less `sudo` is not an option.
[expect](/questions/tagged/expect "show questions tagged 'expect'") could be an option, but it's not present on my stripped-down system.
|
For sudo there is a -S option for accepting the password from standard input. Here is the man entry:
```
-S The -S (stdin) option causes sudo to read the password from
the standard input instead of the terminal device.
```
This will allow you to run a command like:
```
echo myPassword | sudo -S ls /tmp
```
As for ssh, I have made many attempts to automate/script it's usage with no success. There doesn't seem to be any build-in way to pass the password into the command without prompting. As others have mentioned, the "[expect](http://en.wikipedia.org/wiki/Expect)" utility seems like it is aimed at addressing this dilemma but ultimately, setting up the correct private-key authorization is the correct way to go when attempting to automate this.
|
233,222 |
<p>I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has <code>class="selected"</code>. When a different product image is clicks then <code>class="selected"</code> moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.</p>
<p>I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.</p>
|
[
{
"answer_id": 233252,
"author": "Jeff Fritz",
"author_id": 29156,
"author_profile": "https://Stackoverflow.com/users/29156",
"pm_score": 2,
"selected": false,
"text": "<p>Consider the following code:</p>\n\n<pre><code><img id=\"img1\" src=\"1.jpg\" desc=\"d1\" class=\"selected prodImg\" />\n<img id=\"img2\" src=\"2.jpg\" desc=\"d2\" class=\"prodImg\" />\n<img id=\"img3\" src=\"3.jpg\" desc=\"d3\" class=\"prodImg\"/>\n\n<div id=\"d1\">description 1</div>\n<div id=\"d2\" class=\"hidden\">description 2</div>\n<div id=\"d3\" class=\"hidden\">description 3</div>\n\n<script>\n\n $(\".prodImg\").click(function() {\n\n if ($(this).hasClass(\"selected\")) return;\n\n $(\"#\" + $(\".selected\").attr(\"desc\")).addClass(\"hidden\");\n $(\".selected\").removeClass(\"selected\");\n\n $(\"#\" + $(this).attr(\"desc\")).removeClass(\"hidden\");\n $(this).addClass(\"selected\");\n\n });\n\n</script>\n</code></pre>\n\n<p>This should get you pretty close. You need to define the relationship between your images and divs... so I added a 'desc' attribute to the images. The extra 'prodImg' class on the images allows you to ensure that only those images are being wired up for this type of swap in and out behavior.</p>\n"
},
{
"answer_id": 233273,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 1,
"selected": false,
"text": "<p>The Acordian widget has some similar functionality. If you place the images in the headers you would get the effect you want.</p>\n\n<p>Look at <a href=\"http://docs.jquery.com/UI/Accordion\" rel=\"nofollow noreferrer\">http://docs.jquery.com/UI/Accordion</a> for more information.</p>\n"
},
{
"answer_id": 1253712,
"author": "gacon",
"author_id": 86053,
"author_profile": "https://Stackoverflow.com/users/86053",
"pm_score": 0,
"selected": false,
"text": "<pre><code><script>\n\n $(\".prodImg\").click(function() {\n\n if ($(this).hasClass(\"selected\")) return;\n\n\n $('.prodImg').removeClass('selected');\n\n $(this).addClass('selected');\n\n var name = $(this).attr('desc');\n\n $('.'+name).removeClass();\n $('.'+name).addClass(''); \n\n });\n\n</script>\n</code></pre>\n\n<p>I hope this can help you!</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233222",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
I have 3 divs where only one is visible by default, they each contain information about a product. Below this divs is a list of 3 images which are images of the products. By default of course the 1st list item is selected and has `class="selected"`. When a different product image is clicks then `class="selected"` moves to that list item and the div above it changes to hidden and the div containing the other product information needs to appear.
I have searched all over the place for a plugin which can do what I want, they are all limited in some way which stops me doing from doing it.
|
Consider the following code:
```
<img id="img1" src="1.jpg" desc="d1" class="selected prodImg" />
<img id="img2" src="2.jpg" desc="d2" class="prodImg" />
<img id="img3" src="3.jpg" desc="d3" class="prodImg"/>
<div id="d1">description 1</div>
<div id="d2" class="hidden">description 2</div>
<div id="d3" class="hidden">description 3</div>
<script>
$(".prodImg").click(function() {
if ($(this).hasClass("selected")) return;
$("#" + $(".selected").attr("desc")).addClass("hidden");
$(".selected").removeClass("selected");
$("#" + $(this).attr("desc")).removeClass("hidden");
$(this).addClass("selected");
});
</script>
```
This should get you pretty close. You need to define the relationship between your images and divs... so I added a 'desc' attribute to the images. The extra 'prodImg' class on the images allows you to ensure that only those images are being wired up for this type of swap in and out behavior.
|
233,251 |
<p>Since many years a GUI-standard are the menu-bars of applications with menus popping up, if you click or hover an entry in the menu-bar. Some websites implement this feature too, but they are using Javascript, as far as I can see. For different reasons Javascript can be a problem, so the question: Is this possible to implement without Javascript, only using HTML and CSS?</p>
|
[
{
"answer_id": 233266,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 1,
"selected": false,
"text": "<p>You can use the pseudoclass :hover to get an hover effect.</p>\n\n<pre><code>a:link {\n color: blue;\n}\n\na:hover {\n color: red;\n}\n</code></pre>\n\n<p>I can give a more extensive example but not right now (need to get the kids to the dentist).</p>\n"
},
{
"answer_id": 233269,
"author": "Jeff Fritz",
"author_id": 29156,
"author_profile": "https://Stackoverflow.com/users/29156",
"pm_score": 5,
"selected": true,
"text": "<p>I've done something like this before, and it's a trick pulled off by placing the menu items in anchor tags, with submenus in hidden divs INSIDE those anchor tags. The CSS trick is to make the inner div appear during the a:hover event.</p>\n\n<p>It looks something like:</p>\n\n<pre><code><style>\n A DIV { display: none; }\n A:hover DIV { display: block; }\n</style>\n<a href=\"blah.htm\">\n Top Level Menu Text\n <div><ul>\n <li><a href=\"sub1.htm\">Sub Item 1</a></li>\n <li><a href=\"sub2.htm\">Sub Item 2</a></li>\n <li><a href=\"sub3.htm\">Sub Item 3</a></li>\n </ul></div>\n</a>\n</code></pre>\n\n<p>Your mileage may vary...</p>\n\n<p>EDIT: Internet Explorer 6 and lower do NOT support the :hover pseudo-class on other elements besides A. In more 'modern' browsers, it is accepted to be able to use this trick with LI, TD, DIV, SPAN, and most any tag.</p>\n"
},
{
"answer_id": 233277,
"author": "extraneon",
"author_id": 24582,
"author_profile": "https://Stackoverflow.com/users/24582",
"pm_score": 3,
"selected": false,
"text": "<p>Have a look at <a href=\"http://www.cssmenumaker.com/\" rel=\"nofollow noreferrer\">CSS Menu Maker</a>. </p>\n"
},
{
"answer_id": 233302,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": false,
"text": "<p>Best known technique is the <a href=\"http://www.alistapart.com/articles/dropdowns\" rel=\"nofollow noreferrer\">suckerfish menus</a>. Searching for that will result in a lot of interesting menu's. It only needs javascript in IE6 and lower.</p>\n\n<p><a href=\"http://www.htmldog.com/articles/suckerfish/\" rel=\"nofollow noreferrer\">Here's a list of the sons of the suckerfish menus.</a></p>\n"
},
{
"answer_id": 233516,
"author": "bobince",
"author_id": 18936,
"author_profile": "https://Stackoverflow.com/users/18936",
"pm_score": 2,
"selected": false,
"text": "<p>Consider using the CSS methods as a backup for when JavaScript is unavailable. JavaScript can* provide a better user experience for drop-down menus because you can add some delay factors to stop menus immediately disappearing if the mouse briefly leaves their hover area. Pure-CSS menus can sometimes be a bit finicky to use, especially if the hover targets are small.</p>\n\n<p>*: of course, not all menu scripts actually bother to do this...</p>\n"
},
{
"answer_id": 233575,
"author": "Sean Hanley",
"author_id": 7290,
"author_profile": "https://Stackoverflow.com/users/7290",
"pm_score": 1,
"selected": false,
"text": "<p>There's also <a href=\"http://en.wikipedia.org/wiki/Eric_Meyer\" rel=\"nofollow noreferrer\">Eric Meyer</a>'s original article on <a href=\"http://meyerweb.com/eric/css/edge/menus/demo.html\" rel=\"nofollow noreferrer\"><strong>pure CSS menus</strong></a>.</p>\n\n<p>There are bound to be much more robust and modern takes out there now mentioned by others, but I thought I'd mention it for posterity. :)</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233251",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21005/"
] |
Since many years a GUI-standard are the menu-bars of applications with menus popping up, if you click or hover an entry in the menu-bar. Some websites implement this feature too, but they are using Javascript, as far as I can see. For different reasons Javascript can be a problem, so the question: Is this possible to implement without Javascript, only using HTML and CSS?
|
I've done something like this before, and it's a trick pulled off by placing the menu items in anchor tags, with submenus in hidden divs INSIDE those anchor tags. The CSS trick is to make the inner div appear during the a:hover event.
It looks something like:
```
<style>
A DIV { display: none; }
A:hover DIV { display: block; }
</style>
<a href="blah.htm">
Top Level Menu Text
<div><ul>
<li><a href="sub1.htm">Sub Item 1</a></li>
<li><a href="sub2.htm">Sub Item 2</a></li>
<li><a href="sub3.htm">Sub Item 3</a></li>
</ul></div>
</a>
```
Your mileage may vary...
EDIT: Internet Explorer 6 and lower do NOT support the :hover pseudo-class on other elements besides A. In more 'modern' browsers, it is accepted to be able to use this trick with LI, TD, DIV, SPAN, and most any tag.
|
233,255 |
<p>I am working on a project to enhance our production debugging capabilities. Our goal is to reliably produce a minidump on any unhandled exception, whether the exception is managed or unmanaged, and whether it occurs on a managed or unmanaged thread.</p>
<p>We use the excellent <a href="http://www.debuginfo.com/tools/clrdump.html" rel="noreferrer">ClrDump</a> library for this currently, but it does not quite provide the exact features we need, and I'd like to understand the mechanisms behind exception filtering, so I set out to try this for myself.</p>
<p>I started out by following this blog article to install an SEH handler myself: <a href="http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx" rel="noreferrer">http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx</a>. This technique works for console applications, but when I try the same thing from a WinForms application, my filter is not called for any variety of unmanaged exceptions.</p>
<p>What can ClrDump be doing that I'm not doing? ClrDump produces dumps in all cases, so its exception filter must still be called...</p>
<p>Note: I'm aware of ADPlus's capabilities, and we've also considered using the AeDebug registry keys... These are also possibilities, but also have their tradeoffs.</p>
<p>Thanks,
Dave</p>
<pre><code>// Code adapted from <http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx>
LONG WINAPI MyExceptionFilter(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
{
printf("Native exception filter: %X\n",ExceptionInfo->ExceptionRecord->ExceptionCode);
Beep(1000,1000);
Sleep(500);
Beep(1000,1000);
if(oldFilter_ == NULL)
{
return EXCEPTION_CONTINUE_SEARCH;
}
LONG ret = oldFilter_(ExceptionInfo);
printf("Other handler returned %d\n",ret);
return ret;
}
#pragma managed
namespace SEHInstaller
{
public ref class SEHInstall
{
public:
static void InstallHandler()
{
oldFilter_ = SetUnhandledExceptionFilter(MyExceptionFilter);
printf("Installed handler old=%x\n",oldFilter_);
}
};
}
</code></pre>
|
[
{
"answer_id": 233742,
"author": "Chris Becke",
"author_id": 27491,
"author_profile": "https://Stackoverflow.com/users/27491",
"pm_score": 2,
"selected": false,
"text": "<p>SetUnhandledExceptionFilter installs a handler that is invoked when a Win32-excpetion reaches the top of a threads callstack without being handled.</p>\n\n<p>In many language runtimes including managed, language exceptions are implemented using Win32 exceptions. But, the managed runtime will have a top level __try __catch(...) block at the top of each thread that will catch any win32 to runtime exceptions and process them without letting them escape to Win32's top level handler.</p>\n\n<p>Knowledge of the specific runtime would be necessary to inject a handler at this level because the exceptions will never be allowed to escape to Win32's TheadProc handler.</p>\n"
},
{
"answer_id": 238357,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 4,
"selected": true,
"text": "<p>Windows Forms has a built-in exception handler that does the following by default:</p>\n\n<ul>\n<li>Catches an unhandled managed exception when:\n\n<ul>\n<li>no debugger attached, and</li>\n<li>exception occurs during window message processing, and</li>\n<li>jitDebugging = false in App.Config.</li>\n</ul></li>\n<li>Shows dialog to user and prevents app termination.</li>\n</ul>\n\n<p>You can disable the first behaviour by setting <strong>jitDebugging = true</strong> in App.Config. This means that your last chance to stop the app terminating is to catch the unhandled exception by registering for the event Application.ThreadException, e.g. in C#:</p>\n\n<pre><code>Application.ThreadException += new Threading.ThreadExceptionHandler(CatchFormsExceptions);\n</code></pre>\n\n<p>If you decide not to catch the unhandled exception here, then you will need to check and/or change the registry setting <strong>DbgJitDebugLaunchSetting</strong> under HKLM\\Software.NetFramework. This has one of three values of which I'm aware:</p>\n\n<ul>\n<li>0: shows user dialog asking \"debug or terminate\".</li>\n<li>1: lets exception through for CLR to deal with.</li>\n<li>2: launches debugger specified in DbgManagedDebugger registry key.</li>\n</ul>\n\n<p>In Visual Studio, go to Tools>Options>Debugging>JIT to set this key to 0 or 2. But a value of 1 is usually what you want on an end-user's machine. Note that this registry key is acted on before the CLR unhandled exception event that you discuss.</p>\n\n<p>Then you can set the native exception filter that you discussed.</p>\n"
},
{
"answer_id": 1481802,
"author": "Corey Trager",
"author_id": 9328,
"author_profile": "https://Stackoverflow.com/users/9328",
"pm_score": 2,
"selected": false,
"text": "<p>If you want your GUI thread exceptions to work just like your-non GUI ones, so that they get handled the same way, you can do this:</p>\n\n<pre><code>Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);\n</code></pre>\n\n<p>Here's the background:</p>\n\n<p>In a manged GUI app, by default, exceptions that originate in the GUI thread are handled by whatever is assigned to the Application.ThreadException, which you can customize like this:</p>\n\n<pre><code>Application.ThreadException += \n new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);\n</code></pre>\n\n<p>Exceptions that originate in the other threads are handled by AppDomain.CurrentDomain.UnhandledException, which you can customize like this:</p>\n\n<pre><code>AppDomain.CurrentDomain.UnhandledException += \n new UnhandledExceptionEventHandler(Program.CurrentDomain_UnhandledException);\n</code></pre>\n\n<p>Assigning to UnHandledException works exactly like calling Win32 SetUnhandledExceptionFilter.</p>\n\n<p>If you goal is to create minidumps and then use them, you'll need to use Debugging Tools for Windows, sos.dll. You'll need to produce minidumps MiniDumpWithFullMemory.</p>\n\n<p>And then, even then, you probably won't have everything you might want. System.Diagnostics.StackTrace to get the call managed call stack.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233255",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6996/"
] |
I am working on a project to enhance our production debugging capabilities. Our goal is to reliably produce a minidump on any unhandled exception, whether the exception is managed or unmanaged, and whether it occurs on a managed or unmanaged thread.
We use the excellent [ClrDump](http://www.debuginfo.com/tools/clrdump.html) library for this currently, but it does not quite provide the exact features we need, and I'd like to understand the mechanisms behind exception filtering, so I set out to try this for myself.
I started out by following this blog article to install an SEH handler myself: <http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx>. This technique works for console applications, but when I try the same thing from a WinForms application, my filter is not called for any variety of unmanaged exceptions.
What can ClrDump be doing that I'm not doing? ClrDump produces dumps in all cases, so its exception filter must still be called...
Note: I'm aware of ADPlus's capabilities, and we've also considered using the AeDebug registry keys... These are also possibilities, but also have their tradeoffs.
Thanks,
Dave
```
// Code adapted from <http://blogs.microsoft.co.il/blogs/sasha/archive/2007/12.aspx>
LONG WINAPI MyExceptionFilter(__in struct _EXCEPTION_POINTERS *ExceptionInfo)
{
printf("Native exception filter: %X\n",ExceptionInfo->ExceptionRecord->ExceptionCode);
Beep(1000,1000);
Sleep(500);
Beep(1000,1000);
if(oldFilter_ == NULL)
{
return EXCEPTION_CONTINUE_SEARCH;
}
LONG ret = oldFilter_(ExceptionInfo);
printf("Other handler returned %d\n",ret);
return ret;
}
#pragma managed
namespace SEHInstaller
{
public ref class SEHInstall
{
public:
static void InstallHandler()
{
oldFilter_ = SetUnhandledExceptionFilter(MyExceptionFilter);
printf("Installed handler old=%x\n",oldFilter_);
}
};
}
```
|
Windows Forms has a built-in exception handler that does the following by default:
* Catches an unhandled managed exception when:
+ no debugger attached, and
+ exception occurs during window message processing, and
+ jitDebugging = false in App.Config.
* Shows dialog to user and prevents app termination.
You can disable the first behaviour by setting **jitDebugging = true** in App.Config. This means that your last chance to stop the app terminating is to catch the unhandled exception by registering for the event Application.ThreadException, e.g. in C#:
```
Application.ThreadException += new Threading.ThreadExceptionHandler(CatchFormsExceptions);
```
If you decide not to catch the unhandled exception here, then you will need to check and/or change the registry setting **DbgJitDebugLaunchSetting** under HKLM\Software.NetFramework. This has one of three values of which I'm aware:
* 0: shows user dialog asking "debug or terminate".
* 1: lets exception through for CLR to deal with.
* 2: launches debugger specified in DbgManagedDebugger registry key.
In Visual Studio, go to Tools>Options>Debugging>JIT to set this key to 0 or 2. But a value of 1 is usually what you want on an end-user's machine. Note that this registry key is acted on before the CLR unhandled exception event that you discuss.
Then you can set the native exception filter that you discussed.
|
233,261 |
<p>The strongly typed <code>SearchViewData</code> has a field called Colors that in it's turn is a <code>ColorViewData</code>.
In my <code>/Colors.mvc/search</code> I populate this <code>viewData.Model.Colors</code> based on the given search criteria.
Then, based on several factors, I render one of a set of user controls that are able to render itself with a <code>ColorViewData</code>.<br>
So I will end up with:</p>
<pre><code><%Html.RenderPartial("~/Views/Color/_ColorList.ascx", ViewData.Model.Colors);%>
</code></pre>
<p>This used to work just fine, but since the upgrade to the beta1, my user control always ends up with <code>viewdata = null;</code></p>
<p>Suggestions?</p>
|
[
{
"answer_id": 233335,
"author": "Karl Seguin",
"author_id": 34,
"author_profile": "https://Stackoverflow.com/users/34",
"pm_score": 0,
"selected": false,
"text": "<p>Noticed the same thing, I fixed it with the following, though I'm not sure if it's the \"right\" solution:</p>\n\n<pre><code><% Html.RenderPartial(\"xxx\", new ViewDataDictionary(ViewData.Model.Colors)); %>\n</code></pre>\n"
},
{
"answer_id": 234247,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 3,
"selected": true,
"text": "<p>Probably an overload issues. You could call the RenderPartial(string, object, ViewDataDictionary) which makes all three parameters explicit.</p>\n\n<p>One thing we're planning to change is if you call the overload RenderPartial(string, object), we'll pass the current ViewDataDictionary to the partial. We don't do that in the Beta, but it seems this is a very common scenario and will make this method more usable.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233261",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
The strongly typed `SearchViewData` has a field called Colors that in it's turn is a `ColorViewData`.
In my `/Colors.mvc/search` I populate this `viewData.Model.Colors` based on the given search criteria.
Then, based on several factors, I render one of a set of user controls that are able to render itself with a `ColorViewData`.
So I will end up with:
```
<%Html.RenderPartial("~/Views/Color/_ColorList.ascx", ViewData.Model.Colors);%>
```
This used to work just fine, but since the upgrade to the beta1, my user control always ends up with `viewdata = null;`
Suggestions?
|
Probably an overload issues. You could call the RenderPartial(string, object, ViewDataDictionary) which makes all three parameters explicit.
One thing we're planning to change is if you call the overload RenderPartial(string, object), we'll pass the current ViewDataDictionary to the partial. We don't do that in the Beta, but it seems this is a very common scenario and will make this method more usable.
|
233,264 |
<p>I have an ASP.NET application.
Basically the delivery process is this one :</p>
<ul>
<li>Nant builds the application and creates a zip file on the developer's computer with the application files without SVN folders and useless files. This file is delivered with a Nant script.</li>
<li>The zip and nant files are copied to the client's computer</li>
<li>the Nant script replaces the current website files with the file contained in the zip file.</li>
</ul>
<p>My problem is that with this process I have an Unauthorized access error when I try to open the website.
It seems that the files need to have a permission set for the user "<strong>IIS_WPG</strong>".</p>
<p>I don't have the power to change IIS configuration so I have to manually change the permissions of each file. And each time I replace the files the permissions are removed and I need to set them again.</p>
<p>So I have two questions :</p>
<ul>
<li>Can I change files permissions with Nant ? How to do it ?</li>
<li>Is it possible to avoid this problem ? (developers don't have this user on their computers)</li>
</ul>
|
[
{
"answer_id": 233299,
"author": "Jeff Fritz",
"author_id": 29156,
"author_profile": "https://Stackoverflow.com/users/29156",
"pm_score": 3,
"selected": true,
"text": "<p>You need to run the CACLS program in windows to grant permissions to files and folders. From Nant, you can do this with the EXEC task.</p>\n\n<p>Try a tag block like:</p>\n\n<pre><code><exec program=\"cacls\">\n <arg value=\"*\" />\n <arg value=\"/G IIS_WPG:F\" />\n</exec>\n</code></pre>\n"
},
{
"answer_id": 233457,
"author": "Julien N",
"author_id": 28544,
"author_profile": "https://Stackoverflow.com/users/28544",
"pm_score": 3,
"selected": false,
"text": "<p>@Jeff Fritz \nOuch...\nYour suggestion is the right solution but the parameters are... dangerous :).</p>\n\n<p>On dev computers I'm logged as administrator and I tried your suggestion with cmd.</p>\n\n<ul>\n<li>It replaces all the permissions set in order to set only the ones defined in the command (so, after the command, accessing files resulted in a \"Access denied\" even with my admin user)</li>\n<li>It applied on the C:\\WINDOWS\\ directory, while I called the command from the wwwroot folder. :)</li>\n</ul>\n\n<p>So, after some tests, the right command is :</p>\n\n<pre><code>cacls [full folder path] /T /E /G IIS_WPG:F\n</code></pre>\n\n<ul>\n<li>/T : applies on specified folder and subfolders</li>\n<li>/E : <strong>edits</strong> the ACL instead of <strong>replacing</strong> it :)</li>\n</ul>\n"
},
{
"answer_id": 234339,
"author": "Scott Saad",
"author_id": 4916,
"author_profile": "https://Stackoverflow.com/users/4916",
"pm_score": 2,
"selected": false,
"text": "<p>We ended up writing our own task for this with some fairly straight forward code:</p>\n\n<pre><code>[TaskName(\"addusertodir\")]\npublic class AddUserToDirectorySecurity : Task\n{\n [TaskAttribute(\"dir\", Required=true)]\n public string DirPath { get; set; }\n\n [TaskAttribute(\"user\", Required=true)]\n public string UserName { get; set; }\n\n protected override void ExecuteTask()\n {\n FileSystemAccessRule theRule1 = new FileSystemAccessRule(UserName, FileSystemRights.ListDirectory, AccessControlType.Allow);\n FileSystemAccessRule theRule2 = new FileSystemAccessRule(UserName, FileSystemRights.ReadAndExecute, AccessControlType.Allow);\n FileSystemAccessRule theRule3 = new FileSystemAccessRule(UserName, FileSystemRights.Read, AccessControlType.Allow);\n\n DirectorySecurity theDirSecurity = new DirectorySecurity();\n theDirSecurity.AddAccessRule(theRule1);\n theDirSecurity.AddAccessRule(theRule2);\n theDirSecurity.AddAccessRule(theRule3);\n Directory.SetAccessControl(DirPath, theDirSecurity);\n }\n}\n</code></pre>\n\n<p>Then you can write a nant script that loads the custom task and executes:</p>\n\n<pre><code><loadtasks>\n <fileset>\n <include name=\"MyTask.dll\"/>\n </fileset>\n</loadtasks>\n\n<addusertodir dir=\"MyDir\" user=\"IIS_WPG\"/>\n</code></pre>\n\n<p>Obviously, this could be modified for your certain rules or you could even parameterize this in the task if you so wish. We preferred this over the using the exec task as it have us a bit more control over permissions that were being applied.</p>\n"
},
{
"answer_id": 13016846,
"author": "Ted Spence",
"author_id": 419830,
"author_profile": "https://Stackoverflow.com/users/419830",
"pm_score": 2,
"selected": false,
"text": "<p>CACLS is now deprecated. Here's a version that uses ICACLS, the replacement.</p>\n\n<p>Let's say we have the following:</p>\n\n<ul>\n<li>The root folder of our installation is \"c:\\inetpub\\wwwroot\", and it's stored in the NANT variable <code>${paths.myprogram.inetpub}</code></li>\n<li>The folder we want to modify is called \"uploads\", and it's stored in <code>${upload.foldername}</code></li>\n<li>The user we want to grant access to is \"IIS_UPLOAD_USER\", stored in <code>${iis.upload.user}</code></li>\n<li>The permission level we want to grant is \"M\", for \"modify\" permissions, stored in <code>${iis.user.permissionlevel}</code></li>\n</ul>\n\n<p>With these assumptions, our task is this:</p>\n\n<pre><code><exec program=\"icacls\">\n <arg value=\"${path::combine(paths.myprogram.inetpub, upload.foldername)}\" />\n <arg value=\"/grant\" />\n <arg value=\"${iis.upload.user}:${iis.user.permissionlevel}\" />\n</exec>\n</code></pre>\n\n<p>Hope this helps!</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233264",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/28544/"
] |
I have an ASP.NET application.
Basically the delivery process is this one :
* Nant builds the application and creates a zip file on the developer's computer with the application files without SVN folders and useless files. This file is delivered with a Nant script.
* The zip and nant files are copied to the client's computer
* the Nant script replaces the current website files with the file contained in the zip file.
My problem is that with this process I have an Unauthorized access error when I try to open the website.
It seems that the files need to have a permission set for the user "**IIS\_WPG**".
I don't have the power to change IIS configuration so I have to manually change the permissions of each file. And each time I replace the files the permissions are removed and I need to set them again.
So I have two questions :
* Can I change files permissions with Nant ? How to do it ?
* Is it possible to avoid this problem ? (developers don't have this user on their computers)
|
You need to run the CACLS program in windows to grant permissions to files and folders. From Nant, you can do this with the EXEC task.
Try a tag block like:
```
<exec program="cacls">
<arg value="*" />
<arg value="/G IIS_WPG:F" />
</exec>
```
|
233,284 |
<p>I have created a .NET DLL which makes some methods COM visible.</p>
<p>One method is problematic. It looks like this:</p>
<pre><code>bool Foo(byte[] a, ref byte[] b, string c, ref string d)
</code></pre>
<p>VB6 gives a compile error when I attempt to call the method:</p>
<blockquote>
<p>Function or interface marked as
restricted, or the function uses an
Automation type not supported in
Visual Basic.</p>
</blockquote>
<p>I read that array parameters must be passed by reference, so I altered the first parameter in the signature:</p>
<pre><code>bool Foo(ref byte[] a, ref byte[] b, string c, ref string d)
</code></pre>
<p>VB6 still gives the same compile error.</p>
<p>How might I alter the signature to be compatible with VB6?</p>
|
[
{
"answer_id": 233451,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 1,
"selected": false,
"text": "<p>Try</p>\n\n<pre><code>[ComVisible(true)]\nbool Foo([In] ref byte[] a, [In] ref byte[] b, string c, ref string d)\n</code></pre>\n"
},
{
"answer_id": 233486,
"author": "Hans Passant",
"author_id": 17034,
"author_profile": "https://Stackoverflow.com/users/17034",
"pm_score": 4,
"selected": true,
"text": "<p>Declaring the array argument with \"ref\" is required. Your 2nd attempt should have worked just fine, perhaps you forgot to regenerate the .tlb?</p>\n\n<p>Tested code:</p>\n\n<pre><code>[ComVisible(true)]\npublic interface IMyInterface {\n bool Foo(ref byte[] a, ref byte[] b,string c, ref string d);\n}\n\n[ComVisible(true)]\npublic class MyClass : IMyInterface {\n public bool Foo(ref byte[] a, ref byte[] b, string c, ref string d) {\n throw new NotImplementedException();\n }\n}\n\n\n Dim obj As ClassLibrary10.IMyInterface\n Set obj = New ClassLibrary10.MyClass\n Dim binp() As Byte\n Dim bout() As Byte\n Dim sinp As String\n Dim sout As String\n Dim retval As Boolean\n retval = obj.Foo(binp, bout, sinp, sout)\n</code></pre>\n"
},
{
"answer_id": 1519012,
"author": "Marthinus",
"author_id": 101732,
"author_profile": "https://Stackoverflow.com/users/101732",
"pm_score": 1,
"selected": false,
"text": "<p>Something related to this was my problem. I have a method in C# with the following signature:</p>\n\n<pre><code>public long ProcessWiWalletTransaction(ref IWiWalletTransaction wiWalletTransaction)\n</code></pre>\n\n<p>VB 6 kept on complaining \"Function or interface marked as restricted ...\" and I assumed it was my custom object I use in the call. Turns out VB 6 can not do long, had to change the signature to:</p>\n\n<pre><code>public int ProcessWiWalletTransaction(ref IWiWalletTransaction wiWalletTransaction)\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/329888/"
] |
I have created a .NET DLL which makes some methods COM visible.
One method is problematic. It looks like this:
```
bool Foo(byte[] a, ref byte[] b, string c, ref string d)
```
VB6 gives a compile error when I attempt to call the method:
>
> Function or interface marked as
> restricted, or the function uses an
> Automation type not supported in
> Visual Basic.
>
>
>
I read that array parameters must be passed by reference, so I altered the first parameter in the signature:
```
bool Foo(ref byte[] a, ref byte[] b, string c, ref string d)
```
VB6 still gives the same compile error.
How might I alter the signature to be compatible with VB6?
|
Declaring the array argument with "ref" is required. Your 2nd attempt should have worked just fine, perhaps you forgot to regenerate the .tlb?
Tested code:
```
[ComVisible(true)]
public interface IMyInterface {
bool Foo(ref byte[] a, ref byte[] b,string c, ref string d);
}
[ComVisible(true)]
public class MyClass : IMyInterface {
public bool Foo(ref byte[] a, ref byte[] b, string c, ref string d) {
throw new NotImplementedException();
}
}
Dim obj As ClassLibrary10.IMyInterface
Set obj = New ClassLibrary10.MyClass
Dim binp() As Byte
Dim bout() As Byte
Dim sinp As String
Dim sout As String
Dim retval As Boolean
retval = obj.Foo(binp, bout, sinp, sout)
```
|
233,288 |
<p><strong>I have class A:</strong></p>
<pre><code>public class ClassA<T>
</code></pre>
<p><strong>Class B derives from A:</strong></p>
<pre><code>public class ClassB : ClassA<ClassB>
</code></pre>
<p><strong>Class C derives from class B:</strong></p>
<pre><code>public class ClassC : ClassB
</code></pre>
<p><strong>Now I have a generic method with constraints</strong></p>
<pre><code>public static T Method<T>() where T : ClassA<T>
</code></pre>
<p>OK, now I want to call:</p>
<pre><code>ClassC c = Method<ClassC>();
</code></pre>
<p>but I get the compile error saying:
<code>Type argument 'ClassC' does not inherit from or implement the constraint type 'ClassA<ClassC>.</code></p>
<p>Yet, the compiler will allow:</p>
<pre><code>ClassB b = Method<ClassB>();
</code></pre>
<p>My understanding is that this fails because <code>ClassC</code> inherits <code>ClassA<ClassB></code> instead of <code>ClassA<ClassC></code></p>
<p><strong>My real question is, is it possible to create a class deriving from <code>ClassB</code> that can be used in some way with the generic method?</strong></p>
<p>This may seem like generics are overused and I would agree. I am trying to create business layer objects deriving from the subsonic data objects in a separate project.</p>
<p>Note: I have put the < T > with extra spaces otherwise they get stripped from the question.</p>
|
[
{
"answer_id": 233303,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>Well, you could change Method to:</p>\n\n<pre><code>public static T Method<T,U>() where T : ClassA<U> where U : T\n</code></pre>\n\n<p>Does that help at all? It's not much use if you can't change Method of course...</p>\n"
},
{
"answer_id": 233347,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "<p>No. You must change or wrap this method.</p>\n\n<p>Here is the reason.</p>\n\n<p>ClassC inherits from ClassB which inherits from ClassA(ClassB)</p>\n\n<p>ClassC does not inherit from ClassA(ClassC)</p>\n\n<p>No child of ClassB will inherit from ClassA(child class), because they instead inherit from ClassB and ClassB does not inherit from ClassA(child class).</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/aa479859.aspx#fundamentals_topic12\" rel=\"nofollow noreferrer\">Generic types are invariant</a>.</p>\n"
},
{
"answer_id": 233425,
"author": "Tamas Czinege",
"author_id": 8954,
"author_profile": "https://Stackoverflow.com/users/8954",
"pm_score": 1,
"selected": false,
"text": "<p>In most cases it is possible to solve this scenario by having a base non-generic abstract class:</p>\n\n<pre><code>public abstract class BasicClassA\n{\n}\n\npublic class ClassA<T> : BasicClassA\n{\n}\n\npublic class ClassB : ClassA<ClassB>\n{\n}\n\npublic class ClassC : ClassB\n{\n}\n\npublic static T Method<T>() where T : BasicClassA\n{\n return null;\n}\n</code></pre>\n\n<p>Your mileage may vary, though.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233288",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24681/"
] |
**I have class A:**
```
public class ClassA<T>
```
**Class B derives from A:**
```
public class ClassB : ClassA<ClassB>
```
**Class C derives from class B:**
```
public class ClassC : ClassB
```
**Now I have a generic method with constraints**
```
public static T Method<T>() where T : ClassA<T>
```
OK, now I want to call:
```
ClassC c = Method<ClassC>();
```
but I get the compile error saying:
`Type argument 'ClassC' does not inherit from or implement the constraint type 'ClassA<ClassC>.`
Yet, the compiler will allow:
```
ClassB b = Method<ClassB>();
```
My understanding is that this fails because `ClassC` inherits `ClassA<ClassB>` instead of `ClassA<ClassC>`
**My real question is, is it possible to create a class deriving from `ClassB` that can be used in some way with the generic method?**
This may seem like generics are overused and I would agree. I am trying to create business layer objects deriving from the subsonic data objects in a separate project.
Note: I have put the < T > with extra spaces otherwise they get stripped from the question.
|
Well, you could change Method to:
```
public static T Method<T,U>() where T : ClassA<U> where U : T
```
Does that help at all? It's not much use if you can't change Method of course...
|
233,320 |
<p>I'm running Python 2.6 on Unix and when I run the interactive prompt (<a href="http://en.wikipedia.org/wiki/SQLite" rel="noreferrer">SQLite</a> is supposed to be preinstalled) I get:</p>
<pre><code>[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
</code></pre>
<p>How do I resolve this?</p>
|
[
{
"answer_id": 233336,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 3,
"selected": false,
"text": "<pre><code>import sqlite3\n</code></pre>\n\n<p><a href=\"http://docs.python.org/library/sqlite3.html#module-sqlite3\" rel=\"noreferrer\">sqlite3</a> - DB-API 2.0 interface for SQLite databases.</p>\n\n<p>You are missing the <code>.so</code> (shared object) - probably an installation step. In my Linux python installation, <code>_sqlite3</code> is at: </p>\n\n<pre><code>${somewhere}/lib/python2.6/lib-dynload/_sqlite3.so\n</code></pre>\n"
},
{
"answer_id": 233865,
"author": "razong",
"author_id": 29885,
"author_profile": "https://Stackoverflow.com/users/29885",
"pm_score": 5,
"selected": true,
"text": "<p>The error: </p>\n\n<pre><code>ImportError: No module named _sqlite3\n</code></pre>\n\n<p>means that <a href=\"http://en.wikipedia.org/wiki/SQLite\" rel=\"noreferrer\">SQLite</a> 3 does not find the associated shared library. On Mac OS X it's _sqlite3.so and it should be the same on other Unix systems. </p>\n\n<p>To resolve the error you have to locate the _sqlite3.so library on your computer and then check your PYTHONPATH for this directory location. </p>\n\n<p>To print the Python search path enter the following in the Python shell:</p>\n\n<pre><code>import sys\nprint sys.path\n</code></pre>\n\n<p>If the directory containing your library is missing you can try adding it interactively with </p>\n\n<pre><code>sys.path.append('/your/dir/here')\n</code></pre>\n\n<p>and try </p>\n\n<pre><code>import sqlite3\n</code></pre>\n\n<p>again. If this works you have to add this directory permanently to your PYTHONPATH environment variable. </p>\n\n<p>PS: If the library is missing you should (re-)install the module.</p>\n"
},
{
"answer_id": 233883,
"author": "André",
"author_id": 9683,
"author_profile": "https://Stackoverflow.com/users/9683",
"pm_score": 1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>from pysqlite2 import dbapi2 as sqlite\n</code></pre>\n"
},
{
"answer_id": 233967,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 1,
"selected": false,
"text": "<p>On my system <code>_sqlite3.so</code> located at:</p>\n\n<pre><code>'/usr/lib/python2.6/lib-dynload/_sqlite3.so'\n</code></pre>\n\n<p>Check that the directory is in your <code>sys.path</code>:</p>\n\n<pre><code>>>> import sys; print(filter(lambda p: 'lib-dynload' in p, sys.path))\n['/usr/lib/python2.6/lib-dynload']\n</code></pre>\n"
},
{
"answer_id": 939030,
"author": "Dickon Reed",
"author_id": 22668,
"author_profile": "https://Stackoverflow.com/users/22668",
"pm_score": 3,
"selected": false,
"text": "<p>Python 2.6 detects where the sqlite3 development headers are installed, and will silently skip building _sqlite3 if it is not available. If you are building from source, install sqlite3 including development headers. In my case, <code>sudo yum install sqlite-devel</code> sorted this out on a CentOS 4.7. Then, rebuild Python from source code.</p>\n"
},
{
"answer_id": 953786,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 0,
"selected": false,
"text": "<p>Does that fix your problem?</p>\n\n<pre><code>Python 2.5.4 (r254:67916, May 31 2009, 16:56:01)\n[GCC 4.3.3] on linux2\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> import sqlite\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nImportError: No module named sqlite\n>>> import sqlite3\n>>>\n</code></pre>\n"
},
{
"answer_id": 2692335,
"author": "98.",
"author_id": 323429,
"author_profile": "https://Stackoverflow.com/users/323429",
"pm_score": 0,
"selected": false,
"text": "<p>The 2.5.5. Mac port of Python 2.5 now has this hint:</p>\n\n<pre><code>\"py25-sqlite3 @2.5.4 (python, databases)\n This is a stub. sqlite3 is now built with python25\"\n</code></pre>\n\n<p>And so an upgrade of the python25 port to <code>python25 @2.5.5_0</code> made the import work again.\nSince sqlite3 is among the dependencies of python25,\nit is built anew when upgrading python25.\nThus,</p>\n\n<pre><code>$ sudo port upgrade python25\n</code></pre>\n\n<p>does the trick on Mac OS X, ports collection.</p>\n"
},
{
"answer_id": 15269590,
"author": "Rohit Gupta",
"author_id": 2024826,
"author_profile": "https://Stackoverflow.com/users/2024826",
"pm_score": 0,
"selected": false,
"text": "<p>I face the same problem.\nSteps to solve.</p>\n\n<ol>\n<li>Download latest sqlite3 from sqlite website. sqlite-autoconf*</li>\n<li>Install that in 3 simple steps\n<ol>\n<li>./configure</li>\n<li>make</li>\n<li>make install</li>\n</ol></li>\n<li>Rebuild the python\nmake \nmake install</li>\n</ol>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404/"
] |
I'm running Python 2.6 on Unix and when I run the interactive prompt ([SQLite](http://en.wikipedia.org/wiki/SQLite) is supposed to be preinstalled) I get:
```
[root@idev htdocs]# python
Python 2.6 (r26:66714, Oct 23 2008, 16:25:34)
[GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import sqlite
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named sqlite
>>>
```
How do I resolve this?
|
The error:
```
ImportError: No module named _sqlite3
```
means that [SQLite](http://en.wikipedia.org/wiki/SQLite) 3 does not find the associated shared library. On Mac OS X it's \_sqlite3.so and it should be the same on other Unix systems.
To resolve the error you have to locate the \_sqlite3.so library on your computer and then check your PYTHONPATH for this directory location.
To print the Python search path enter the following in the Python shell:
```
import sys
print sys.path
```
If the directory containing your library is missing you can try adding it interactively with
```
sys.path.append('/your/dir/here')
```
and try
```
import sqlite3
```
again. If this works you have to add this directory permanently to your PYTHONPATH environment variable.
PS: If the library is missing you should (re-)install the module.
|
233,328 |
<p>I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?</p>
|
[
{
"answer_id": 233339,
"author": "John Carter",
"author_id": 8331,
"author_profile": "https://Stackoverflow.com/users/8331",
"pm_score": 10,
"selected": true,
"text": "<pre><code>set print elements 0\n</code></pre>\n\n<p><a href=\"http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_57.html#IDX353\" rel=\"noreferrer\">From the GDB manual</a>: </p>\n\n<blockquote><code>set print elements </code><i><code>number-of-elements</code></i></blockquote>\n\n<blockquote>\nSet a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the <code>set print elements</code> command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. <b>Setting <i>number-of-elements</i> to zero means that the printing is unlimited</b>.\n</blockquote>\n"
},
{
"answer_id": 253120,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": false,
"text": "<p>As long as your program's in a sane state, you can also <code>call (void)puts(your_string)</code> to print it to stdout. Same principle applies to all functions available to the debugger, actually.</p>\n"
},
{
"answer_id": 7677311,
"author": "Wichert Akkerman",
"author_id": 211490,
"author_profile": "https://Stackoverflow.com/users/211490",
"pm_score": 5,
"selected": false,
"text": "<p>There is a third option: the x command, which allows you to set a different limit for the specific command instead of changing a global setting. To print the first 300 characters of a string you can use <code>x/300s your_string</code>. The output might be a bit harder to read. For example printing a SQL query results in:</p>\n\n<pre>\n(gdb) x/300sb stmt.c_str()\n0x9cd948: \"SELECT article.r\"...\n0x9cd958: \"owid FROM articl\"...\n..\n</pre>\n"
},
{
"answer_id": 8909030,
"author": "abstraktor",
"author_id": 647213,
"author_profile": "https://Stackoverflow.com/users/647213",
"pm_score": 5,
"selected": false,
"text": "<p>Just to complete it:</p>\n\n<pre><code>(gdb) p (char[10]) *($ebx)\n$87 = \"asdfasdfe\\n\"\n</code></pre>\n\n<p>You must give a length, but may change the representation of that string:</p>\n\n<pre><code>(gdb) p/x (char[10]) *($ebx)\n$90 = {0x61,\n 0x73,\n 0x64,\n 0x66,\n 0x61,\n 0x73,\n 0x64,\n 0x66,\n 0x65,\n 0xa}\n</code></pre>\n\n<p>This may be useful if you want to debug by their values</p>\n"
},
{
"answer_id": 34075827,
"author": "korry",
"author_id": 3882261,
"author_profile": "https://Stackoverflow.com/users/3882261",
"pm_score": 6,
"selected": false,
"text": "<p>The <code>printf</code> command will print the complete strings:</p>\n\n<pre><code>(gdb) printf \"%s\\n\", string\n</code></pre>\n"
},
{
"answer_id": 37984536,
"author": "mrtimdog",
"author_id": 309870,
"author_profile": "https://Stackoverflow.com/users/309870",
"pm_score": 2,
"selected": false,
"text": "<p>Using <code>set elements ...</code> isn't always the best way. It would be useful if there were a distinct <code>set string-elements ...</code>.</p>\n\n<p>So, I use these functions in my .gdbinit:</p>\n\n<pre><code>define pstr\n ptype $arg0._M_dataplus._M_p\n printf \"[%d] = %s\\n\", $arg0._M_string_length, $arg0._M_dataplus._M_p\nend\n\ndefine pcstr\n ptype $arg0\n printf \"[%d] = %s\\n\", strlen($arg0), $arg0\nend\n</code></pre>\n\n<p>Caveats:</p>\n\n<ul>\n<li>The first is c++ lib dependent as it accesses members of std::string, but is easily adjusted.</li>\n<li>The second can only be used on a running program as it calls strlen.</li>\n</ul>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8331/"
] |
I want to print the full length of a C-string in GDB. By default it's being abbreviated, how do I force GDB to print the whole string?
|
```
set print elements 0
```
[From the GDB manual](http://ftp.gnu.org/old-gnu/Manuals/gdb-5.1.1/html_node/gdb_57.html#IDX353):
> `set print elements` *`number-of-elements`*
>
> Set a limit on how many elements of an array GDB will print. If GDB is printing a large array, it stops printing after it has printed the number of elements set by the `set print elements` command. This limit also applies to the display of strings. When GDB starts, this limit is set to 200. **Setting *number-of-elements* to zero means that the printing is unlimited**.
>
|
233,421 |
<p>Is there currently a way to host a shared Git repository in Windows? I understand that you can configure the Git service in Linux with:</p>
<pre><code>git daemon
</code></pre>
<p>Is there a native Windows option, short of sharing folders, to host a Git service?</p>
<p>EDIT:
I am currently using the cygwin install of git to store and work with git repositories in Windows, but I would like to take the next step of hosting a repository with a service that can provide access to others.</p>
|
[
{
"answer_id": 233444,
"author": "Clokey",
"author_id": 2438,
"author_profile": "https://Stackoverflow.com/users/2438",
"pm_score": 2,
"selected": false,
"text": "<p>Have you considered using the cygwin layer? See <a href=\"http://fab.cba.mit.edu/classes/MIT/863.07/people/steve/git.html\" rel=\"nofollow noreferrer\">this link</a>.</p>\n"
},
{
"answer_id": 233453,
"author": "David Arno",
"author_id": 7122,
"author_profile": "https://Stackoverflow.com/users/7122",
"pm_score": 3,
"selected": false,
"text": "<p>If you are working in a Windows environment, have you considered <a href=\"http://www.selenic.com/mercurial/wiki/\" rel=\"noreferrer\">Mercurial</a>? It is a distributed version control system like Git, but integrates far more neatly and easily with Windows.</p>\n"
},
{
"answer_id": 524113,
"author": "Henk",
"author_id": 41664,
"author_profile": "https://Stackoverflow.com/users/41664",
"pm_score": 2,
"selected": false,
"text": "<p>You do not need to host a service, you can also create a shared repository on a shared drive. Just create a bare repository. You can clone an existing repo into a shared one using: \"git clone --bare --shared [source] [dest]\". You can also init a new repository using \"git init --bare --shared=all\".</p>\n\n<p>Henk</p>\n"
},
{
"answer_id": 558980,
"author": "Matthew McCullough",
"author_id": 56039,
"author_profile": "https://Stackoverflow.com/users/56039",
"pm_score": 3,
"selected": false,
"text": "<p>I'm currently using <a href=\"http://pigtail.net/LRP/printsrv/cygwin-sshd.html\" rel=\"noreferrer\">cygwin's ssh daemon on Windows</a> to serve up and allow remote access to my repo. It works quite well, I have complete control over who accesses my repo by their ssh certificates, and the performance blazes, even over remote WAN and VPN links.</p>\n\n<p><a href=\"http://scie.nti.st/2007/11/14/hosting-git-repositories-the-easy-and-secure-way\" rel=\"noreferrer\">Another solution is to use Gitosis</a>. It is a tool that makes hosting repos much easier.</p>\n"
},
{
"answer_id": 782857,
"author": "Ibrahim",
"author_id": 90551,
"author_profile": "https://Stackoverflow.com/users/90551",
"pm_score": 0,
"selected": false,
"text": "<p>I think what Henk is saying is that you can create a shared repository on a drive and then copy it to some common location that both of you have access to. If there is some company server or something that you both have ssh access to, you can put the repository someplace where you can SCP it back to your own computer, and then pull from that. I did this for my self a little while, since I have two computers. It's a hassle, but it does work.</p>\n"
},
{
"answer_id": 2275844,
"author": "Derek Greer",
"author_id": 1219618,
"author_profile": "https://Stackoverflow.com/users/1219618",
"pm_score": 7,
"selected": true,
"text": "<p>Here are some steps you can follow to get the git daemon running under Windows:</p>\n\n<p><em>(Prerequisites: A default Cygwin installation and a git client that supports git daemon)</em></p>\n\n<p><strong>Step 1</strong>: Open a bash shell</p>\n\n<p><strong>Step 2</strong>: In the directory /cygdrive/c/cygwin64/usr/local/bin/, create a file named \"gitd\" with the following content:</p>\n\n<pre><code>#!/bin/bash\n\n/usr/bin/git daemon --reuseaddr --base-path=/git --export-all --verbose --enable=receive-pack\n</code></pre>\n\n<p><strong>Step 3</strong>: Run the following cygrunsrv command from an elevated prompt (i.e. as admin) to install the script as a service (Note: assumes Cygwin is installed at C:\\cygwin64):</p>\n\n<pre><code>cygrunsrv --install gitd \\\n --path c:/cygwin64/bin/bash.exe \\\n --args c:/cygwin64/usr/local/bin/gitd \\\n --desc \"Git Daemon\" \\\n --neverexits \\\n --shutdown\n</code></pre>\n\n<p><strong>Step 4</strong>: Run the following command to start the service:</p>\n\n<p>cygrunsrv --start gitd</p>\n\n<p>You are done. If you want to test it, here is a quick and dirty script that shows that you can push over the git protocol to your local machine:</p>\n\n<pre><code>#!/bin/bash\n\necho \"Creating main git repo ...\"\nmkdir -p /git/testapp.git\ncd /git/testapp.git\ngit init --bare\ntouch git-daemon-export-ok\necho \"Creating local repo ...\"\ncd\nmkdir testapp\ncd testapp\ngit init\necho \"Creating test file ...\"\ntouch testfile\ngit add -A\ngit commit -m 'Test message'\necho \"Pushing master to main repo ...\"\ngit push git://localhost/testapp.git master\n</code></pre>\n"
},
{
"answer_id": 4208755,
"author": "isaac",
"author_id": 511283,
"author_profile": "https://Stackoverflow.com/users/511283",
"pm_score": 3,
"selected": false,
"text": "<p>If you get the error <code>cygrunsrv: Error starting a service: QueryServiceStatus: Win32 error 1062: The service has not been started.</code> after running the command:</p>\n\n<pre><code>cygrunsrv --start gitd\n</code></pre>\n\n<p>that means that you did not create the 'base-path' folder.</p>\n\n<p>Creating the folder '/git' and rerunning the command will fix this.</p>\n"
},
{
"answer_id": 5126956,
"author": "Artem",
"author_id": 635494,
"author_profile": "https://Stackoverflow.com/users/635494",
"pm_score": 2,
"selected": false,
"text": "<p>Now msysGit supports git daemon ! It works fine (for me at least). I gonna try to make it run as service...</p>\n"
},
{
"answer_id": 5256436,
"author": "Alex Burtsev",
"author_id": 235715,
"author_profile": "https://Stackoverflow.com/users/235715",
"pm_score": 3,
"selected": false,
"text": "<p>Installing CygWin is an overkill, read this tutorial on how to do it faster and native:</p>\n\n<p><a href=\"http://code.google.com/p/tortoisegit/wiki/HOWTO_CentralServerWindowsXP\" rel=\"noreferrer\">http://code.google.com/p/tortoisegit/wiki/HOWTO_CentralServerWindowsXP</a></p>\n"
},
{
"answer_id": 6225974,
"author": "Daniel O",
"author_id": 697,
"author_profile": "https://Stackoverflow.com/users/697",
"pm_score": 4,
"selected": false,
"text": "<p>Here's a dedicated git server for windows: <a href=\"https://github.com/jakubgarfield/Bonobo-Git-Server/wiki\" rel=\"noreferrer\">https://github.com/jakubgarfield/Bonobo-Git-Server/wiki</a></p>\n"
},
{
"answer_id": 6351449,
"author": "disrvptor",
"author_id": 494307,
"author_profile": "https://Stackoverflow.com/users/494307",
"pm_score": 0,
"selected": false,
"text": "<p>For Windows 7 x64 and Cygwin 1.7.9 I needed to use /usr/bin/gitd as the args argument of cygrunsrv</p>\n\n<pre><code>cygrunsrv --install gitd \\\n --path c:/cygwin/bin/bash.exe \\\n --args /usr/bin/gitd \\\n --desc \"Git Daemon\" \\\n --neverexits \\\n --shutdown\n</code></pre>\n\n<p>Also, I needed to run bash as an Administrator to install the service.</p>\n"
},
{
"answer_id": 6556829,
"author": "David Thomas",
"author_id": 583715,
"author_profile": "https://Stackoverflow.com/users/583715",
"pm_score": 2,
"selected": false,
"text": "<p>On Windows, you can also <strong>serve Git repositories with Apache over HTTP or HTTPS, using the DAV extension.</strong></p>\n\n<p>The Git repository path can then be protected with Apache authentication checks such as restricting to certain IP addresses or htpasswd/htdigest type authentication.</p>\n\n<p>The limitation of using htpasswd/htdigest authentication is that the username:password is passed in the requested Git URL, so restricting access to the Git URL to certain IP addresses is better. </p>\n\n<p><em>Edit:</em> Note, you can leave the password out of the Git URL and Git will prompt you for the password on push and fetch/pull instead.</p>\n\n<p>Using HTTPS means all the data is encrypted in transfer.</p>\n\n<p>It's easy enough to set up, and works.</p>\n\n<p>The following example shows the combination of access control by IP address and user:password over standard HTTP.</p>\n\n<p><strong>Example Apache Virtualhost</strong></p>\n\n<pre><code>## GIT HTTP DAV ##\n<VirtualHost *:80>\n\n ServerName git.example.com\n DocumentRoot C:\\webroot\\htdocs\\restricted\\git\n ErrorLog C:\\webroot\\apache\\logs\\error-git-webdav.log\n\n <Location />\n DAV on\n # Restrict Access\n AuthType Basic\n AuthName \"Restricted Area\"\n AuthUserFile \"C:\\webroot\\apache\\conf\\git-htpasswd\"\n # To valid user\n Require valid-user\n # AND valid IP address\n Order Deny,Allow\n Deny from all\n # Example IP 1\n Allow from 203.22.56.67 \n # Example IP 2\n Allow from 202.12.33.44 \n # Require both authentication checks to be satisfied\n Satisfy all\n </Location>\n\n</VirtualHost>\n</code></pre>\n\n<p><strong>Example .git/config</strong></p>\n\n<pre><code>[core]\n repositoryformatversion = 0\n filemode = true\n bare = false\n logallrefupdates = true\n[remote \"origin\"]\n fetch = +refs/heads/*:refs/remotes/origin/*\n url = http://username:[email protected]/codebase.git\n[branch \"master\"]\n remote = origin\n merge = refs/heads/master\n</code></pre>\n"
},
{
"answer_id": 9159577,
"author": "poiuytrez",
"author_id": 112976,
"author_profile": "https://Stackoverflow.com/users/112976",
"pm_score": 4,
"selected": false,
"text": "<p><a href=\"http://gitstack.com\" rel=\"noreferrer\">GitStack</a> might be your best choice. It is currently free (for up to 2 users) <strike>and open source</strike> at the time of writing. </p>\n"
},
{
"answer_id": 13155841,
"author": "Lazy Badger",
"author_id": 960558,
"author_profile": "https://Stackoverflow.com/users/960558",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.scm-manager.org/\" rel=\"nofollow\">SCM Manager</a></p>\n\n<ul>\n<li>Lightweight http-server for Git, Mercurial, Subversion repos <strong>from a box</strong> (only Java is needed)</li>\n<li>Web-interface for management of users, ACLs, repos</li>\n</ul>\n"
},
{
"answer_id": 19708638,
"author": "Gian Marco",
"author_id": 66629,
"author_profile": "https://Stackoverflow.com/users/66629",
"pm_score": 2,
"selected": false,
"text": "<p>At work I'm using GitBlit GO installed on a Windows Server. Work flawlessly and integrate well with ActiveDirectory for user authentication and authorization. It is also free and opensource (Apache licensed)</p>\n\n<p><a href=\"http://gitblit.com/\" rel=\"nofollow\">GitBlit homepage</a></p>\n\n<p>Only HTTP(S) access is supported, no SSH, but under Windows you shouldn't need anything more.</p>\n"
},
{
"answer_id": 34112884,
"author": "gerryLowry",
"author_id": 249176,
"author_profile": "https://Stackoverflow.com/users/249176",
"pm_score": 1,
"selected": false,
"text": "<p>this is a 2015 answer to a question that is over 7 years old.</p>\n\n<p>For $10 one time payment, from <a href=\"https://bitbucket.org/product/server\" rel=\"nofollow\">https://bitbucket.org/product/server</a>, one can purchase a 64-bit Windows licence for up to <strong>10 users</strong>.</p>\n\n<p>Apparently 32-bit versions are only available via their archive.</p>\n\n<p><strong>Bitbucket Server</strong> was previously known as <strong>Stash</strong>.</p>\n\n<p>Please note that i have not tried this version but $10 seems like a good deal; <a href=\"https://www.atlassian.com/software/bitbucket/pricing?tab=host-on-your-server\" rel=\"nofollow\">here</a> i read that Atlassian gives the $10 to charity. FWIW</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233421",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29156/"
] |
Is there currently a way to host a shared Git repository in Windows? I understand that you can configure the Git service in Linux with:
```
git daemon
```
Is there a native Windows option, short of sharing folders, to host a Git service?
EDIT:
I am currently using the cygwin install of git to store and work with git repositories in Windows, but I would like to take the next step of hosting a repository with a service that can provide access to others.
|
Here are some steps you can follow to get the git daemon running under Windows:
*(Prerequisites: A default Cygwin installation and a git client that supports git daemon)*
**Step 1**: Open a bash shell
**Step 2**: In the directory /cygdrive/c/cygwin64/usr/local/bin/, create a file named "gitd" with the following content:
```
#!/bin/bash
/usr/bin/git daemon --reuseaddr --base-path=/git --export-all --verbose --enable=receive-pack
```
**Step 3**: Run the following cygrunsrv command from an elevated prompt (i.e. as admin) to install the script as a service (Note: assumes Cygwin is installed at C:\cygwin64):
```
cygrunsrv --install gitd \
--path c:/cygwin64/bin/bash.exe \
--args c:/cygwin64/usr/local/bin/gitd \
--desc "Git Daemon" \
--neverexits \
--shutdown
```
**Step 4**: Run the following command to start the service:
cygrunsrv --start gitd
You are done. If you want to test it, here is a quick and dirty script that shows that you can push over the git protocol to your local machine:
```
#!/bin/bash
echo "Creating main git repo ..."
mkdir -p /git/testapp.git
cd /git/testapp.git
git init --bare
touch git-daemon-export-ok
echo "Creating local repo ..."
cd
mkdir testapp
cd testapp
git init
echo "Creating test file ..."
touch testfile
git add -A
git commit -m 'Test message'
echo "Pushing master to main repo ..."
git push git://localhost/testapp.git master
```
|
233,434 |
<p>I am trying to make our SQL Server Integration Services packages as portable as possible and the one thing that is preventing that is that the path to the config is always an absolute path, which makes testing and deployment a headache. Are there any suggestions for making this more manageble?</p>
<p>Another issue is when another developer gets the package out of source control the path is specific to the developers machine.</p>
|
[
{
"answer_id": 233528,
"author": "Malik Daud Ahmad Khokhar",
"author_id": 1688440,
"author_profile": "https://Stackoverflow.com/users/1688440",
"pm_score": 5,
"selected": true,
"text": "<p>If you are trying to execute your packages using Visual Studio then the configuration file path will be hardcoded in there. So if you move your project around you'll need to change the path in the package settings. To avoid this you could use the Environment variable option to store the configuration file path. Then you'll only need to change that.</p>\n<p>For testing and deployment however you should probably use the dtexec utility to execute your packages. Make some batch files for that. Preferably one for each different environment. Here the configuration file path can be relative.</p>\n<pre><code>dtexec /File Package.dtsx /Conf configuration.dtsConfig\n</code></pre>\n<p>This is if you're packages are on file system. You can also store them in SQL Server. You can also store your configuration in SQL Server which may provide flexibility.</p>\n"
},
{
"answer_id": 10531456,
"author": "Thea",
"author_id": 327771,
"author_profile": "https://Stackoverflow.com/users/327771",
"pm_score": 2,
"selected": false,
"text": "<p>After several hours trying to make this work I found a solution <a href=\"https://web.archive.org/web/20180620162930/http://www.beyeblogs.com/rda_corp/archive/2010/02/errors_locating.php\" rel=\"nofollow noreferrer\">here</a> (not the best one, but it works) </p>\n\n<ol>\n<li>Locate your configuration files (dtsconfig files) in the same directory as your solution file (.sln file)</li>\n<li>ALWAYS open your solution by double-clicking the solution file (.sln file). This will set the ‘working folder’ to be where the solution lives, your configuration file will be read correctly</li>\n</ol>\n\n<p>Otherwise the relative paths did not work for me.</p>\n"
},
{
"answer_id": 10662642,
"author": "Debarchan",
"author_id": 1404702,
"author_profile": "https://Stackoverflow.com/users/1404702",
"pm_score": 1,
"selected": false,
"text": "<p>Check out the free utility that can edit SSIS configuration file paths without BIDS:\n<a href=\"http://ssisconfigeditor.codeplex.com/\" rel=\"nofollow\">http://ssisconfigeditor.codeplex.com/</a></p>\n"
},
{
"answer_id": 19417144,
"author": "Mick",
"author_id": 342669,
"author_profile": "https://Stackoverflow.com/users/342669",
"pm_score": 0,
"selected": false,
"text": "<p>My stock standard trick for these sorts of problems are mapping drives.</p>\n\n<p>Either by using a <a href=\"http://windows.microsoft.com/en-au/windows-vista/create-a-shortcut-to-map-a-network-drive\" rel=\"nofollow\">mapped network drive</a> or by using <a href=\"http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/subst.mspx?mfr=true\" rel=\"nofollow\">Subst</a> (both methods are interchangable).</p>\n\n<p>e.g. Map the location of your package to N:\\ then inside your package use paths using N:\\MyParentPackage.dtsx, N:\\MyChildPackage.dtsx. The packages can be on totally different drives in different folders on different machines, it'll work once you map the package location to the N:\\</p>\n\n<p>I usually put a script along side the project files to map the drive, which maps the drive so it can be easily run before. One gotcha, if you're using subst on VISTA - Win8, map it for elevated and non-elevated.</p>\n\n<p>I use the same approach for file references in Visual Studio projects. Only issue with this approach, you use to solve too many issues in your dev environment and you'll run out of drives letters.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233434",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12915/"
] |
I am trying to make our SQL Server Integration Services packages as portable as possible and the one thing that is preventing that is that the path to the config is always an absolute path, which makes testing and deployment a headache. Are there any suggestions for making this more manageble?
Another issue is when another developer gets the package out of source control the path is specific to the developers machine.
|
If you are trying to execute your packages using Visual Studio then the configuration file path will be hardcoded in there. So if you move your project around you'll need to change the path in the package settings. To avoid this you could use the Environment variable option to store the configuration file path. Then you'll only need to change that.
For testing and deployment however you should probably use the dtexec utility to execute your packages. Make some batch files for that. Preferably one for each different environment. Here the configuration file path can be relative.
```
dtexec /File Package.dtsx /Conf configuration.dtsConfig
```
This is if you're packages are on file system. You can also store them in SQL Server. You can also store your configuration in SQL Server which may provide flexibility.
|
233,455 |
<p>I am making a program in C# to connect to a webcam and do some image manipulation with it.</p>
<p>I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.</p>
<p>This is the code I use to connect the webcam:</p>
<pre><code>mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, 320, 240, 1024, 0);
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
</code></pre>
<p>And this is what I use to copy the image to the clipboard:</p>
<pre><code>SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
tempObj = Clipboard.GetDataObject();
tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
</code></pre>
<p>There's some error checking which I have removed from the code to make it shorter.</p>
|
[
{
"answer_id": 233854,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried Clipboard.GetImage()? You could also try the various Clipboard.Contains*() methods to see what format the data is stored in the clipboard.</p>\n"
},
{
"answer_id": 234423,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 5,
"selected": true,
"text": "<p>I've recently started doing some hobby work in this area.</p>\n\n<p>We settled on using the <a href=\"http://sourceforge.net/projects/opencv/\" rel=\"noreferrer\">OpenCV</a> library with the <a href=\"http://code.google.com/p/opencvdotnet/\" rel=\"noreferrer\">opencvdotnet</a> wrapper. It supports capturing frames from a webcam:</p>\n\n<pre><code>using (var cv = new OpenCVDotNet.CVCapture(0))\n{\n var image = cv.CreateCompatibleImage();\n // ...\n cv.Release();\n}\n</code></pre>\n\n<p>And if you're doing image manipulation, OpenCV's image processing algorithms have been wrapped within the OpenCVDotNet.Algs assembly.</p>\n\n<p>If you decide to go this route be sure to install OpenCV version 1.0 (and install it to \"c:\\program files\\opencv\" if you are on Vista 64-bit, or \"mklink OpenCV 'c:\\program files (x86)\\OpenCV`\" from the correct directory or else opencvdotnet will not install).</p>\n"
},
{
"answer_id": 234694,
"author": "ctacke",
"author_id": 13154,
"author_profile": "https://Stackoverflow.com/users/13154",
"pm_score": 3,
"selected": false,
"text": "<p>There are really two ways to get camera data into your application, DirectShow and WIA. Microsoft recommends that you use <a href=\"http://msdn.microsoft.com/en-us/library/ms630368.aspx\" rel=\"noreferrer\">WIA</a>, and the interface for WIA is fairly simple to wrap your brain around. I created and published an open source <a href=\"http://blog.opennetcf.com/ctacke/2007/12/21/WIADesktopLibrary.aspx\" rel=\"noreferrer\">WIA desktop library</a> based on work I did a while ago.</p>\n\n<p>Now the problem with WIA in some cases is that it's too simple. For example, if you want to adjust camera properties (like frame rate, resolution, etc) then WIA falls down. Microsoft deprecated DirectShow, but they really didn't give us any replacement that has all of its capabilities, and I've found that it continues to work fine on all existing platforms (it's very entrenched, so I can't imagine support going away any time soon).</p>\n\n<p>There is a very good <a href=\"http://directshownet.sourceforge.net/\" rel=\"noreferrer\">DirectShow library over at SourceForge</a>. The only \"problem\" with it is it's really complex and that stems from the fact that DShow is just so damned complex and confusing in the first place. There are lots of things that the wrapper can do that just aren't easy to work out, but they do provide samples for a lot of common use cases like showing video or capturing a frame. If you want to add overlays, or insert other filters, it can do it, but be forewarned that it's not at all straightforward.</p>\n"
},
{
"answer_id": 4130339,
"author": "nikib3ro",
"author_id": 237858,
"author_profile": "https://Stackoverflow.com/users/237858",
"pm_score": 2,
"selected": false,
"text": "<p>Take a look at this article:\n<a href=\"http://www.codeproject.com/KB/miscctrl/webcam_c_sharp.aspx\" rel=\"nofollow\">http://www.codeproject.com/KB/miscctrl/webcam_c_sharp.aspx</a></p>\n\n<p>It is way too simpler than installing and using OpenCVNetWrapper.</p>\n"
},
{
"answer_id": 5007060,
"author": "Shachar Weis",
"author_id": 233001,
"author_profile": "https://Stackoverflow.com/users/233001",
"pm_score": 0,
"selected": false,
"text": "<p>OpenCV capture, EMGU capture and all other capture libraries I have tried<br>\nall have the same problem: You cannot go higher than 640x480 programatically<br>\n(without opening the windows video source window).<br></p>\n\n<p>I suggest using this (which does work):<br>\n<a href=\"https://github.com/ofTheo/videoInput\" rel=\"nofollow\">https://github.com/ofTheo/videoInput</a></p>\n"
},
{
"answer_id": 11665781,
"author": "Fredrik Johansson",
"author_id": 325874,
"author_profile": "https://Stackoverflow.com/users/325874",
"pm_score": 0,
"selected": false,
"text": "<p>This was also asked in <a href=\"https://stackoverflow.com/questions/2881858/how-to-get-web-cam-images-in-c\">How to get web cam images in C#?</a> and you might find the following useful (Sorry for spamming, but this really helps answering the question):</p>\n\n<p>I've just released the complete sourcecode of my Windows app CamTimer (written in .NET/C#). Download/view the complete code (with working Webcam examples) at <a href=\"https://github.com/johanssonrobotics/CamTimer\" rel=\"nofollow noreferrer\">https://github.com/johanssonrobotics/CamTimer</a></p>\n\n<p>Happy coding!</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233455",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31151/"
] |
I am making a program in C# to connect to a webcam and do some image manipulation with it.
I have a working application that uses win32 api (avicap32.dll) to connect to the webcam and send messages to it that sends it to the clipboard. The problem is that, while accessible from paint, reading it from the program results in null pointers.
This is the code I use to connect the webcam:
```
mCapHwnd = capCreateCaptureWindowA("WebCap", 0, 0, 0, 320, 240, 1024, 0);
SendMessage(mCapHwnd, WM_CAP_CONNECT, 0, 0);
SendMessage(mCapHwnd, WM_CAP_SET_PREVIEW, 0, 0);
```
And this is what I use to copy the image to the clipboard:
```
SendMessage(mCapHwnd, WM_CAP_GET_FRAME, 0, 0);
SendMessage(mCapHwnd, WM_CAP_COPY, 0, 0);
tempObj = Clipboard.GetDataObject();
tempImg = (System.Drawing.Bitmap)tempObj.GetData(System.Windows.Forms.DataFormats.Bitmap);
```
There's some error checking which I have removed from the code to make it shorter.
|
I've recently started doing some hobby work in this area.
We settled on using the [OpenCV](http://sourceforge.net/projects/opencv/) library with the [opencvdotnet](http://code.google.com/p/opencvdotnet/) wrapper. It supports capturing frames from a webcam:
```
using (var cv = new OpenCVDotNet.CVCapture(0))
{
var image = cv.CreateCompatibleImage();
// ...
cv.Release();
}
```
And if you're doing image manipulation, OpenCV's image processing algorithms have been wrapped within the OpenCVDotNet.Algs assembly.
If you decide to go this route be sure to install OpenCV version 1.0 (and install it to "c:\program files\opencv" if you are on Vista 64-bit, or "mklink OpenCV 'c:\program files (x86)\OpenCV`" from the correct directory or else opencvdotnet will not install).
|
233,467 |
<p>I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).</p>
<p>What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.</p>
<p>I know that <code><a href="url" target="_blank"></code> is out. I also know that <code><a href="#" onclick="window.open(url);"></code> isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like <code><span onclick="window.open(url);"></code> and then style the SPAN to look like a link.</p>
<p>One solution I'm leaning towards is <code><a href="url" rel="external"></code> and using JavaScript to set all targets to '_blank' on those anchors marked 'external'.</p>
<p>Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.</p>
<p>UPDATE: I say target="_blank" is a no no, because I've read in <a href="http://www.sitepoint.com/article/standards-compliant-world/3/" rel="noreferrer">several places</a> that the target attribute is going to be phased out of XHTML.</p>
|
[
{
"answer_id": 233477,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 4,
"selected": false,
"text": "<p>Why is <code>target=\"_blank\"</code> a bad idea?</p>\n\n<p>It's supposed to do exactly what you want.</p>\n\n<p>edit: (see comments) point taken, but I do think that using javascript to do such a task can lead to having some people quite upset (those who middle click to open on a new window by habit, and those who use a NoScript extension)</p>\n"
},
{
"answer_id": 233482,
"author": "BoboTheCodeMonkey",
"author_id": 30532,
"author_profile": "https://Stackoverflow.com/users/30532",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps I'm misunderstanding something but why don't you want to use target=\"_blank\"? That's the way I would do it. If you're looking for the most compatible, then any sort of JavaScript would be out as you can't be sure that the client has JS enabled.</p>\n"
},
{
"answer_id": 233495,
"author": "Mark S. Rasmussen",
"author_id": 12469,
"author_profile": "https://Stackoverflow.com/users/12469",
"pm_score": 1,
"selected": false,
"text": "<pre><code><a href=\"http://www.google.com\" onclick=\"window.open(this.href); return false\">\n</code></pre>\n\n<p>This will still open the link (albeit in the same window) if the user has JS disabled. Otherwise it works exactly like target=blank, and it's easy to use as you just have to append the onclick function (perhaps by using JQuery) to all normal tags.</p>\n"
},
{
"answer_id": 233503,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 6,
"selected": true,
"text": "<p>I am using the last method you proposed. I add rel=\"external\" or something similar and then use jQuery to iterate through all links and assign them a click handler:</p>\n\n<pre><code>$(document).ready(function() {\n $('a[rel*=external]').click(function(){\n window.open($(this).attr('href'));\n return false; \n });\n});\n</code></pre>\n\n<p>I find this the best method because:</p>\n\n<ul>\n<li>it is very clear semantically: you have a link to an external resource</li>\n<li>it is standards-compliant</li>\n<li>it degrades gracefully (you have a very simple link with regular <code>href</code> attribute)</li>\n<li>it still allows user to middle-click the link and open it in new tab if they wish</li>\n</ul>\n"
},
{
"answer_id": 233658,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>If you use any flavor of strict doctype or the coming real xhtml-flavors, target isn't allowed ...</p>\n\n<p>Using transitional, whatever being HTML4.01 or XHTML1, you can use Damirs solution, though it fails to implement the windowName-property which is necessary in window.open():</p>\n\n<p>In plain html:</p>\n\n<pre><code><a href=\"...\" target=\"_blank\" onclick=\"window.open(this.href, 'newWin'); return false;\">link</a>\n</code></pre>\n\n<p>If however you use one of the strict doctypes your only way of opening links would be to use this solution without the target-attribute ...</p>\n\n<p>-- by the way, the number of non-js-browsers is often miscalculated, looking up the counters numbers refer very different numbers, and I'm wondering how many of those non-js-browsers is crawlers and the like !-)</p>\n"
},
{
"answer_id": 233809,
"author": "Shadow2531",
"author_id": 1697,
"author_profile": "https://Stackoverflow.com/users/1697",
"pm_score": 0,
"selected": false,
"text": "<p>If I'm on a form page and clicking on a moreinfo.html link (for example) causes me to lose data unless I open it in a new tab/window, just tell me.</p>\n\n<p>You can trick me in to opening a new tab/window with window.open() or target=\"_blank\", but I might have targets and pop-ups disabled. If JS, targets and pop-ups are required for you to trick me into opening a new window/tab, tell me before I get started on the form.</p>\n\n<p>Or, make links to another page a form request, so that when the visitor submits, the current form data is saved so they can continue from last time, if possible.</p>\n"
},
{
"answer_id": 236037,
"author": "Fczbkk",
"author_id": 22920,
"author_profile": "https://Stackoverflow.com/users/22920",
"pm_score": 2,
"selected": false,
"text": "<pre><code><a href=\"http://some.website.com/\" onclick=\"return !window.open( this.href );\">link text</a>\n</code></pre>\n\n<p>Details are described in my <a href=\"https://stackoverflow.com/questions/134845/href-for-javascript-links-or-javascriptvoid0#143410\">answer to another question</a>.</p>\n"
},
{
"answer_id": 236080,
"author": "Mnementh",
"author_id": 21005,
"author_profile": "https://Stackoverflow.com/users/21005",
"pm_score": 4,
"selected": false,
"text": "<p>Please, <strong>don't force</strong> opening a link in a new window.</p>\n\n<p>Reasons against it:</p>\n\n<ul>\n<li>It infringes the rule of the least astonishment.</li>\n<li>The back-button don't work and the user not possibly knows why.</li>\n<li>What happen in tabbed browsers? New tab or new window? And whichever happens, is it what you wants, if you mix tabs and windows?</li>\n</ul>\n\n<p>The reason I always hear in favor of opening a new window is that the user will not leave the site. But be sure, I will never come back to a site that annoys me. And if the site takes away control from me, that is a big annoyance.</p>\n\n<p>A way may be, that you give two links, one is normal, the other opens it in a new window. Add the second with a little symbol after the normal link. This way users of your site stay in control of which link they want to click on.</p>\n"
},
{
"answer_id": 1107714,
"author": "alex",
"author_id": 31671,
"author_profile": "https://Stackoverflow.com/users/31671",
"pm_score": 3,
"selected": false,
"text": "<p>Here is a plugin I wrote for jQuery</p>\n\n<pre><code> (function($){ \n $.fn.newWindow = function(options) { \n var defaults = {\n titleText: 'Link opens in a new window' \n };\n\n options = $.extend(defaults, options);\n\n return this.each(function() { \n var obj = $(this);\n\n if (options.titleText) { \n if (obj.attr('title')) {\n var newTitle = obj.attr('title') + ' (' \n + options.titleText + ')';\n } else {\n var newTitle = options.titleText;\n }; \n obj.attr('title', newTitle); \n }; \n\n obj.click(function(event) {\n event.preventDefault(); \n var newBlankWindow = window.open(obj.attr('href'), '_blank');\n newBlankWindow.focus();\n }); \n }); \n }; \n })(jQuery); \n</code></pre>\n\n<p><strong>Example Usage</strong></p>\n\n<pre><code>$('a[rel=external]').newWindow();\n</code></pre>\n\n<p>You can also change, or remove the title text, by passing in some options</p>\n\n<p>Example to change title text:</p>\n\n<pre><code>$('a[rel=external]').newWindow( { titleText: 'This is a new window link!' } );\n</code></pre>\n\n<p>Example to remove it alltogether</p>\n\n<pre><code>$('a[rel=external]').newWindow( { titleText: '' } );\n</code></pre>\n"
},
{
"answer_id": 3366946,
"author": "Mac",
"author_id": 406196,
"author_profile": "https://Stackoverflow.com/users/406196",
"pm_score": 0,
"selected": false,
"text": "<p>I use this...</p>\n\n<pre><code>$(function() {\n $(\"a:not([href^='\"+window.location.hostname+\"'])\").click(function(){\n window.open(this.href);\n return false;\n }).attr(\"title\", \"Opens in a new window\");\n});\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233467",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22303/"
] |
I know that most links should be left up to the end-user to decide how to open, but we can't deny that there are times you almost 'have to' force into a new window (for example to maintain data in a form on the current page).
What I'd like to know is what the consensus is on the 'best' way to open a link in a new browser window.
I know that `<a href="url" target="_blank">` is out. I also know that `<a href="#" onclick="window.open(url);">` isn't ideal for a variety of reasons. I've also tried to completely replace anchors with something like `<span onclick="window.open(url);">` and then style the SPAN to look like a link.
One solution I'm leaning towards is `<a href="url" rel="external">` and using JavaScript to set all targets to '\_blank' on those anchors marked 'external'.
Are there any other ideas? What's better? I'm looking for the most XHTML-compliant and easiest way to do this.
UPDATE: I say target="\_blank" is a no no, because I've read in [several places](http://www.sitepoint.com/article/standards-compliant-world/3/) that the target attribute is going to be phased out of XHTML.
|
I am using the last method you proposed. I add rel="external" or something similar and then use jQuery to iterate through all links and assign them a click handler:
```
$(document).ready(function() {
$('a[rel*=external]').click(function(){
window.open($(this).attr('href'));
return false;
});
});
```
I find this the best method because:
* it is very clear semantically: you have a link to an external resource
* it is standards-compliant
* it degrades gracefully (you have a very simple link with regular `href` attribute)
* it still allows user to middle-click the link and open it in new tab if they wish
|
233,468 |
<p>I have a number of custom controls that I am trying to enable designer support for. The signature looks something like the following:</p>
<pre><code>[ToolboxData("<{0}:MyDropDownList runat=\"server\" CustomProp="123"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
... code here
}
</code></pre>
<p>This works fine, but when I drag a control onto the page from the toolbox, the TagPrefix that gets added is "cc1":</p>
<pre><code><%@ Register Assembly="DBMClientPortal.Controls" Namespace="DBMClientPortal.Controls"
TagPrefix="cc1" %>
</code></pre>
<p>Obviously it is somewhat irrelevant what that TagPrefix is... it works as it stands, but I figured I <em>must</em> be able to change it somehow and curiosity got the better of me...</p>
<p>Anyone know how to define what the TagPrefix will be set to when dragging a custom control onto a page in visual studio?</p>
<p>Thanks,
Max</p>
|
[
{
"answer_id": 233484,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 4,
"selected": true,
"text": "<p>It looks something like this:</p>\n\n<pre><code>[assembly:TagPrefix(\"MyControls\",\"RequiredTextBox\")]\n</code></pre>\n\n<p>and <a href=\"http://msdn.microsoft.com/en-us/library/system.web.ui.tagprefixattribute.tagprefixattribute.aspx\" rel=\"noreferrer\">here's</a> some more info about it.</p>\n"
},
{
"answer_id": 238881,
"author": "Eilon",
"author_id": 31668,
"author_profile": "https://Stackoverflow.com/users/31668",
"pm_score": 1,
"selected": false,
"text": "<p>FYI, the TagPrefix attribute is only a <em>suggestion</em> to Visual Studio and other designer tools. If the user already has your namespace registered to a different tag prefix then it is free to use that tag prefix. Also, if your suggested tag prefix is already in use and points to a different namespace, the Visual Studio will use an auto-generated tag prefix instead.</p>\n\n<p>However, the odds of either one of those happening is fairly small if you choose a tag prefix that is based on your product's or company's name.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233468",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29662/"
] |
I have a number of custom controls that I am trying to enable designer support for. The signature looks something like the following:
```
[ToolboxData("<{0}:MyDropDownList runat=\"server\" CustomProp="123"></{0}:MyDropDownList>")]
public class MyDropDownList: DropDownList
{
... code here
}
```
This works fine, but when I drag a control onto the page from the toolbox, the TagPrefix that gets added is "cc1":
```
<%@ Register Assembly="DBMClientPortal.Controls" Namespace="DBMClientPortal.Controls"
TagPrefix="cc1" %>
```
Obviously it is somewhat irrelevant what that TagPrefix is... it works as it stands, but I figured I *must* be able to change it somehow and curiosity got the better of me...
Anyone know how to define what the TagPrefix will be set to when dragging a custom control onto a page in visual studio?
Thanks,
Max
|
It looks something like this:
```
[assembly:TagPrefix("MyControls","RequiredTextBox")]
```
and [here's](http://msdn.microsoft.com/en-us/library/system.web.ui.tagprefixattribute.tagprefixattribute.aspx) some more info about it.
|
233,491 |
<p>Specifically, I currently have a JPanel with a TitledBorder. I want to customize the look of the border. In my app's current state, the title is drawn, but not the line border itself.</p>
<p>If I bind an imagePainter to the panelBorder method for Panel objects, I can put a custom image around panels -- however it only shows up on those panels that I haven't explicitly set the border on in the code. Here's what that code looks like:</p>
<pre><code><style id="PanelStyle">
<state>
<imagePainter method="panelBorder" path="images/thick border.png" sourceInsets="3 3 3 3" />
</state>
</style>
<bind style="PanelStyle" type="region" key="Panel" />
</code></pre>
<p>How can I do the opposite -- that is, make this custom image only show up on panels I've applied a TitledBorder to?</p>
<p>I have also tried using a named panel:</p>
<pre><code>panel.setName("MyPanel")
</code></pre>
<p>and a name binding:</p>
<pre><code><bind style="PanelStyle" type="name" key="MyPanel">
</code></pre>
<p>This allows me to change the style of only particular panels, which is good. However, it does not solve the original problem: I still can't customize my panel's NamedBorder.</p>
<p>If I specify a NamedBorder, my PanelBorder painter is ignored, and just the name is printed. If I take away my NamedBorder, I <i>can</i> use my custom border graphic, but then I have to poke and prod my layout to get a JLabel in the same place that the title was previously, which is undesirable.</p>
<p>Further research has uncovered that the reason there is no rendered line is that TitledBorder's constructor takes an argument of another Border, which it renders in addition to the title. I was not passing this argument, and the default depends on your selected L&F. Back when I was using the System L&F, the default was a LineBorder. Apparently Synth's default is an EmptyBorder. Explicitly specifying the LineBorder gets me the line back, which solves most of my problem.</p>
<p>The rest of my problem involves using a custom graphic for the LineBorder. For now I'm getting by rendering my custom graphic as a second PanelBackground image -- it gets composited on top of the actual background and achieves the desired visual effect, though it's not the ideal implementation.</p>
|
[
{
"answer_id": 279305,
"author": "SpooneyDinosaur",
"author_id": 22386,
"author_profile": "https://Stackoverflow.com/users/22386",
"pm_score": 1,
"selected": false,
"text": "<p>Specify the name of the component you want to apply the special style to, not the region:</p>\n\n<pre><code><bind style=\"PanelStyle\" type=\"name\" key=\"mySpecialPanel\" />\n</code></pre>\n\n<p>In your Java code, you'll need to set the component's name to match the name you supplied in the XML:</p>\n\n<pre><code>panel.setName(\"mySpecialPanel\");\n</code></pre>\n\n<p>You might consider extending JPanel so that all panels have the same name:</p>\n\n<pre><code>public class MySpecialPanel extends JPanel \n{ \n public MySpecialPanel(String title) \n {\n super(title);\n this.setName(\"mySpecialPanel\"); \n } \n}\n</code></pre>\n"
},
{
"answer_id": 1118556,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>We had the same problem. Of course your workaround (which you described above) works but it is not a solution.</p>\n\n<p>The workaround we used is:</p>\n\n<p>Instead of:</p>\n\n<pre><code>BorderFactory.createTitledBorder(\"title\");\n</code></pre>\n\n<p>You should use:</p>\n\n<pre><code>Border objBorder = BorderFactory.createLineBorder(Color.black); \n//Also you can create all the rest of the borders here.\nBorderFactory.createTitledBorder(objBorder, \"title\");\n</code></pre>\n"
},
{
"answer_id": 1345420,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>ha, got the reason.\n From TitledBorder.getBorder, if synth look and feel is used. TitledBorder.border should be defined in the xml file.</p>\n\n<pre><code>public Border getBorder() { \n Border b = border;\nif (b == null)\n b = UIManager.getBorder(\"TitledBorder.border\");\n return b; \n}\n</code></pre>\n\n<p>so my answer is:</p>\n\n<pre><code><object id=\"TitledBorder_Color\" class=\"java.awt.Color\">\n <int>140</int>\n\n <int>125</int>\n\n <int>100</int>\n\n <int>255</int>\n </object>\n\n <object id=\"LineBorder\" class=\"javax.swing.border.LineBorder\">\n <object idref=\"TitledBorder_Color\"/>\n </object>\n\n <defaultsProperty key=\"TitledBorder.border\" type=\"idref\" value=\"LineBorder\"/>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7161/"
] |
Specifically, I currently have a JPanel with a TitledBorder. I want to customize the look of the border. In my app's current state, the title is drawn, but not the line border itself.
If I bind an imagePainter to the panelBorder method for Panel objects, I can put a custom image around panels -- however it only shows up on those panels that I haven't explicitly set the border on in the code. Here's what that code looks like:
```
<style id="PanelStyle">
<state>
<imagePainter method="panelBorder" path="images/thick border.png" sourceInsets="3 3 3 3" />
</state>
</style>
<bind style="PanelStyle" type="region" key="Panel" />
```
How can I do the opposite -- that is, make this custom image only show up on panels I've applied a TitledBorder to?
I have also tried using a named panel:
```
panel.setName("MyPanel")
```
and a name binding:
```
<bind style="PanelStyle" type="name" key="MyPanel">
```
This allows me to change the style of only particular panels, which is good. However, it does not solve the original problem: I still can't customize my panel's NamedBorder.
If I specify a NamedBorder, my PanelBorder painter is ignored, and just the name is printed. If I take away my NamedBorder, I *can* use my custom border graphic, but then I have to poke and prod my layout to get a JLabel in the same place that the title was previously, which is undesirable.
Further research has uncovered that the reason there is no rendered line is that TitledBorder's constructor takes an argument of another Border, which it renders in addition to the title. I was not passing this argument, and the default depends on your selected L&F. Back when I was using the System L&F, the default was a LineBorder. Apparently Synth's default is an EmptyBorder. Explicitly specifying the LineBorder gets me the line back, which solves most of my problem.
The rest of my problem involves using a custom graphic for the LineBorder. For now I'm getting by rendering my custom graphic as a second PanelBackground image -- it gets composited on top of the actual background and achieves the desired visual effect, though it's not the ideal implementation.
|
Specify the name of the component you want to apply the special style to, not the region:
```
<bind style="PanelStyle" type="name" key="mySpecialPanel" />
```
In your Java code, you'll need to set the component's name to match the name you supplied in the XML:
```
panel.setName("mySpecialPanel");
```
You might consider extending JPanel so that all panels have the same name:
```
public class MySpecialPanel extends JPanel
{
public MySpecialPanel(String title)
{
super(title);
this.setName("mySpecialPanel");
}
}
```
|
233,504 |
<p>I am trying to programatically set the dpi metadata of an jpeg image in Java. The source of the image is a scanner, so I get the horizontal/vertical resolution from TWAIN, along with the image raw data. I'd like to save this info for better print results.</p>
<p>Here's the code I have so far. It saves the raw image (byteArray) to a JPEG file, but it ignores the X/Ydensity information I specify via IIOMetadata. Any advice what I'm doing wrong? </p>
<p>Any other solution (third-party library, etc) would be welcome too. </p>
<pre><code>import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream
import org.w3c.dom.Element;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
public boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file)
{
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster wr = bufferedImage.getRaster();
wr.setPixels(0, 0, width, height, byteArray);
try
{
// Image writer
JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file));
imageWriter.setOutput(ios);
// Compression
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(0.85f);
// Metadata (dpi)
IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams);
Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
jfif.setAttribute("resUnits", "1"); // density is dots per inch
// Write and clean up
imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams);
ios.close();
imageWriter.dispose();
}
catch (Exception e)
{
return false;
}
return true;
}
</code></pre>
<p>Thanks!</p>
|
[
{
"answer_id": 234142,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 2,
"selected": false,
"text": "<p>I would seem this could be a bug. </p>\n\n<p>I found this post <a href=\"http://www.velocityreviews.com/forums/t360709-imageio-iiometadatasetfromtree-cripples-data.html\" rel=\"nofollow noreferrer\">from a few google searches</a></p>\n\n<p>Apparently there are alot more that point to a bug as well.</p>\n\n<p>The post above talks about using JMagick as a third party work around. </p>\n"
},
{
"answer_id": 1276894,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": true,
"text": "<p>Some issues that were not considered here:</p>\n\n<ol>\n<li><p>The tree is not directly mapped to the IOMetaData. To apply data from tree, add following call after setting the densities and raster parameters:</p>\n\n<pre><code>data.setFromTree(\"javax_imageio_jpeg_image_1.0\", tree);\n</code></pre></li>\n<li><p>don't use the meta data as first parameter in the write call. See <code>JPEGImageWriter#write(IIOMetaData, IIOImage, ImageWriteParam)</code>. If streamMetaData is not NULL, a warning (WARNING_STREAM_METADATA_IGNORED) will be generated.</p></li>\n<li><p>set the meta data as <code>IOMetadata</code> of the <code>IOImage</code>. These meta data are used by JPEGImageWriter. The correct write call then is</p>\n\n<pre><code>imageWriter.write(null, new IIOImage(F_scaledImg, null, data), jpegParams);\n</code></pre></li>\n</ol>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31155/"
] |
I am trying to programatically set the dpi metadata of an jpeg image in Java. The source of the image is a scanner, so I get the horizontal/vertical resolution from TWAIN, along with the image raw data. I'd like to save this info for better print results.
Here's the code I have so far. It saves the raw image (byteArray) to a JPEG file, but it ignores the X/Ydensity information I specify via IIOMetadata. Any advice what I'm doing wrong?
Any other solution (third-party library, etc) would be welcome too.
```
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.File;
import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream
import org.w3c.dom.Element;
import com.sun.imageio.plugins.jpeg.JPEGImageWriter;
public boolean saveJpeg(int[] byteArray, int width, int height, int dpi, String file)
{
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
WritableRaster wr = bufferedImage.getRaster();
wr.setPixels(0, 0, width, height, byteArray);
try
{
// Image writer
JPEGImageWriter imageWriter = (JPEGImageWriter) ImageIO.getImageWritersBySuffix("jpeg").next();
ImageOutputStream ios = ImageIO.createImageOutputStream(new File(file));
imageWriter.setOutput(ios);
// Compression
JPEGImageWriteParam jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
jpegParams.setCompressionQuality(0.85f);
// Metadata (dpi)
IIOMetadata data = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), jpegParams);
Element tree = (Element)data.getAsTree("javax_imageio_jpeg_image_1.0");
Element jfif = (Element)tree.getElementsByTagName("app0JFIF").item(0);
jfif.setAttribute("Xdensity", Integer.toString(dpi));
jfif.setAttribute("Ydensity", Integer.toString(dpi));
jfif.setAttribute("resUnits", "1"); // density is dots per inch
// Write and clean up
imageWriter.write(data, new IIOImage(bufferedImage, null, null), jpegParams);
ios.close();
imageWriter.dispose();
}
catch (Exception e)
{
return false;
}
return true;
}
```
Thanks!
|
Some issues that were not considered here:
1. The tree is not directly mapped to the IOMetaData. To apply data from tree, add following call after setting the densities and raster parameters:
```
data.setFromTree("javax_imageio_jpeg_image_1.0", tree);
```
2. don't use the meta data as first parameter in the write call. See `JPEGImageWriter#write(IIOMetaData, IIOImage, ImageWriteParam)`. If streamMetaData is not NULL, a warning (WARNING\_STREAM\_METADATA\_IGNORED) will be generated.
3. set the meta data as `IOMetadata` of the `IOImage`. These meta data are used by JPEGImageWriter. The correct write call then is
```
imageWriter.write(null, new IIOImage(F_scaledImg, null, data), jpegParams);
```
|
233,553 |
<p>I have a very simple jQuery Datepicker calendar:</p>
<pre><code>$(document).ready(function(){
$("#date_pretty").datepicker({
});
});
</code></pre>
<p>and of course in the HTML...</p>
<pre><code><input type="text" size="10" value="" id="date_pretty"/>
</code></pre>
<p>Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.</p>
|
[
{
"answer_id": 233654,
"author": "lucas",
"author_id": 31172,
"author_profile": "https://Stackoverflow.com/users/31172",
"pm_score": 6,
"selected": false,
"text": "<pre><code>var myDate = new Date();\nvar prettyDate =(myDate.getMonth()+1) + '/' + myDate.getDate() + '/' +\n myDate.getFullYear();\n$(\"#date_pretty\").val(prettyDate);\n</code></pre>\n\n<p>seemed to work, but there might be a better way out there..</p>\n"
},
{
"answer_id": 233752,
"author": "Marcus",
"author_id": 26848,
"author_profile": "https://Stackoverflow.com/users/26848",
"pm_score": 3,
"selected": false,
"text": "<p>The solution is:</p>\n\n<pre><code>$(document).ready(function(){\n $(\"#date_pretty\").datepicker({ \n });\n var myDate = new Date();\n var month = myDate.getMonth() + 1;\n var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();\n $(\"#date_pretty\").val(prettyDate);\n});\n</code></pre>\n\n<p>Thanks grayghost!</p>\n"
},
{
"answer_id": 397907,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<pre><code>$(function()\n{\n$('.date-pick').datePicker().val(new Date().asString()).trigger('change');\n});\n</code></pre>\n\n<p>Source: <a href=\"http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html\" rel=\"nofollow noreferrer\">http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/datePickerDefaultToday.html</a></p>\n"
},
{
"answer_id": 2325607,
"author": "CiscoIPPhone",
"author_id": 70365,
"author_profile": "https://Stackoverflow.com/users/70365",
"pm_score": 10,
"selected": true,
"text": "<p><strong>Update: There are reports this no longer works in Chrome.</strong></p>\n\n<p>This is concise and does the job (obsolete):</p>\n\n<pre><code>$(\".date-pick\").datepicker('setDate', new Date());\n</code></pre>\n\n<p>This is less concise, utilizing <a href=\"https://www.w3schools.com/jquery/jquery_chaining.asp\" rel=\"noreferrer\">chaining</a> allows it to work in chrome (2019-06-04):</p>\n\n<pre><code>$(\".date-pick\").datepicker().datepicker('setDate', new Date());\n</code></pre>\n"
},
{
"answer_id": 3515662,
"author": "Jeff Girard",
"author_id": 424420,
"author_profile": "https://Stackoverflow.com/users/424420",
"pm_score": 3,
"selected": false,
"text": "<p>This code will assure to use your datepicker's format:</p>\n\n<pre><code>$('#date-selector').datepicker('setDate', new Date());\n</code></pre>\n\n<p>No need to re-apply format, it uses the datepicker predefined-one by you on datepicker initialization (if you have assigned it!) ;)</p>\n"
},
{
"answer_id": 4714808,
"author": "gmail user",
"author_id": 344394,
"author_profile": "https://Stackoverflow.com/users/344394",
"pm_score": 0,
"selected": false,
"text": "<pre><code>var prettyDate = $.datepicker.formatDate('dd-M-yy', new Date());\nalert(prettyDate);\n</code></pre>\n\n<p>Assign the prettyDate to the necessary control.</p>\n"
},
{
"answer_id": 5014025,
"author": "quocnguyen",
"author_id": 619263,
"author_profile": "https://Stackoverflow.com/users/619263",
"pm_score": 2,
"selected": false,
"text": "<pre><code>$('input[name*=\"date\"]').datepicker({\n dateFormat: 'dd-mm-yy',\n changeMonth: true,\n changeYear: true,\n beforeShow: function(input, instance) { \n $(input).datepicker('setDate', new Date());\n }\n });\n</code></pre>\n"
},
{
"answer_id": 8945264,
"author": "Ravi Ram",
"author_id": 665387,
"author_profile": "https://Stackoverflow.com/users/665387",
"pm_score": 8,
"selected": false,
"text": "<p>You must FIRST call datepicker() > <strong>then</strong> use 'setDate' to get the current date.</p>\n\n<pre><code>$(\".date-pick\").datepicker();\n$(\".date-pick\").datepicker(\"setDate\", new Date());\n</code></pre>\n\n<p>OR chain your setDate method call after your datepicker initialization, as noted in a comment on this answer </p>\n\n<pre><code>$('.date-pick').datepicker({ /* optional option parameters... */ })\n .datepicker(\"setDate\", new Date());\n</code></pre>\n\n<p>It will <strong>NOT</strong> work with just </p>\n\n<pre><code>$(\".date-pick\").datepicker(\"setDate\", new Date());\n</code></pre>\n\n<p><em><strong>NOTE</em></strong> : <em>Acceptable setDate parameters are described <a href=\"http://api.jqueryui.com/datepicker/#method-setDate\">here</a></em></p>\n"
},
{
"answer_id": 11172015,
"author": "KirilleXXI",
"author_id": 1247342,
"author_profile": "https://Stackoverflow.com/users/1247342",
"pm_score": 5,
"selected": false,
"text": "<p>Set to <strong><em>today</em></strong>:</p>\n\n<pre><code>$('#date_pretty').datepicker('setDate', '+0');\n</code></pre>\n\n<p>Set to <strong><em>yesterday</em></strong>:</p>\n\n<pre><code>$('#date_pretty').datepicker('setDate', '-1');\n</code></pre>\n\n<p>And so on with any number of days <strong><em>before</em></strong> or <strong><em>after</em></strong> <em>today's date</em>.</p>\n\n<p>See <a href=\"http://jqueryui.com/demos/datepicker/#methods\" rel=\"noreferrer\">jQuery UI › Methods › setDate</a>.</p>\n"
},
{
"answer_id": 11423185,
"author": "maozx",
"author_id": 1516208,
"author_profile": "https://Stackoverflow.com/users/1516208",
"pm_score": 2,
"selected": false,
"text": "<p>In order to set the datepicker to a certain default time (the current date in my case) on loading, AND then have the option to choose another date the syntax is :</p>\n\n<pre><code> $(function() { \n // initialize the datapicker\n $(\"#date\").datepicker();\n\n // set the time\n var currentDate = new Date();\n $(\"#date\").datepicker(\"setDate\",currentDate);\n\n // set the options for the button \n $(\"#date\").datepicker(\"option\",{\n dateFormat: 'dd/mm',\n showOn: \"button\",\n // whatever option Or event you want \n });\n });\n</code></pre>\n"
},
{
"answer_id": 11819375,
"author": "Salman A",
"author_id": 87015,
"author_profile": "https://Stackoverflow.com/users/87015",
"pm_score": 6,
"selected": false,
"text": "<p>The <a href=\"http://api.jqueryui.com/datepicker/#method-setDate\" rel=\"noreferrer\"><code>setDate()</code></a> method sets the date and updates the associated control. Here is how:</p>\n\n<pre><code>$(\"#datepicker1\").datepicker({\n dateFormat: \"yy-mm-dd\"\n}).datepicker(\"setDate\", \"0\");\n</code></pre>\n\n<p><a href=\"http://jsfiddle.net/salman/ZBFFJ/\" rel=\"noreferrer\"><strong>Demo</strong></a></p>\n\n<p>As mentioned in documentation, <code>setDate()</code> happily accepts the JavaScript Date object, number or a string:</p>\n\n<blockquote>\n <p>The new date may be a Date object or a string in the current date\n format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a\n string of values and periods ('y' for years, 'm' for months, 'w' for\n weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected\n date.</p>\n</blockquote>\n\n<p>In case you are wondering, setting <a href=\"http://api.jqueryui.com/datepicker/#option-defaultDate\" rel=\"noreferrer\"><code>defaultDate</code></a> property in the constructor <em>does not</em> update the associated control.</p>\n"
},
{
"answer_id": 13040921,
"author": "Gary Medina",
"author_id": 1769834,
"author_profile": "https://Stackoverflow.com/users/1769834",
"pm_score": 3,
"selected": false,
"text": "<p>David K Egghead's code worked perfectly, thank you!</p>\n\n<pre><code>$(\".date-pick\").datepicker(); \n$(\".date-pick\").datepicker(\"setDate\", new Date()); \n</code></pre>\n\n<p>I also managed to trim it a little and it also worked:</p>\n\n<pre><code>$(\".date-pick\").datepicker().datepicker(\"setDate\", new Date()); \n</code></pre>\n"
},
{
"answer_id": 15870913,
"author": "Celestz",
"author_id": 2181385,
"author_profile": "https://Stackoverflow.com/users/2181385",
"pm_score": 3,
"selected": false,
"text": "<p>This one worked for me.</p>\n\n<pre><code>$('#inputName')\n .datepicker()\n .datepicker('setDate', new Date());\n</code></pre>\n"
},
{
"answer_id": 20998323,
"author": "Les Mizzell",
"author_id": 3173655,
"author_profile": "https://Stackoverflow.com/users/3173655",
"pm_score": 1,
"selected": false,
"text": "<p>Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:</p>\n\n<pre><code> $( \"#datepicker\" ).datepicker();\n <?php if (!empty($oneEVENT['start_ts'])): ?>\n $( \"#datepicker\" ).datepicker( \"setDate\", \"<?php echo $startDATE; ?>\" );\n <? else: ?>\n $(\"#datepicker\").datepicker('setDate', new Date()); \n <?php endif; ?>\n });\n</code></pre>\n"
},
{
"answer_id": 28745931,
"author": "thejustv",
"author_id": 2466310,
"author_profile": "https://Stackoverflow.com/users/2466310",
"pm_score": 0,
"selected": false,
"text": "<p>Try this </p>\n\n<pre><code>$(this).datepicker(\"destroy\").datepicker({\n changeMonth: false, changeYear: false,defaultDate:new Date(), dateFormat: \"dd-mm-yy\", showOn: \"focus\", yearRange: \"-5:+10\"\n }).focus();\n</code></pre>\n"
},
{
"answer_id": 31229651,
"author": "Nadir",
"author_id": 3282722,
"author_profile": "https://Stackoverflow.com/users/3282722",
"pm_score": 1,
"selected": false,
"text": "<p>To pre-populate date, first you have to initialise datepicker, then pass setDate parameter value.</p>\n\n<pre><code>$(\"#date_pretty\").datepicker().datepicker(\"setDate\", new Date());\n</code></pre>\n"
},
{
"answer_id": 32376073,
"author": "chispitaos",
"author_id": 2271755,
"author_profile": "https://Stackoverflow.com/users/2271755",
"pm_score": 2,
"selected": false,
"text": "<p>You've got 2 options:</p>\n\n<p><strong>OPTION A)</strong> Marks as \"active\" in your calendar, only when you click in the input.</p>\n\n<p><strong>Js</strong>:</p>\n\n<pre><code>$('input.datepicker').datepicker(\n { \n changeMonth: false,\n changeYear: false,\n beforeShow: function(input, instance) { \n $(input).datepicker('setDate', new Date());\n }\n } \n );\n</code></pre>\n\n<p><strong>Css</strong>:</p>\n\n<pre><code>div.ui-datepicker table.ui-datepicker-calendar .ui-state-active,\n div.ui-datepicker table.ui-datepicker-calendar .ui-widget-content .ui-state-active {\n background: #1ABC9C;\n border-radius: 50%;\n color: #fff;\n cursor: pointer;\n display: inline-block;\n width: 24px; height: 24px;\n }\n</code></pre>\n\n<p><strong>OPTION B)</strong> Input by default with today.\nYou've to populate first the datepicker .</p>\n\n<pre>$(\"input.datepicker\").datepicker().datepicker(\"setDate\", new Date());</pre>\n"
},
{
"answer_id": 36155885,
"author": "Alpha2k",
"author_id": 3257288,
"author_profile": "https://Stackoverflow.com/users/3257288",
"pm_score": 0,
"selected": false,
"text": "<p>This works better for me as sometimes I have troubles calling <code>.datepicker('setDate', new Date());</code> as it messes if if i have the datepicker already configured with parameters. </p>\n\n<pre><code>$(\"#myDateText\").val(moment(new Date()).format('DD/MM/YYYY'));\n</code></pre>\n"
},
{
"answer_id": 58394022,
"author": "nikhil",
"author_id": 8208024,
"author_profile": "https://Stackoverflow.com/users/8208024",
"pm_score": 0,
"selected": false,
"text": "<p>Use This:</p>\n\n<p><code>$(\".datepicker\").datepicker({ dateFormat: 'dd-M-yy' }).datepicker('setDate', new Date());</code></p>\n\n<p>To Get Date in Format Eg: 10-Oct-2019 which will be more understandable for users.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233553",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26848/"
] |
I have a very simple jQuery Datepicker calendar:
```
$(document).ready(function(){
$("#date_pretty").datepicker({
});
});
```
and of course in the HTML...
```
<input type="text" size="10" value="" id="date_pretty"/>
```
Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.
|
**Update: There are reports this no longer works in Chrome.**
This is concise and does the job (obsolete):
```
$(".date-pick").datepicker('setDate', new Date());
```
This is less concise, utilizing [chaining](https://www.w3schools.com/jquery/jquery_chaining.asp) allows it to work in chrome (2019-06-04):
```
$(".date-pick").datepicker().datepicker('setDate', new Date());
```
|
233,560 |
<p>I have developed about 300 Applications which I would like to provide with multi-language capabilities independent from the Operating System. I have written a just-in-time translator, but that is too slow in applications with many components. What would you suggest I do?</p>
|
[
{
"answer_id": 233592,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "<p>We are using <a href=\"http://www.sicomponents.com/tsilang1.html\" rel=\"nofollow noreferrer\">TsiLang</a> and are very happy with it.</p>\n\n<p>One of the best points is that you can pretranslate the project with a dictionary (which you filled from existing translations).</p>\n"
},
{
"answer_id": 233626,
"author": "Davy Landman",
"author_id": 11098,
"author_profile": "https://Stackoverflow.com/users/11098",
"pm_score": 3,
"selected": true,
"text": "<p>I've heard that the <a href=\"http://www.tsilang.com/?siteid2=1\" rel=\"nofollow noreferrer\">TsiLang components</a> are nice, but your looking at an inplace solution...</p>\n\n<p>I've used <a href=\"http://dxgettext.po.dk/\" rel=\"nofollow noreferrer\">GNU gettext for Delphi</a> which does exactly the thing you want, it loads the translations from a text file and replaces the text in your components. It even has a pas/dfm scanner to automatically generate the English translation file.</p>\n\n<p>It's also possible to automatically change your pascal source code to inject the gettext procedure inplace of your static strings. If I'm not mistaken it just adds a underscore as function to it, as below.</p>\n\n<pre><code>ShowMessage('Hello'); // before\nShowMessage(_('Hello')); // after\n</code></pre>\n\n<p>I must say it has been 2 years since I last used this method.</p>\n\n<p>One thing will remain problematic, the Delphi components are not unicode enabled (D2009 fixes this), so when you don't change the components you'll still have limited support for other languages. </p>\n"
},
{
"answer_id": 233629,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 2,
"selected": false,
"text": "<p>A good free solution would be <a href=\"http://dybdahl.dk/dxgettext/\" rel=\"nofollow noreferrer\">GNU gettext for Delphi</a>. It has some capabilities not present in TsiLang - for example, you can put the knowledge on how to count things (different endings for one, two, four, hundred and two, many ...) into the translation file so that you don't have to teach each program to know this stuff.</p>\n\n<p>License for the Delphi part is very permissive but I'm not sure how much the included GNU stuff will affect your application.</p>\n"
},
{
"answer_id": 243113,
"author": "Lars Truijens",
"author_id": 1242,
"author_profile": "https://Stackoverflow.com/users/1242",
"pm_score": 1,
"selected": false,
"text": "<p>Get <a href=\"http://www.multilizer.com/\" rel=\"nofollow noreferrer\">Multilizer</a>. It is made in Delphi and it can handle Delphi programs like no other with special support for VCL. You can even redo your screens easy for every language. With Multilizer you can use different techniques to translate and run your program.</p>\n"
},
{
"answer_id": 245508,
"author": "lkessler",
"author_id": 30176,
"author_profile": "https://Stackoverflow.com/users/30176",
"pm_score": 1,
"selected": false,
"text": "<p>Delphi 2009 has added an Integrated Translation Environment/External Translation Manager\nITE and ETM are now available for both Delphi and C++Builder.</p>\n\n<p>In Codegear's article: <a href=\"http://dn.codegear.com/article/38869\" rel=\"nofollow noreferrer\">What's New in Delphi and C++Builder 2009</a>, they state:</p>\n\n<blockquote>\n <p>The Integrated Translation Environment\n (ITE) is a part of the IDE that\n simplifies localizing your projects.\n ITE can create a new localized project\n from an existing project. ITE does not\n automatically translate text, but\n provides a dialog listing all text\n that needs to be localized and fields\n in which to enter the corresponding\n translated text. Once you have entered\n the translated text and built the\n localized project, you can set another\n language active and display a form in\n the localized text; you don't have to\n switch locales and reboot your system.\n This allows you to perform\n localization without requiring a\n localized system.</p>\n \n <p>The External Translation Manager (ETM)\n is a standalone application that works\n with DFM files and text strings in the\n source code. Although ETM does not\n allow you to create a new localized\n project, it does provide a dialog\n listing localized text and the\n translated text, similarly to ITE.</p>\n</blockquote>\n\n<p>This is what I plan to try first once I am at the point that I want to Internationalize my product.</p>\n\n<p>However, to me the easy part is to translate the program. The hard part is to translate the help file.</p>\n"
},
{
"answer_id": 398702,
"author": "stpe",
"author_id": 25815,
"author_profile": "https://Stackoverflow.com/users/25815",
"pm_score": 1,
"selected": false,
"text": "<p>I would say <a href=\"http://dybdahl.dk/dxgettext/\" rel=\"nofollow noreferrer\">GNU gettext for Delphi</a> in combination with <a href=\"http://www.tmssoftware.com/site/tmsuni.asp\" rel=\"nofollow noreferrer\">TMS Unicode Component Pack</a> (previously free under TntWare) to get unicode support in the components.</p>\n\n<p>To work with, or have translators work with, the gettext files I recommend looking at the free cross-platform <a href=\"http://www.poedit.net/\" rel=\"nofollow noreferrer\">Poedit</a> that may edit the .po files.</p>\n"
},
{
"answer_id": 1697251,
"author": "Mihaela",
"author_id": 105949,
"author_profile": "https://Stackoverflow.com/users/105949",
"pm_score": 1,
"selected": false,
"text": "<p>Just to mention <a href=\"http://www.devexpress.com/Products/VCL/ExQuantumGrid/key_localization.xml\" rel=\"nofollow noreferrer\">cxLocalizer</a> if you own DexExpress components.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233560",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3535708/"
] |
I have developed about 300 Applications which I would like to provide with multi-language capabilities independent from the Operating System. I have written a just-in-time translator, but that is too slow in applications with many components. What would you suggest I do?
|
I've heard that the [TsiLang components](http://www.tsilang.com/?siteid2=1) are nice, but your looking at an inplace solution...
I've used [GNU gettext for Delphi](http://dxgettext.po.dk/) which does exactly the thing you want, it loads the translations from a text file and replaces the text in your components. It even has a pas/dfm scanner to automatically generate the English translation file.
It's also possible to automatically change your pascal source code to inject the gettext procedure inplace of your static strings. If I'm not mistaken it just adds a underscore as function to it, as below.
```
ShowMessage('Hello'); // before
ShowMessage(_('Hello')); // after
```
I must say it has been 2 years since I last used this method.
One thing will remain problematic, the Delphi components are not unicode enabled (D2009 fixes this), so when you don't change the components you'll still have limited support for other languages.
|
233,564 |
<p>I have created a multi column datastore on a table that allows me to do full text indexing on the table. What I need to be able to do is weight each column different and add the scores together.</p>
<p>The following query works, but is slow:</p>
<pre><code>SELECT document.*, Score(1) + 2*Score(2) as Score
FROM document
WHERE (CONTAINS(documentContent, 'the_keyword', 1) > 0
OR CONTAINS(documentTitle, 'the_keyword', 2) > 0 )
ORDER BY Score DESC
</code></pre>
<p>After quite a bit of Googling, people have proposed the solution as:</p>
<pre><code>SELECT document.*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 OR ((the_keyword) within documentText)',1) > 0)
ORDER BY Score Desc
</code></pre>
<p>The above query is faster than its predecessor but it does not solve the actual problem. In this case, if the keyword is found in the documentTitle, it will not search the documentText (it uses the OR operator). What I really need is to ADD the two scores together so that if a keyword appears in the title AND the text it will have a higher score than if it only appears in the title. </p>
<p>So, how do you add the scores for weighted columns in one CONTAINS clause? </p>
|
[
{
"answer_id": 233694,
"author": "user31183",
"author_id": 31183,
"author_profile": "https://Stackoverflow.com/users/31183",
"pm_score": 3,
"selected": true,
"text": "<p>Instead of the OR operator, use ACCUM:</p>\n\n<p>SELECT document.*, Score(1) as Score\nFROM document\nWHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 <strong>ACCUM</strong> ((the_keyword) within documentText)',1) > 0)\nORDER BY Score Desc</p>\n"
},
{
"answer_id": 233761,
"author": "BIBD",
"author_id": 685,
"author_profile": "https://Stackoverflow.com/users/685",
"pm_score": 0,
"selected": false,
"text": "<p>What if you do a nested select?</p>\n\n<pre><code>select *, Score(1) + 2 * Score(2) as Score\nfrom (\n SELECT document.*, Score(1) as Score\n FROM document\n WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))\n OR ((the_keyword) within documentText)',1) > 0)\n)\nORDER BY Score Desc\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233564",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31169/"
] |
I have created a multi column datastore on a table that allows me to do full text indexing on the table. What I need to be able to do is weight each column different and add the scores together.
The following query works, but is slow:
```
SELECT document.*, Score(1) + 2*Score(2) as Score
FROM document
WHERE (CONTAINS(documentContent, 'the_keyword', 1) > 0
OR CONTAINS(documentTitle, 'the_keyword', 2) > 0 )
ORDER BY Score DESC
```
After quite a bit of Googling, people have proposed the solution as:
```
SELECT document.*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the_keyword) within documentTitle))*2 OR ((the_keyword) within documentText)',1) > 0)
ORDER BY Score Desc
```
The above query is faster than its predecessor but it does not solve the actual problem. In this case, if the keyword is found in the documentTitle, it will not search the documentText (it uses the OR operator). What I really need is to ADD the two scores together so that if a keyword appears in the title AND the text it will have a higher score than if it only appears in the title.
So, how do you add the scores for weighted columns in one CONTAINS clause?
|
Instead of the OR operator, use ACCUM:
SELECT document.\*, Score(1) as Score
FROM document
WHERE CONTAINS(dummy, '(((the\_keyword) within documentTitle))\*2 **ACCUM** ((the\_keyword) within documentText)',1) > 0)
ORDER BY Score Desc
|
233,579 |
<p>I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer. </p>
<p>What would this syntax look like?</p>
<p>I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?</p>
<p>(By now we definitely know that closures not will be included in the next Java release)</p>
<p>OR </p>
<p><strong>edit: <a href="http://puredanger.com/tech/2009/11/18/closures-after-all/" rel="noreferrer">http://puredanger.com/tech/2009/11/18/closures-after-all/</a> :D</strong></p>
<p><strong>edit2: Re-thinking JDK7: <a href="http://blogs.oracle.com/mr/entry/rethinking_jdk7" rel="noreferrer">http://blogs.oracle.com/mr/entry/rethinking_jdk7</a></strong></p>
<p><strong>edit3: There’s not a moment to lose!: <a href="http://blogs.oracle.com/mr/entry/quartet" rel="noreferrer">http://blogs.oracle.com/mr/entry/quartet</a></strong></p>
|
[
{
"answer_id": 233595,
"author": "Steven Huwig",
"author_id": 28604,
"author_profile": "https://Stackoverflow.com/users/28604",
"pm_score": 5,
"selected": true,
"text": "<p>Have a look at <a href=\"http://www.javac.info/\" rel=\"noreferrer\">http://www.javac.info/</a> .</p>\n\n<p>It seems like this is how it would look:</p>\n\n<pre><code>boolean even = { int x => x % 2 == 0 }.invoke(15);\n</code></pre>\n\n<p>where the <code>{ int x => x % 2 == 0 }</code> bit is the closure.</p>\n"
},
{
"answer_id": 233598,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>It really depends on what gets introduced, and indeed <em>whether</em> it will be introduced at all. There are a number of closure proposals of varying sizes.</p>\n\n<p>See <a href=\"http://tech.puredanger.com/java7#closures\" rel=\"noreferrer\">Alex Miller's Java 7 page</a> for the proposals and various blog posts.</p>\n\n<p>Personally I'd love to see closures - they're <a href=\"http://csharpindepth.com/Articles/Chapter5/Closures.aspx\" rel=\"noreferrer\">beautiful and incredibly helpful</a> - but I fear that some of the proposals are pretty hairy.</p>\n"
},
{
"answer_id": 233624,
"author": "Agusti-N",
"author_id": 24639,
"author_profile": "https://Stackoverflow.com/users/24639",
"pm_score": 2,
"selected": false,
"text": "<p>This is the java 7 features <a href=\"http://tech.puredanger.com/java7/#switch\" rel=\"nofollow noreferrer\">http://tech.puredanger.com/java7/#switch</a> the examples are very usefull.</p>\n"
},
{
"answer_id": 234004,
"author": "oxbow_lakes",
"author_id": 16853,
"author_profile": "https://Stackoverflow.com/users/16853",
"pm_score": 2,
"selected": false,
"text": "<p>Note that a \"function-type\" is really a type under the proposal:</p>\n\n<pre><code>{int => boolean} evaluateInt; //declare variable of \"function\" type\nevaluateInt = {int x => x % 2 }; //assignment\n</code></pre>\n"
},
{
"answer_id": 234628,
"author": "jsight",
"author_id": 1432,
"author_profile": "https://Stackoverflow.com/users/1432",
"pm_score": 2,
"selected": false,
"text": "<p>I think there is still a lot of debate going in with regards to what syntax will ultimately be used. I'd actually be pretty surprised if this does make it into Java 7 due to all of that.</p>\n"
},
{
"answer_id": 822606,
"author": "Dónal",
"author_id": 2648,
"author_profile": "https://Stackoverflow.com/users/2648",
"pm_score": 4,
"selected": false,
"text": "<p>In November 2009 there was a surprising u-turn on this issue, and <a href=\"http://java.dzone.com/news/closures-coming-java-7\" rel=\"nofollow noreferrer\">closures will now be added</a> to Java 7.</p>\n\n<h2>Update</h2>\n\n<p>Closures (AKA lambdas expressions) in Java 7 didn't happen. They were <em>finally</em> added in the first release of Java 8 in 2014.</p>\n"
},
{
"answer_id": 841574,
"author": "Peter Lawrey",
"author_id": 57695,
"author_profile": "https://Stackoverflow.com/users/57695",
"pm_score": 1,
"selected": false,
"text": "<p>Closures have some serious edge cases. I would say that Closures are a much more significant change than Generics and the later still has a number hairy edge cases.\ne.g. The Java Collections libraries cannot be written/compiled without warnings.</p>\n"
},
{
"answer_id": 1414560,
"author": "Mario Fusco",
"author_id": 112779,
"author_profile": "https://Stackoverflow.com/users/112779",
"pm_score": 2,
"selected": false,
"text": "<p>Unofortunately you will not find closure in Java 7. If you are looking for a lighter solution to have closure in java just now check out the lambdaj project:</p>\n\n<p><a href=\"http://code.google.com/p/lambdaj/\" rel=\"nofollow noreferrer\">http://code.google.com/p/lambdaj/</a></p>\n"
},
{
"answer_id": 2807083,
"author": "Pedro Rolo",
"author_id": 330889,
"author_profile": "https://Stackoverflow.com/users/330889",
"pm_score": 2,
"selected": false,
"text": "<p>closures will be annoyinglly verbose if there won't be any sort of type inference... :(</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/148909/"
] |
I have heard that closures could be introduced in the next Java standard that is scheduled to be released somewhere around next summer.
What would this syntax look like?
I read somewhere that introducing closures in java is a bigger change than generic was in java 5. Is this true? pros and cons?
(By now we definitely know that closures not will be included in the next Java release)
OR
**edit: <http://puredanger.com/tech/2009/11/18/closures-after-all/> :D**
**edit2: Re-thinking JDK7: <http://blogs.oracle.com/mr/entry/rethinking_jdk7>**
**edit3: There’s not a moment to lose!: <http://blogs.oracle.com/mr/entry/quartet>**
|
Have a look at <http://www.javac.info/> .
It seems like this is how it would look:
```
boolean even = { int x => x % 2 == 0 }.invoke(15);
```
where the `{ int x => x % 2 == 0 }` bit is the closure.
|
233,622 |
<p>It sounds a lot more complicated than it really is.</p>
<p>So in Perl, you can do something like this:</p>
<pre><code>foreach my $var (@vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
</code></pre>
<p>I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.</p>
<p>I've tried the following:</p>
<pre><code>hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
</code></pre>
<p>Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):</p>
<pre><code>{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
</code></pre>
<p>But every time I do this, firebug throws the following error:</p>
<p>"XML filter is applied to non-xml data"</p>
|
[
{
"answer_id": 233685,
"author": "roenving",
"author_id": 23142,
"author_profile": "https://Stackoverflow.com/users/23142",
"pm_score": 0,
"selected": false,
"text": "<p>Why would you want to change an array into another array ?-)</p>\n\n<p>-- why not simply access the data, if you want to simplify or filter, you can traverse the arrays of the object directly !-)</p>\n"
},
{
"answer_id": 233689,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 0,
"selected": false,
"text": "<p>This works. Just dump it into a script block to test.</p>\n\n<pre><code> d = {\n 'results':{\n 'datasets_a':{\n 'dataset_one':{\n 'data':{\n 'sample':'hello'\n },\n 'extra_info':{\n //stuff\n }\n },\n 'dataset_two':{\n ///\n }\n ///\n },\n 'datasets_b':{\n ///\n }\n }\n}\nalert(d.results.datasets_a.dataset_one.data.sample)\n</code></pre>\n\n<p>I hope this pasted in correctly. This editor doesn't like my line breaks in code.</p>\n\n<pre><code>d = {\n 'results':{\n 'datasets_a':{\n 'dataset_one':{\n 'data':{\n 'sample':'hello'\n },\n 'extra_info':{\n //stuff\n }\n },\n 'dataset_two':{\n ///\n }\n ///\n },\n 'datasets_b':{\n ///\n }\n }\n};\n\nalert(d.results.datasets_a.dataset_one.data.sample)\n</code></pre>\n"
},
{
"answer_id": 233693,
"author": "Robert K",
"author_id": 24950,
"author_profile": "https://Stackoverflow.com/users/24950",
"pm_score": 3,
"selected": true,
"text": "<p>I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.</p>\n\n<p>Assuming you received the above example:</p>\n\n<pre><code>$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];\n// Or the shorter form:\n$('result').innerHTML = data.results.dataset_a.dataset_two.data;\n</code></pre>\n\n<p>Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.</p>\n\n<p>Your example is failing because of some convoluted logic I just caught.</p>\n\n<pre><code>$.each(data.results), function(name, result) {\n hash_table[result.(name).extra_info.a] = result.(name).some_dataset;\n});\n</code></pre>\n\n<p>Now, the foreach loop goes through the variable <code>data.results</code> to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be <code>name = \"datasets_a\" item = object</code>. Following me so far? Now you access the returned hash, the object in <code>item</code>, as though it has the child key in <code>name</code> ... \"datasets_a\". But wait, this <strong>is</strong> the object!</p>\n\n<p>If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233622",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22390/"
] |
It sounds a lot more complicated than it really is.
So in Perl, you can do something like this:
```
foreach my $var (@vars) {
$hash_table{$var->{'id'}} = $var->{'data'};
}
```
I have a JSON object and I want to do the same thing, but with a javascript associative array in jQuery.
I've tried the following:
```
hash_table = new Array();
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
```
Where data is a JSON object gotten from a $.getJSON call. It looks more or less like this (my JSON syntax may be a little off, sorry):
```
{
results:{
datasets_a:{
dataset_one:{
data:{
//stuff
}
extra_info:{
//stuff
}
}
dataset_two:{
...
}
...
}
datasets_b:{
...
}
}
}
```
But every time I do this, firebug throws the following error:
"XML filter is applied to non-xml data"
|
I think you can use the JSON response as an associative array. So you should be able to go directly in and use the JSON.
Assuming you received the above example:
```
$('result').innerHTML = data['results']['dataset_a']['dataset_two']['data'];
// Or the shorter form:
$('result').innerHTML = data.results.dataset_a.dataset_two.data;
```
Understand that I haven't tested this, but it's safer to use the square brackets with a variable than it is to use parenthesis plus the name with the dot accessor.
Your example is failing because of some convoluted logic I just caught.
```
$.each(data.results), function(name, result) {
hash_table[result.(name).extra_info.a] = result.(name).some_dataset;
});
```
Now, the foreach loop goes through the variable `data.results` to find the internal elements at a depth of 1. The item it finds is given to the lambda with the key of the item. AKA, the first result will be `name = "datasets_a" item = object`. Following me so far? Now you access the returned hash, the object in `item`, as though it has the child key in `name` ... "datasets\_a". But wait, this **is** the object!
If all else fails... write your result JSON into a text field dynamically and ensure it is formatted properly.
|
233,643 |
<p>I'd like to link to some PDFs in one of my controller views. What's the best practice for accomplishing this? The CakePHP webroot folder contains a ./files/ subfolder, I am confounded by trying to link to it without using "magic" pathnames in my href (e.g. "/path/to/my/webroot/files/myfile.pdf").</p>
<p>What are my options?</p>
<p><strong>EDIT:</strong> I didn't adequately describe my question. I was attempting to link to files in /app/webroot/files/ in a platform-agnostic (ie. no <code>mod_rewrite</code>) way.</p>
<p>I've since worked around this issue by storing such files outside the CakePHP directory structure.</p>
|
[
{
"answer_id": 238045,
"author": "Jonas Due Vesterheden",
"author_id": 7445,
"author_profile": "https://Stackoverflow.com/users/7445",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure I understand the question correctly, but here goes. Basically any file you put in the webroot folder will be accessible on the webserver, so if you put the file in webroot/files/file.pdf you would simply link to /files/file.pdf.</p>\n\n<p>If that doesn't work, please clarify your question...</p>\n"
},
{
"answer_id": 239322,
"author": "Alexander Morland",
"author_id": 4013,
"author_profile": "https://Stackoverflow.com/users/4013",
"pm_score": 5,
"selected": true,
"text": "<pre><code>$html->link('Pdf', '/files/myfile.pdf');\n</code></pre>\n"
},
{
"answer_id": 280429,
"author": "Chris Hawes",
"author_id": 22776,
"author_profile": "https://Stackoverflow.com/users/22776",
"pm_score": 0,
"selected": false,
"text": "<p>or...</p>\n\n<pre><code><a href=\"<?php echo $html->url('/files/somefile.pdf'); ?>\">Link Text</a>\n</code></pre>\n"
},
{
"answer_id": 373511,
"author": "user42801",
"author_id": 42801,
"author_profile": "https://Stackoverflow.com/users/42801",
"pm_score": 1,
"selected": false,
"text": "<p>or..</p>\n\n<pre><code><a href=\"<?php echo $this->webroot; ?>files/somefile.pdf\">Link Text</a>\n</code></pre>\n\n<p>:)</p>\n"
},
{
"answer_id": 3513309,
"author": "James Revillini",
"author_id": 336397,
"author_profile": "https://Stackoverflow.com/users/336397",
"pm_score": 2,
"selected": false,
"text": "<p>I can confirm that this is an issue when mod_rewrite is not being used. </p>\n\n<pre><code><?php echo $html->link('pdf', '/files/test.pdf'); ?>\n</code></pre>\n\n<p>outputs</p>\n\n<pre><code><a href=\"/pathtoapp/index.php/files/test.pdf\">pdf</a>\n</code></pre>\n\n<p>it should output</p>\n\n<pre><code><a href=\"/pathtoapp/app/webroot/files/test.pdf\">pdf</a>\n</code></pre>\n"
},
{
"answer_id": 3591865,
"author": "sotomsa",
"author_id": 433847,
"author_profile": "https://Stackoverflow.com/users/433847",
"pm_score": 2,
"selected": false,
"text": "<p>This should work</p>\n\n<pre><code><?php echo $html->link('pdf', $this->webroot('files'.DS.'test.pdf'); ?>\n</code></pre>\n"
},
{
"answer_id": 4089513,
"author": "zmonteca",
"author_id": 186782,
"author_profile": "https://Stackoverflow.com/users/186782",
"pm_score": 3,
"selected": false,
"text": "<p>This is somewhat tangential, but for access to such a location in Models and other places you can simply do this: </p>\n\n<pre><code>$file = WWW_ROOT . DS . 'files' . DS;\n</code></pre>\n\n<p>This tactic might be helpful to someone accessing files for static data loading, such as XML or JSON.</p>\n\n<p>This is not recommended for public consumption or public linking.</p>\n"
},
{
"answer_id": 46291489,
"author": "Keila",
"author_id": 8630387,
"author_profile": "https://Stackoverflow.com/users/8630387",
"pm_score": 0,
"selected": false,
"text": "<pre><code> <a href=\"<?php echo $this->request->webroot . 'carpetadentrodelwebroot/archivo.pdf'; ?>\" target=\"pdf-frame\" download=\"nombreParaDescarga\">Descargar Archivo</a>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233643",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5030/"
] |
I'd like to link to some PDFs in one of my controller views. What's the best practice for accomplishing this? The CakePHP webroot folder contains a ./files/ subfolder, I am confounded by trying to link to it without using "magic" pathnames in my href (e.g. "/path/to/my/webroot/files/myfile.pdf").
What are my options?
**EDIT:** I didn't adequately describe my question. I was attempting to link to files in /app/webroot/files/ in a platform-agnostic (ie. no `mod_rewrite`) way.
I've since worked around this issue by storing such files outside the CakePHP directory structure.
|
```
$html->link('Pdf', '/files/myfile.pdf');
```
|
233,673 |
<p>While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:</p>
<pre><code>flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
</code></pre>
<p>Note that this example mindfully avoids <code>lambda</code>. It prints "4 4 4", which is surprising. I'd expect "0 2 4". </p>
<p>This equivalent Perl code does it right:</p>
<pre><code>my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
</code></pre>
<p>"0 2 4" is printed.</p>
<p>Can you please explain the difference ?</p>
<hr>
<p>Update: </p>
<p>The problem <strong>is not</strong> with <code>i</code> being global. This displays the same behavior:</p>
<pre><code>flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
</code></pre>
<p>As the commented line shows, <code>i</code> is unknown at that point. Still, it prints "4 4 4".</p>
|
[
{
"answer_id": 233713,
"author": "Alex Coventry",
"author_id": 1941213,
"author_profile": "https://Stackoverflow.com/users/1941213",
"pm_score": 2,
"selected": false,
"text": "<p>The variable <code>i</code> is a global, whose value is 2 at each time the function <code>f</code> is called.</p>\n\n<p>I would be inclined to implement the behavior you're after as follows:</p>\n\n<pre><code>>>> class f:\n... def __init__(self, multiplier): self.multiplier = multiplier\n... def __call__(self, multiplicand): return self.multiplier*multiplicand\n... \n>>> flist = [f(i) for i in range(3)]\n>>> [g(2) for g in flist]\n[0, 2, 4]\n</code></pre>\n\n<p><strong>Response to your update</strong>: It's not the globalness of <code>i</code> <em>per se</em> which is causing this behavior, it's the fact that it's a variable from an enclosing scope which has a fixed value over the times when f is called. In your second example, the value of <code>i</code> is taken from the scope of the <code>kkk</code> function, and nothing is changing that when you call the functions on <code>flist</code>.</p>\n"
},
{
"answer_id": 233800,
"author": "Null303",
"author_id": 13787,
"author_profile": "https://Stackoverflow.com/users/13787",
"pm_score": 4,
"selected": false,
"text": "<p>look at this:</p>\n\n<pre><code>for f in flist:\n print f.func_closure\n\n\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n(<cell at 0x00C980B0: int object at 0x009864B4>,)\n</code></pre>\n\n<p>It means they all point to the same i variable instance, which will have a value of 2 once the loop is over.</p>\n\n<p>A readable solution:</p>\n\n<pre><code>for i in xrange(3):\n def ffunc(i):\n def func(x): return x * i\n return func\n flist.append(ffunc(i))\n</code></pre>\n"
},
{
"answer_id": 233822,
"author": "Rafał Dowgird",
"author_id": 12166,
"author_profile": "https://Stackoverflow.com/users/12166",
"pm_score": 2,
"selected": false,
"text": "<p>The problem is that all of the local functions bind to the same environment and thus to the same <code>i</code> variable. The solution (workaround) is to create separate environments (stack frames) for each function (or lambda):</p>\n\n<pre><code>t = [ (lambda x: lambda y : x*y)(x) for x in range(5)]\n\n>>> t[1](2)\n2\n>>> t[2](2)\n4\n</code></pre>\n"
},
{
"answer_id": 233835,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 8,
"selected": true,
"text": "<p>Python is actually behaving as defined. <b>Three separate functions</b> are created, but they each have the <b>closure of the environment they're defined in</b> - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, <b>i is modified</b>, and the closures all <b>refer to the same i</b>.</p>\n<p>Here is the best solution I can come up with - create a function creater and invoke <i>that</i> instead. This will force <b>different environments</b> for each of the functions created, with a <b>different i</b> in each one.</p>\n<pre><code>flist = []\n\nfor i in xrange(3):\n def funcC(j):\n def func(x): return x * j\n return func\n flist.append(funcC(i))\n\nfor f in flist:\n print f(2)\n</code></pre>\n<p>This is what happens when you mix side effects and functional programming.</p>\n"
},
{
"answer_id": 235764,
"author": "piro",
"author_id": 10138,
"author_profile": "https://Stackoverflow.com/users/10138",
"pm_score": 7,
"selected": false,
"text": "<p>The functions defined in the loop keep accessing the same variable <code>i</code> while its value changes. At the end of the loop, all the functions point to the same variable, which is holding the last value in the loop: the effect is what reported in the example.</p>\n\n<p>In order to evaluate <code>i</code> and use its value, a common pattern is to set it as a parameter default: parameter defaults are evaluated when the <code>def</code> statement is executed, and thus the value of the loop variable is frozen.</p>\n\n<p>The following works as expected:</p>\n\n<pre><code>flist = []\n\nfor i in xrange(3):\n def func(x, i=i): # the *value* of i is copied in func() environment\n return x * i\n flist.append(func)\n\nfor f in flist:\n print f(2)\n</code></pre>\n"
},
{
"answer_id": 236044,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 2,
"selected": false,
"text": "<p>I'm still not entirely convinced why in some languages this works one way, and in some another way. In Common Lisp it's like Python:</p>\n\n<pre><code>(defvar *flist* '())\n\n(dotimes (i 3 t)\n (setf *flist* \n (cons (lambda (x) (* x i)) *flist*)))\n\n(dolist (f *flist*) \n (format t \"~a~%\" (funcall f 2)))\n</code></pre>\n\n<p>Prints \"6 6 6\" (note that here the list is from 1 to 3, and built in reverse\").\nWhile in Scheme it works like in Perl:</p>\n\n<pre><code>(define flist '())\n\n(do ((i 1 (+ 1 i)))\n ((>= i 4))\n (set! flist \n (cons (lambda (x) (* i x)) flist)))\n\n(map \n (lambda (f)\n (printf \"~a~%\" (f 2)))\n flist)\n</code></pre>\n\n<p>Prints \"6 4 2\"</p>\n\n<p>And as I've mentioned already, Javascript is in the Python/CL camp. It appears there is an implementation decision here, which different languages approach in distinct ways. I would love to understand what is the decision, exactly.</p>\n"
},
{
"answer_id": 236253,
"author": "Brian",
"author_id": 9493,
"author_profile": "https://Stackoverflow.com/users/9493",
"pm_score": 3,
"selected": false,
"text": "<p>What is happening is that the variable i is captured, and the functions are returning the value it is bound to at the time it is called. In functional languages this kind of situation never arises, as i wouldn't be rebound. However with python, and also as you've seen with lisp, this is no longer true.</p>\n\n<p>The difference with your scheme example is to do with the semantics of the do loop. Scheme is effectively creating a new i variable each time through the loop, rather than reusing an existing i binding as with the other languages. If you use a different variable created external to the loop and mutate it, you'll see the same behaviour in scheme. Try replacing your loop with:</p>\n\n<pre><code>(let ((ii 1)) (\n (do ((i 1 (+ 1 i)))\n ((>= i 4))\n (set! flist \n (cons (lambda (x) (* ii x)) flist))\n (set! ii i))\n))\n</code></pre>\n\n<p>Take a look <a href=\"http://lambda-the-ultimate.org/node/2648\" rel=\"noreferrer\">here</a> for some further discussion of this.</p>\n\n<p>[Edit] Possibly a better way to describe it is to think of the do loop as a macro which performs the following steps:</p>\n\n<ol>\n<li>Define a lambda taking a single parameter (i), with a body defined by the body of the loop,</li>\n<li>An immediate call of that lambda with appropriate values of i as its parameter. </li>\n</ol>\n\n<p>ie. the equivalent to the below python:</p>\n\n<pre><code>flist = []\n\ndef loop_body(i): # extract body of the for loop to function\n def func(x): return x*i\n flist.append(func)\n\nmap(loop_body, xrange(3)) # for i in xrange(3): body\n</code></pre>\n\n<p>The i is no longer the one from the parent scope but a brand new variable in its own scope (ie. the parameter to the lambda) and so you get the behaviour you observe. Python doesn't have this implicit new scope, so the body of the for loop just shares the i variable.</p>\n"
},
{
"answer_id": 6805307,
"author": "Luca Invernizzi",
"author_id": 633403,
"author_profile": "https://Stackoverflow.com/users/633403",
"pm_score": 5,
"selected": false,
"text": "<p>Here's how you do it using the <code>functools</code> library (which I'm not sure was available at the time the question was posed).</p>\n<pre><code>from functools import partial\n\nflist = []\n\ndef func(i, x): return x * i\n\nfor i in range(3):\n flist.append(partial(func, i))\n\nfor f in flist:\n print(f(2))\n</code></pre>\n<p>Outputs 0 2 4, as expected.</p>\n"
},
{
"answer_id": 11626867,
"author": "darkfeline",
"author_id": 469721,
"author_profile": "https://Stackoverflow.com/users/469721",
"pm_score": 1,
"selected": false,
"text": "<p>The reasoning behind the behavior has already been explained, and multiple solutions have been posted, but I think this is the most pythonic (remember, everything in Python is an object!):</p>\n\n<pre><code>flist = []\n\nfor i in xrange(3):\n def func(x): return x * func.i\n func.i=i\n flist.append(func)\n\nfor f in flist:\n print f(2)\n</code></pre>\n\n<p>Claudiu's answer is pretty good, using a function generator, but piro's answer is a hack, to be honest, as it's making i into a \"hidden\" argument with a default value (it'll work fine, but it's not \"pythonic\").</p>\n"
},
{
"answer_id": 64895238,
"author": "Inyoung Kim 김인영",
"author_id": 8471995,
"author_profile": "https://Stackoverflow.com/users/8471995",
"pm_score": 1,
"selected": false,
"text": "<p>I didn't like how solutions above created <code>wrappers</code> in the loop. Note: python 3.xx</p>\n<pre><code>flist = []\n\ndef func(i):\n return lambda x: x * i\n\nfor i in range(3):\n flist.append(func(i))\n\nfor f in flist:\n print f(2)\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233673",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8206/"
] |
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:
```
flist = []
for i in xrange(3):
def func(x): return x * i
flist.append(func)
for f in flist:
print f(2)
```
Note that this example mindfully avoids `lambda`. It prints "4 4 4", which is surprising. I'd expect "0 2 4".
This equivalent Perl code does it right:
```
my @flist = ();
foreach my $i (0 .. 2)
{
push(@flist, sub {$i * $_[0]});
}
foreach my $f (@flist)
{
print $f->(2), "\n";
}
```
"0 2 4" is printed.
Can you please explain the difference ?
---
Update:
The problem **is not** with `i` being global. This displays the same behavior:
```
flist = []
def outer():
for i in xrange(3):
def inner(x): return x * i
flist.append(inner)
outer()
#~ print i # commented because it causes an error
for f in flist:
print f(2)
```
As the commented line shows, `i` is unknown at that point. Still, it prints "4 4 4".
|
Python is actually behaving as defined. **Three separate functions** are created, but they each have the **closure of the environment they're defined in** - in this case, the global environment (or the outer function's environment if the loop is placed inside another function). This is exactly the problem, though - in this environment, **i is modified**, and the closures all **refer to the same i**.
Here is the best solution I can come up with - create a function creater and invoke *that* instead. This will force **different environments** for each of the functions created, with a **different i** in each one.
```
flist = []
for i in xrange(3):
def funcC(j):
def func(x): return x * j
return func
flist.append(funcC(i))
for f in flist:
print f(2)
```
This is what happens when you mix side effects and functional programming.
|
233,691 |
<p><strong>Scenario:</strong></p>
<p>The task I have at hand is to enable a single-signon solution between different organizations/websites. I start as an authenticated user on one organization's website, convert specific information into an Xml document, encrypt the document with triple des, and send that over as a post variable to the second organizations login page.</p>
<p><strong>Question:</strong></p>
<p>Once I have my xml data packaged, how do I programmatically perform a post to the second website and have the user's browser redirected to the second website as well.</p>
<p>This should behave just like having a form like: </p>
<p><em>action="http://www.www.com/posthere" method="post"</em></p>
<p>... and having a hidden text field like: </p>
<p><em>input type="hidden" value="my encrypted xml"</em></p>
<p>This is being written in asp.net 2.0 webforms.</p>
<p>--</p>
<p><strong>Edit:</strong> Nic asks why the html form I describe above will not work. Answer: I have no control over either site; I am building the "middle man" that makes all of this happen. Site 1 is forwarding a user to the page that I am making, I have to build the XML, and then forward it to site 2. Site 1 does not want the user to know about my site, the redirect should be transparent. </p>
<p>The process I have described above is what both parties (site A and site B) mandate.</p>
|
[
{
"answer_id": 233817,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "<p>You are thinking about this too process oriented, it would take you a month of sundays to try and work out all the bugs and moving parts with what you suggest.</p>\n\n<p>You are already doing a post to another server so you really don't need to do anything. The form you have is already perfect, and when the other server intercepts the request that is when it makes the decision to either allow to user in and continue in through the site, or redirect them back to their Referer (sic) in the header. When redirecting back to the Referer they may want to tack on a message that says what was wrong, such as ?error=no_auth</p>\n"
},
{
"answer_id": 234851,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "<p>Send back a document that contains the from with hidden input and include an onload handler that posts the form immediately to the other site. Using jquery's document.ready() solves the issue of whether the DOM is loaded before the post occurs, though there are other ways to do this without jquery. You might want to include some small message on the screen to the effect that the user will be redirected shortly and provide a link which also does the post </p>\n\n<pre><code>...headers left out...\n\n<script type='text/javascript'>\n\n$(document).ready( function() {\n $('form:first').submit();\n });\n</script>\n\n<body>\n <form action='othersiteurl' method='POST'>\n <input type='hidden' value='your-encrypted-xml\" />\n </form>\n</body>\n</code></pre>\n"
},
{
"answer_id": 243546,
"author": "craigmoliver",
"author_id": 12252,
"author_profile": "https://Stackoverflow.com/users/12252",
"pm_score": 0,
"selected": false,
"text": "<p>I wrote on this for another question a while back. Hope this helps:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/72125/how-do-you-pass-an-authenticaticated-session-between-app-domains#73077\">How do you pass an authenticaticated session between app domains</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5289/"
] |
**Scenario:**
The task I have at hand is to enable a single-signon solution between different organizations/websites. I start as an authenticated user on one organization's website, convert specific information into an Xml document, encrypt the document with triple des, and send that over as a post variable to the second organizations login page.
**Question:**
Once I have my xml data packaged, how do I programmatically perform a post to the second website and have the user's browser redirected to the second website as well.
This should behave just like having a form like:
*action="http://www.www.com/posthere" method="post"*
... and having a hidden text field like:
*input type="hidden" value="my encrypted xml"*
This is being written in asp.net 2.0 webforms.
--
**Edit:** Nic asks why the html form I describe above will not work. Answer: I have no control over either site; I am building the "middle man" that makes all of this happen. Site 1 is forwarding a user to the page that I am making, I have to build the XML, and then forward it to site 2. Site 1 does not want the user to know about my site, the redirect should be transparent.
The process I have described above is what both parties (site A and site B) mandate.
|
Send back a document that contains the from with hidden input and include an onload handler that posts the form immediately to the other site. Using jquery's document.ready() solves the issue of whether the DOM is loaded before the post occurs, though there are other ways to do this without jquery. You might want to include some small message on the screen to the effect that the user will be redirected shortly and provide a link which also does the post
```
...headers left out...
<script type='text/javascript'>
$(document).ready( function() {
$('form:first').submit();
});
</script>
<body>
<form action='othersiteurl' method='POST'>
<input type='hidden' value='your-encrypted-xml" />
</form>
</body>
```
|
233,711 |
<p>I use an anonymous object to pass my Html Attributes to some helper methods.
If the consumer didn't add an ID attribute, I want to add it in my helper method.</p>
<p>How can I add an attribute to this anonymous object?</p>
|
[
{
"answer_id": 233730,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>I assume you mean anonymous types here, e.g. <code>new { Name1=value1, Name2=value2}</code> etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.</p>\n\n<p>What you <em>could</em> do is write <code>new { old.Name1, old.Name2, ID=myId }</code> but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.</p>\n\n<p>Alternatively, you could create a container object which <em>always</em> had an ID and whatever other object contained the rest of the properties.</p>\n"
},
{
"answer_id": 233810,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}\n</code></pre>\n\n<p>This would accept the id value the textbox should have and the label should refer to.\nIf the consumer now doesn't include the \"id\" property in the textBoxHtmlAttributes, the method will create an incorrect label.</p>\n\n<p>I can check through reflection if this attribute is added in the labelHtmlAttributes object. If so, I want to add it or create a new anonymous object that has it added.\nBut because I can't create a new anonymous type by walking through the old attributes and adding my own \"id\" attribute, I'm kind of stuck.</p>\n\n<p>A container with a strongly typed ID property and then an anonymous typed \"attributes\" property would require code rewrites that don't weigh up to the \"add an id field\" requirement.</p>\n\n<p>Hope this response is understandable. It's the end of the day, can't get my brains in line anymore..</p>\n"
},
{
"answer_id": 4416536,
"author": "Khaja Minhajuddin",
"author_id": 24105,
"author_profile": "https://Stackoverflow.com/users/24105",
"pm_score": 6,
"selected": false,
"text": "<p>The following extension class would get you what you need.</p>\n\n<pre><code>public static class ObjectExtensions\n{\n public static IDictionary<string, object> AddProperty(this object obj, string name, object value)\n {\n var dictionary = obj.ToDictionary();\n dictionary.Add(name, value);\n return dictionary;\n }\n\n // helper\n public static IDictionary<string, object> ToDictionary(this object obj)\n {\n IDictionary<string, object> result = new Dictionary<string, object>();\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);\n foreach (PropertyDescriptor property in properties){\n result.Add(property.Name, property.GetValue(obj));\n }\n return result;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6753841,
"author": "Levitikon",
"author_id": 467339,
"author_profile": "https://Stackoverflow.com/users/467339",
"pm_score": 5,
"selected": true,
"text": "<p>If you're trying to extend this method:</p>\n\n<pre><code>public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);\n</code></pre>\n\n<p>Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:</p>\n\n<p>This should do the trick:</p>\n\n<pre><code> public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)\n {\n RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);\n\n // Add more parameters\n foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)\n {\n routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);\n }\n\n return helper.ActionLink(linkText, actionName, routeValueDictionary);\n }\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233711",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11333/"
] |
I use an anonymous object to pass my Html Attributes to some helper methods.
If the consumer didn't add an ID attribute, I want to add it in my helper method.
How can I add an attribute to this anonymous object?
|
If you're trying to extend this method:
```
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
```
Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:
This should do the trick:
```
public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
{
RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
// Add more parameters
foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
{
routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
}
return helper.ActionLink(linkText, actionName, routeValueDictionary);
}
```
|
233,718 |
<p>This question is about App domains and Sessions. Is it possible to have IIS run each User Session in a seperate App Domain. If Yes, Could you please let me settings in the config file that affect this.</p>
<p>Regards,
Anil.</p>
|
[
{
"answer_id": 233730,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "<p>I assume you mean anonymous types here, e.g. <code>new { Name1=value1, Name2=value2}</code> etc. If so, you're out of luck - anonymous types are normal types in that they're fixed, compiled code. They just happen to be autogenerated.</p>\n\n<p>What you <em>could</em> do is write <code>new { old.Name1, old.Name2, ID=myId }</code> but I don't know if that's really what you want. Some more details on the situation (including code samples) would be ideal.</p>\n\n<p>Alternatively, you could create a container object which <em>always</em> had an ID and whatever other object contained the rest of the properties.</p>\n"
},
{
"answer_id": 233810,
"author": "Boris Callens",
"author_id": 11333,
"author_profile": "https://Stackoverflow.com/users/11333",
"pm_score": -1,
"selected": false,
"text": "<pre><code>public static string TextBox(this HtmlHelper html, string value, string labelText, string textBoxId, object textBoxHtmlAttributes, object labelHtmlAttributes){}\n</code></pre>\n\n<p>This would accept the id value the textbox should have and the label should refer to.\nIf the consumer now doesn't include the \"id\" property in the textBoxHtmlAttributes, the method will create an incorrect label.</p>\n\n<p>I can check through reflection if this attribute is added in the labelHtmlAttributes object. If so, I want to add it or create a new anonymous object that has it added.\nBut because I can't create a new anonymous type by walking through the old attributes and adding my own \"id\" attribute, I'm kind of stuck.</p>\n\n<p>A container with a strongly typed ID property and then an anonymous typed \"attributes\" property would require code rewrites that don't weigh up to the \"add an id field\" requirement.</p>\n\n<p>Hope this response is understandable. It's the end of the day, can't get my brains in line anymore..</p>\n"
},
{
"answer_id": 4416536,
"author": "Khaja Minhajuddin",
"author_id": 24105,
"author_profile": "https://Stackoverflow.com/users/24105",
"pm_score": 6,
"selected": false,
"text": "<p>The following extension class would get you what you need.</p>\n\n<pre><code>public static class ObjectExtensions\n{\n public static IDictionary<string, object> AddProperty(this object obj, string name, object value)\n {\n var dictionary = obj.ToDictionary();\n dictionary.Add(name, value);\n return dictionary;\n }\n\n // helper\n public static IDictionary<string, object> ToDictionary(this object obj)\n {\n IDictionary<string, object> result = new Dictionary<string, object>();\n PropertyDescriptorCollection properties = TypeDescriptor.GetProperties(obj);\n foreach (PropertyDescriptor property in properties){\n result.Add(property.Name, property.GetValue(obj));\n }\n return result;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 6753841,
"author": "Levitikon",
"author_id": 467339,
"author_profile": "https://Stackoverflow.com/users/467339",
"pm_score": 5,
"selected": true,
"text": "<p>If you're trying to extend this method:</p>\n\n<pre><code>public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);\n</code></pre>\n\n<p>Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:</p>\n\n<p>This should do the trick:</p>\n\n<pre><code> public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)\n {\n RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);\n\n // Add more parameters\n foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)\n {\n routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);\n }\n\n return helper.ActionLink(linkText, actionName, routeValueDictionary);\n }\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
This question is about App domains and Sessions. Is it possible to have IIS run each User Session in a seperate App Domain. If Yes, Could you please let me settings in the config file that affect this.
Regards,
Anil.
|
If you're trying to extend this method:
```
public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues);
```
Although I'm sure Khaja's Object extensions would work, you might get better performance by creating a RouteValueDictionary and passing in the routeValues object, add your additional parameters from the Context, then return using the ActionLink overload that takes a RouteValueDictionary instead of an object:
This should do the trick:
```
public static MvcHtmlString MyLink(this HtmlHelper helper, string linkText, string actionName, object routeValues)
{
RouteValueDictionary routeValueDictionary = new RouteValueDictionary(routeValues);
// Add more parameters
foreach (string parameter in helper.ViewContext.RequestContext.HttpContext.Request.QueryString.AllKeys)
{
routeValueDictionary.Add(parameter, helper.ViewContext.RequestContext.HttpContext.Request.QueryString[parameter]);
}
return helper.ActionLink(linkText, actionName, routeValueDictionary);
}
```
|
233,719 |
<p>I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function</p>
<pre><code>window.clipboardData.getData("Text")
</code></pre>
<p>Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?</p>
|
[
{
"answer_id": 233781,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 1,
"selected": false,
"text": "<p>I believe people use a hidden Flash element to read the clipboard data from the browsers you mentioned.</p>\n"
},
{
"answer_id": 233838,
"author": "scunliffe",
"author_id": 6144,
"author_profile": "https://Stackoverflow.com/users/6144",
"pm_score": 2,
"selected": false,
"text": "<p><strong><em>NO.</em></strong> And if you do find a hack (e.g. old version of flash) do not depend on it.</p>\n\n<p>Can I ask why you want to read from the clipboard? If the user wants to pass along the clipboard contents, all they need to do is paste.</p>\n"
},
{
"answer_id": 234711,
"author": "eyelidlessness",
"author_id": 17964,
"author_profile": "https://Stackoverflow.com/users/17964",
"pm_score": 5,
"selected": true,
"text": "<p>Safari supports reading the clipboard during <code>onpaste</code> events:</p>\n\n<p><a href=\"http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/CopyAndPaste.html#//apple_ref/doc/uid/30001234-176911\" rel=\"noreferrer\">Information</a></p>\n\n<p>You want to do something like:</p>\n\n<pre><code>someDomNode.onpaste = function(e) {\n var paste = e.clipboardData && e.clipboardData.getData ?\n e.clipboardData.getData('text/plain') : // Standard\n window.clipboardData && window.clipboardData.getData ?\n window.clipboardData.getData('Text') : // MS\n false;\n if(paste) {\n // ...\n }\n};\n</code></pre>\n"
},
{
"answer_id": 258325,
"author": "agsamek",
"author_id": 33608,
"author_profile": "https://Stackoverflow.com/users/33608",
"pm_score": 4,
"selected": false,
"text": "<p>Online Spreadsheets hook <kbd>Ctrl</kbd>+<kbd>C</kbd>, <kbd>Ctrl</kbd>+<kbd>V</kbd> events and transfer focus to a hidden TextArea control and either set it contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.</p>\n"
},
{
"answer_id": 54373125,
"author": "Kim",
"author_id": 2396925,
"author_profile": "https://Stackoverflow.com/users/2396925",
"pm_score": 1,
"selected": false,
"text": "<p>Using @agsamek suggestion I created a little test snipped and got it to work. In my case I need to wait after a fresh pageload for pasted input, so I focus on an out-of-view textarea and read the text from there.</p>\n\n<p>You could extend this to listen to specific keys (paste combination) and then focus on the hidden field. There would definitely more work to be done as I think you need to re-focus then on the last focused element and paste content there.</p>\n\n<p>For my use-case though this was enough to make it work in latest Chrome and Firefox. Suggestions welcome.</p>\n\n<p><a href=\"https://jsfiddle.net/wuestkamp/91dxjv7s/11/\" rel=\"nofollow noreferrer\">https://jsfiddle.net/wuestkamp/91dxjv7s/11/</a></p>\n\n<pre><code>$(function () {\n\n $('body').prepend('<input type=\"text\" id=\"hidden_textbox\" style=\"position: absolute; width:0px; height: 0px; top: -100px; left: -100px\">');\n\n var $hiddenTextbox = $('#hidden_textbox');\n $hiddenTextbox.focus();\n\n $(document).on('paste', function () {\n setTimeout(function () {\n var val = $hiddenTextbox.val();\n\n console.log('pasted: ' + val);\n\n }, 50);\n\n });\n\n});\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25960/"
] |
I'm trying to read the contents of the clipboard using JavaScript. With Internet Explorer it's possible using the function
```
window.clipboardData.getData("Text")
```
Is there a similar way of reading the clipboard in Firefox, Safari and Chrome?
|
Safari supports reading the clipboard during `onpaste` events:
[Information](http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/CopyAndPaste.html#//apple_ref/doc/uid/30001234-176911)
You want to do something like:
```
someDomNode.onpaste = function(e) {
var paste = e.clipboardData && e.clipboardData.getData ?
e.clipboardData.getData('text/plain') : // Standard
window.clipboardData && window.clipboardData.getData ?
window.clipboardData.getData('Text') : // MS
false;
if(paste) {
// ...
}
};
```
|
233,721 |
<p>As per RFC1035, dns names may contain \ddd \x and quote symbol. Please explain with examples about those.</p>
|
[
{
"answer_id": 233941,
"author": "jj33",
"author_id": 430,
"author_profile": "https://Stackoverflow.com/users/430",
"pm_score": 2,
"selected": false,
"text": "<p><a href=\"http://www.ietf.org/rfc/rfc1035.txt\" rel=\"nofollow noreferrer\">RFC1035</a> doesn't say that DNS <strong>names</strong> can contain those characters. In section 5 (MASTER FILES) it says that the <strong>file</strong> that contains the RR information can contain those characters. Specifically: \"Because these files are text files several special encodings are\nnecessary to allow arbitrary data to be loaded.\" There's text other than domains that can go into zone files. For instance, the entry in a TXT record is free text, so you might want to put a binary character in it, represented with a \\ddd string, etc. You are also allowed to make comments, so you might use these \"special encodings\" in your comments.</p>\n\n<p>There is support for internationalized domain names, but RFC1035 is from 1987, it wasn't talking about i18n domain names at that time.</p>\n\n<p>EDIT: I just reread it and I think I'm wrong. The stuff above is technically about the file format. However, this is also in the RFC in section 3.1:</p>\n\n<blockquote>\n<pre><code>Although labels can contain any 8 bit values in octets that make up a\nlabel, it is strongly recommended that labels follow the preferred\nsyntax described elsewhere in this memo, which is compatible with\nexisting host naming conventions. Name servers and resolvers must\ncompare labels in a case-insensitive manner (i.e., A=a), assuming ASCII\nwith zero parity. Non-alphabetic codes must match exactly.\n</code></pre>\n</blockquote>\n\n<p>So, that says that any 8-bit char can be part of a label (where a label is that part of the domain name between dots). This doc is describing the technical capability of the DNS protocol, though. Common usage is a different thing. In fact, in section \"2.3.1. Preferred name syntax\":</p>\n\n<pre><code>The following syntax will result in\nfewer problems with many applications\nthat use domain names (e.g., mail,\nTELNET).\n\n<domain> ::= <subdomain> | \" \"\n\n<subdomain> ::= <label> | <subdomain>\n\".\" <label>\n\n<label> ::= <letter> [ [ <ldh-str> ]\n<let-dig> ]\n\n<ldh-str> ::= <let-dig-hyp> |\n<let-dig-hyp> <ldh-str>\n\n<let-dig-hyp> ::= <let-dig> | \"-\"\n\n<let-dig> ::= <letter> | <digit>\n\n<letter> ::= any one of the 52\nalphabetic characters A through Z in\nupper case and a through z in lower\ncase\n\n<digit> ::= any one of the ten digits\n0 through 9\n</code></pre>\n\n<p>In other words, the DNS protocol was defined from the beginning to work with 8-bit ascii. However, if you actually wanted your programs to be able to use the domains in the DNS, you should stick with [a-z-].</p>\n\n<p>As for an example, I think this just meant you could have a DNS entry like this:</p>\n\n<pre><code>IHaveAn\\020EmbeddedTab IN A 172.24.3.1\n</code></pre>\n"
},
{
"answer_id": 1587319,
"author": "bortzmeyer",
"author_id": 15625,
"author_profile": "https://Stackoverflow.com/users/15625",
"pm_score": 1,
"selected": false,
"text": "<p>The recommended reading is <a href=\"http://www.ietf.org/rfc/rfc2181.txt\" rel=\"nofollow noreferrer\">RFC 2181</a>, whose section 11 explains well the issue.</p>\n\n<p>Otherwise, for an example, see <code>maps-to-nonascii.rfc-test.net</code>. This name is an alias for a name with non-ASCII characters.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
As per RFC1035, dns names may contain \ddd \x and quote symbol. Please explain with examples about those.
|
[RFC1035](http://www.ietf.org/rfc/rfc1035.txt) doesn't say that DNS **names** can contain those characters. In section 5 (MASTER FILES) it says that the **file** that contains the RR information can contain those characters. Specifically: "Because these files are text files several special encodings are
necessary to allow arbitrary data to be loaded." There's text other than domains that can go into zone files. For instance, the entry in a TXT record is free text, so you might want to put a binary character in it, represented with a \ddd string, etc. You are also allowed to make comments, so you might use these "special encodings" in your comments.
There is support for internationalized domain names, but RFC1035 is from 1987, it wasn't talking about i18n domain names at that time.
EDIT: I just reread it and I think I'm wrong. The stuff above is technically about the file format. However, this is also in the RFC in section 3.1:
>
>
> ```
> Although labels can contain any 8 bit values in octets that make up a
> label, it is strongly recommended that labels follow the preferred
> syntax described elsewhere in this memo, which is compatible with
> existing host naming conventions. Name servers and resolvers must
> compare labels in a case-insensitive manner (i.e., A=a), assuming ASCII
> with zero parity. Non-alphabetic codes must match exactly.
>
> ```
>
>
So, that says that any 8-bit char can be part of a label (where a label is that part of the domain name between dots). This doc is describing the technical capability of the DNS protocol, though. Common usage is a different thing. In fact, in section "2.3.1. Preferred name syntax":
```
The following syntax will result in
fewer problems with many applications
that use domain names (e.g., mail,
TELNET).
<domain> ::= <subdomain> | " "
<subdomain> ::= <label> | <subdomain>
"." <label>
<label> ::= <letter> [ [ <ldh-str> ]
<let-dig> ]
<ldh-str> ::= <let-dig-hyp> |
<let-dig-hyp> <ldh-str>
<let-dig-hyp> ::= <let-dig> | "-"
<let-dig> ::= <letter> | <digit>
<letter> ::= any one of the 52
alphabetic characters A through Z in
upper case and a through z in lower
case
<digit> ::= any one of the ten digits
0 through 9
```
In other words, the DNS protocol was defined from the beginning to work with 8-bit ascii. However, if you actually wanted your programs to be able to use the domains in the DNS, you should stick with [a-z-].
As for an example, I think this just meant you could have a DNS entry like this:
```
IHaveAn\020EmbeddedTab IN A 172.24.3.1
```
|
233,749 |
<p>I have this loop, which I am using to get the values of all cells within all rows of a gridview and then write it to a csv file. My loop looks like this:</p>
<pre><code>string filename = @"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";
StreamWriter sWriter = new StreamWriter(filename);
string Str = string.Empty;
string headertext = "";
sWriter.WriteLine(headertext);
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
</code></pre>
<p>The problem with this code is that, when stepping through, the 2nd loop (the one going through the columns) does not begin as the debugger does not hit this loop and thus my file is empty.</p>
<p>Any ideas on what is causing this? The code itself looks fine.</p>
<p>Thanks</p>
|
[
{
"answer_id": 233891,
"author": "EFrank",
"author_id": 28572,
"author_profile": "https://Stackoverflow.com/users/28572",
"pm_score": 1,
"selected": false,
"text": "<p>I think the inner loop should access the <em>Cells</em>, not the columns:</p>\n\n<pre><code> for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)\n {\n\n for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)\n {\n\n Str = this.GridView3.Rows[i].Cells[j].Text.ToString();\n\n\n sWriter.Write(Str);\n }\n }\n</code></pre>\n"
},
{
"answer_id": 233951,
"author": "Timothy Carter",
"author_id": 4660,
"author_profile": "https://Stackoverflow.com/users/4660",
"pm_score": 0,
"selected": false,
"text": "<p>Adding in line numbers, if I understand your question correctly, you're saying that when debugging, you never reach line 8. If that is the case then I would expect your issue is that when you're actually processing through the loop there are no rows in your gridview. To figure out why that is the case, I would recommend looking at where you are in the post cycle for your page</p>\n\n<pre><code> string filename = @\"C:\\Users\\gurdip.sira\\Documents\\Visual Studio 2008\\WebSites\\Supressions\\APP_DATA\\surpressionstest.csv\";//1\n StreamWriter sWriter = new StreamWriter(filename);//2\n string Str = string.Empty;//3\n string headertext = \"\"; //4\n sWriter.WriteLine(headertext); //5\n for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++) //6\n { //7\n for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++) //8\n { //9\n Str = this.GridView3.Rows[i].Cells[j].Text.ToString();//10\n sWriter.Write(Str);//11\n }//12\n sWriter.WriteLine();//13\n }//14\n sWriter.Close();//15\n}//16\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233749",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30004/"
] |
I have this loop, which I am using to get the values of all cells within all rows of a gridview and then write it to a csv file. My loop looks like this:
```
string filename = @"C:\Users\gurdip.sira\Documents\Visual Studio 2008\WebSites\Supressions\APP_DATA\surpressionstest.csv";
StreamWriter sWriter = new StreamWriter(filename);
string Str = string.Empty;
string headertext = "";
sWriter.WriteLine(headertext);
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Columns.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
sWriter.Write(Str);
}
sWriter.WriteLine();
}
sWriter.Close();
```
The problem with this code is that, when stepping through, the 2nd loop (the one going through the columns) does not begin as the debugger does not hit this loop and thus my file is empty.
Any ideas on what is causing this? The code itself looks fine.
Thanks
|
I think the inner loop should access the *Cells*, not the columns:
```
for (int i = 0; i <= (this.GridView3.Rows.Count - 1); i++)
{
for (int j = 0; j <= (this.GridView3.Rows[i].Cells.Count - 1); j++)
{
Str = this.GridView3.Rows[i].Cells[j].Text.ToString();
sWriter.Write(Str);
}
}
```
|
233,756 |
<p>i've written a UserControl descendant that <strong>is</strong> in an assembly dll.</p>
<p>How do i drop the control on a form?</p>
<pre><code>namespace StackOverflowExample
{
public partial class MonthViewCalendar : UserControl
{
...
}
}
</code></pre>
<p>i've added a reference to the assembly under the <strong>References</strong> node in the <strong>Solution Explorer</strong>, but no new control has appeared in my <strong>Toolbox</strong>.</p>
<p>How do i make the control appear in the Toolbox so i can drop it on a form?</p>
<hr>
<p><strong>Update 1</strong>:</p>
<p>i tried building the assembly while the Visual Studio option:</p>
<p><strong>Tools</strong>--><strong>Options...</strong>--><strong>Windows Forms Designer</strong>--><strong>AutoToolboxPopulate</strong> = true</p>
<p>The control didn't appear when in the toolbox in a new solution.</p>
<p>Note: i somehow mistakenly wrote "...that is <em>not</em> in an assembly dll...". i don't know how i managed to write that, when it specifically <em>is</em> in an assembly dll. Controls have magically appeared when they're in the same project, but not now that it's a different project/solution.</p>
<hr>
<p><strong>Update 2: Answer</strong></p>
<ol>
<li>Right-click the <strong>Toolbox</strong></li>
<li>Select <strong>Choose Items...</strong></li>
<li><strong>.NET Framework Components</strong> tab</li>
<li>Select <strong>Browse...</strong></li>
<li><p>Browse to the <strong>assembly dll</strong> file that contains the control and select <strong>Open</strong></p>
<p>Note: Controls in the assembly will silently be added to the list of .NET Framework Components.</p></li>
<li><strong>Check</strong> each of the controls you wish to appear in the toolbox</li>
<li>Select <strong>OK</strong></li>
</ol>
|
[
{
"answer_id": 233770,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": -1,
"selected": false,
"text": "<p>Add the ToolboxAttribute to your class.</p>\n"
},
{
"answer_id": 233774,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 0,
"selected": false,
"text": "<p>You need to build the project containing the control you've created and make sure your options are set for the Toolbox to rebuild. If you haven't changed it from defaults, it should work; otherwise, go to <strong>Tools-->Options...</strong> and select the Windows Forms Designer group. Make sure the <strong>AutoToolboxPopulate</strong> option is set to <strong>true</strong>.</p>\n\n<p>You don't need the <code>ToolboxItemAttribute</code> for it to work. If the providing assembly is in the same solution as the consuming assembly, it should appear in the toolbox. If the providing assembly is not part of the solution, you can manually add the assembly to the toolbox by selecting **Choose items...* from the toolbox context menu and adding your assembly directly. If you want the toolbox to automatically pick them up, you will need to use the <code>ToolboxItemAttribute</code>.</p>\n"
},
{
"answer_id": 233792,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 3,
"selected": true,
"text": "<p>Normally, when you build your project, your user control will appear in your toolbox at the top. Normally, you will see a new pane with each of your Assemblies and the controls in there.</p>\n\n<p>If that doesn't happen, you can also add your control by right clicking on the toolbox, selecting <em>Choose Items</em>, then under <em>.NET Framework Components</em> browsing for your assembly, adding it, then make sure your control is checked.</p>\n"
},
{
"answer_id": 233958,
"author": "Martin Marconcini",
"author_id": 2684,
"author_profile": "https://Stackoverflow.com/users/2684",
"pm_score": 0,
"selected": false,
"text": "<p>I stumbled upon some problems with this. In the end, just rebuild and re-reference will work. I had preferred to inherit from UserControl. It made my life simpler ;)</p>\n\n<p>If for example you want to create a \"rounded border\" label, do something like this:</p>\n\n<pre><code>using System;\nusing System.ComponentModel;\nusing System.Drawing;\nusing System.Drawing.Drawing2D;\nusing System.Windows.Forms;\n\nnamespace YourUIControls\n{\n [DefaultProperty(\"TextString\")]\n [DefaultEvent(\"TextClick\")]\n public partial class RoundedLabel : UserControl\n {\n public RoundedLabel()\n {\n InitializeComponent();\n }\n protected override void OnPaint(PaintEventArgs e)\n {\n //Draw your label here…\n }\n }\n}\n</code></pre>\n\n<p>Compile and add a reference to the output. You'll be able to drag that to the Toolbox and later to the Designer. </p>\n"
},
{
"answer_id": 6016469,
"author": "Alain van Lith",
"author_id": 755522,
"author_profile": "https://Stackoverflow.com/users/755522",
"pm_score": 1,
"selected": false,
"text": "<p>What I notice is that User Controls and Components are only automatically added to the Toolbox by vs2005 when your project (containing the controls/components) is located in the same folder as your solution. When this project is in a subfolder vs2005 won't add the controls and components in the Toolbox.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12597/"
] |
i've written a UserControl descendant that **is** in an assembly dll.
How do i drop the control on a form?
```
namespace StackOverflowExample
{
public partial class MonthViewCalendar : UserControl
{
...
}
}
```
i've added a reference to the assembly under the **References** node in the **Solution Explorer**, but no new control has appeared in my **Toolbox**.
How do i make the control appear in the Toolbox so i can drop it on a form?
---
**Update 1**:
i tried building the assembly while the Visual Studio option:
**Tools**-->**Options...**-->**Windows Forms Designer**-->**AutoToolboxPopulate** = true
The control didn't appear when in the toolbox in a new solution.
Note: i somehow mistakenly wrote "...that is *not* in an assembly dll...". i don't know how i managed to write that, when it specifically *is* in an assembly dll. Controls have magically appeared when they're in the same project, but not now that it's a different project/solution.
---
**Update 2: Answer**
1. Right-click the **Toolbox**
2. Select **Choose Items...**
3. **.NET Framework Components** tab
4. Select **Browse...**
5. Browse to the **assembly dll** file that contains the control and select **Open**
Note: Controls in the assembly will silently be added to the list of .NET Framework Components.
6. **Check** each of the controls you wish to appear in the toolbox
7. Select **OK**
|
Normally, when you build your project, your user control will appear in your toolbox at the top. Normally, you will see a new pane with each of your Assemblies and the controls in there.
If that doesn't happen, you can also add your control by right clicking on the toolbox, selecting *Choose Items*, then under *.NET Framework Components* browsing for your assembly, adding it, then make sure your control is checked.
|
233,793 |
<p>I'm trying to dynamically add some textboxes (input type=text) to a page in javascript and prefill them. The textboxes are coming up, but they are coming up empty. What is the proper way to pre-fill a textbox. Ideally I'd love to use the trick of creating a child div, setting the innerhtml property, and then adding that div to the parent main div but that didn't work. Then I thought I'd use the dom but setting textboxname.value before or after insertion won't work and doing txttextbox.setattribute('value','somevalue') won't work either. Works fine in firefox. What gives? This has to be possible? Here is my code. I know I'm only using string literals, but these will be replaced with the results of a web service call eventually. Below is some code. Oh and how do you format code to show up as you type it? I thought it said to indent four spaces, and I did that but the code is still on one line. Sorry about that.</p>
<pre><code>var table=document.createElement('table');
var tbody=document.createElement('tbody');
var row=document.createElement('tr');
row.appendChild(document.createElement('td').appendChild(document.createTextNode('E-mail')));
var txtEmail=document.createElement('input');
row.appendChild(document.createElement('td').appendChild(txtEmail));
tbody.appendChild(row);
table.appendChild(tbody);
//document.getElementById('additionalEmails').innerHTML="";
document.getElementById('additionalEmails').appendChild(table);
</code></pre>
|
[
{
"answer_id": 233815,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 2,
"selected": false,
"text": "<pre><code>txtEmail.value = 'my text'\n</code></pre>\n\n<p>Does not work?</p>\n"
},
{
"answer_id": 233853,
"author": "Diodeus - James MacFarlane",
"author_id": 12579,
"author_profile": "https://Stackoverflow.com/users/12579",
"pm_score": 2,
"selected": false,
"text": "<p>You can also use <a href=\"http://prototypejs.org\" rel=\"nofollow noreferrer\">Prototype</a> to do this easily:</p>\n\n<pre><code>document.body.insert(new Element(\"input\", { type: \"text\", size:20, value:'hello world' })) \n</code></pre>\n"
},
{
"answer_id": 233893,
"author": "mmacaulay",
"author_id": 22152,
"author_profile": "https://Stackoverflow.com/users/22152",
"pm_score": 0,
"selected": false,
"text": "<p>I've encountered problems similar to this in the past, and while my memory is a bit fuzzy on why it was happening exactly, I think you may need to make sure the element is actually added to the DOM before modifying its value. e.g:</p>\n\n<pre>\n<code>\nvar txtEmail=document.createElement('input');\n\ndocument.getElementById('someElementThatAlreadyExists').appendChild(txtEmail);\n\ntxtEmail.value = 'sample text';\n</code>\n</pre>\n"
},
{
"answer_id": 234078,
"author": "Chris Westbrook",
"author_id": 16891,
"author_profile": "https://Stackoverflow.com/users/16891",
"pm_score": 0,
"selected": false,
"text": "<p>I ended up solving this problem by injecting the html directly into a page via a child div. That did work, it's just that I am blind and the software I use to read the screen for some stupid reason failed to see the text in the textbox. Go figure. Thanks for the tip on prototype though, if I ever decide not to cheat and add the eleements to the dom directly, I'll do it that way.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16891/"
] |
I'm trying to dynamically add some textboxes (input type=text) to a page in javascript and prefill them. The textboxes are coming up, but they are coming up empty. What is the proper way to pre-fill a textbox. Ideally I'd love to use the trick of creating a child div, setting the innerhtml property, and then adding that div to the parent main div but that didn't work. Then I thought I'd use the dom but setting textboxname.value before or after insertion won't work and doing txttextbox.setattribute('value','somevalue') won't work either. Works fine in firefox. What gives? This has to be possible? Here is my code. I know I'm only using string literals, but these will be replaced with the results of a web service call eventually. Below is some code. Oh and how do you format code to show up as you type it? I thought it said to indent four spaces, and I did that but the code is still on one line. Sorry about that.
```
var table=document.createElement('table');
var tbody=document.createElement('tbody');
var row=document.createElement('tr');
row.appendChild(document.createElement('td').appendChild(document.createTextNode('E-mail')));
var txtEmail=document.createElement('input');
row.appendChild(document.createElement('td').appendChild(txtEmail));
tbody.appendChild(row);
table.appendChild(tbody);
//document.getElementById('additionalEmails').innerHTML="";
document.getElementById('additionalEmails').appendChild(table);
```
|
```
txtEmail.value = 'my text'
```
Does not work?
|
233,802 |
<p>I am trying to detect Blackberry user agents in my app, which works fine in my development version. But nothing happens when I redeploy the app in production.</p>
<p>application_helper.rb</p>
<pre><code> def blackberry_user_agent?
request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Blackberry)/]
end
</code></pre>
<p>application.html.erb</p>
<pre><code><% if blackberry_user_agent? -%>
<div class="message">
<p>Using a Blackberry? <a href="http://mobile.site.ca/">Use the mobile optimized version</a>.</p>
</div>
</code></pre>
<p>I've tried clearing the cache using rake tmp:cache:clear and restarted mongrel a few times. Apparently the HTTP_USER_AGENT is coming back nil in production. I am using Nginx with a mongrel cluster.</p>
|
[
{
"answer_id": 233986,
"author": "Mike Breen",
"author_id": 22346,
"author_profile": "https://Stackoverflow.com/users/22346",
"pm_score": 3,
"selected": true,
"text": "<p>Are you using Apache or nginx in front of your mongrel(s)?</p>\n\n<p>Are you logging the user_agent? This is from my nginx.conf:</p>\n\n<pre><code>log_format main '$remote_addr - $remote_user [$time_local] $request '\n '\"$status\" $body_bytes_sent \"$http_referer\" '\n '\"$http_user_agent\" \"http_x_forwarded_for\"';\n</code></pre>\n"
},
{
"answer_id": 248115,
"author": "Gabe Hollombe",
"author_id": 30632,
"author_profile": "https://Stackoverflow.com/users/30632",
"pm_score": 5,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>request.user_agent\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10258/"
] |
I am trying to detect Blackberry user agents in my app, which works fine in my development version. But nothing happens when I redeploy the app in production.
application\_helper.rb
```
def blackberry_user_agent?
request.env["HTTP_USER_AGENT"] && request.env["HTTP_USER_AGENT"][/(Blackberry)/]
end
```
application.html.erb
```
<% if blackberry_user_agent? -%>
<div class="message">
<p>Using a Blackberry? <a href="http://mobile.site.ca/">Use the mobile optimized version</a>.</p>
</div>
```
I've tried clearing the cache using rake tmp:cache:clear and restarted mongrel a few times. Apparently the HTTP\_USER\_AGENT is coming back nil in production. I am using Nginx with a mongrel cluster.
|
Are you using Apache or nginx in front of your mongrel(s)?
Are you logging the user\_agent? This is from my nginx.conf:
```
log_format main '$remote_addr - $remote_user [$time_local] $request '
'"$status" $body_bytes_sent "$http_referer" '
'"$http_user_agent" "http_x_forwarded_for"';
```
|
233,842 |
<p>I am using VB.Net WinForms. I would like to call the Adobe Reader 9 ActiveX control to print some PDFs. I have added the ActiveX control to the VS toolbox (the dll is AcroPDF.dll, the COM name "Adobe PDF Reader". After some experiment the following code works.</p>
<pre><code>Dim files As String() = Directory.GetFiles(TextBoxPath.Text, "*.pdf", SearchOption.TopDirectoryOnly)
Using ActiveXPDF As New AxAcroPDFLib.AxAcroPDF
Me.Controls.Add(ActiveXPDF)
ActiveXPDF.Hide()
For Each filename As String In files
ActiveXPDF.LoadFile(filename)
ActiveXPDF.printAll()
'Begin Yukky Hack '
Dim endTime As Date = DateAdd(DateInterval.Second, 20, Now)
Do While Now < endTime
My.Application.DoEvents()
Loop
'End Yuk '
Next
End Using
</code></pre>
<p>Without the Yuk bit this will only print some of the PDFs, it seems that the End Using statement is calling dispose on the control before it has finished printing.</p>
<p>Therefore it seems the call to printAll is non-blocking but I can't find a callback or status property I can query to see if the print spooling has been completed. I am missing a property/method or is there a more elegant (and more responsive) work around?</p>
|
[
{
"answer_id": 234124,
"author": "Rick Minerich",
"author_id": 9251,
"author_profile": "https://Stackoverflow.com/users/9251",
"pm_score": 0,
"selected": false,
"text": "<p>We ended up using Adobe's PDF Verifier for our own testing purposes. In order to do this we had to actually launch acrobat and manipulate it's interface programmatically using <a href=\"http://www.pinvoke.net/default.aspx/user32.SendInput\" rel=\"nofollow noreferrer\">SendInput</a>. </p>\n\n<p>I would be very interested in seeing if it would be possible to use an internal API instead.</p>\n"
},
{
"answer_id": 396134,
"author": "Jimmy Bergmark - JTB World",
"author_id": 49501,
"author_profile": "https://Stackoverflow.com/users/49501",
"pm_score": 3,
"selected": true,
"text": "<p>Using this method to print multiple documents is not going to work good as you found.</p>\n\n<p>Having it work is quite tricky but here is a general description of the solution.</p>\n\n<p>I use System.Diagnostics.Process to print using myProcess.StartInfo.Verb = \"Print\"\nThen I check the Status and State of printer queue in two steps to make sure that the printing is ready enough to be able to print the next document. Use WMI and ManagementObjectSearcher to enumerate the printer info using \"SELECT * FROM Win32_Printer\".\nThe logic is that I try to see if the spooling is started before continuing to print the next one. </p>\n\n<p>See <a href=\"http://msdn.microsoft.com/en-us/library/aa394363.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa394363.aspx</a> for the Win32_Printer WMI class.</p>\n"
},
{
"answer_id": 1862454,
"author": "Ed Zenker",
"author_id": 226624,
"author_profile": "https://Stackoverflow.com/users/226624",
"pm_score": -1,
"selected": false,
"text": "<p>You can use this code to display any file with its appropriate software.</p>\n\n<pre><code>Sub Show_Document(ByVal FILENAME As String)\n Dim p As Process = Nothing\n Try\n If My.Computer.FileSystem.FileExists(FILENAME) Then\n p = Process.Start(FILENAME)\n p.Dispose()\n End If\n\n Catch ex As Exception\n\n Finally\n\n End Try\n\nEnd Sub\n</code></pre>\n"
},
{
"answer_id": 9227853,
"author": "Anderson",
"author_id": 1202042,
"author_profile": "https://Stackoverflow.com/users/1202042",
"pm_score": 1,
"selected": false,
"text": "<p>I had the same problem using AcroPDF in Delphi.. then I figured out that when I \"stop\" the processo using a message, AcroPDF starts to print.</p>\n\n<p>So I just create a modal TForm that closes itself after some seconds. </p>\n\n<pre><code>var\n formModal : TFormModal;\nbegin\n formModal := TFormModal.Create(self);\n //PrintMethodHere \n frmPecas.CarregarDocumentoParaImpressao();\n formModal.ShowModal;\nend;\n</code></pre>\n\n<p>The TFormModal is this and I just insert a loading icon on the form to represents something like \"printing\".</p>\n\n<pre><code>unit FModal;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, ExtCtrls, Animate, GIFCtrl;\n\ntype\n TFormModal = class(TForm)\n Timer: TTimer;\n imgGif: TRxGIFAnimator;\n procedure TimerTimer(Sender: TObject);\n procedure FormShow(Sender: TObject);\n procedure FormClose(Sender: TObject; var Action: TCloseAction);\n procedure FormCreate(Sender: TObject);\n procedure FormKeyDown(Sender: TObject; var Key: Word;\n Shift: TShiftState);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n FormModal: TFormModal;\n\nimplementation\n\n{$R *.dfm}\n// Author: Anderson Mello Date: 09-fev-2012\n// DEscription: Using TTimer after 5 seconds I close this form\nprocedure TFormModal.TimerTimer(Sender: TObject);\nbegin\n close;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: Enable the timer only when the form is shown\nprocedure TFormModal.FormShow(Sender: TObject);\nbegin\n Timer.Enabled := true;\nend;\n\n// Description: disable when close\nprocedure TFormModal.FormClose(Sender: TObject; var Action: TCloseAction);\nbegin\n Timer.Enabled := false;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: disable close button \"X\", so the user can't close \nprocedure TFormModal.FormCreate(Sender: TObject);\nvar\n hSysMenu:HMENU;\nbegin\n hSysMenu:=GetSystemMenu(Self.Handle,False);\n if hSysMenu <> 0 then begin\n EnableMenuItem(hSysMenu,SC_CLOSE,MF_BYCOMMAND or MF_GRAYED);\n DrawMenuBar(Self.Handle);\n end;\n KeyPreview:=True;\nend;\n\n// Author: Anderson Mello Date: 09-fev-2012\n// Description: disable shortcuts to close\nprocedure TFormModal.FormKeyDown(Sender: TObject; var Key: Word;\n Shift: TShiftState);\nbegin\n if (Key = VK_F4) and (ssAlt in Shift) then\n Key:=0;\nend;\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233842",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29411/"
] |
I am using VB.Net WinForms. I would like to call the Adobe Reader 9 ActiveX control to print some PDFs. I have added the ActiveX control to the VS toolbox (the dll is AcroPDF.dll, the COM name "Adobe PDF Reader". After some experiment the following code works.
```
Dim files As String() = Directory.GetFiles(TextBoxPath.Text, "*.pdf", SearchOption.TopDirectoryOnly)
Using ActiveXPDF As New AxAcroPDFLib.AxAcroPDF
Me.Controls.Add(ActiveXPDF)
ActiveXPDF.Hide()
For Each filename As String In files
ActiveXPDF.LoadFile(filename)
ActiveXPDF.printAll()
'Begin Yukky Hack '
Dim endTime As Date = DateAdd(DateInterval.Second, 20, Now)
Do While Now < endTime
My.Application.DoEvents()
Loop
'End Yuk '
Next
End Using
```
Without the Yuk bit this will only print some of the PDFs, it seems that the End Using statement is calling dispose on the control before it has finished printing.
Therefore it seems the call to printAll is non-blocking but I can't find a callback or status property I can query to see if the print spooling has been completed. I am missing a property/method or is there a more elegant (and more responsive) work around?
|
Using this method to print multiple documents is not going to work good as you found.
Having it work is quite tricky but here is a general description of the solution.
I use System.Diagnostics.Process to print using myProcess.StartInfo.Verb = "Print"
Then I check the Status and State of printer queue in two steps to make sure that the printing is ready enough to be able to print the next document. Use WMI and ManagementObjectSearcher to enumerate the printer info using "SELECT \* FROM Win32\_Printer".
The logic is that I try to see if the spooling is started before continuing to print the next one.
See <http://msdn.microsoft.com/en-us/library/aa394363.aspx> for the Win32\_Printer WMI class.
|
233,850 |
<p>What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game? I always find the piece rotation and representation schemes confusing.</p>
<p>Most tetris games seem to use a naive "remake the array of blocks" at each rotation:</p>
<p><a href="http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris" rel="noreferrer">http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris</a></p>
<p>However, some use pre-built encoded numbers and bit shifting to represent each piece:</p>
<p><a href="http://www.codeplex.com/wintris" rel="noreferrer">http://www.codeplex.com/wintris</a></p>
<p>Is there a method to do this using mathematics (not sure that would work on a cell based board)?</p>
|
[
{
"answer_id": 233882,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 5,
"selected": false,
"text": "<p>There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.</p>\n\n<p>But there are rotation algorithms. </p>\n\n<p>Chose a centerpoint and rotate pi/2. </p>\n\n<p>If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).\nApply this for each block and the piece is rotated.</p>\n\n<p>Each x is the previous y and each y - the previous x. Which gives the following matrix:</p>\n\n<pre><code>[ 0 1 ]\n[ -1 0 ]\n</code></pre>\n\n<p>For counterclockwise rotation, use:</p>\n\n<pre><code>[ 0 -1 ]\n[ 1 0 ]\n</code></pre>\n"
},
{
"answer_id": 233892,
"author": "mspmsp",
"author_id": 21724,
"author_profile": "https://Stackoverflow.com/users/21724",
"pm_score": 0,
"selected": false,
"text": "<p>I have used a shape position and set of four coordinates for the four points in all the shapes. Since it's in 2D space, you can easy apply a 2D rotational matrice to the points.</p>\n\n<p>The points are divs so their css class is turned from off to on. (this is after clearing the css class of where they were last turn.)</p>\n"
},
{
"answer_id": 233894,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "<p>Personally I've always just represented the rotations by hand - with very few shapes, it's easy to code that way. Basically I had (as pseudo-code)</p>\n\n<pre><code>class Shape\n{\n Color color;\n ShapeRotation[] rotations;\n}\n\nclass ShapeRotation\n{\n Point[4] points;\n}\n\nclass Point\n{\n int x, y;\n}\n</code></pre>\n\n<p>At least conceptually - a multi-dimensional array of points directly in shape would do the trick too :)</p>\n"
},
{
"answer_id": 233909,
"author": "AgentThirteen",
"author_id": 26199,
"author_profile": "https://Stackoverflow.com/users/26199",
"pm_score": 3,
"selected": false,
"text": "<p>Since there are only 4 possible orientations for each shape, why not use an array of states for the shape and rotating CW or CCW simply increments or decrements the index of the shape state (with wraparound for the index)? I would think that might be quicker than performing rotation calculations and whatnot.</p>\n"
},
{
"answer_id": 233985,
"author": "Dave Cluderay",
"author_id": 30933,
"author_profile": "https://Stackoverflow.com/users/30933",
"pm_score": 4,
"selected": false,
"text": "<p>This is how I did it recently in a jQuery/CSS based tetris game.</p>\n\n<p>Work out the centre of the block (to be used as a pivot point), i.e. the centre of the block shape.\nCall that (px, py).</p>\n\n<p>Each brick that makes up the block shape will rotate around that point.\nFor each brick, you can apply the following calculation...</p>\n\n<p>Where each brick's width and height is q, the brick's current location (of the upper left corner) is (x1, y1) and the new brick location is (x2, y2):</p>\n\n<pre><code>x2 = (y1 + px - py)\n\ny2 = (px + py - x1 - q)\n</code></pre>\n\n<p>To rotate the opposite direction:</p>\n\n<pre><code>x2 = (px + py - y1 - q)\n\ny2 = (x1 + py - px)\n</code></pre>\n\n<p>This calculation is based on a 2D affine matrix transformation.\nIf you are interested in how I got to this let me know.</p>\n"
},
{
"answer_id": 1740038,
"author": "BeMasher",
"author_id": 211769,
"author_profile": "https://Stackoverflow.com/users/211769",
"pm_score": 2,
"selected": false,
"text": "<p>If you're doing this in python, cell-based instead of coordinate pairs it's very simple to rotate a nested list.</p>\n\n<pre><code>rotate = lambda tetrad: zip(*tetrad[::-1])\n\n# S Tetrad\ntetrad = rotate([[0,0,0,0], [0,0,0,0], [0,1,1,0], [1,1,0,0]])\n</code></pre>\n"
},
{
"answer_id": 1996601,
"author": "mdm",
"author_id": 25318,
"author_profile": "https://Stackoverflow.com/users/25318",
"pm_score": 2,
"selected": false,
"text": "<p>I derived a rotation algorithm from matrix rotations <a href=\"https://stackoverflow.com/questions/1457605/rotating-cordinates-around-pivot-tetris\">here</a>. To sum it up: If you have a list of coordinates for all cells that make up the block, e.g. [(0, 1), (1, 1), (2, 1), (3, 1)] or [(1, 0), (0, 1), (1, 1), (2, 1)]:</p>\n\n<pre><code> 0123 012\n0.... 0.#.\n1#### or 1###\n2.... 2...\n3....\n</code></pre>\n\n<p>you can calculate the new coordinates using</p>\n\n<pre><code>x_new = y_old\ny_new = 1 - (x_old - (me - 2))\n</code></pre>\n\n<p>for clockwise rotation and</p>\n\n<pre><code>x_new = 1 - (y_old - (me - 2))\ny_new = x_old\n</code></pre>\n\n<p>for counter-clockwise rotation. <code>me</code> is the maximum extent of the block, i.e. <code>4</code> for I-blocks, <code>2</code> for O-blocks and <code>3</code> for all other blocks.</p>\n"
},
{
"answer_id": 2753376,
"author": "Ricardo Sousa",
"author_id": 330791,
"author_profile": "https://Stackoverflow.com/users/330791",
"pm_score": 3,
"selected": false,
"text": "<p>You can rotate a matrix only by applying mathematical operations to it. If you have a matrix, say:</p>\n\n<pre><code>Mat A = [1,1,1]\n [0,0,1]\n [0,0,0]\n</code></pre>\n\n<p>To rotate it, multiply it by its transpose and then by this matrix ([I]dentity [H]orizontaly [M]irrored):</p>\n\n<pre><code>IHM(A) = [0,0,1]\n [0,1,0]\n [1,0,0]\n</code></pre>\n\n<p>Then you'll have:</p>\n\n<pre><code>Mat Rotation = Trn(A)*IHM(A) = [1,0,0]*[0,0,1] = [0,0,1]\n [1,0,0] [0,1,0] = [0,0,1]\n [1,1,0] [1,0,0] = [0,1,1]\n</code></pre>\n\n<p>Note: Center of rotation will be the center of the matrix, in this case at (2,2).</p>\n"
},
{
"answer_id": 4610709,
"author": "JaMaZz",
"author_id": 564778,
"author_profile": "https://Stackoverflow.com/users/564778",
"pm_score": 1,
"selected": false,
"text": "<p>for 3x3 sized tetris pieces\nflip x and y of your piece \nthen swap the outer columns\nthat's what I figured out some time</p>\n"
},
{
"answer_id": 8131337,
"author": "Jason Rae",
"author_id": 680565,
"author_profile": "https://Stackoverflow.com/users/680565",
"pm_score": 5,
"selected": false,
"text": "<p>When I was trying to figure out how rotations would work for my tetris game, this was the first question that I found on stack overflow. Even though this question is old, I think my input will help others trying to figure this out algorithmically. First, I disagree that hard coding each piece and rotation will be easier. Gamecat's answer is correct, but I wanted to elaborate on it. Here are the steps I used to solve the rotation problem in Java.</p>\n\n<ol>\n<li><p>For each shape, determine where its origin will be. I used the points on the diagram from <a href=\"http://tetris.wikia.com/wiki/SRS\" rel=\"noreferrer\">this page</a> to assign my origin points. Keep in mind that, depending on your implementation, you may have to modify the origin every time the piece is moved by the user.</p></li>\n<li><p>Rotation assumes the origin is located at point (0,0), so you will have to translate each block before it can be rotated. For example, suppose your origin is currently at point (4, 5). This means that before the shape can be rotated, each block must be translated -4 in the x-coordinate and -5 in the y-coordinate to be relative to (0,0).</p></li>\n<li><p>In Java, a typical coordinate plane starts with point (0,0) in the upper left most corner and then increases to the right and down. To compensate for this in my implementation, I multiplied each point by -1 before rotation.</p></li>\n<li><p>Here are the formulae I used to figure out the new x and y coordinate after a counter-clockwise rotation. For more information on this, I would check out the Wikipedia page on <a href=\"http://en.wikipedia.org/wiki/Rotation_matrix\" rel=\"noreferrer\">Rotation Matrix</a>. x' and y' are the new coordinates:</p>\n\n<p>x' = x * cos(PI/2) - y * sin(PI/2) and y' = x * sin(PI/2) + y * cos(PI/2)\n.</p></li>\n<li><p>For the last step, I just went through steps 2 and 3 in reverse order. So I multiplied my results by -1 again and then translated the blocks back to their original coordinates.</p></li>\n</ol>\n\n<p>Here is the code that worked for me (in Java) to get an idea of how to do it in your language:</p>\n\n<pre><code>public synchronized void rotateLeft(){\n\n Point[] rotatedCoordinates = new Point[MAX_COORDINATES];\n\n for(int i = 0; i < MAX_COORDINATES; i++){\n\n // Translates current coordinate to be relative to (0,0)\n Point translationCoordinate = new Point(coordinates[i].x - origin.x, coordinates[i].y - origin.y);\n\n // Java coordinates start at 0 and increase as a point moves down, so\n // multiply by -1 to reverse\n translationCoordinate.y *= -1;\n\n // Clone coordinates, so I can use translation coordinates\n // in upcoming calculation\n rotatedCoordinates[i] = (Point)translationCoordinate.clone();\n\n // May need to round results after rotation\n rotatedCoordinates[i].x = (int)Math.round(translationCoordinate.x * Math.cos(Math.PI/2) - translationCoordinate.y * Math.sin(Math.PI/2)); \n rotatedCoordinates[i].y = (int)Math.round(translationCoordinate.x * Math.sin(Math.PI/2) + translationCoordinate.y * Math.cos(Math.PI/2));\n\n // Multiply y-coordinate by -1 again\n rotatedCoordinates[i].y *= -1;\n\n // Translate to get new coordinates relative to\n // original origin\n rotatedCoordinates[i].x += origin.x;\n rotatedCoordinates[i].y += origin.y;\n\n // Erase the old coordinates by making them black\n matrix.fillCell(coordinates[i].x, coordinates[i].y, Color.black);\n\n }\n // Set new coordinates to be drawn on screen\n setCoordinates(rotatedCoordinates.clone());\n}\n</code></pre>\n\n<p>This method is all that is needed to rotate your shape to the left, which turns out to be much smaller (depending on your language) than defining each rotation for every shape.</p>\n"
},
{
"answer_id": 12767925,
"author": "Mickey Tin",
"author_id": 1649615,
"author_profile": "https://Stackoverflow.com/users/1649615",
"pm_score": 0,
"selected": false,
"text": "<p>If array size is 3*3 ,than the simplest way to rotate it for example in anti-clockwise direction is:</p>\n\n<pre><code>oldShapeMap[3][3] = {{1,1,0},\n {0,1,0},\n {0,1,1}};\n\nbool newShapeMap[3][3] = {0};\nint gridSize = 3;\n\nfor(int i=0;i<gridSize;i++)\n for(int j=0;j<gridSize;j++)\n newShapeMap[i][j] = oldShapeMap[j][(gridSize-1) - i];\n/*newShapeMap now contain: \n {{0,0,1},\n {1,1,1},\n {1,0,0}};\n\n*/ \n</code></pre>\n"
},
{
"answer_id": 14926239,
"author": "Andrew Fader",
"author_id": 962968,
"author_profile": "https://Stackoverflow.com/users/962968",
"pm_score": 0,
"selected": false,
"text": "<p>In Ruby, at least, you can actually use matrices. Represent your piece shapes as nested arrays of arrays like [[0,1],[0,2],[0,3]]</p>\n\n<pre><code>require 'matrix'\nshape = shape.map{|arr|(Matrix[arr] * Matrix[[0,-1],[1,0]]).to_a.flatten}\n</code></pre>\n\n<p>However, I agree that hard-coding the shapes is feasible since there are 7 shapes and 4 states for each = 28 lines and it will never be any more than that.</p>\n\n<p>For more on this see my blog post at \n<a href=\"https://content.pivotal.io/blog/the-simplest-thing-that-could-possibly-work-in-tetris\" rel=\"nofollow noreferrer\">https://content.pivotal.io/blog/the-simplest-thing-that-could-possibly-work-in-tetris</a> and a completely working implementation (with minor bugs) at <a href=\"https://github.com/andrewfader/Tetronimo\" rel=\"nofollow noreferrer\">https://github.com/andrewfader/Tetronimo</a></p>\n"
},
{
"answer_id": 27721888,
"author": "Playmen Paychek",
"author_id": 4408437,
"author_profile": "https://Stackoverflow.com/users/4408437",
"pm_score": 2,
"selected": false,
"text": "<p>If we assume that the central square of the tetromino has coordinates (x0, y0) which remains unchanged then the rotation of the other 3 squares in Java will look like this:</p>\n\n<pre><code>private void rotateClockwise()\n{\n if(rotatable > 0) //We don't rotate tetromino O. It doesn't have central square.\n {\n int i = y1 - y0;\n y1 = (y0 + x1) - x0;\n x1 = x0 - i;\n i = y2 - y0;\n y2 = (y0 + x2) - x0;\n x2 = x0 - i;\n i = y3 - y0;\n y3 = (y0 + x3) - x0;\n x3 = x0 - i; \n }\n}\n\nprivate void rotateCounterClockwise()\n{\n if(rotatable > 0)\n {\n int i = y1 - y0;\n y1 = (y0 - x1) + x0;\n x1 = x0 + i;\n i = y2 - y0;\n y2 = (y0 - x2) + x0;\n x2 = x0 + i;\n i = y3 - y0;\n y3 = (y0 - x3) + x0;\n x3 = x0 + i;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 34164786,
"author": "Ferit",
"author_id": 1079908,
"author_profile": "https://Stackoverflow.com/users/1079908",
"pm_score": 3,
"selected": false,
"text": "<p><strong>Representation</strong></p>\n\n<p>Represent each piece in the minimum matrix where 1's represent spaces occupied by the tetriminoe and 0's represent empty space. Example:</p>\n\n<pre><code>originalMatrix = \n[0, 0, <b>1</b>]\n[<b>1</b>, <b>1</b>, <b>1</b>]\n</code></pre> \n\n<blockquote>\n <p><a href=\"https://i.stack.imgur.com/BfZKD.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/BfZKD.jpg\" alt=\"enter image description here\"></a></p>\n</blockquote>\n\n<p><strong>Rotation Formula</strong></p>\n\n<pre><code>clockwise90DegreesRotatedMatrix = reverseTheOrderOfColumns(Transpose(originalMatrix))\n\nanticlockwise90DegreesRotatedMatrix = reverseTheOrderOfRows(Transpose(originalMatrix))\n</code></pre>\n\n<p><strong>Illustration</strong></p>\n\n<pre><code>originalMatrix = \n x y z\na[0, 0, <b>1</b>]\nb[<b>1</b>, <b>1</b>, <b>1</b>]\n</code></pre> \n\n<p><pre><code>transposed = transpose(originalMatrix)\n a b\nx[0, <b>1</b>]\ny[0, <b>1</b>]\nz[<b>1</b>, <b>1</b>]\n</pre></code></p>\n\n<p><pre><code>counterClockwise90DegreesRotated = reverseTheOrderOfRows(transposed)\n a b\nz[<b>1</b>, <b>1</b>]\ny[0, <b>1</b>]\nx[0, <b>1</b>]\n</pre></code></p>\n\n<p><a href=\"https://i.stack.imgur.com/cTiEk.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/cTiEk.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><pre><code>clockwise90DegreesRotated = reverseTheOrderOfColumns(transposed)\n b a\nx[<b>1</b>, 0]\ny[<b>1</b>, 0]\nz[<b>1</b>, <b>1</b>]\n</pre></code></p>\n\n<p><a href=\"https://i.stack.imgur.com/fTvMj.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/fTvMj.jpg\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 47006916,
"author": "Vincent",
"author_id": 270663,
"author_profile": "https://Stackoverflow.com/users/270663",
"pm_score": 0,
"selected": false,
"text": "<p>Python:</p>\n\n<pre><code>pieces = [\n [(0,0),(0,1),(0,2),(0,3)],\n [(0,0),(0,1),(1,0),(1,1)],\n [(1,0),(0,1),(1,1),(1,2)],\n [(0,0),(0,1),(1,0),(2,0)],\n [(0,0),(0,1),(1,1),(2,1)],\n [(0,1),(1,0),(1,1),(2,0)]\n]\n\ndef get_piece_dimensions(piece):\n max_r = max_c = 0\n for point in piece:\n max_r = max(max_r, point[0])\n max_c = max(max_c, point[1])\n return max_r, max_c\n\ndef rotate_piece(piece):\n max_r, max_c = get_piece_dimensions(piece)\n new_piece = []\n for r in range(max_r+1):\n for c in range(max_c+1):\n if (r,c) in piece:\n new_piece.append((c, max_r-r))\n return new_piece\n</code></pre>\n"
},
{
"answer_id": 66210899,
"author": "vadimv",
"author_id": 417174,
"author_profile": "https://Stackoverflow.com/users/417174",
"pm_score": 0,
"selected": false,
"text": "<p>In Java:</p>\n<pre><code>private static char[][] rotateMatrix(char[][] m) {\n final int h = m.length;\n final int w = m[0].length;\n final char[][] t = new char[h][w];\n\n for(int y = 0; y < h; y++) {\n for(int x = 0; x < w; x++) {\n t[w - x - 1][y] = m[y][x];\n }\n }\n return t;\n}\n</code></pre>\n<p>A simple Tetris implementation as a single-page application in Java:\n<a href=\"https://github.com/vadimv/rsp-tetris\" rel=\"nofollow noreferrer\">https://github.com/vadimv/rsp-tetris</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233850",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21826/"
] |
What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game? I always find the piece rotation and representation schemes confusing.
Most tetris games seem to use a naive "remake the array of blocks" at each rotation:
<http://www.codeplex.com/Project/ProjectDirectory.aspx?ProjectSearchText=tetris>
However, some use pre-built encoded numbers and bit shifting to represent each piece:
<http://www.codeplex.com/wintris>
Is there a method to do this using mathematics (not sure that would work on a cell based board)?
|
There is a limited amount of shapes, so I would use a fixed table and no calculation. That saves time.
But there are rotation algorithms.
Chose a centerpoint and rotate pi/2.
If a block of a piece starts at (1,2) it moves clockwise to (2,-1) and (-1,-2) and (-1, 2).
Apply this for each block and the piece is rotated.
Each x is the previous y and each y - the previous x. Which gives the following matrix:
```
[ 0 1 ]
[ -1 0 ]
```
For counterclockwise rotation, use:
```
[ 0 -1 ]
[ 1 0 ]
```
|
233,870 |
<p>I know the statement:</p>
<pre><code>create table xyz_new as select * from xyz;
</code></pre>
<p>Which copies the structure and the data, but what if I just want the structure?</p>
|
[
{
"answer_id": 233879,
"author": "branchgabriel",
"author_id": 30807,
"author_profile": "https://Stackoverflow.com/users/30807",
"pm_score": 4,
"selected": false,
"text": "<p>Using sql developer select the table and click on the DDL tab</p>\n\n<p>You can use that code to create a new table with no data when you run it in a sql worksheet</p>\n\n<p>sqldeveloper is a free to use app from oracle.</p>\n\n<p>If the table has sequences or triggers the ddl will sometimes generate those for you too. You just have to be careful what order you make them in and know when to turn the triggers on or off.</p>\n"
},
{
"answer_id": 233890,
"author": "Jim Hudson",
"author_id": 8051,
"author_profile": "https://Stackoverflow.com/users/8051",
"pm_score": 10,
"selected": true,
"text": "<p>Just use a where clause that won't select any rows:</p>\n\n<pre><code>create table xyz_new as select * from xyz where 1=0;\n</code></pre>\n\n<h3>Limitations</h3>\n\n<p>The following things will not be copied to the new table:</p>\n\n<ul>\n<li>sequences</li>\n<li>triggers</li>\n<li>indexes</li>\n<li>some constraints may not be copied</li>\n<li>materialized view logs</li>\n</ul>\n\n<p>This also does not handle partitions</p>\n\n<hr>\n"
},
{
"answer_id": 240371,
"author": "Dave Costa",
"author_id": 6568,
"author_profile": "https://Stackoverflow.com/users/6568",
"pm_score": 6,
"selected": false,
"text": "<p>I used the method that you accepted a lot, but as someone pointed out it doesn't duplicate constraints (except for NOT NULL, I think).</p>\n\n<p>A more advanced method if you want to duplicate the full structure is:</p>\n\n<pre><code>SET LONG 5000\nSELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME' ) FROM DUAL;\n</code></pre>\n\n<p>This will give you the full create statement text which you can modify as you wish for creating the new table. You would have to change the names of the table and all constraints of course.</p>\n\n<p>(You could also do this in older versions using EXP/IMP, but it's much easier now.)</p>\n\n<p><strong>Edited to add</strong>\nIf the table you are after is in a different schema:</p>\n\n<pre><code>SELECT dbms_metadata.get_ddl( 'TABLE', 'MY_TABLE_NAME', 'OTHER_SCHEMA_NAME' ) FROM DUAL;\n</code></pre>\n"
},
{
"answer_id": 5101313,
"author": "Digo",
"author_id": 631805,
"author_profile": "https://Stackoverflow.com/users/631805",
"pm_score": 0,
"selected": false,
"text": "<p>you can also do a </p>\n\n<pre><code>create table abc_new as select * from abc; \n</code></pre>\n\n<p>then truncate the table <code>abc_new</code>. Hope this will suffice your requirement.</p>\n"
},
{
"answer_id": 12166768,
"author": "Donkha",
"author_id": 1631369,
"author_profile": "https://Stackoverflow.com/users/1631369",
"pm_score": -1,
"selected": false,
"text": "<p>The task above can be completed in two simple steps.</p>\n<h3>STEP 1:</h3>\n<pre><code>CREATE table new_table_name AS(Select * from old_table_name);\n</code></pre>\n<p>The <code>query</code> above creates a duplicate of a table (with contents as well).</p>\n<p>To get the structure, delete the contents of the table using.</p>\n<h3>STEP 2:</h3>\n<pre><code>DELETE * FROM new_table_name.\n</code></pre>\n<p>Hope this solves your problem. And thanks to the earlier posts. Gave me a lot of insight.</p>\n"
},
{
"answer_id": 20721832,
"author": "sunleo",
"author_id": 1755242,
"author_profile": "https://Stackoverflow.com/users/1755242",
"pm_score": 4,
"selected": false,
"text": "<pre><code>create table xyz_new as select * from xyz where rownum = -1;\n</code></pre>\n\n<p>To avoid iterate again and again and insert nothing based on the condition where 1=2</p>\n"
},
{
"answer_id": 21630355,
"author": "user3284249",
"author_id": 3284249,
"author_profile": "https://Stackoverflow.com/users/3284249",
"pm_score": 1,
"selected": false,
"text": "<p>Simply write a query like:</p>\n\n<pre><code>create table new_table as select * from old_table where 1=2;\n</code></pre>\n\n<p>where <code>new_table</code> is the name of the new table that you want to create and <code>old_table</code> is the name of the existing table whose structure you want to copy, this will copy only structure.</p>\n"
},
{
"answer_id": 29763613,
"author": "Prashant Mishra",
"author_id": 4534585,
"author_profile": "https://Stackoverflow.com/users/4534585",
"pm_score": -1,
"selected": false,
"text": "<pre><code>Create table target_table \nAs\nSelect * \nfrom source_table \nwhere 1=2;\n</code></pre>\n\n<p>Source_table is the table u wanna copy the structure of.</p>\n"
},
{
"answer_id": 30775531,
"author": "Yariv Scheingut",
"author_id": 4998286,
"author_profile": "https://Stackoverflow.com/users/4998286",
"pm_score": 0,
"selected": false,
"text": "<p>Using pl/sql developer you can right click on the table_name either in the sql workspace or in the object explorer, than click on \"view\" and than click \"view sql\" which generates the sql script to create the table along with all the constraints, indexes, partitions etc..</p>\n\n<p>Next you run the script using the new_table_name</p>\n"
},
{
"answer_id": 32097825,
"author": "Diogo Maschio",
"author_id": 3961267,
"author_profile": "https://Stackoverflow.com/users/3961267",
"pm_score": 0,
"selected": false,
"text": "<p>In other way you can get ddl of table creation from command listed below, and execute the creation.</p>\n\n<pre><code>SELECT DBMS_METADATA.GET_DDL('TYPE','OBJECT_NAME','DATA_BASE_USER') TEXT FROM DUAL \n</code></pre>\n\n<ul>\n<li><code>TYPE</code> is <code>TABLE</code>,<code>PROCEDURE</code> etc.</li>\n</ul>\n\n<p>With this command you can get majority of ddl from database objects.</p>\n"
},
{
"answer_id": 34213500,
"author": "Mohsen Molaei",
"author_id": 1939606,
"author_profile": "https://Stackoverflow.com/users/1939606",
"pm_score": 3,
"selected": false,
"text": "<p>You can do this\n<code>Create table New_table as select * from Old_table where 1=2 ;</code>\n<strong>but be careful</strong>\nThe table you create does not have any Index, PK and so on like the old_table.</p>\n"
},
{
"answer_id": 40981693,
"author": "Brian Leach",
"author_id": 2800402,
"author_profile": "https://Stackoverflow.com/users/2800402",
"pm_score": 2,
"selected": false,
"text": "<pre><code> DECLARE\n l_ddl VARCHAR2 (32767);\nBEGIN\n l_ddl := REPLACE (\n REPLACE (\n DBMS_LOB.SUBSTR (DBMS_METADATA.get_ddl ('TABLE', 'ACTIVITY_LOG', 'OLDSCHEMA'))\n , q'[\"OLDSCHEMA\"]'\n , q'[\"NEWSCHEMA\"]'\n )\n , q'[\"OLDTABLSPACE\"]'\n , q'[\"NEWTABLESPACE\"]'\n );\n\n EXECUTE IMMEDIATE l_ddl;\nEND; \n</code></pre>\n"
},
{
"answer_id": 43438077,
"author": "Alok",
"author_id": 7867894,
"author_profile": "https://Stackoverflow.com/users/7867894",
"pm_score": 0,
"selected": false,
"text": "<h2><strong>copy without table data</strong></h2>\n\n<pre><code>create table <target_table> as select * from <source_table> where 1=2;\n</code></pre>\n\n<h2><strong>copy with table data</strong></h2>\n\n<pre><code>create table <target_table> as select * from <source_table>;\n</code></pre>\n"
},
{
"answer_id": 45991389,
"author": "guesswho",
"author_id": 7026895,
"author_profile": "https://Stackoverflow.com/users/7026895",
"pm_score": 1,
"selected": false,
"text": "<pre><code>SELECT * INTO newtable\nFROM oldtable\nWHERE 1 = 0;\n</code></pre>\n\n<p>Create a new, empty table using the schema of another. Just add a WHERE clause that causes the query to return no data:</p>\n"
},
{
"answer_id": 48831620,
"author": "Dima Korobskiy",
"author_id": 534217,
"author_profile": "https://Stackoverflow.com/users/534217",
"pm_score": 1,
"selected": false,
"text": "<p><code>WHERE 1 = 0</code> or similar false conditions work, but I dislike how they look. Marginally cleaner code for Oracle 12c+ IMHO is</p>\n\n<p><code>\nCREATE TABLE bar AS\n SELECT *\n FROM foo\n FETCH FIRST 0 ROWS ONLY;\n</code></p>\n\n<p>Same limitations apply: only column definitions and their nullability are copied into a new table.</p>\n"
},
{
"answer_id": 57484494,
"author": "Jeevan Reddy Gujjula",
"author_id": 6581613,
"author_profile": "https://Stackoverflow.com/users/6581613",
"pm_score": -1,
"selected": false,
"text": "<blockquote>\n <ol>\n <li>create table xyz_new as select * from xyz;</li>\n </ol>\n</blockquote>\n\n<p>-- This will create table and copy all data.</p>\n\n<blockquote>\n <ol start=\"2\">\n <li>delete from xyz_new;</li>\n </ol>\n</blockquote>\n\n<p>-- This will have same table structure but all data copied will be deleted.</p>\n\n<p>If you want to overcome the limitations specified by answer:\n<a href=\"https://stackoverflow.com/questions/233870/how-can-i-create-a-copy-of-an-oracle-table-without-copying-the-data#answer-233890\">How can I create a copy of an Oracle table without copying the data?</a></p>\n"
},
{
"answer_id": 64233045,
"author": "pahariayogi",
"author_id": 2316223,
"author_profile": "https://Stackoverflow.com/users/2316223",
"pm_score": 1,
"selected": false,
"text": "<p>If one needs to create a table (with an empty structure) just to <strong>EXCHANGE PARTITION</strong>, it is best to use the "..FOR EXCHANGE.." clause. It's available only from <em>Oracle version <strong>12.2</strong></em> onwards though.</p>\n<pre><code>CREATE TABLE t1_temp FOR EXCHANGE WITH TABLE t1;\n</code></pre>\n<p>This addresses 'ORA-14097' during the 'exchange partition' seamlessly if table structures are not exactly copied by normal CTAS operation. I have seen Oracle missing some of the "DEFAULT" column and "HIDDEN" columns definitions from the original table.</p>\n<blockquote>\n<p>ORA-14097: column type or size mismatch in ALTER TABLE EXCHANGE\nPARTITION</p>\n</blockquote>\n<p><a href=\"https://oracle-base.com/articles/12c/create-table-for-exchange-with-table-12cr2#create-table-for-exchange-with-table\" rel=\"nofollow noreferrer\">See this for further read...</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5662/"
] |
I know the statement:
```
create table xyz_new as select * from xyz;
```
Which copies the structure and the data, but what if I just want the structure?
|
Just use a where clause that won't select any rows:
```
create table xyz_new as select * from xyz where 1=0;
```
### Limitations
The following things will not be copied to the new table:
* sequences
* triggers
* indexes
* some constraints may not be copied
* materialized view logs
This also does not handle partitions
---
|
233,896 |
<p>Whenever I drop a new database object from server explorer into the dbml, Visual Studio replaces the connection string in the designer file with a new one that it automatically adds to the connection strings in my config file. They both have exactly the same parameters, just different names.</p>
<p>How do I force Visual Studio to use and keep the connection string I already have?</p>
<p>For example, in the dbml-designer.cs, I have this:</p>
<pre><code>base(global::System.Configuration.ConfigurationManager.ConnectionStrings["ConnString1"].ConnectionString, mappingSource)
</code></pre>
<p>which is automatically generated. In my config file, I have:</p>
<pre><code><add name="DefaultConnString" connectionString="EXACTLYTHESAME"
providerName="System.Data.SqlClient" /> <add name="ConnString1" connectionString="EXACTLYTHESAME"
providerName="System.Data.SqlClient" />
</code></pre>
<p>Where ConnString1 is added automatically whenever I drag a database object to the dbml.</p>
<p>I want the designer.cs to use DefaultConnstring.</p>
|
[
{
"answer_id": 249527,
"author": "alextansc",
"author_id": 19582,
"author_profile": "https://Stackoverflow.com/users/19582",
"pm_score": 1,
"selected": false,
"text": "<p>You'll need to make sure the connectionstring used in the Server Explorer of your Visual Studio is the same as the one already defined within the dbml file. </p>\n\n<p>I'm not too sure what do you mean by different name, do you mean database name? When I have a different database name for development and production, what I normally do is I keep the development connectionstring value when developing, but change the connectionstring value in my main application. This is because I normally develop my LINQ logic in a separate assembly.</p>\n\n<p>Alternatively, you keep two connectionstrings: one for adding new database object, the other for testing, as example. Of course, you'll then have to be extra careful in keeping track of which connectionstring you'll use.</p>\n"
},
{
"answer_id": 255245,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 4,
"selected": true,
"text": "<p>There's a good post that pretty much explains your options here: </p>\n\n<p><a href=\"http://blog.jongallant.com/2007/11/linq-web-app-connection-strings.html#.UGA8Q42PUg0\" rel=\"nofollow noreferrer\">http://blog.jongallant.com/2007/11/linq-web-app-connection-strings.html#.UGA8Q42PUg0</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30604/"
] |
Whenever I drop a new database object from server explorer into the dbml, Visual Studio replaces the connection string in the designer file with a new one that it automatically adds to the connection strings in my config file. They both have exactly the same parameters, just different names.
How do I force Visual Studio to use and keep the connection string I already have?
For example, in the dbml-designer.cs, I have this:
```
base(global::System.Configuration.ConfigurationManager.ConnectionStrings["ConnString1"].ConnectionString, mappingSource)
```
which is automatically generated. In my config file, I have:
```
<add name="DefaultConnString" connectionString="EXACTLYTHESAME"
providerName="System.Data.SqlClient" /> <add name="ConnString1" connectionString="EXACTLYTHESAME"
providerName="System.Data.SqlClient" />
```
Where ConnString1 is added automatically whenever I drag a database object to the dbml.
I want the designer.cs to use DefaultConnstring.
|
There's a good post that pretty much explains your options here:
<http://blog.jongallant.com/2007/11/linq-web-app-connection-strings.html#.UGA8Q42PUg0>
|
233,905 |
<p>Is is better to do a joined query like this:</p>
<pre><code>var employer = (from person in db.People
join employer in db.Employers
on person.EmployerID equals employer.EmployerID
where person.PersonID == idPerson
select employer).FirstOrDefault();
</code></pre>
<p>Or is it just as good to do the easy thing and do this (with null checks):</p>
<pre><code>var employer = (from person in db.People
where person.PersonID == idPerson
select person).FirstOrDefault().Employer;
</code></pre>
<p>Obviously, in this one I would actually have to do it in 2 statements to get in the null check.</p>
<p>Is there any sort of best practice here for either readability or performance issues?</p>
|
[
{
"answer_id": 233920,
"author": "David Basarab",
"author_id": 2469,
"author_profile": "https://Stackoverflow.com/users/2469",
"pm_score": 1,
"selected": false,
"text": "<p>The second one could evaluate to null which would result in an error.</p>\n\n<p>I like the first one better because if it is null then you can deal with it without an exception being thrown.</p>\n"
},
{
"answer_id": 233928,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 1,
"selected": false,
"text": "<p>I find the first one better to read, but I am not sure of the differences in implementation.</p>\n\n<p>I strongly recommend using LinqPad to see the Generated SQL that will help you figure out differences.</p>\n"
},
{
"answer_id": 233943,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "<p>I'd use this:</p>\n\n<pre><code>var employer = (from person in db.People\n where person.PersonID == idPerson\n select person.Employer).FirstOrDefault();\n</code></pre>\n\n<p>It's got the simplicity of the first version but still only fetches the data for the employer (rather than the person <em>and</em> the employer).</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233905",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4797/"
] |
Is is better to do a joined query like this:
```
var employer = (from person in db.People
join employer in db.Employers
on person.EmployerID equals employer.EmployerID
where person.PersonID == idPerson
select employer).FirstOrDefault();
```
Or is it just as good to do the easy thing and do this (with null checks):
```
var employer = (from person in db.People
where person.PersonID == idPerson
select person).FirstOrDefault().Employer;
```
Obviously, in this one I would actually have to do it in 2 statements to get in the null check.
Is there any sort of best practice here for either readability or performance issues?
|
I'd use this:
```
var employer = (from person in db.People
where person.PersonID == idPerson
select person.Employer).FirstOrDefault();
```
It's got the simplicity of the first version but still only fetches the data for the employer (rather than the person *and* the employer).
|
233,908 |
<p>I need to replace some 2- and 3-digit numbers with the same number plus 10000. So</p>
<pre><code>Photo.123.aspx
</code></pre>
<p>needs to become</p>
<pre><code>Photo.10123.aspx
</code></pre>
<p>and also</p>
<pre><code>Photo.12.aspx
</code></pre>
<p>needs to become</p>
<pre><code>Photo.10012.aspx
</code></pre>
<p>I know that in .NET I can delegate the replacement to a function and just add 10000 to the number, but I'd rather stick to garden-variety RegEx if I can. Any ideas?</p>
|
[
{
"answer_id": 233914,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": false,
"text": "<p>I think that using a RegEx for the match, and a function for the replace is most appropriate in this case, you are doing simple math, use something that is designed to do it.....</p>\n"
},
{
"answer_id": 233955,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 0,
"selected": false,
"text": "<p>did you try just using <a href=\"http://msdn.microsoft.com/en-us/library/system.string.padleft.aspx\" rel=\"nofollow noreferrer\">PadLeft</a>?</p>\n"
},
{
"answer_id": 233977,
"author": "wprl",
"author_id": 17847,
"author_profile": "https://Stackoverflow.com/users/17847",
"pm_score": 1,
"selected": false,
"text": "<p>If it's only two or three digit numbers:</p>\n\n<p>(I assume you are using .NET Regex since we are talking about .aspx files)</p>\n\n<p>Check for: <code>Photo\\.{\\d\\d\\d}\\.aspx</code></p>\n\n<p>Replace with: <code>Photo.10\\1.aspx</code></p>\n\n<p>Then check against: <code>Photo\\.{\\d\\d}\\.aspx</code></p>\n\n<p>Replace with: <code>Photo.100\\1.aspx</code></p>\n"
},
{
"answer_id": 234026,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 0,
"selected": false,
"text": "<p>This appears to do what you want:</p>\n\n<pre><code>static public string Evaluator(Match match) \n{\n return \"Photo.1\" \n + match.Groups[1].Captures[0].Value.PadLeft(4, '0')\n + \".aspx\";\n}\n\npublic void Code(params string[] args)\n{\n string pattern = @\"Photo\\.([\\d]+)\\.aspx\";\n string test = \"Photo.123.aspx\";\n Regex regex = new Regex(pattern);\n string converted = regex.Replace(test, Evaluator) \n Console.WriteLine(converted);\n}\n</code></pre>\n"
},
{
"answer_id": 234050,
"author": "Brad Gilbert",
"author_id": 1337,
"author_profile": "https://Stackoverflow.com/users/1337",
"pm_score": 3,
"selected": false,
"text": "<p>Is there any reason it has to be <code>VB.NET</code>?</p>\n<h3>Perl</h3>\n<pre><code>s(\n Photo\\. (\\d{2,3}) \\.aspx\n){\n "Photo." . ($1 + 10000) . ".aspx"\n}xe\n</code></pre>\n"
},
{
"answer_id": 234055,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 1,
"selected": false,
"text": "<p>James Curran did it little faster than me but well here is what I have for you. Think it's the smallest code you can have with Regex to do what you want.</p>\n\n<pre><code> Regex regex = new Regex(@\"(\\d\\d\\d?)\", RegexOptions.None);\n string result = regex.Replace(@\"Photo.123.asp\", delegate(Match m) \n {\n return \"Photo.1\"\n + m.Groups[1].Captures[0].Value.PadLeft(4, '0')\n + \".aspx\";\n }\n );\n</code></pre>\n"
},
{
"answer_id": 234063,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 2,
"selected": false,
"text": "<p>Try the following:</p>\n\n<pre><code>\"Photo\\./d\\.aspx\" and replace with \"Photo.1000$1.aspx\"\n\"Photo\\./d/d\\.aspx\" and replace with \"Photo.100$1.aspx\"\n\"Photo\\./d/d/d\\.aspx\" and replace with \"Photo.10$1.aspx\"\n</code></pre>\n\n<p>That is the only way I see this happening.</p>\n"
},
{
"answer_id": 234085,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 0,
"selected": false,
"text": "<p>This will match the right part of the string, but won't tell you if it's two digits or three.</p>\n\n<pre><code>[^\\d][\\d]{2,3}[^\\d]\n</code></pre>\n\n<p>Still, you could use that to grab the number, convert it to an int, add 10000, and convert that to the string you need.</p>\n"
},
{
"answer_id": 234166,
"author": "Dan Finucane",
"author_id": 30026,
"author_profile": "https://Stackoverflow.com/users/30026",
"pm_score": 4,
"selected": true,
"text": "<p>James is right that you want to use the Regex.Replace method that takes a MatchEvaluator argument. The match evaluator delegate is where you can take the numeric string you get in the match and convert it into a number that you can add 10,000 to. I used a lambda expression in place of the explicit delegate because its more compact and readable.</p>\n\n<pre><code>using System;\nusing System.Text.RegularExpressions;\n\nnamespace RenameAspxFile\n{\n sealed class Program\n {\n private static readonly Regex _aspxFileNameRegex = new Regex(@\"(\\S+\\.)(\\d+)(\\.aspx)\", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);\n private static readonly string[] _aspxFileNames= {\"Photo.123.aspx\", \"Photo.456.aspx\", \"BigPhoto.789.aspx\"};\n\n static void Main(string[] args)\n {\n Program program = new Program();\n program.Run();\n }\n\n void Run()\n {\n foreach (string aspxFileName in _aspxFileNames)\n {\n Console.WriteLine(\"Renamed '{0}' to '{1}'\", aspxFileName, AddTenThousandToPhotoNumber(aspxFileName));\n }\n }\n\n string AddTenThousandToPhotoNumber(string aspxFileName)\n {\n return _aspxFileNameRegex.Replace(aspxFileName, match => String.Format(\"{0}{1}{2}\", match.Result(\"$1\"), Int32.Parse(match.Result(\"$2\")) + 10000, match.Result(\"$3\")));\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 3389244,
"author": "Niall Murphy",
"author_id": 188397,
"author_profile": "https://Stackoverflow.com/users/188397",
"pm_score": 0,
"selected": false,
"text": "<p>Found this question since I was trying to do something similar in Vim.\nIll put the solution here.</p>\n\n<pre><code>:s/Photo\\.\\d\\+\\.aspx/\\=Photo\\.submatch(0)+10000\\.aspx/g\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233908",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/239663/"
] |
I need to replace some 2- and 3-digit numbers with the same number plus 10000. So
```
Photo.123.aspx
```
needs to become
```
Photo.10123.aspx
```
and also
```
Photo.12.aspx
```
needs to become
```
Photo.10012.aspx
```
I know that in .NET I can delegate the replacement to a function and just add 10000 to the number, but I'd rather stick to garden-variety RegEx if I can. Any ideas?
|
James is right that you want to use the Regex.Replace method that takes a MatchEvaluator argument. The match evaluator delegate is where you can take the numeric string you get in the match and convert it into a number that you can add 10,000 to. I used a lambda expression in place of the explicit delegate because its more compact and readable.
```
using System;
using System.Text.RegularExpressions;
namespace RenameAspxFile
{
sealed class Program
{
private static readonly Regex _aspxFileNameRegex = new Regex(@"(\S+\.)(\d+)(\.aspx)", RegexOptions.Compiled | RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase);
private static readonly string[] _aspxFileNames= {"Photo.123.aspx", "Photo.456.aspx", "BigPhoto.789.aspx"};
static void Main(string[] args)
{
Program program = new Program();
program.Run();
}
void Run()
{
foreach (string aspxFileName in _aspxFileNames)
{
Console.WriteLine("Renamed '{0}' to '{1}'", aspxFileName, AddTenThousandToPhotoNumber(aspxFileName));
}
}
string AddTenThousandToPhotoNumber(string aspxFileName)
{
return _aspxFileNameRegex.Replace(aspxFileName, match => String.Format("{0}{1}{2}", match.Result("$1"), Int32.Parse(match.Result("$2")) + 10000, match.Result("$3")));
}
}
}
```
|
233,919 |
<p>I have been working with T-SQL in MS SQL for some time now and somehow whenever I have to insert data into a table I tend to use syntax:</p>
<pre><code>INSERT INTO myTable <something here>
</code></pre>
<p>I understand that keyword <code>INTO</code> is optional here and I do not have to use it but somehow it grew into habit in my case.</p>
<p>My question is: </p>
<ul>
<li>Are there any implications of using <code>INSERT</code> syntax versus <code>INSERT INTO</code>?</li>
<li>Which one complies fully with the standard?</li>
<li>Are they both valid in other implementations of SQL standard?</li>
</ul>
|
[
{
"answer_id": 233937,
"author": "DOK",
"author_id": 27637,
"author_profile": "https://Stackoverflow.com/users/27637",
"pm_score": 1,
"selected": false,
"text": "<p>They both do the same thing. INTO is optional (in SQL Server's T-SQL) but aids readability.</p>\n"
},
{
"answer_id": 233945,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 8,
"selected": true,
"text": "<p><code>INSERT INTO</code> is the standard. Even though <code>INTO</code> is optional in most implementations, it's required in a few, so it's a good idea to include it to ensure that your code is portable.</p>\n\n<p>You can find links to several versions of the SQL standard <a href=\"http://en.wikipedia.org/wiki/SQL#Standardization\" rel=\"noreferrer\">here</a>. I found an HTML version of an older standard <a href=\"http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt\" rel=\"noreferrer\">here</a>.</p>\n"
},
{
"answer_id": 233956,
"author": "Tony Andrews",
"author_id": 18747,
"author_profile": "https://Stackoverflow.com/users/18747",
"pm_score": 4,
"selected": false,
"text": "<p>It may be optional in mySQL, but it is mandatory in some other DBMSs, for example Oracle. So SQL will be more potentially portable with the INTO keyword, for what it's worth.</p>\n"
},
{
"answer_id": 233962,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 5,
"selected": false,
"text": "<p>They are the same thing, <code>INTO</code> is completely optional in T-SQL (other SQL dialects may differ).</p>\n\n<p>Contrary to the other answers, I think it impairs readability to use <code>INTO</code>.</p>\n\n<p>I think it is a conceptional thing: In my perception, I am not inserting a <em>row</em> into a table named \"Customer\", but I am inserting a <em>Customer</em>. (This is connected to the fact that I use to name my tables in singular, not plural).</p>\n\n<p>If you follow the first concept, <code>INSERT INTO Customer</code> would most likely \"feel right\" for you.</p>\n\n<p>If you follow the second concept, it would most likely be <code>INSERT Customer</code> for you.</p>\n"
},
{
"answer_id": 233965,
"author": "AgentThirteen",
"author_id": 26199,
"author_profile": "https://Stackoverflow.com/users/26199",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer using it. It maintains the same syntax delineation feel and readability as other parts of the SQL language, like <code>group BY</code>, <code>order BY</code>.</p>\n"
},
{
"answer_id": 234111,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 2,
"selected": false,
"text": "<p>One lesson I leaned about this issue is that you should always keep it consistent! If you use INSERT INTO, don't use INSERT as well. If you don't do it, some programmers may ask the same question again.</p>\n\n<p>Here is my another related example case: I had a chance to update a very very long stored procedure in MS SQL 2005. The problem is that too many data were inserted to a result table. I had to find out where the data came from. I tried to find out where new records were added. At the beginning section of SP, I saw several INSERT INTOs. Then I tried to find \"INSERT INTO\" and updated them, but I missed one place where only \"INSERT\" was used. That one actually inserted 4k+ rows of empty data in some columns! Of course, I should just search for INSERT. However, that happened to me. I blame the previous programmer IDIOT:):)</p>\n"
},
{
"answer_id": 236616,
"author": "Tom",
"author_id": 13219,
"author_profile": "https://Stackoverflow.com/users/13219",
"pm_score": 0,
"selected": false,
"text": "<p>If available use the standard function. Not that you ever need portability for your particular database, but chances are you need portability for your SQL knowledge.\nA particular nasty T-SQL example is the use of isnull, use coalesce!</p>\n"
},
{
"answer_id": 679812,
"author": "devXen",
"author_id": 50021,
"author_profile": "https://Stackoverflow.com/users/50021",
"pm_score": 3,
"selected": false,
"text": "<p>In SQL Server 2005, you could have something in between INSERT and INTO like this:</p>\n\n<pre>\nINSERT top(5) INTO tTable1 SELECT * FROM tTable2;\n</pre>\n\n<p>Though it works without the INTO, I prefer using INTO for readability. </p>\n"
},
{
"answer_id": 42154841,
"author": "Garry_G",
"author_id": 3660147,
"author_profile": "https://Stackoverflow.com/users/3660147",
"pm_score": 1,
"selected": false,
"text": "<p>I started wtiting SQL on ORACLE, so when I see code without INTO it just looks 'broken' and confusing.</p>\n\n<p>Yes, it is just my opinion, and I'm not saying you <em>should</em> always use INTO. But it you don't you should be aware that many other people will probably think the same thing, especially if they haven't started scripting with newer implementations.</p>\n\n<p>With SQL I think it's also very important to realise that you ARE adding a ROW to a TABLE, and not working with objects. I think it would be unhelpful to a new developer to think of SQL table rows/entries as objects. Again, just me opinion.</p>\n"
},
{
"answer_id": 73897741,
"author": "Kai - Kazuya Ito",
"author_id": 8172439,
"author_profile": "https://Stackoverflow.com/users/8172439",
"pm_score": 0,
"selected": false,
"text": "<p><code>INSERT INTO</code> is <strong>SQL standard</strong> while <code>INSERT</code> without <code>INTO</code> is not <strong>SQL standard</strong>.</p>\n<p>I experimented them on <strong>SQL Server</strong>, <strong>MySQL</strong>, <strong>PostgreSQL</strong> and <strong>SQLite</strong> as shown below.</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Database</th>\n<th><strong>INSERT INTO</strong></th>\n<th><strong>INSERT</strong></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>SQL Server</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Possible</strong></td>\n</tr>\n<tr>\n<td><strong>MySQL</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Possible</strong></td>\n</tr>\n<tr>\n<td><strong>PostgreSQL</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Impossible</strong></td>\n</tr>\n<tr>\n<td><strong>SQLite</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Impossible</strong></td>\n</tr>\n</tbody>\n</table>\n</div>\n<p>In addition, I also experimented <code>DELETE FROM</code> and <code>DELETE</code> without <code>FROM</code> on <strong>SQL Server</strong>, <strong>MySQL</strong>, <strong>PostgreSQL</strong> and <strong>SQLite</strong> as shown below:</p>\n<div class=\"s-table-container\">\n<table class=\"s-table\">\n<thead>\n<tr>\n<th>Database</th>\n<th><strong>DELETE FROM</strong></th>\n<th><strong>DELETE</strong></th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td><strong>SQL Server</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Possible</strong></td>\n</tr>\n<tr>\n<td><strong>MySQL</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Impossible</strong></td>\n</tr>\n<tr>\n<td><strong>PostgreSQL</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Impossible</strong></td>\n</tr>\n<tr>\n<td><strong>SQLite</strong></td>\n<td><strong>Possible</strong></td>\n<td><strong>Impossible</strong></td>\n</tr>\n</tbody>\n</table>\n</div>"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233919",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3241/"
] |
I have been working with T-SQL in MS SQL for some time now and somehow whenever I have to insert data into a table I tend to use syntax:
```
INSERT INTO myTable <something here>
```
I understand that keyword `INTO` is optional here and I do not have to use it but somehow it grew into habit in my case.
My question is:
* Are there any implications of using `INSERT` syntax versus `INSERT INTO`?
* Which one complies fully with the standard?
* Are they both valid in other implementations of SQL standard?
|
`INSERT INTO` is the standard. Even though `INTO` is optional in most implementations, it's required in a few, so it's a good idea to include it to ensure that your code is portable.
You can find links to several versions of the SQL standard [here](http://en.wikipedia.org/wiki/SQL#Standardization). I found an HTML version of an older standard [here](http://www.contrib.andrew.cmu.edu/~shadow/sql/sql1992.txt).
|
233,922 |
<p>I have this code to give me a rollover on submit buttons, and I'm trying to make it more generic:</p>
<pre><code>$('.rollover').hover(
function(){ // Change the input image's source when we "roll on"
srcPath = $(this).attr("src");
srcPathOver = ???????
/*need to manipulate srcPath to change from
img/content/go-button.gif
into
img/content/go-button-over.gif
*/
$(this).attr({ src : srcPathOver});
},
function(){ // Change the input image's source back to the default on "roll off"
$(this).attr({ src : srcPath});
}
);
</code></pre>
<p>Two things really,</p>
<p>I want to learn how manipulate the <code>srcPath</code> variable to append the text '-over' onto the gif filename, to give a new image for the rollover. Can anyone suggest a way to do this?</p>
<p>Also, can someone tell me if this code could be refined at all? I'm a bit new to jQuery and wondered if the syntax could be improved upon.</p>
<p>Many thanks.</p>
|
[
{
"answer_id": 234025,
"author": "Matt Ephraim",
"author_id": 22291,
"author_profile": "https://Stackoverflow.com/users/22291",
"pm_score": 2,
"selected": false,
"text": "<p>You should be able to use a regex replace to modify your source path. Like this: </p>\n\n<pre><code>srcPathOver = srcPath.replace(/([^.]*)\\.(.*)/, \"$1-over.$2\");\n</code></pre>\n\n<p>More on JavaScript regexes <a href=\"http://www.regular-expressions.info/javascript.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>As far as how you're doing it, I'd make sure that you define your srcPath variable like this </p>\n\n<pre><code>var srcPath;\n$('.rollover').hover(...\n</code></pre>\n\n<p>The code you have above makes it look like srcPath is a global variable, which is not what you want. </p>\n"
},
{
"answer_id": 234028,
"author": "LorenzCK",
"author_id": 3118,
"author_profile": "https://Stackoverflow.com/users/3118",
"pm_score": 3,
"selected": false,
"text": "<p>To manipulate the file name and append \"-over\" you simply have to do some Javascript string manipulation, like this:</p>\n\n<pre><code>function appendOver(srcPath){\n var index = s.indexOf('.');\n\n var before = s.substr(0, index);\n var after = s.substr(index);\n\n return before + \"-over\" + after;\n}\n</code></pre>\n\n<p>This should return the original filename (in all possible formats) and add the '-over' string just before the extension dot.</p>\n"
},
{
"answer_id": 234042,
"author": "jcampbell1",
"author_id": 20512,
"author_profile": "https://Stackoverflow.com/users/20512",
"pm_score": 5,
"selected": true,
"text": "<pre><code>$('.rollover').hover(\n function(){ // Change the input image's source when we \"roll on\"\n var t = $(this);\n t.attr('src',t.attr('src').replace(/([^.]*)\\.(.*)/, \"$1-over.$2\"));\n },\n function(){ \n var t= $(this);\n t.attr('src',t.attr('src').replace('-over',''));\n }\n );\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233922",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
I have this code to give me a rollover on submit buttons, and I'm trying to make it more generic:
```
$('.rollover').hover(
function(){ // Change the input image's source when we "roll on"
srcPath = $(this).attr("src");
srcPathOver = ???????
/*need to manipulate srcPath to change from
img/content/go-button.gif
into
img/content/go-button-over.gif
*/
$(this).attr({ src : srcPathOver});
},
function(){ // Change the input image's source back to the default on "roll off"
$(this).attr({ src : srcPath});
}
);
```
Two things really,
I want to learn how manipulate the `srcPath` variable to append the text '-over' onto the gif filename, to give a new image for the rollover. Can anyone suggest a way to do this?
Also, can someone tell me if this code could be refined at all? I'm a bit new to jQuery and wondered if the syntax could be improved upon.
Many thanks.
|
```
$('.rollover').hover(
function(){ // Change the input image's source when we "roll on"
var t = $(this);
t.attr('src',t.attr('src').replace(/([^.]*)\.(.*)/, "$1-over.$2"));
},
function(){
var t= $(this);
t.attr('src',t.attr('src').replace('-over',''));
}
);
```
|
233,936 |
<p>Ok let me make an example:</p>
<pre><code><head>
<script type="text/javascript">
$(document).ready(function(){
$("#options_2").hide();
$("#options_3").hide();
});
</script>
</head>
<body>
<div id="options_1">option 1</div>
<div id="options_2">option 2</div>
<div id="options_3">option 3</div>
<a href="" class="selected">choose option 1</a>
<a href="">choose option 2</a>
<a href="">choose option 3</a>
</body>
</code></pre>
<p>As you can see only option 1 is visible by default, and the link you click to show option 1 has the class="selected" by default, showing the user that that option is currently selected. I basically want it so that when they click "choose option 2" the options 1 div hides itself and the options 2 div shows itself, and then gives the second link the selected class and removes the class from the image link.</p>
<p>It basically just tabs using links and divs but due to the format I have to display it in I cannot use any of the tabs plugins I have found online.</p>
|
[
{
"answer_id": 234009,
"author": "Wayne Austin",
"author_id": 31109,
"author_profile": "https://Stackoverflow.com/users/31109",
"pm_score": 2,
"selected": false,
"text": "<p>Given the format your given I'd do something like the following, assign each link with an id that can understandably refer to it's associated div (like \"link_1\" for \"option_1\") and use the following jQuery:</p>\n\n<pre><code>$('a#link_1').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_1').show();\n $('div#option_1').siblings('div').hide();\n});\n $('a#link_2').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_2').show();\n $('div#option_2').siblings('div').hide();\n});\n $('a#link_3').click(function() {\n $(this).attr(\"class\", \"selected\");\n $(this).siblings('a').removeClass(\"selected\");\n $('div#option_3').show();\n $('div#option_3').siblings('div').hide();\n});\n</code></pre>\n\n<p>I haven't done jQuery for a little while, but that should be right :)</p>\n"
},
{
"answer_id": 234022,
"author": "Matt Goddard",
"author_id": 5185,
"author_profile": "https://Stackoverflow.com/users/5185",
"pm_score": 5,
"selected": true,
"text": "<p>First of all give your links a class or Id (I've used a class), which will make it easier to do the swap in</p>\n\n<pre><code><div id=\"options_1\" class=\"tab\" >option 1</div>\n<div id=\"options_2\" class=\"tab\">option 2</div>\n<div id=\"options_3\" class=\"tab\">option 3</div>\n\n$(document).ready(function () {\n\n var clickHandler = function (link) {\n $('.tab').hide();\n $('#option_' + link.data.id).show();\n $('.selected').removeClass('selected');\n $(this).attr('class','selected');\n }\n\n $('.link1').bind('click', {id:'1'} ,clickHandler);\n $('.link2').bind('click', {id:'2'} ,clickHandler);\n $('.link3').bind('click', {id:'3'} ,clickHandler);\n})\n</code></pre>\n"
},
{
"answer_id": 234041,
"author": "Damir Zekić",
"author_id": 401510,
"author_profile": "https://Stackoverflow.com/users/401510",
"pm_score": 1,
"selected": false,
"text": "<p>You can help yourself if you add IDs to your links in form 'options_1_select' and a class 'opener'. Then you can assign a single event handler to all of your links:</p>\n\n<pre><code>$('a.opener').click(function() {\n // mark current link as selected and unmark all others\n $(this)\n .addClass('selected')\n .siblings('a').removeClass('selected');\n\n // find a div to show, and hide its siblings\n $('#' + $(this).attr('id').substring(0, 9))\n .show()\n .siblings('div').hide();\n});\n</code></pre>\n"
},
{
"answer_id": 2573518,
"author": "ajma",
"author_id": 60117,
"author_profile": "https://Stackoverflow.com/users/60117",
"pm_score": 1,
"selected": false,
"text": "<p>Sounds like you want an accordion.</p>\n\n<p>jQuery UI provides one: <a href=\"http://jqueryui.com/demos/accordion/\" rel=\"nofollow noreferrer\">http://jqueryui.com/demos/accordion/</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
Ok let me make an example:
```
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#options_2").hide();
$("#options_3").hide();
});
</script>
</head>
<body>
<div id="options_1">option 1</div>
<div id="options_2">option 2</div>
<div id="options_3">option 3</div>
<a href="" class="selected">choose option 1</a>
<a href="">choose option 2</a>
<a href="">choose option 3</a>
</body>
```
As you can see only option 1 is visible by default, and the link you click to show option 1 has the class="selected" by default, showing the user that that option is currently selected. I basically want it so that when they click "choose option 2" the options 1 div hides itself and the options 2 div shows itself, and then gives the second link the selected class and removes the class from the image link.
It basically just tabs using links and divs but due to the format I have to display it in I cannot use any of the tabs plugins I have found online.
|
First of all give your links a class or Id (I've used a class), which will make it easier to do the swap in
```
<div id="options_1" class="tab" >option 1</div>
<div id="options_2" class="tab">option 2</div>
<div id="options_3" class="tab">option 3</div>
$(document).ready(function () {
var clickHandler = function (link) {
$('.tab').hide();
$('#option_' + link.data.id).show();
$('.selected').removeClass('selected');
$(this).attr('class','selected');
}
$('.link1').bind('click', {id:'1'} ,clickHandler);
$('.link2').bind('click', {id:'2'} ,clickHandler);
$('.link3').bind('click', {id:'3'} ,clickHandler);
})
```
|
233,979 |
<p>I am trying to link to a file that has the '#' character in via a window.open() call. The file does exist and can be linked to just fine using a normal anchor tag.</p>
<p>I have tried escaping the '#' character with '%23' but when the window.open(myurl) gets processed, the '%23' becomes '%2523'. This tells me that my url string is being escapped by the window.open call changing the '%' to the '%25'.</p>
<p>Are there ways to work around this extra escaping.</p>
<p>Sample code:</p>
<pre><code><script language="javascript">
function escapePound(url)
{
// original attempt
newUrl = url.replace("#", "%23");
// first answer attempt - doesn't work
// newUrl = url.replace("#", "\\#");
return newUrl;
}
</script>
<a href="#top" onclick="url = '\\\\MyUNCPath\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(escapePound(url)); return true;">Some Doc</a>
</code></pre>
<p>URL that yells says "file://MyUNCPath/PropertyRushRefi-Add%25231-ABCDEF.RTF" cannot be found</p>
|
[
{
"answer_id": 234002,
"author": "StingyJack",
"author_id": 16391,
"author_profile": "https://Stackoverflow.com/users/16391",
"pm_score": 0,
"selected": false,
"text": "<p>Did you try using the standard text escape char \"\\\"?</p>\n\n<pre><code>\\#\n</code></pre>\n"
},
{
"answer_id": 234018,
"author": "Kon",
"author_id": 22303,
"author_profile": "https://Stackoverflow.com/users/22303",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried URL encoding via JavaScript as done <a href=\"http://cass-hacks.com/articles/code/js_url_encode_decode/\" rel=\"nofollow noreferrer\">here</a> and <a href=\"http://www.albionresearch.com/misc/urlencode.php\" rel=\"nofollow noreferrer\">here</a>?</p>\n"
},
{
"answer_id": 234031,
"author": "Rahul",
"author_id": 16308,
"author_profile": "https://Stackoverflow.com/users/16308",
"pm_score": 4,
"selected": true,
"text": "<p>You seek the dark magicks of <a href=\"http://www.w3schools.com/jsref/jsref_encodeURI.asp\" rel=\"nofollow noreferrer\">encodeURI</a>:</p>\n\n<pre><code>window.open(\"http://your-url.com/\" + encodeURIComponent(\"foo#123.jpg\"));\n</code></pre>\n"
},
{
"answer_id": 234061,
"author": "Claudio",
"author_id": 30122,
"author_profile": "https://Stackoverflow.com/users/30122",
"pm_score": 0,
"selected": false,
"text": "<p>Have you tried not escaping the url?</p>\n\n<pre><code><a href=\"#top onclick=\"url = '\\\\\\\\MyUNCPath\\\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(url); return true;\">Some Doc</a>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/233979",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18284/"
] |
I am trying to link to a file that has the '#' character in via a window.open() call. The file does exist and can be linked to just fine using a normal anchor tag.
I have tried escaping the '#' character with '%23' but when the window.open(myurl) gets processed, the '%23' becomes '%2523'. This tells me that my url string is being escapped by the window.open call changing the '%' to the '%25'.
Are there ways to work around this extra escaping.
Sample code:
```
<script language="javascript">
function escapePound(url)
{
// original attempt
newUrl = url.replace("#", "%23");
// first answer attempt - doesn't work
// newUrl = url.replace("#", "\\#");
return newUrl;
}
</script>
<a href="#top" onclick="url = '\\\\MyUNCPath\\PropertyRushRefi-Add#1-ABCDEF.RTF'; window.open(escapePound(url)); return true;">Some Doc</a>
```
URL that yells says "file://MyUNCPath/PropertyRushRefi-Add%25231-ABCDEF.RTF" cannot be found
|
You seek the dark magicks of [encodeURI](http://www.w3schools.com/jsref/jsref_encodeURI.asp):
```
window.open("http://your-url.com/" + encodeURIComponent("foo#123.jpg"));
```
|
234,008 |
<p>I need to create at runtime instances of a class that uses generics, like <code>class<T></code>, without knowing previously the type T they will have, I would like to do something like that:</p>
<pre><code>public Dictionary<Type, object> GenerateLists(List<Type> types)
{
Dictionary<Type, object> lists = new Dictionary<Type, object>();
foreach (Type type in types)
{
lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
}
return lists;
}
</code></pre>
<p>...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?</p>
|
[
{
"answer_id": 234016,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "<p>You can't do it like that - the point of generics is mostly <em>compile-time</em> type-safety - but you can do it with reflection:</p>\n\n<pre><code>public Dictionary<Type, object> GenerateLists(List<Type> types)\n{\n Dictionary<Type, object> lists = new Dictionary<Type, object>();\n\n foreach (Type type in types)\n {\n Type genericList = typeof(List<>).MakeGenericType(type);\n lists.Add(type, Activator.CreateInstance(genericList));\n }\n\n return lists;\n}\n</code></pre>\n"
},
{
"answer_id": 234082,
"author": "jonnii",
"author_id": 4590,
"author_profile": "https://Stackoverflow.com/users/4590",
"pm_score": 2,
"selected": false,
"text": "<p>Depending on how often you're calling this method then using Activator.CreateInstance could be slow. Another option is to do something like this:</p>\n\n<p>private Dictionary> delegates = new Dictionary>();</p>\n\n<pre><code> public Dictionary<Type, object> GenerateLists(List<Type> types)\n {\n Dictionary<Type, object> lists = new Dictionary<Type, object>();\n\n foreach (Type type in types)\n {\n if (!delegates.ContainsKey(type))\n delegates.Add(type, CreateListDelegate(type));\n lists.Add(type, delegates[type]());\n }\n\n return lists;\n }\n\n private Func<object> CreateListDelegate(Type type)\n {\n MethodInfo createListMethod = GetType().GetMethod(\"CreateList\");\n MethodInfo genericCreateListMethod = createListMethod.MakeGenericMethod(type);\n return Delegate.CreateDelegate(typeof(Func<object>), this, genericCreateListMethod) as Func<object>;\n }\n\n public object CreateList<T>()\n {\n return new List<T>();\n }\n</code></pre>\n\n<p>On the first hit it'll create a delegate to the generic method that creates the list and then puts that in a dictionary. On each subsequent hit you'll just call the delegate for that type.</p>\n\n<p>Hope this helps!</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234008",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21668/"
] |
I need to create at runtime instances of a class that uses generics, like `class<T>`, without knowing previously the type T they will have, I would like to do something like that:
```
public Dictionary<Type, object> GenerateLists(List<Type> types)
{
Dictionary<Type, object> lists = new Dictionary<Type, object>();
foreach (Type type in types)
{
lists.Add(type, new List<type>()); /* this new List<type>() doesn't work */
}
return lists;
}
```
...but I can't. I think it is not possible to write in C# inside the generic brackets a type variable. Is there another way to do it?
|
You can't do it like that - the point of generics is mostly *compile-time* type-safety - but you can do it with reflection:
```
public Dictionary<Type, object> GenerateLists(List<Type> types)
{
Dictionary<Type, object> lists = new Dictionary<Type, object>();
foreach (Type type in types)
{
Type genericList = typeof(List<>).MakeGenericType(type);
lists.Add(type, Activator.CreateInstance(genericList));
}
return lists;
}
```
|
234,027 |
<p>How can I find the index in a string that matches a boost regex?</p>
|
[
{
"answer_id": 234248,
"author": "Anthony Williams",
"author_id": 5597,
"author_profile": "https://Stackoverflow.com/users/5597",
"pm_score": 3,
"selected": false,
"text": "<p>Use the <code>position</code> member function of the <code>match_results</code>:</p>\n\n<pre><code>int find_match_offset(std::string const& string_to_search,\n boost::regex const& expression)\n{\n boost::smatch results;\n if(boost::regex_match(string_to_search,results,expression))\n {\n return results.position()\n }\n return -1;\n}\n</code></pre>\n"
},
{
"answer_id": 234277,
"author": "Paolo Tedesco",
"author_id": 15622,
"author_profile": "https://Stackoverflow.com/users/15622",
"pm_score": 4,
"selected": true,
"text": "<p>If you use boost::regex_match it's the whole string that's matching.<br>\nMaybe you mean to use regex_search:</p>\n\n<pre><code>void index(boost::regex& re,const std::string& input){\n boost::match_results<std::string::const_iterator> what;\n boost::match_flag_type flags = boost::match_default;\n std::string::const_iterator s = input.begin();\n std::string::const_iterator e = input.end();\n while (boost::regex_search(s,e,what,re,flags)){\n std::cout << what.position() << std::endl;\n std::string::difference_type l = what.length();\n std::string::difference_type p = what.position();\n s += p + l;\n }\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234027",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3153/"
] |
How can I find the index in a string that matches a boost regex?
|
If you use boost::regex\_match it's the whole string that's matching.
Maybe you mean to use regex\_search:
```
void index(boost::regex& re,const std::string& input){
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
std::string::const_iterator s = input.begin();
std::string::const_iterator e = input.end();
while (boost::regex_search(s,e,what,re,flags)){
std::cout << what.position() << std::endl;
std::string::difference_type l = what.length();
std::string::difference_type p = what.position();
s += p + l;
}
}
```
|
234,044 |
<p>I am trying to achieve anonymous personalization in a ASP.net environment. I know that ASP.NET 2.0 provide <a href="http://www.odetocode.com/articles/440.aspx" rel="nofollow noreferrer">Profile</a>. However, I want to avoid traffic to the database as much as possible since the site I am working on is a relatively high traffic site.</p>
<p>The other obvious solution is cookie, but given the <a href="http://www.ietf.org/rfc/rfc2109.txt" rel="nofollow noreferrer">limitation of cookie</a>, I was wondering if anyone have any efficient method to store information into cookie. Does anyone know how amazon or yahoo deals anon. personalization?</p>
<p>Ultimately, We are trying to serve up different dynamic content to our user base on a set of business rules outline in a pre-defined campaign. The reason is to measure conversion rate in our site. The same campaign can be use on all different pages of the site. The reason I need to set this to a cookie is that the user is able to see the same content served up previously if we want it to be. So this is what I have in cookie right now.</p>
<pre><code> campaign code:page id:result display
</code></pre>
<p>And you can see that this will build up if there is a lot of campaign and each campaign is used on many pages.</p>
<p>Thanks in advance!</p>
|
[
{
"answer_id": 239386,
"author": "Ady",
"author_id": 31395,
"author_profile": "https://Stackoverflow.com/users/31395",
"pm_score": 0,
"selected": false,
"text": "<p>I'd create a database record for the visitor and only store the ID in the cookie, this way you can look up all the personalised details from the database, and keep the cookie size to a minimum.</p>\n\n<p>If database speed is an issue, perhaps use a differrent database and server to store the personalisations.</p>\n\n<p>Alternativly you could store personal data in the file system, and load into the session when the visitor returns matching the cookie ID.</p>\n\n<p>If identifying the user and cookie clearing is an issue, you cold use and ActiveX control, but this requires installation on the client computer, which people could object to.</p>\n"
},
{
"answer_id": 239397,
"author": "Luk",
"author_id": 5789,
"author_profile": "https://Stackoverflow.com/users/5789",
"pm_score": 2,
"selected": false,
"text": "<p>If database load is an issue, you can retrieve the personalization when the user starts his session on the website, and then store it on the session state. This way, only the first page load will make a call to the database.</p>\n\n<p>You can store the user ID in the cookie.</p>\n\n<p>Just remember to persist the session in the db when the user updates his preferences, and deleting old db records after a while might be a good idea too if that many anonymous users will visit your website.</p>\n"
},
{
"answer_id": 679413,
"author": "eduncan911",
"author_id": 56693,
"author_profile": "https://Stackoverflow.com/users/56693",
"pm_score": 1,
"selected": false,
"text": "<p>If you want to persist the changes, such as each campaign view, there really isn't any way around accessing to write those changes. ASP.NET Membership is not bad on a high-volume site (>1 mil a day), when used correctly. For instance, you should be wrapping calls to the membership provider in a cached object, and refresh often (short expiration). Also, make sure to set the cacheRefreshInterval on the RoleProvider. This will force asp.net to cache the Roles in a cookie, to cut down on DB activity.</p>\n\n<p>Another way to look at this is to take Ady's advice and to seperate the Membership into a separate DB. Yet again, another great feature of the ASP.NET Membership provider - you can set a different SQL connection string, and load it up on a different DB and/or server.</p>\n\n<p>There are several other techniques around the membership provider that can really increase performance. Some quick google searches comes up a number of them.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31206/"
] |
I am trying to achieve anonymous personalization in a ASP.net environment. I know that ASP.NET 2.0 provide [Profile](http://www.odetocode.com/articles/440.aspx). However, I want to avoid traffic to the database as much as possible since the site I am working on is a relatively high traffic site.
The other obvious solution is cookie, but given the [limitation of cookie](http://www.ietf.org/rfc/rfc2109.txt), I was wondering if anyone have any efficient method to store information into cookie. Does anyone know how amazon or yahoo deals anon. personalization?
Ultimately, We are trying to serve up different dynamic content to our user base on a set of business rules outline in a pre-defined campaign. The reason is to measure conversion rate in our site. The same campaign can be use on all different pages of the site. The reason I need to set this to a cookie is that the user is able to see the same content served up previously if we want it to be. So this is what I have in cookie right now.
```
campaign code:page id:result display
```
And you can see that this will build up if there is a lot of campaign and each campaign is used on many pages.
Thanks in advance!
|
If database load is an issue, you can retrieve the personalization when the user starts his session on the website, and then store it on the session state. This way, only the first page load will make a call to the database.
You can store the user ID in the cookie.
Just remember to persist the session in the db when the user updates his preferences, and deleting old db records after a while might be a good idea too if that many anonymous users will visit your website.
|
234,056 |
<p>Anyone got a ready made function that will take an XML string and return a correctly indented string?</p>
<p>eg</p>
<pre><code><XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>
</code></pre>
<p>and will return nicely formatted String in return after inserting linebreaks and tabs or spaces?</p>
|
[
{
"answer_id": 234101,
"author": "gabr",
"author_id": 4997,
"author_profile": "https://Stackoverflow.com/users/4997",
"pm_score": 3,
"selected": false,
"text": "<p>Using <a href=\"http://www.omnixml.com/\" rel=\"noreferrer\">OmniXML</a>:</p>\n\n<pre><code>program TestIndentXML;\n\n{$APPTYPE CONSOLE}\n\nuses\n SysUtils,\n OmniXML,\n OmniXMLUtils;\n\nfunction IndentXML(const xml: string): string;\nvar\n xmlDoc: IXMLDocument;\nbegin\n Result := '';\n xmlDoc := CreateXMLDoc;\n if not XMLLoadFromAnsiString(xmlDoc, xml) then\n Exit;\n Result := XMLSaveToAnsiString(xmlDoc, ofIndent);\nend;\n\nbegin\n Writeln(IndentXML('<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>'));\n Readln;\nend.\n</code></pre>\n\n<p>The code fragment above is released to public domain.</p>\n"
},
{
"answer_id": 234105,
"author": "dacracot",
"author_id": 13930,
"author_profile": "https://Stackoverflow.com/users/13930",
"pm_score": 2,
"selected": false,
"text": "<p>Using XSLT...</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" version=\"1.0\">\n <xsl:output method=\"xml\" indent=\"yes\" />\n <xsl:template match=\"/\">\n <xsl:copy-of select=\".\"/>\n </xsl:template>\n</xsl:stylesheet>\n</code></pre>\n"
},
{
"answer_id": 234230,
"author": "Jim McKeeth",
"author_id": 255,
"author_profile": "https://Stackoverflow.com/users/255",
"pm_score": 1,
"selected": false,
"text": "<p>The XML Document DOM object build into Delphi has a pretty formatting option. You just load your XML into it and save it back out, and if you have that option set then it makes it all pretty. </p>\n\n<p>I'll look it up and update this answer.</p>\n"
},
{
"answer_id": 235901,
"author": "Bruce McGee",
"author_id": 19183,
"author_profile": "https://Stackoverflow.com/users/19183",
"pm_score": 5,
"selected": true,
"text": "<p>The RTL has <a href=\"http://docwiki.embarcadero.com/Libraries/XE5/en/Xml.XMLDoc.FormatXMLData\" rel=\"noreferrer\">FormatXMLData</a> in XMLDoc.pas that accepts and returns strings.</p>\n"
},
{
"answer_id": 249291,
"author": "Richard A",
"author_id": 24355,
"author_profile": "https://Stackoverflow.com/users/24355",
"pm_score": 2,
"selected": false,
"text": "<p>I have used <a href=\"http://tidy.sourceforge.net/\" rel=\"nofollow noreferrer\">Tidy</a> with <a href=\"http://elsdoerfer.name/=libtidy\" rel=\"nofollow noreferrer\">libtidy</a> from Michael Elsdörfer. It give you heaps of options and you can configure them externally to the application. Also applicable to HTML.</p>\n\n<p>This is some very rough code that I used. Do with it as you please.</p>\n\n<pre><code>function TForm1.DoTidy(const Source: string): string;\nvar\n Tidy : TLibTidy;\nbegin\n if not TidyGlobal.LoadTidyLibrary('libtidy.dll') then\n begin\n // Application.MessageBox('TidyLib is not available.', 'Error', 16);\n // exit;\n raise Exception.Create('Cannot load TidyLib.dll');\n end;\n Tidy := TLibTidy.Create(Self);\n try\n Tidy.LoadConfigFile(ExtractFilePath(Application.ExeName) +\n 'tidyconfig.txt');\n // Tidy.Configuration.IndentContent := tsYes;\n // Tidy.Configuration.IndentSpaces := 5;\n // Tidy.Configuration.UpperCaseTags := False;\n // Tidy.Configuration.NumEntities := True;\n // Tidy.Configuration.AccessibilityCheckLevel := 2;\n // Tidy.Configuration.InlineTags := 'foo,bar';\n // Tidy.Configuration.XmlDecl := True;\n // Tidy.Configuration.XmlTags := True;\n // Tidy.Configuration.CharEncoding := TidyUTF8;\n // Tidy.Configuration.WrapLen := 0;\n // Tidy.SaveConfigFile('tidyconfig.txt');\n Tidy.ParseString(Source);\n Result := Tidy.RunDiagnosticsAndRepair;\n finally\n Tidy.Free;\n end;\nend;\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234056",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6244/"
] |
Anyone got a ready made function that will take an XML string and return a correctly indented string?
eg
```
<XML><TAG1>A</TAG1><TAG2><Tag3></Tag3></TAG2></XML>
```
and will return nicely formatted String in return after inserting linebreaks and tabs or spaces?
|
The RTL has [FormatXMLData](http://docwiki.embarcadero.com/Libraries/XE5/en/Xml.XMLDoc.FormatXMLData) in XMLDoc.pas that accepts and returns strings.
|
234,059 |
<p>I have the following code:</p>
<pre><code>MemoryStream foo(){
MemoryStream ms = new MemoryStream();
// write stuff to ms
return ms;
}
void bar(){
MemoryStream ms2 = foo();
// do stuff with ms2
return;
}
</code></pre>
<p>Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later? </p>
<p>I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.</p>
|
[
{
"answer_id": 234068,
"author": "Nick",
"author_id": 26161,
"author_profile": "https://Stackoverflow.com/users/26161",
"pm_score": 3,
"selected": false,
"text": "<p>All streams implement IDisposable. Wrap your Memory stream in a using statement and you'll be fine and dandy. The using block will ensure your stream is closed and disposed no matter what.</p>\n\n<p>wherever you call Foo you can do using(MemoryStream ms = foo()) and i think you should still be ok.</p>\n"
},
{
"answer_id": 234070,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 1,
"selected": false,
"text": "<p>If an object implements IDisposable, you must call the .Dispose method when you're done.</p>\n\n<p>In some objects, Dispose means the same as Close and vice versa, in that case, either is good.</p>\n\n<p>Now, for your particular question, no, you will not leak memory.</p>\n"
},
{
"answer_id": 234071,
"author": "Rob Prouse",
"author_id": 30827,
"author_profile": "https://Stackoverflow.com/users/30827",
"pm_score": 7,
"selected": true,
"text": "<p>If something is Disposable, you should always Dispose it. You should be using a <code>using</code> statement in your <code>bar()</code> method to make sure <code>ms2</code> gets Disposed.</p>\n\n<p>It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a warning.</p>\n"
},
{
"answer_id": 234077,
"author": "Steve",
"author_id": 22712,
"author_profile": "https://Stackoverflow.com/users/22712",
"pm_score": -1,
"selected": false,
"text": "<p>I'm no .net expert, but perhaps the problem here is resources, namely the file handle, and not memory. I guess the garbage collector will eventually free the stream, and close the handle, but I think it would always be best practice to close it explicitly, to make sure you flush out the contents to disk.</p>\n"
},
{
"answer_id": 234080,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 3,
"selected": false,
"text": "<p>Calling <code>.Dispose()</code> (or wrapping with <code>Using</code>) is not required.</p>\n\n<p>The reason you call <code>.Dispose()</code> is to <strong>release the resource as soon as possible</strong>.</p>\n\n<p>Think in terms of, say, the Stack Overflow server, where we have a limited set of memory and thousands of requests coming in. We don't want to wait around for scheduled garbage collection, we want to release that memory ASAP so it's available for new incoming requests.</p>\n"
},
{
"answer_id": 234232,
"author": "OwenP",
"author_id": 2547,
"author_profile": "https://Stackoverflow.com/users/2547",
"pm_score": 2,
"selected": false,
"text": "<p>You won't leak memory, but your code reviewer is correct to indicate you should close your stream. It's polite to do so.</p>\n\n<p>The only situation in which you might leak memory is when you accidentally leave a reference to the stream and never close it. You still aren't really leaking memory, but you <em>are</em> needlessly extending the amount of time that you claim to be using it.</p>\n"
},
{
"answer_id": 234257,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 8,
"selected": false,
"text": "<p>You won't leak anything - at least in the current implementation.</p>\n\n<p>Calling Dispose won't clean up the memory used by MemoryStream any faster. It <em>will</em> stop your stream from being viable for Read/Write calls after the call, which may or may not be useful to you.</p>\n\n<p>If you're absolutely sure that you <em>never</em> want to move from a MemoryStream to another kind of stream, it's not going to do you any harm to not call Dispose. However, it's generally good practice partly because if you ever <em>do</em> change to use a different Stream, you don't want to get bitten by a hard-to-find bug because you chose the easy way out early on. (On the other hand, there's the YAGNI argument...)</p>\n\n<p>The other reason to do it anyway is that a new implementation <em>may</em> introduce resources which would be freed on Dispose.</p>\n"
},
{
"answer_id": 312299,
"author": "Chris R. Donnelly",
"author_id": 17152,
"author_profile": "https://Stackoverflow.com/users/17152",
"pm_score": 2,
"selected": false,
"text": "<p>I would recommend wrapping the MemoryStream in <code>bar()</code> in a <code>using</code> statement mainly for consistency:</p>\n\n<ul>\n<li>Right now MemoryStream does not free memory on <code>.Dispose()</code>, but it is possible that at some point in the future it might, or you (or someone else at your company) might replace it with your own custom MemoryStream that does, etc.</li>\n<li>It helps to establish a pattern in your project to ensure <em>all</em> Streams get disposed -- the line is more firmly drawn by saying \"all Streams must be disposed\" instead of \"some Streams must be disposed, but certain ones don't have to\"...</li>\n<li>If you ever change the code to allow for returning other types of Streams, you'll need to change it to dispose anyway.</li>\n</ul>\n\n<p>Another thing I usually do in cases like <code>foo()</code> when creating and returning an IDisposable is to ensure that any failure between constructing the object and the <code>return</code> is caught by an exception, disposes the object, and rethrows the exception:</p>\n\n<pre><code>MemoryStream x = new MemoryStream();\ntry\n{\n // ... other code goes here ...\n return x;\n}\ncatch\n{\n // \"other code\" failed, dispose the stream before throwing out the Exception\n x.Dispose();\n throw;\n}\n</code></pre>\n"
},
{
"answer_id": 869521,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Disposal of unmanaged resources is non-deterministic in garbage collected languages. Even if you call Dispose explicitly, you have absolutely no control over when the backing memory is actually freed. Dispose is implicitly called when an object goes out of scope, whether it be by exiting a using statement, or popping up the callstack from a subordinate method. This all being said, sometimes the object may actually be a wrapper for a managed resource (e.g. file). This is why it's good practice to explicitly close in finally statements or to use the using statement. \nCheers</p>\n"
},
{
"answer_id": 870605,
"author": "Joe",
"author_id": 13087,
"author_profile": "https://Stackoverflow.com/users/13087",
"pm_score": 3,
"selected": false,
"text": "<p>This is already answered, but I'll just add that the good old-fashioned principle of information hiding means you may at some future point want to refactor:</p>\n\n<pre><code>MemoryStream foo()\n{ \n MemoryStream ms = new MemoryStream(); \n // write stuff to ms \n return ms;\n}\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>Stream foo()\n{ \n ...\n}\n</code></pre>\n\n<p>This emphasizes that callers should not care what kind of Stream is being returned, and makes it possible to change the internal implementation (e.g. when mocking for unit testing).</p>\n\n<p>You then will need be in trouble if you haven't used Dispose in your bar implementation:</p>\n\n<pre><code>void bar()\n{ \n using (Stream s = foo())\n {\n // do stuff with s\n return;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2837425,
"author": "Triynko",
"author_id": 88409,
"author_profile": "https://Stackoverflow.com/users/88409",
"pm_score": 5,
"selected": false,
"text": "<p><strong>Yes there's <em>a</em> leak</strong>, depending on how you define LEAK and how much LATER you mean...</p>\n\n<p>If by leak you mean \"the memory remains allocated, unavailable for use, even though you're done using it\" and by latter you mean anytime after calling dispose, then then yes there may be a leak, although its not permanent (i.e. for the life of your applications runtime).</p>\n\n<p>To free the managed memory used by the MemoryStream, <strong>you need to unreference it</strong>, by nullifying your reference to it, so it becomes eligible for garbage collection right away. If you fail to do this, then you create a temporary leak from the time you're done using it, until your reference goes out of scope, because in the meantime the memory will not be available for allocation.</p>\n\n<p>The benefit of the using statement (over simply calling dispose) is that you can DECLARE your reference in the using statement. When the using statement finishes, not only is dispose called, but your reference goes out of scope, effectively nullifying the reference and making your object eligible for garbage collection immediately without requiring you to remember to write the \"reference=null\" code.</p>\n\n<p>While failing to unreference something right away is not a classical \"permanent\" memory leak, it definitely has the same effect. For example, if you keep your reference to the MemoryStream (even after calling dispose), and a little further down in your method you try to allocate more memory... the memory in use by your still-referenced memory stream will not be available to you until you nullify the reference or it goes out of scope, even though you called dispose and are done using it.</p>\n"
},
{
"answer_id": 14211270,
"author": "user1957438",
"author_id": 1957438,
"author_profile": "https://Stackoverflow.com/users/1957438",
"pm_score": -1,
"selected": false,
"text": "<p>MemorySteram is nothing but array of byte, which is managed object.\nForget to dispose or close this has no side effect other than over head of finalization.<br>\nJust check constuctor or flush method of MemoryStream in reflector and it will be clear why you don't need to worry about closing or disposing it other than just for matter of following good practice. </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234059",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26286/"
] |
I have the following code:
```
MemoryStream foo(){
MemoryStream ms = new MemoryStream();
// write stuff to ms
return ms;
}
void bar(){
MemoryStream ms2 = foo();
// do stuff with ms2
return;
}
```
Is there any chance that the MemoryStream that I've allocated will somehow fail to be disposed of later?
I've got a peer review insisting that I manually close this, and I can't find the information to tell if he has a valid point or not.
|
If something is Disposable, you should always Dispose it. You should be using a `using` statement in your `bar()` method to make sure `ms2` gets Disposed.
It will eventually get cleaned up by the garbage collector, but it is always good practice to call Dispose. If you run FxCop on your code, it would flag it as a warning.
|
234,064 |
<p>Using data binding, how do you bind a new object that uses value types? </p>
<p>Simple example:</p>
<pre><code>public class Person() {
private string _firstName;
private DateTime _birthdate;
private int _favoriteNumber;
//Properties
}
</code></pre>
<p>If I create a new Person() and bind it to a form with text boxes. Birth Date displays as 01/01/0001 and Favorite Number as 0. These fields are required, but I would like these boxes to be empty and have the user fill them in.</p>
<p>The solution also needs to be able to default fields. In our example, I may want the Favorite Number to default to 42.</p>
<p>I'm specifically asking about Silverlight, but I assume WPF and WinForms probably have the same issue.</p>
<p><b>EDIT:</b></p>
<p>I thought of Nullable types, however we are currently using the same domain objects on client and server and I don't want to have required fields be Nullable. I'm hoping the databinding engine exposes a way to know it is binding a new object?</p>
|
[
{
"answer_id": 234155,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 2,
"selected": false,
"text": "<p>Perhaps you can try Nullable types?</p>\n\n<pre><code>public class Person() {\n private string? _firstName;\n private DateTime? _birthdate;\n private int? _favoriteNumber;\n //Properties\n}\n</code></pre>\n\n<p>or </p>\n\n<pre><code>public class Person() {\n private Nullable<string> _firstName;\n private Nullable<DateTime> _birthdate;\n private Nullable<int> _favoriteNumber;\n //Properties\n}\n</code></pre>\n\n<p>which is actually the same.</p>\n\n<p>Now, the default values are null, and you can force the properties to have a value by setting them.</p>\n\n<p>More about Nullable types:</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx</a></p>\n"
},
{
"answer_id": 237273,
"author": "Senkwe",
"author_id": 6419,
"author_profile": "https://Stackoverflow.com/users/6419",
"pm_score": 0,
"selected": false,
"text": "<p>I'd rewrite the Person class to looks something more like this...</p>\n\n<pre><code>public class Person\n {\n private int _favoriteNumber = 0;\n public string FavoriteNumber\n {\n get\n {\n return _favoriteNumber > 0 ? _favoriteNumber.ToString() : string.Empty;\n }\n set\n {\n _favoriteNumber = Convert.ToInt32(value);\n }\n }\n\n private DateTime _birthDate = DateTime.MinValue;\n private string BirthDate \n {\n get\n {\n return _birthDate == DateTime.MinValue ? string.Empty : _birthDate.ToString(); //or _birthDate.ToShortDateString() etc etc\n }\n set\n {\n _birthDate = DateTime.Parse(value);\n }\n }\n }\n</code></pre>\n"
},
{
"answer_id": 237335,
"author": "nyxtom",
"author_id": 19753,
"author_profile": "https://Stackoverflow.com/users/19753",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the IValueConverter to format your textbox bindings to default values based on the value of the object. Here's a few links on the IValueConverter</p>\n\n<p><a href=\"http://ascendedguard.com/2007/08/data-binding-with-value-converters.html\" rel=\"nofollow noreferrer\">http://ascendedguard.com/2007/08/data-binding-with-value-converters.html</a>\n<a href=\"http://weblogs.asp.net/marianor/archive/2007/09/18/using-ivalueconverter-to-format-binding-values-in-wpf.aspx\" rel=\"nofollow noreferrer\">http://weblogs.asp.net/marianor/archive/2007/09/18/using-ivalueconverter-to-format-binding-values-in-wpf.aspx</a></p>\n\n<p>Unfortunately this might not be what you need since you don't have the option of the Nullable value for each of these properties. </p>\n\n<p>What you can do is to set the default properties for your object when you do the databinding.</p>\n\n<p>You can do this by having a Person.Empty object for default values. Or setting these values explicitly when the DataContext is set. </p>\n\n<p>Either way should work though :)</p>\n"
},
{
"answer_id": 237419,
"author": "Ian Oakes",
"author_id": 21606,
"author_profile": "https://Stackoverflow.com/users/21606",
"pm_score": 1,
"selected": false,
"text": "<p>Try using a value converter, here's an example that should get your started. </p>\n\n<p>The basic idea is to convert the default value for a type to null when the data is being displayed, and to convert any null values back to the types default value, when the binding source is updated.</p>\n\n<pre><code>public class DefaultValueToNullConverter : IValueConverter\n{\n public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n Type valueType = parameter as Type;\n\n if (value != null && valueType != null && value.Equals(defautValue(valueType)))\n {\n result = null;\n }\n\n return result;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)\n {\n object result = value;\n Type valueType = parameter as Type;\n\n if (value == null && valueType != null )\n {\n result = defautValue(valueType);\n }\n return result;\n }\n\n private object defautValue(Type type)\n {\n object result = null;\n if (type == typeof(int))\n {\n result = 0;\n }\n else if (type == typeof(DateTime))\n {\n result = DateTime.MinValue;\n }\n return result;\n }\n}\n</code></pre>\n\n<p>Then in your xaml reference the converter like this</p>\n\n<pre><code><Page.Resources>\n <local:DefaultValueToNullConverter x:Key=\"DefaultValueToNullConverter\"/>\n</Page.Resources>\n\n<TextBox \n Text=\"{Binding \n Path=BirthDate, \n Converter={StaticResource DefaultValueToNullConverter},\n ConverterParameter={x:Type sys:DateTime}}\" \n />\n</code></pre>\n"
},
{
"answer_id": 244267,
"author": "Brian Leahy",
"author_id": 580,
"author_profile": "https://Stackoverflow.com/users/580",
"pm_score": 0,
"selected": false,
"text": "<p>After you have your converter in place, you also need to impliment INotifyPropertyChanged on the Person object. That way you can set the binding's Mode=TwoWay two way databinding will update the value in the object when a change is made on the textbox, and vis a vis.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234064",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4231/"
] |
Using data binding, how do you bind a new object that uses value types?
Simple example:
```
public class Person() {
private string _firstName;
private DateTime _birthdate;
private int _favoriteNumber;
//Properties
}
```
If I create a new Person() and bind it to a form with text boxes. Birth Date displays as 01/01/0001 and Favorite Number as 0. These fields are required, but I would like these boxes to be empty and have the user fill them in.
The solution also needs to be able to default fields. In our example, I may want the Favorite Number to default to 42.
I'm specifically asking about Silverlight, but I assume WPF and WinForms probably have the same issue.
**EDIT:**
I thought of Nullable types, however we are currently using the same domain objects on client and server and I don't want to have required fields be Nullable. I'm hoping the databinding engine exposes a way to know it is binding a new object?
|
Perhaps you can try Nullable types?
```
public class Person() {
private string? _firstName;
private DateTime? _birthdate;
private int? _favoriteNumber;
//Properties
}
```
or
```
public class Person() {
private Nullable<string> _firstName;
private Nullable<DateTime> _birthdate;
private Nullable<int> _favoriteNumber;
//Properties
}
```
which is actually the same.
Now, the default values are null, and you can force the properties to have a value by setting them.
More about Nullable types:
<http://msdn.microsoft.com/en-us/library/b3h38hb0.aspx>
|
234,076 |
<p>I have a "Login" button that I want to be disabled until 3 text boxes on the same WPF form are populated with text (user, password, server). </p>
<p>I have a backing object with a boolean property called IsLoginEnabled which returns True if and only if all 3 controls have data. However, when should I be checking this property? Should it be on the LostFocus event of each of the 3 dependent controls?</p>
<p>Thanks!</p>
<p>vg1890</p>
|
[
{
"answer_id": 234118,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, I would say the easiest option would be to check it on the LostFocus or TextChanged event of each of those controls. However, if you want to do a little heavier lifting, you could implement the boolean as a dependency property that you could have bound to the button's Enable.\n<a href=\"http://msdn.microsoft.com/en-us/library/ms750428.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/ms750428.aspx</a></p>\n"
},
{
"answer_id": 234140,
"author": "Nick",
"author_id": 26161,
"author_profile": "https://Stackoverflow.com/users/26161",
"pm_score": 0,
"selected": false,
"text": "<p>Can you just databind your IsLoginEnabled right to the Enabled property of the login button?</p>\n"
},
{
"answer_id": 234158,
"author": "Andrew",
"author_id": 5662,
"author_profile": "https://Stackoverflow.com/users/5662",
"pm_score": 2,
"selected": true,
"text": "<p>I'd get the \"backing object\" to raise the <code>IsLoginEnabled</code> changed event when any of the 3 fields are updated. You can then bind the button to the IsLoginEnabled property and not have to keep checking it.</p>\n\n<p>The pseudocode would look something like this:</p>\n\n<pre><code>Public Event IsLoginEnabledChanged As EventHandler\n\nPublic Property User() As String\nGet.. ' snipped for brevity\nSet(ByVal value As String)\n mUser = value\n RaiseEvent IsLoginEnabledChanged(Me, New EventArgs())\nEnd Set\n\n' do the same in the Set for Password() and Server() properties\n</code></pre>\n\n<p>The trick to this is naming the Event <code>[PropertyName]Changed</code> (i.e. <code>IsLogonEnabledChanged</code>) - because raising this event will automagically notify any bound controls :o)</p>\n"
},
{
"answer_id": 235019,
"author": "Vin",
"author_id": 1747,
"author_profile": "https://Stackoverflow.com/users/1747",
"pm_score": 0,
"selected": false,
"text": "<p>I think you could use <strong>RoutedCommands</strong> one of the most useful features of WPF. Basically add a <strong>CommandBinding</strong>, to use <strong>OnExecute</strong> and <strong>OnQueryCommandEnabled</strong> to manage button's enabled state.</p>\n\n<p><a href=\"http://blogs.msdn.com/dancre/archive/2006/08/05/dm-v-vm-part-5-commands.aspx\" rel=\"nofollow noreferrer\">Check out this wonderful explanation on using RoutedCommands in WPF</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/132931/"
] |
I have a "Login" button that I want to be disabled until 3 text boxes on the same WPF form are populated with text (user, password, server).
I have a backing object with a boolean property called IsLoginEnabled which returns True if and only if all 3 controls have data. However, when should I be checking this property? Should it be on the LostFocus event of each of the 3 dependent controls?
Thanks!
vg1890
|
I'd get the "backing object" to raise the `IsLoginEnabled` changed event when any of the 3 fields are updated. You can then bind the button to the IsLoginEnabled property and not have to keep checking it.
The pseudocode would look something like this:
```
Public Event IsLoginEnabledChanged As EventHandler
Public Property User() As String
Get.. ' snipped for brevity
Set(ByVal value As String)
mUser = value
RaiseEvent IsLoginEnabledChanged(Me, New EventArgs())
End Set
' do the same in the Set for Password() and Server() properties
```
The trick to this is naming the Event `[PropertyName]Changed` (i.e. `IsLogonEnabledChanged`) - because raising this event will automagically notify any bound controls :o)
|
234,090 |
<p>How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:</p>
<pre><code><input name = "deleteGameButton" type = "submit" value = "Delete"
onclick = "submitToServlet('DeleteGameServlet');">
</code></pre>
<p>Here is the corresponding javascript:</p>
<pre><code> function submitToServlet(newAction)
{
document.userGameForm.action = newAction;
}
</code></pre>
<p>I'd like the servlet to have access to userBean</p>
<pre><code> <jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />
</code></pre>
|
[
{
"answer_id": 234125,
"author": "Vladimir Dyuzhev",
"author_id": 1163802,
"author_profile": "https://Stackoverflow.com/users/1163802",
"pm_score": 3,
"selected": true,
"text": "<p>You kind of mess things here.</p>\n\n<p>onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was <strong>generated</strong>. To pass parameters back to servlet you need to use good old form fields, and submit the form. </p>\n\n<p>Add more fields to the form, set their values before submit, then submit.</p>\n\n<p>In Servlet call request.getParameter(\"name\");</p>\n\n<p>P.S. To automate this kind of things <strong>USE STRUTS</strong>. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.</p>\n"
},
{
"answer_id": 234127,
"author": "David Santamaria",
"author_id": 24097,
"author_profile": "https://Stackoverflow.com/users/24097",
"pm_score": 0,
"selected": false,
"text": "<p>Hi try with the next tag:</p>\n\n<pre><code><jsp:useBean id = \"userBean\" scope = \"session\" class = \"org.project.User\"/>\n <jsp:setProperty name=\"beanName\" property=\"propertyname\" value=\"value\"/>\n</jsp:useBean>\n</code></pre>\n\n<p>more <a href=\"http://java.sun.com/products/jsp/tags/syntaxref.fm13.html\" rel=\"nofollow noreferrer\">here</a></p>\n\n<p>Good luck!</p>\n"
},
{
"answer_id": 234826,
"author": "mtruesdell",
"author_id": 6479,
"author_profile": "https://Stackoverflow.com/users/6479",
"pm_score": 2,
"selected": false,
"text": "<p>It depends exactly what you are trying to do. The </p>\n\n<p><code><jsp:useBean id = \"userBean\" scope = \"session\" class = \"org.project.User\" /></code></p>\n\n<p>tag will allow you to use the userBean attribute of the session in your jsp. If there is not a userBean attribute in the session, it will create a new one (using the default constructor for org.project.User) and place it in the session.</p>\n\n<p>Then, when you get to the servlet, you can retrieve it with:</p>\n\n<pre><code>User user = (User)request.getSession().getAttribute(\"userBean\");\n</code></pre>\n"
},
{
"answer_id": 5337181,
"author": "Naveen kumar HR",
"author_id": 664042,
"author_profile": "https://Stackoverflow.com/users/664042",
"pm_score": 1,
"selected": false,
"text": "<pre><code> getServletConfig().getServletContext().getRequestDispatcher(\"servlet path & name\"); \n dispatcher.forward (request, response);\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234090",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25280/"
] |
How do I pass a parameter from a page's useBean in JSP to a servlet in Java? I have some data in a form that gets passed no problem with a submit button, but no way to send anything else. Please help? Here is my code:
```
<input name = "deleteGameButton" type = "submit" value = "Delete"
onclick = "submitToServlet('DeleteGameServlet');">
```
Here is the corresponding javascript:
```
function submitToServlet(newAction)
{
document.userGameForm.action = newAction;
}
```
I'd like the servlet to have access to userBean
```
<jsp:useBean id = "userBean" scope = "session" class = "org.project.User" />
```
|
You kind of mess things here.
onclick() is Javascript and executed on client side. It has no (direct) way to update session-scoped bean. That bean is left on server-side, and was used when the HTML page was **generated**. To pass parameters back to servlet you need to use good old form fields, and submit the form.
Add more fields to the form, set their values before submit, then submit.
In Servlet call request.getParameter("name");
P.S. To automate this kind of things **USE STRUTS**. :-) Struts does exactly what you want: before passing the parameters to action, it populates the bean with those parameters. Transparently.
|
234,091 |
<p>We have a highly specialized DAL which sits over our DB. Our apps need to use this DAL to correctly operate against this DB.</p>
<p>The generated DAL (which sits on some custom base classes) has various 'Rec' classes (Table1Rec, Table2Rec) each of which represents the record structure of a given table.</p>
<p>Here is a sample Pseudo-class...</p>
<pre><code>Public Class SomeTableRec
Private mField1 As String
Private mField1isNull As Boolean
Private mField2 As Integer
Private mField2isNull As Boolean
Public Sub New()
mField1isNull = True
mField2isNull = True
End Sub
Public Property Field1() As String
Get
Return mField1
End Get
Set(ByVal value As String)
mField1 = value
mField1isNull = False
End Set
End Property
Public ReadOnly Property Field1isNull() As Boolean
Get
Return mField1isNull
End Get
End Property
Public Property Field2() As Integer
Get
Return mField2
End Get
Set(ByVal value As Integer)
mField2 = value
mField2isNull = False
End Set
End Property
Public ReadOnly Property Field2isNull() As Boolean
Get
Return mField2isNull
End Get
End Property
End Class
</code></pre>
<p>Each class has properties for each of the fields...
Thus I can write...</p>
<pre><code>Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
Table2Rec.Field2 = 500
</code></pre>
<p>Where a field can accept a NULL value, there is an additional property which indicates if the value is currently null.</p>
<p>Thus....</p>
<pre><code>Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
If Table1Rec.Field1Null then
' This clearly is not true
End If
If Table1Rec.Field2Null then
' This will be true
End If
</code></pre>
<p>This works because the constructor of the class sets all NULLproperties to True and the setting of any FieldProperty will cause the equivalent NullProperty to be set to false.</p>
<p>I have recently had the need to expose my DAL over the web through a web service (which I of course intend to secure) and have discovered that while the structure of the 'Rec' class remains intact over the web... All logic is lost..</p>
<p>If someone were to run the previous piece of code remotely they would notice that neither condition would prove true as there is no client side code which sets null to true.</p>
<p><strong>I get the feeling I have architected this all wrong, but cannot see how I should improve it.</strong></p>
<p><strong>What is the correct way to architect this?</strong></p>
|
[
{
"answer_id": 234216,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 0,
"selected": false,
"text": "<p>Web services are designed to expose operation(methods) & data contracts but not internal implementation logic. This is a \"good thing\" in the world of service-oriented architecture. The scenario you describe is a remote/distributed object architecture. Web services will not support what you are trying to do. Please see this <a href=\"https://stackoverflow.com/questions/187006/how-to-expose-objects-through-wcf#187079\" title=\"Using WCF\">post</a> for more information.</p>\n"
},
{
"answer_id": 614630,
"author": "digiguru",
"author_id": 5055,
"author_profile": "https://Stackoverflow.com/users/5055",
"pm_score": 2,
"selected": true,
"text": "<p>Not sure if I fully understand the question, but you can have nullable data types in XML. </p>\n\n<p>So this...</p>\n\n<pre><code>Imports System.Web\nImports System.Web.Services\nImports System.Web.Services.Protocols\n\n<WebService(Namespace:=\"http://tempuri.org/\")> _\n<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _\n<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _\nPublic Class Testing\n Inherits System.Web.Services.WebService\n\n <WebMethod()> _\n Public Function GetObjects() As Generic.List(Of TestObject)\n Dim list As New Generic.List(Of TestObject)\n list.Add(New TestObject(Nothing, \"Empty ID Object\"))\n list.Add(New TestObject(1, \"Full ID Object\"))\n list.Add(New TestObject(2, Nothing))\n Return list\n End Function\n\n Public Class TestObject\n Public Sub New()\n _name = String.Empty\n _id = Nothing\n End Sub\n Public Sub New(ByVal id As Nullable(Of Integer), ByVal name As String)\n _name = name\n _id = id\n End Sub\n Private _name As String\n Public Property Name() As String\n Get\n Return _name\n End Get\n Set(ByVal value As String)\n _name = value\n End Set\n End Property\n\n Private _id As Nullable(Of Integer)\n Public Property ID() As Nullable(Of Integer)\n Get\n Return _id\n End Get\n Set(ByVal value As Nullable(Of Integer))\n _id = value\n End Set\n End Property\n End Class\n\nEnd Class\n</code></pre>\n\n<p>outputs this (with nullable areas)</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\" ?> \n<ArrayOfTestObject xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://tempuri.org/\">\n <TestObject>\n <Name>Empty ID Object</Name> \n <ID xsi:nil=\"true\" /> \n </TestObject>\n <TestObject>\n <Name>Full ID Object</Name> \n <ID>1</ID> \n </TestObject>\n <TestObject>\n <ID>2</ID> \n </TestObject>\n</ArrayOfTestObject>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11356/"
] |
We have a highly specialized DAL which sits over our DB. Our apps need to use this DAL to correctly operate against this DB.
The generated DAL (which sits on some custom base classes) has various 'Rec' classes (Table1Rec, Table2Rec) each of which represents the record structure of a given table.
Here is a sample Pseudo-class...
```
Public Class SomeTableRec
Private mField1 As String
Private mField1isNull As Boolean
Private mField2 As Integer
Private mField2isNull As Boolean
Public Sub New()
mField1isNull = True
mField2isNull = True
End Sub
Public Property Field1() As String
Get
Return mField1
End Get
Set(ByVal value As String)
mField1 = value
mField1isNull = False
End Set
End Property
Public ReadOnly Property Field1isNull() As Boolean
Get
Return mField1isNull
End Get
End Property
Public Property Field2() As Integer
Get
Return mField2
End Get
Set(ByVal value As Integer)
mField2 = value
mField2isNull = False
End Set
End Property
Public ReadOnly Property Field2isNull() As Boolean
Get
Return mField2isNull
End Get
End Property
End Class
```
Each class has properties for each of the fields...
Thus I can write...
```
Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
Table2Rec.Field2 = 500
```
Where a field can accept a NULL value, there is an additional property which indicates if the value is currently null.
Thus....
```
Dim Rec as New Table1Rec
Table1Rec.Field1 = "SomeString"
If Table1Rec.Field1Null then
' This clearly is not true
End If
If Table1Rec.Field2Null then
' This will be true
End If
```
This works because the constructor of the class sets all NULLproperties to True and the setting of any FieldProperty will cause the equivalent NullProperty to be set to false.
I have recently had the need to expose my DAL over the web through a web service (which I of course intend to secure) and have discovered that while the structure of the 'Rec' class remains intact over the web... All logic is lost..
If someone were to run the previous piece of code remotely they would notice that neither condition would prove true as there is no client side code which sets null to true.
**I get the feeling I have architected this all wrong, but cannot see how I should improve it.**
**What is the correct way to architect this?**
|
Not sure if I fully understand the question, but you can have nullable data types in XML.
So this...
```
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class Testing
Inherits System.Web.Services.WebService
<WebMethod()> _
Public Function GetObjects() As Generic.List(Of TestObject)
Dim list As New Generic.List(Of TestObject)
list.Add(New TestObject(Nothing, "Empty ID Object"))
list.Add(New TestObject(1, "Full ID Object"))
list.Add(New TestObject(2, Nothing))
Return list
End Function
Public Class TestObject
Public Sub New()
_name = String.Empty
_id = Nothing
End Sub
Public Sub New(ByVal id As Nullable(Of Integer), ByVal name As String)
_name = name
_id = id
End Sub
Private _name As String
Public Property Name() As String
Get
Return _name
End Get
Set(ByVal value As String)
_name = value
End Set
End Property
Private _id As Nullable(Of Integer)
Public Property ID() As Nullable(Of Integer)
Get
Return _id
End Get
Set(ByVal value As Nullable(Of Integer))
_id = value
End Set
End Property
End Class
End Class
```
outputs this (with nullable areas)
```
<?xml version="1.0" encoding="utf-8" ?>
<ArrayOfTestObject xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<TestObject>
<Name>Empty ID Object</Name>
<ID xsi:nil="true" />
</TestObject>
<TestObject>
<Name>Full ID Object</Name>
<ID>1</ID>
</TestObject>
<TestObject>
<ID>2</ID>
</TestObject>
</ArrayOfTestObject>
```
|
234,110 |
<p>I'm trying to do a very simple INSERT using VB.NET. For some reason I'm getting a SqlException on every insert though. The data is inserted, but still get the following: </p>
<p>Violation of PRIMARY KEY constraint 'PK_User'. Cannot insert duplicate key in object 'dbo.Employee'. The statement has been terminated</p>
<p>When I check in SQL Management Studio, the data is succesfully inserted.</p>
<p>Here is the code where the problem is happening</p>
<pre><code>Try
conn.Open()
Dim insertSQL As String = "insert into Employee(uName, firstName, lastName,
On_Switch, On_Phone) " + "values('" & uName & "', '" & firstName & "', '" _
& lastName & "', '" & onSwitch & "', '" & onPhone & "')"
Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn)
If (AddCom.ExecuteNonQuery() = 1) Then
lblError.Text = "User Added."
' string urlBack = "../ViewAsset.aspx?DeptID=" + DeptID;
' Response.Redirect(urlBack);
End If
conn.Close()
Catch ex As SqlException
Dim ExMsg As String = ex.Message.ToString()
lblError.Text = ExMsg
</code></pre>
<p>I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I'm doing in VB, but I'm lost as to what it is.</p>
|
[
{
"answer_id": 234132,
"author": "Joseph Anderson",
"author_id": 18102,
"author_profile": "https://Stackoverflow.com/users/18102",
"pm_score": 3,
"selected": true,
"text": "<p>Two theories. Either your code is being executed twice, or there's a trigger on the Employee table that's attempting an insert following the successful insert. (Edit: @Mitchel Sellers is exactly right, if the same code works in c# it's absolutely not a trigger issue.)</p>\n\n<p>My hunch is that your code is being executed twice. Try running with the debugger attached and a breakpoint set on the ExecuteNonQuery - I think you'll find that some other method calls this method multiple times.</p>\n\n<p>@Mitchel Sellers - GOOD CATCH ON THE SQL INJECTION BUG! Parameters, please! </p>\n"
},
{
"answer_id": 234162,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 3,
"selected": false,
"text": "<p>As a side note, I STRONGLY recommend changing to parameterized queries to prevent the risk of SQL injection that your current code is not protected from.</p>\n\n<p>For the error issue, I would check to see that your code isn't being called twice in the VB version.</p>\n"
},
{
"answer_id": 236880,
"author": "BenR",
"author_id": 18039,
"author_profile": "https://Stackoverflow.com/users/18039",
"pm_score": 0,
"selected": false,
"text": "<p>As another side note, I noticed that your code could potentially leave a sql connection open. If you're using the .NET 2.0 framework you should use the Using statement. It ensures that connections are closed and disposed even if an exception is thrown. Check this article on MSDN for more detail: <a href=\"http://msdn.microsoft.com/en-us/library/htd05whh.aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/htd05whh.aspx</a>. The other option would be to add the close statement in a Finally block of your try-catch handler.</p>\n"
},
{
"answer_id": 245198,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you are executing this code within an event of some sort make sure you have not subscribed to the event multiple times. I have had this problem in asp.net. Usually I just delete the click event handler in the code behind and the onclick attribute in the aspx file if it exists there as well and then try it again.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
I'm trying to do a very simple INSERT using VB.NET. For some reason I'm getting a SqlException on every insert though. The data is inserted, but still get the following:
Violation of PRIMARY KEY constraint 'PK\_User'. Cannot insert duplicate key in object 'dbo.Employee'. The statement has been terminated
When I check in SQL Management Studio, the data is succesfully inserted.
Here is the code where the problem is happening
```
Try
conn.Open()
Dim insertSQL As String = "insert into Employee(uName, firstName, lastName,
On_Switch, On_Phone) " + "values('" & uName & "', '" & firstName & "', '" _
& lastName & "', '" & onSwitch & "', '" & onPhone & "')"
Dim AddCom As SqlCommand = New SqlCommand(insertSQL, conn)
If (AddCom.ExecuteNonQuery() = 1) Then
lblError.Text = "User Added."
' string urlBack = "../ViewAsset.aspx?DeptID=" + DeptID;
' Response.Redirect(urlBack);
End If
conn.Close()
Catch ex As SqlException
Dim ExMsg As String = ex.Message.ToString()
lblError.Text = ExMsg
```
I went back and tested the same code in C# and there is no Exception thrown. It seems to be something small I'm doing in VB, but I'm lost as to what it is.
|
Two theories. Either your code is being executed twice, or there's a trigger on the Employee table that's attempting an insert following the successful insert. (Edit: @Mitchel Sellers is exactly right, if the same code works in c# it's absolutely not a trigger issue.)
My hunch is that your code is being executed twice. Try running with the debugger attached and a breakpoint set on the ExecuteNonQuery - I think you'll find that some other method calls this method multiple times.
@Mitchel Sellers - GOOD CATCH ON THE SQL INJECTION BUG! Parameters, please!
|
234,131 |
<p>I did this tests and the results seems the count function scale linearly. I have another function relying strongly in the efficiency to know if there are any data, so I would like to know how to replace this select count(*) with another more efficient (maybe constant?) query or data structure.</p>
<blockquote>
<p>psql -d testdb -U postgres -f truncate_and_insert_1000_rows.sql > NUL</p>
<p>psql -d testdb -U postgres -f count_data.sql</p>
</blockquote>
<h2>--------------------------------------------------------------------------------</h2>
<p>Aggregate (cost=36.75..36.76 rows=1 width=0) (actual time=0.762..0.763 rows=1
loops=1)
-> Seq Scan on datos (cost=0.00..31.40 rows=2140 width=0) (actual time=0.02
8..0.468 rows=1000 loops=1)
Total runtime: <strong>0.846 ms</strong>
(3 filas)</p>
<blockquote>
<p>psql -d testdb -U postgres -f truncate_and_insert_10000_rows.sql > NUL</p>
<p>psql -d testdb -U postgres -f count_data.sql</p>
</blockquote>
<h2>--------------------------------------------------------------------------------</h2>
<p>Aggregate (cost=197.84..197.85 rows=1 width=0) (actual time=6.191..6.191 rows=
1 loops=1)
-> Seq Scan on datos (cost=0.00..173.07 rows=9907 width=0) (actual time=0.0
09..3.407 rows=10000 loops=1)
Total runtime: <strong>6.271 ms</strong>
(3 filas)</p>
<blockquote>
<p>psql -d testdb -U postgres -f truncate_and_insert_100000_rows.sql > NUL</p>
<p>psql -d testdb -U postgres -f count_data.sql</p>
</blockquote>
<h2>--------------------------------------------------------------------------------</h2>
<p>Aggregate (cost=2051.60..2051.61 rows=1 width=0) (actual time=74.075..74.076 r
ows=1 loops=1)
-> Seq Scan on datos (cost=0.00..1788.48 rows=105248 width=0) (actual time=
0.032..46.024 rows=100000 loops=1)
Total runtime: <strong>74.164 ms</strong>
(3 filas)</p>
<blockquote>
<p>psql -d prueba -U postgres -f truncate_and_insert_1000000_rows.sql > NUL</p>
<p>psql -d testdb -U postgres -f count_data.sql</p>
</blockquote>
<h2>--------------------------------------------------------------------------------</h2>
<p>Aggregate (cost=19720.00..19720.01 rows=1 width=0) (actual time=637.486..637.4
87 rows=1 loops=1)
-> Seq Scan on datos (cost=0.00..17246.60 rows=989360 width=0) (actual time
=0.028..358.831 rows=1000000 loops=1)
Total runtime: <strong>637.582 ms</strong>
(3 filas)</p>
<p>the definition of data is</p>
<pre><code>CREATE TABLE data
(
id INTEGER NOT NULL,
text VARCHAR(100),
CONSTRAINT pk3 PRIMARY KEY (id)
);
</code></pre>
|
[
{
"answer_id": 234153,
"author": "warren",
"author_id": 4418,
"author_profile": "https://Stackoverflow.com/users/4418",
"pm_score": 0,
"selected": false,
"text": "<p>How a count on the primary key field where it is NOT NULL, limiting the query at 1 response?</p>\n\n<p>Since a primary key <em>must</em> exist, if there is one, you have data, yes?</p>\n"
},
{
"answer_id": 234164,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "<p>If all you care about is 1 row or no rows. Limit your query to the first row - why count all of the rows just to find out if there's 1 or more, or zero...</p>\n\n<p>use the equivalent of ROWNUM = 1 or TOP 1 or whatever postgres gives you.</p>\n"
},
{
"answer_id": 234305,
"author": "Milen A. Radev",
"author_id": 15785,
"author_profile": "https://Stackoverflow.com/users/15785",
"pm_score": -1,
"selected": true,
"text": "<p>You may find <a href=\"http://wiki.postgresql.org/wiki/Slow_Counting\" rel=\"nofollow noreferrer\">this</a> useful.</p>\n"
},
{
"answer_id": 234561,
"author": "Patryk Kordylewski",
"author_id": 30927,
"author_profile": "https://Stackoverflow.com/users/30927",
"pm_score": 2,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code>SELECT t.primary_key IS NOT NULL FROM table t LIMIT 1;\n</code></pre>\n\n<p>You will get TRUE if there are records and NULL if there are none.</p>\n"
},
{
"answer_id": 286578,
"author": "Tometzky",
"author_id": 15862,
"author_profile": "https://Stackoverflow.com/users/15862",
"pm_score": 4,
"selected": false,
"text": "<p>select true from table limit 1;</p>\n"
},
{
"answer_id": 1691576,
"author": "Michael Buen",
"author_id": 11432,
"author_profile": "https://Stackoverflow.com/users/11432",
"pm_score": 3,
"selected": false,
"text": "<pre><code>select exists(select * from your_table_here) as has_row\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234131",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18300/"
] |
I did this tests and the results seems the count function scale linearly. I have another function relying strongly in the efficiency to know if there are any data, so I would like to know how to replace this select count(\*) with another more efficient (maybe constant?) query or data structure.
>
> psql -d testdb -U postgres -f truncate\_and\_insert\_1000\_rows.sql > NUL
>
>
> psql -d testdb -U postgres -f count\_data.sql
>
>
>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Aggregate (cost=36.75..36.76 rows=1 width=0) (actual time=0.762..0.763 rows=1
loops=1)
-> Seq Scan on datos (cost=0.00..31.40 rows=2140 width=0) (actual time=0.02
8..0.468 rows=1000 loops=1)
Total runtime: **0.846 ms**
(3 filas)
>
> psql -d testdb -U postgres -f truncate\_and\_insert\_10000\_rows.sql > NUL
>
>
> psql -d testdb -U postgres -f count\_data.sql
>
>
>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Aggregate (cost=197.84..197.85 rows=1 width=0) (actual time=6.191..6.191 rows=
1 loops=1)
-> Seq Scan on datos (cost=0.00..173.07 rows=9907 width=0) (actual time=0.0
09..3.407 rows=10000 loops=1)
Total runtime: **6.271 ms**
(3 filas)
>
> psql -d testdb -U postgres -f truncate\_and\_insert\_100000\_rows.sql > NUL
>
>
> psql -d testdb -U postgres -f count\_data.sql
>
>
>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Aggregate (cost=2051.60..2051.61 rows=1 width=0) (actual time=74.075..74.076 r
ows=1 loops=1)
-> Seq Scan on datos (cost=0.00..1788.48 rows=105248 width=0) (actual time=
0.032..46.024 rows=100000 loops=1)
Total runtime: **74.164 ms**
(3 filas)
>
> psql -d prueba -U postgres -f truncate\_and\_insert\_1000000\_rows.sql > NUL
>
>
> psql -d testdb -U postgres -f count\_data.sql
>
>
>
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
Aggregate (cost=19720.00..19720.01 rows=1 width=0) (actual time=637.486..637.4
87 rows=1 loops=1)
-> Seq Scan on datos (cost=0.00..17246.60 rows=989360 width=0) (actual time
=0.028..358.831 rows=1000000 loops=1)
Total runtime: **637.582 ms**
(3 filas)
the definition of data is
```
CREATE TABLE data
(
id INTEGER NOT NULL,
text VARCHAR(100),
CONSTRAINT pk3 PRIMARY KEY (id)
);
```
|
You may find [this](http://wiki.postgresql.org/wiki/Slow_Counting) useful.
|
234,174 |
<p>I couldn't figure out why NHibernate is doing this. </p>
<p>Here's part of my table in MS SQL</p>
<pre><code>CREATE TABLE Person (
nameFamily text,
nameGiven text
)
</code></pre>
<p>Here's Person.hbm.xml</p>
<pre><code><hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Infosci.Dpd.Model.Person,Infosci.Dpd.Model" table="Person" lazy="true">
<property type="string" name="NameGiven" column="nameGiven" />
<property type="string" name="NameFamily" column="nameFamily" />
</class>
</hibernate>
</code></pre>
<p>And in my Person.cs I name my property like the following</p>
<pre><code> string NameFamily
{
get ;
set ;
}
string NameGiven
{
get ;
set ;
}
</code></pre>
<p>Then I try to create a record using the following code</p>
<pre><code> ISession session = NHibernateHelper.GetCurrentSession();
Person person = new Person();
person.NameFamily = "lee";
session.Save(person);
</code></pre>
<p>And what's weird is when I try do execute it, NHibernate actually change the column name by doing the following </p>
<pre><code>NHibernate: INSERT INTO Person (name_family,name_given.......
</code></pre>
<p>So here NHibernate chagne my column name from NameFamily to name_family although I did specify the column name. </p>
<p>Is this a NHibernate bug? Or is there any configuration I need to do?</p>
<p>And here's my hibernate config file</p>
<pre><code><?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=xxxxxxx;Initial Catalog=xx;Integrated Security=True;Pooling=False;User ID=xxxx;Password=xxxx</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
</code></pre>
<p>And this is how I create the sessionFactory</p>
<pre><code> sessionFactory = new `Configuration().Configure("hibernate.cfg.xml").
SetNamingStrategy(ImprovedNamingStrategy.Instance).
AddFile("Person.hbm.xml").
BuildSessionFactory();`
</code></pre>
|
[
{
"answer_id": 234245,
"author": "DJ.",
"author_id": 10492,
"author_profile": "https://Stackoverflow.com/users/10492",
"pm_score": 2,
"selected": false,
"text": "<p>That's a \"feature\" of SetNamingStrategy(ImprovedNamingStrategy.Instance)</p>\n\n<p>It will add underscores before each uppercase letter in mixed-cased names.</p>\n\n<p>Not sure how you disable it (me not being a nhibernate user) </p>\n"
},
{
"answer_id": 234563,
"author": "user22839",
"author_id": 22839,
"author_profile": "https://Stackoverflow.com/users/22839",
"pm_score": 1,
"selected": false,
"text": "<p>What I end up doing is just use the default naming strategy or SetNamingStrategy(DefaultNamingStrategy.Instance)</p>\n\n<p>the default naming strategy will leave mix-cased name untouched</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234174",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22839/"
] |
I couldn't figure out why NHibernate is doing this.
Here's part of my table in MS SQL
```
CREATE TABLE Person (
nameFamily text,
nameGiven text
)
```
Here's Person.hbm.xml
```
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2">
<class name="Infosci.Dpd.Model.Person,Infosci.Dpd.Model" table="Person" lazy="true">
<property type="string" name="NameGiven" column="nameGiven" />
<property type="string" name="NameFamily" column="nameFamily" />
</class>
</hibernate>
```
And in my Person.cs I name my property like the following
```
string NameFamily
{
get ;
set ;
}
string NameGiven
{
get ;
set ;
}
```
Then I try to create a record using the following code
```
ISession session = NHibernateHelper.GetCurrentSession();
Person person = new Person();
person.NameFamily = "lee";
session.Save(person);
```
And what's weird is when I try do execute it, NHibernate actually change the column name by doing the following
```
NHibernate: INSERT INTO Person (name_family,name_given.......
```
So here NHibernate chagne my column name from NameFamily to name\_family although I did specify the column name.
Is this a NHibernate bug? Or is there any configuration I need to do?
And here's my hibernate config file
```
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory>
<property name="connection.provider">NHibernate.Connection.DriverConnectionProvider</property>
<property name="dialect">NHibernate.Dialect.MsSql2000Dialect</property>
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string">Data Source=xxxxxxx;Initial Catalog=xx;Integrated Security=True;Pooling=False;User ID=xxxx;Password=xxxx</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
```
And this is how I create the sessionFactory
```
sessionFactory = new `Configuration().Configure("hibernate.cfg.xml").
SetNamingStrategy(ImprovedNamingStrategy.Instance).
AddFile("Person.hbm.xml").
BuildSessionFactory();`
```
|
That's a "feature" of SetNamingStrategy(ImprovedNamingStrategy.Instance)
It will add underscores before each uppercase letter in mixed-cased names.
Not sure how you disable it (me not being a nhibernate user)
|
234,177 |
<p>As usual, some background information first:</p>
<p>Database A (Access database) - Holds a table that has information I need from only two columns. The information from these two columns is needed for an application that will be used by people that cannot access database A.</p>
<p>Database B (Access database) - Holds a table that contains only two columns (mirrors to what we need from table A). Database B is accessible to all users of the application. One issue is that on of the column names is not the same as it is in the table from Database A.</p>
<p>What I need to do is transfer the necessary data via a utility that will run automatically, say once a week (the two databases don't need to be totally in sync, just close). The transfer utility will be run from a user account that has access to both databases (obviously).</p>
<p>Here's the approach I've taken (again if there is a better way, please suggest away):</p>
<ol>
<li><p>Grab the data from database A. It is only the two columns from the necessary table.</p></li>
<li><p>Write the data out to [tablename].txt file using a DataReader object and WriterStream object. I've done this so I can use a schema.ini file and force the data columns to have the same name as they will be in Database B.</p></li>
<li><p>Create a DataSet object, containing a DataTable that mirrors the table from Database B.</p></li>
<li><p>Suck the information from the .txt file into the DataTable using the Microsoft.Jet.OLEDB.4.0 provider with extended properties of text, hdr=yes and fmt=delimited (to match how I have the schema.ini file setup and the .txt file setup). I'm using a DataAdapter to fill the DataTable.</p></li>
<li><p>Create another DataSet object, containing a DataTable that mirrors the table from Database B. </p></li>
<li><p>Suck in the information from Database B so that it contains all the current data found in the table that needs to be updated from Database A. Again I'm using a DataAdapter to fill this DataTable (a different one from Step 5, since they are both using different data sources).</p></li>
<li><p>Merge the DataTable that holds the data from Database A (or the .txt file, technically).</p></li>
<li><p>Update Database B's table with the changes.</p></li>
</ol>
<p>I've written update, delete and insert commands manually for the DataAdapter that is repsonsible for talking to Database B. However, this logic is never used because the DataSet-From-Database-B.Merge(Dataset-From-TxtFile[tableName]) doesn't flip the HasChanges flag. This means the DataSet-From-Database-B.Update doesn't fire any of the commands.</p>
<p>So is there any way I can get the data from DataSet-From-TxtFile to merge and apply to Database B using the method I'm using? Am I missing a crucial step here?</p>
<p>I know I could always delete all the records from Database B's table and then just insert all the records from the text file (even if I had to loop through each record in the DataSet and apply row.SetAdded to ensure it triggers the HasChanges flag), but I'd rather have it apply ONLY the changes each time.</p>
<p>I'm using c# and the 2.0 Framework (which I realize means I can use DataTables and TableAdapters instead of DataSets and DataAdapters since I'm only dealing with a single table, but anyway).</p>
<p>TIA</p>
|
[
{
"answer_id": 234188,
"author": "Mitchel Sellers",
"author_id": 13279,
"author_profile": "https://Stackoverflow.com/users/13279",
"pm_score": 0,
"selected": false,
"text": "<p>Why not simply use a data reader, and loop through the records, doing manual inserts if needed into database B?</p>\n\n<p>Rather than working with datasets, merging, etc..</p>\n"
},
{
"answer_id": 234415,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": true,
"text": "<p>Setting aside for a moment that I would use SQLServer and only have a single table with multiple views controlling who could see what information in it to avoid the whole synchronization problem...</p>\n\n<p>I think that @Mitchel is correct here. Just write a program that connects to both databases, load A table and B table, respectively. Then, for each element (column pair) in A make sure it is in B. If not, then insert it in B. Then, for each element in B, make sure it is in A. If not, then remove it from B. The save B. I don't see the need to go to a file first.</p>\n\n<p>Pseudocode:</p>\n\n<pre><code>DataTable A = load table from A\nDataTable B = load table from B\n\nforeach row in A\n col1 = row[col1]\n col2 = row[col2]\n matchRow = B.select( \"col1 = \" + col1 + \" and col2 = \" + col2)\n if not matchRow exists\n add new row to B with col1,col2\n end\nend\n\nforeach row in B\n col1 = row[col1]\n col2 = row[col2]\n matchRow = A.select( \"col1 = \" + col1 + \" and col2 = \" + col2)\n if not matchRow exists\n remove row from B\n end\nend\n\nupdate B\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234177",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9732/"
] |
As usual, some background information first:
Database A (Access database) - Holds a table that has information I need from only two columns. The information from these two columns is needed for an application that will be used by people that cannot access database A.
Database B (Access database) - Holds a table that contains only two columns (mirrors to what we need from table A). Database B is accessible to all users of the application. One issue is that on of the column names is not the same as it is in the table from Database A.
What I need to do is transfer the necessary data via a utility that will run automatically, say once a week (the two databases don't need to be totally in sync, just close). The transfer utility will be run from a user account that has access to both databases (obviously).
Here's the approach I've taken (again if there is a better way, please suggest away):
1. Grab the data from database A. It is only the two columns from the necessary table.
2. Write the data out to [tablename].txt file using a DataReader object and WriterStream object. I've done this so I can use a schema.ini file and force the data columns to have the same name as they will be in Database B.
3. Create a DataSet object, containing a DataTable that mirrors the table from Database B.
4. Suck the information from the .txt file into the DataTable using the Microsoft.Jet.OLEDB.4.0 provider with extended properties of text, hdr=yes and fmt=delimited (to match how I have the schema.ini file setup and the .txt file setup). I'm using a DataAdapter to fill the DataTable.
5. Create another DataSet object, containing a DataTable that mirrors the table from Database B.
6. Suck in the information from Database B so that it contains all the current data found in the table that needs to be updated from Database A. Again I'm using a DataAdapter to fill this DataTable (a different one from Step 5, since they are both using different data sources).
7. Merge the DataTable that holds the data from Database A (or the .txt file, technically).
8. Update Database B's table with the changes.
I've written update, delete and insert commands manually for the DataAdapter that is repsonsible for talking to Database B. However, this logic is never used because the DataSet-From-Database-B.Merge(Dataset-From-TxtFile[tableName]) doesn't flip the HasChanges flag. This means the DataSet-From-Database-B.Update doesn't fire any of the commands.
So is there any way I can get the data from DataSet-From-TxtFile to merge and apply to Database B using the method I'm using? Am I missing a crucial step here?
I know I could always delete all the records from Database B's table and then just insert all the records from the text file (even if I had to loop through each record in the DataSet and apply row.SetAdded to ensure it triggers the HasChanges flag), but I'd rather have it apply ONLY the changes each time.
I'm using c# and the 2.0 Framework (which I realize means I can use DataTables and TableAdapters instead of DataSets and DataAdapters since I'm only dealing with a single table, but anyway).
TIA
|
Setting aside for a moment that I would use SQLServer and only have a single table with multiple views controlling who could see what information in it to avoid the whole synchronization problem...
I think that @Mitchel is correct here. Just write a program that connects to both databases, load A table and B table, respectively. Then, for each element (column pair) in A make sure it is in B. If not, then insert it in B. Then, for each element in B, make sure it is in A. If not, then remove it from B. The save B. I don't see the need to go to a file first.
Pseudocode:
```
DataTable A = load table from A
DataTable B = load table from B
foreach row in A
col1 = row[col1]
col2 = row[col2]
matchRow = B.select( "col1 = " + col1 + " and col2 = " + col2)
if not matchRow exists
add new row to B with col1,col2
end
end
foreach row in B
col1 = row[col1]
col2 = row[col2]
matchRow = A.select( "col1 = " + col1 + " and col2 = " + col2)
if not matchRow exists
remove row from B
end
end
update B
```
|
234,210 |
<p>I'm trying to write a web application using SpringMVC. Normally I'd just map some made-up file extension to Spring's front controller and live happily, but this time I'm going for REST-like URLs, with no file-name extensions.</p>
<p>Mapping everything under my context path to the front controller (let's call it "<strong>app</strong>") means I should take care of static files also, something I'd rather not do (why reinvent yet another weel?), so some combination with tomcat's default servlet (let's call it "<strong>tomcat</strong>") appears to be the way to go.</p>
<p>I got the thing to work doing something like </p>
<pre class="lang-xml prettyprint-override"><code><servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
</code></pre>
<p>and repeating the latter for each one of the file extensions of my static content. I'm just wondering why the following setups, which to me are equivalent to the one above, don't work.</p>
<pre class="lang-xml prettyprint-override"><code><!-- failed attempt #1 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
<!-- failed attempt #2 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>/some-static-content-folder/*</url-pattern>
</servlet-mapping>
</code></pre>
<p>Can anyone shed some light?</p>
|
[
{
"answer_id": 244754,
"author": "Adam Crume",
"author_id": 25498,
"author_profile": "https://Stackoverflow.com/users/25498",
"pm_score": 2,
"selected": false,
"text": "<p>I've never tried to map a servlet like this, but I <em>would</em> argue that /* does technically both start with / and end with /*, even though the same character is used for both matches.</p>\n"
},
{
"answer_id": 245143,
"author": "Philip Tinney",
"author_id": 14930,
"author_profile": "https://Stackoverflow.com/users/14930",
"pm_score": 6,
"selected": true,
"text": "<p>I think I may know what is going on.</p>\n\n<p>In your working web.xml you have set your servlet to be the default servlet (/ by itself is the default servlet called if there are no other matches), it will answer any request that doesn't match another mapping.</p>\n\n<p>In Failed 1 your /* mapping does appear to be a valid path mapping. With the /* mapping in web.xml it answers all requests except other path mappings. According to the specification extension mappings are implicit mappings that are overwritten by explicit mappings. That's why the extension mapping failed. Everything was explicitly mapped to app.</p>\n\n<p>In Failed 2, App is responsible for everything, except content that matches the static content mapping. To show what is happening in the quick test I set up. Here is an example. <code>/some-static-content-folder/</code> contains <code>test.png</code></p>\n\n<p>Trying to access test.png I tried:</p>\n\n<pre><code>/some-static-content-folder/test.png\n</code></pre>\n\n<p>and the file was not found. However trying</p>\n\n<pre><code>/some-static-content-folder/some-static-content-folder/test.png\n</code></pre>\n\n<p>it comes up. So it seems that the Tomcat default servlet (6.0.16 at least) drops the servlet mapping and will try to find the file by using the remaining path. According to this post <a href=\"https://stackoverflow.com/questions/132052\">Servlet for serving static content</a> Jetty gives the behavior you and I were expecting.</p>\n\n<p>Is there some reason you can't do something like map a root directory for your rest calls. Something like app mapped to /rest_root/* than you are responsible for anything that goes on in the rest_root folder, but anywhere else should be handled by Tomcat, unless you make another explicit mapping. I suggest setting your rest servlet to a path mapping, because it declares the intent better. Using / or /* don't seem appropriate, since you have to map out the exceptions. Using SO as an example, my rest mappings would be something like</p>\n\n<blockquote>\n <p>/users/* for the user servlet</p>\n \n <p>/posts/* for the posts servlet</p>\n</blockquote>\n\n<p>Mapping order</p>\n\n<ol>\n<li>Explicit (Path mappings)</li>\n<li>Implicit (Extension mappings)</li>\n<li>Default (/)</li>\n</ol>\n\n<p>Please correct anything that I got wrong.</p>\n"
},
{
"answer_id": 26670813,
"author": "PragmaCoder",
"author_id": 231896,
"author_profile": "https://Stackoverflow.com/users/231896",
"pm_score": 2,
"selected": false,
"text": "<p>For reference, the \"failed attempt #2\" is perfectly correct in version of Tomcat >= to 6.0.29.</p>\n\n<p>It was the result of a Tomcat bug that get fixed in version 6.0.29:</p>\n\n<p><a href=\"https://issues.apache.org/bugzilla/show_bug.cgi?id=50026\" rel=\"nofollow\">https://issues.apache.org/bugzilla/show_bug.cgi?id=50026</a> </p>\n\n<pre><code><!-- Correct for Tomcat >= 6.0.29 or other Servlet containers -->\n<servlet-mapping>\n <servlet-name>app</servlet-name>\n <url-pattern>/</url-pattern>\n</servlet-mapping>\n\n<servlet-mapping>\n <servlet-name>default</servlet-name>\n <url-pattern>/some-static-content-folder/*</url-pattern>\n</servlet-mapping>\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6069/"
] |
I'm trying to write a web application using SpringMVC. Normally I'd just map some made-up file extension to Spring's front controller and live happily, but this time I'm going for REST-like URLs, with no file-name extensions.
Mapping everything under my context path to the front controller (let's call it "**app**") means I should take care of static files also, something I'd rather not do (why reinvent yet another weel?), so some combination with tomcat's default servlet (let's call it "**tomcat**") appears to be the way to go.
I got the thing to work doing something like
```xml
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
```
and repeating the latter for each one of the file extensions of my static content. I'm just wondering why the following setups, which to me are equivalent to the one above, don't work.
```xml
<!-- failed attempt #1 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>*.ext</url-pattern>
</servlet-mapping>
<!-- failed attempt #2 -->
<servlet-mapping>
<servlet-name>app</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>tomcat</servlet-name>
<url-pattern>/some-static-content-folder/*</url-pattern>
</servlet-mapping>
```
Can anyone shed some light?
|
I think I may know what is going on.
In your working web.xml you have set your servlet to be the default servlet (/ by itself is the default servlet called if there are no other matches), it will answer any request that doesn't match another mapping.
In Failed 1 your /\* mapping does appear to be a valid path mapping. With the /\* mapping in web.xml it answers all requests except other path mappings. According to the specification extension mappings are implicit mappings that are overwritten by explicit mappings. That's why the extension mapping failed. Everything was explicitly mapped to app.
In Failed 2, App is responsible for everything, except content that matches the static content mapping. To show what is happening in the quick test I set up. Here is an example. `/some-static-content-folder/` contains `test.png`
Trying to access test.png I tried:
```
/some-static-content-folder/test.png
```
and the file was not found. However trying
```
/some-static-content-folder/some-static-content-folder/test.png
```
it comes up. So it seems that the Tomcat default servlet (6.0.16 at least) drops the servlet mapping and will try to find the file by using the remaining path. According to this post [Servlet for serving static content](https://stackoverflow.com/questions/132052) Jetty gives the behavior you and I were expecting.
Is there some reason you can't do something like map a root directory for your rest calls. Something like app mapped to /rest\_root/\* than you are responsible for anything that goes on in the rest\_root folder, but anywhere else should be handled by Tomcat, unless you make another explicit mapping. I suggest setting your rest servlet to a path mapping, because it declares the intent better. Using / or /\* don't seem appropriate, since you have to map out the exceptions. Using SO as an example, my rest mappings would be something like
>
> /users/\* for the user servlet
>
>
> /posts/\* for the posts servlet
>
>
>
Mapping order
1. Explicit (Path mappings)
2. Implicit (Extension mappings)
3. Default (/)
Please correct anything that I got wrong.
|
234,215 |
<p>I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text. </p>
<pre><code><w:p>
<w:r>
<w:t> html formatted content is in here taken from xml file! </w:t>
</w:r>
</w:p>
</code></pre>
<p>This is how my templates are sort of set up. I have a recursive call-template function that does text replacement against the source xml content. When it comes across a "<code><b></code>" tag, I output a string in CDATA containing "<code></w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t></code>" to close the current run and start up a new run with bold formatting enabled. when it gets to a "<code></b></code>" tag, it replaces it with the following CDATA string "<code></w:t></w:r><w:r><w:t></code>".</p>
<p>What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts. Is this possible?</p>
|
[
{
"answer_id": 239235,
"author": "GerG",
"author_id": 17249,
"author_profile": "https://Stackoverflow.com/users/17249",
"pm_score": 0,
"selected": false,
"text": "<p>I can most probably help you if only I understood your problem... Is the html in a CDATA section or is it parsed as part of the input doc (and thus well-formed XML)?\nSince you talk about 'text replacement' I'll assume that you treat the 'html formatted content' as a single string (CDATA) and therefor need a recursive call-template function to perform string replacement. The only way you're going to be able to use an XSL matching template to do what you're doing now is to make the html part of the parsed document (your input document). In such a case you could just match the <code>b</code> tag and replace it with the appropriate output (again: this assumes that it can always be parsed as valid XML). Your problem now has shifted... since (if I understood your problem correctly) what you're trying to do is close the <code>w:t</code> and <code>w:r</code> elements and then 'reopen' them... this is hard because it's (as you probably suspect) very hard to do this nicely in XSLT (you cannot just create an element in template A and then close it in template B). You'll have to start messing with unescaped output etc. to make this happen. I now I've made a lot of assumptions but here is a small example to help you on your way:</p>\n\n<p><em>input.xml</em></p>\n\n<pre><code><doc xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n<w:p>\n <w:r>\n <w:t>before<b>bold</b>after</w:t>\n </w:r>\n</w:p>\n</doc>\n</code></pre>\n\n<p><em>convert_html.xsl</em></p>\n\n<p></p>\n\n<pre><code><xsl:template match=\"@*|node()\">\n <xsl:copy>\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:copy>\n</xsl:template>\n\n<xsl:template match=\"/doc/w:p/w:r/w:t//b\">\n <xsl:value-of select=\"'&lt;/w:t>&lt;/w:r>&lt;w:r>&lt;w:rPr>&lt;w:b/>&lt;/w:rPr>&lt;w:t>'\" disable-output-escaping=\"yes\" />\n <xsl:apply-templates select=\"@*|node()\"/>\n <xsl:value-of select=\"'&lt;/w:t>&lt;/w:r>&lt;w:r>&lt;w:t>'\" disable-output-escaping=\"yes\" />\n</xsl:template>\n</code></pre>\n\n<p></p>\n\n<p>Now running </p>\n\n<pre><code>xalan input.xml convert_html.xsl\n</code></pre>\n\n<p>produces</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?><doc xmlns:w=\"urn:schemas-microsoft-com:office:word\">\n<w:p>\n <w:r>\n <w:t>before</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>bold</w:t></w:r><w:r><w:t>after</w:t>\n </w:r>\n</w:p>\n</doc>\n</code></pre>\n\n<p>which I guess is what you wanted.</p>\n\n<p>Hope this helps you somewhat.</p>\n"
},
{
"answer_id": 240076,
"author": "Andrew Cowenhoven",
"author_id": 12281,
"author_profile": "https://Stackoverflow.com/users/12281",
"pm_score": 0,
"selected": false,
"text": "<p>From your description, it sounds like you can parse the embedded html. If so, simply applying templates should do what you want. The wordML in the output may not be right, but hopefully this will help. </p>\n\n<p>Sample input:</p>\n\n<pre><code><text>\n <para>\n Test for paragraph 1\n </para>\n <para>\n Test for <b>paragraph 2</b>\n </para>\n</text>\n</code></pre>\n\n<p>Transform:</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"utf-8\"?>\n<xsl:stylesheet version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\" xmlns:w=\"http://foo\">\n<xsl:template match=\"/\">\n <w:p>\n <w:r>\n <xsl:apply-templates/>\n </w:r> \n </w:p>\n</xsl:template>\n <xsl:template match=\"para\">\n <w:t>\n <xsl:apply-templates/>\n </w:t>\n </xsl:template>\n\n <xsl:template match=\"b\">\n <w:rPr>\n <w:b/>\n </w:rPr>\n <xsl:value-of select=\".\"/>\n </xsl:template>\n</xsl:stylesheet> \n</code></pre>\n\n<p>Result:</p>\n\n<pre><code><w:p xmlns:w=\"http://foo\">\n <w:r>\n <w:t>\n Test for paragraph 1\n </w:t>\n <w:t>\n Test for <w:rPr><w:b /></w:rPr>paragraph 2\n </w:t>\n </w:r>\n</w:p>\n</code></pre>\n"
},
{
"answer_id": 251078,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 2,
"selected": false,
"text": "<p>Working with WordML is tricky. One tip when converting arbitrary XML to WordML using XSLT is to not worry about the text runs when processing blocks, but to instead create a template that matches text() nodes directly, and create the text runs there. It turns out that Word doesn't care if you nest text runs, which makes the problem much easier to solve.</p>\n\n<pre><code> <xsl:template match=\"text()\" priority=\"1\">\n <w:r>\n <w:t>\n <xsl:value-of select=\".\"/>\n </w:t>\n </w:r> \n </xsl:template>\n\n <xsl:template match=\"@*|node()\">\n <xsl:apply-templates select=\"@*|node()\"/>\n </xsl:template>\n\n <xsl:template match=\"para\">\n <w:p>\n <xsl:apply-templates select=\"text() | *\" />\n </w:p>\n </xsl:template>\n\n <xsl:template match=\"b\">\n <w:r>\n <w:rPr>\n <w:b />\n </w:rPr>\n <w:t><xsl:apply-templates /></w:t>\n </w:r>\n </xsl:template>\n</code></pre>\n\n<p>This avoids the bad XSLT technique of inserting tags directly as escaped text. You'll end up with the bold tag as a nested text run, but as I said, Word couldn't care less. If you use this technique, you'll need to be careful to not apply templates to the empty space between paragraphs, since it will trigger the text template and create an out-of-context run.</p>\n"
},
{
"answer_id": 1189335,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>To completely finish the HTML > WordML I recommend this edited version of your code: </p>\n\n<pre><code><xsl:template match=\"Body\"><xsl:apply-templates select=\"p\"/></xsl:template>\n\n<xsl:template match=\"text()\" priority=\"1\"><w:r><w:t><xsl:value-of select=\".\"/></w:t></w:r></xsl:template>\n\n<xsl:template match=\"@*|node()\"><xsl:apply-templates select=\"@*|node()\"/></xsl:template>\n\n<xsl:template match=\"p\"><w:p><xsl:apply-templates select=\"text() | *\" /></w:p></xsl:template>\n\n<xsl:template match=\"b\"><w:r><w:rPr><w:b /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n<xsl:template match=\"i\"><w:r><w:rPr><w:i /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n<xsl:template match=\"u\"><w:r><w:rPr><w:u w:val=\"single\" /></w:rPr><xsl:apply-templates /></w:r></xsl:template>\n</code></pre>\n\n<p>supposing you have your HTML somewhere in a XMl wrapped in a tag </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234215",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31229/"
] |
I am creating a WordML document from an xml file whose elements sometimes contain html-formatted text.
```
<w:p>
<w:r>
<w:t> html formatted content is in here taken from xml file! </w:t>
</w:r>
</w:p>
```
This is how my templates are sort of set up. I have a recursive call-template function that does text replacement against the source xml content. When it comes across a "`<b>`" tag, I output a string in CDATA containing "`</w:t></w:r><w:r><w:rPr><w:b/></w:rPr><w:t>`" to close the current run and start up a new run with bold formatting enabled. when it gets to a "`</b>`" tag, it replaces it with the following CDATA string "`</w:t></w:r><w:r><w:t>`".
What I'd like to do is use XSL to close the run tag and start a new run without using CDATA string inserts. Is this possible?
|
Working with WordML is tricky. One tip when converting arbitrary XML to WordML using XSLT is to not worry about the text runs when processing blocks, but to instead create a template that matches text() nodes directly, and create the text runs there. It turns out that Word doesn't care if you nest text runs, which makes the problem much easier to solve.
```
<xsl:template match="text()" priority="1">
<w:r>
<w:t>
<xsl:value-of select="."/>
</w:t>
</w:r>
</xsl:template>
<xsl:template match="@*|node()">
<xsl:apply-templates select="@*|node()"/>
</xsl:template>
<xsl:template match="para">
<w:p>
<xsl:apply-templates select="text() | *" />
</w:p>
</xsl:template>
<xsl:template match="b">
<w:r>
<w:rPr>
<w:b />
</w:rPr>
<w:t><xsl:apply-templates /></w:t>
</w:r>
</xsl:template>
```
This avoids the bad XSLT technique of inserting tags directly as escaped text. You'll end up with the bold tag as a nested text run, but as I said, Word couldn't care less. If you use this technique, you'll need to be careful to not apply templates to the empty space between paragraphs, since it will trigger the text template and create an out-of-context run.
|
234,217 |
<p><strong>Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET.</strong> That being said...</p>
<p>I would like to allow the user to enter any equation, like the following, into a text box:</p>
<pre><code>x = x / 2 * 0.07914
x = x^2 / 5
</code></pre>
<p>And have that equation applied to incoming data points. The incoming data points are represented by <strong>x</strong> and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:</p>
<pre><code>float ApplyEquation (string equation, float dataPoint)
{
// parse the equation string and figure out how to do the math
// lots of messy code here...
}
</code></pre>
<p>When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:</p>
<pre><code>FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x); // I could then apply the equation to my incoming data like this
</code></pre>
<p>Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.</p>
<p>The app would basically be writing new code at run time. Is this possible with .NET?</p>
|
[
{
"answer_id": 234228,
"author": "Scott Dorman",
"author_id": 1559,
"author_profile": "https://Stackoverflow.com/users/1559",
"pm_score": 2,
"selected": false,
"text": "<p>You can try looking at either CodeDom or Lambda Expression Trees. I think either one of those should allow you to accomplish this. Expression trees are probably the better way to go but also have a higher learning curve.</p>\n"
},
{
"answer_id": 234235,
"author": "Totty",
"author_id": 30838,
"author_profile": "https://Stackoverflow.com/users/30838",
"pm_score": -1,
"selected": false,
"text": "<p>I would do a recursive function that doesn't write code but instead applies basic operators to portions of a string based on special characters found in that string.\nIf more than one special character is found, it breaks up the string and calls itself on those two portions.</p>\n"
},
{
"answer_id": 234236,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 2,
"selected": false,
"text": "<p>You could start <a href=\"http://www.codeproject.com/KB/dotnet/Expr.aspx\" rel=\"nofollow noreferrer\">here</a> and if you really want to get into it, <a href=\"http://boo.codehaus.org/\" rel=\"nofollow noreferrer\">Boo</a> can be modified to meet your needs. You could also integrate <a href=\"http://luaforge.net/projects/luainterface/\" rel=\"nofollow noreferrer\">LUA with .NET</a>. Any three of these could be utilized within the body of a delegate for your <code>ConvertEquationToCode</code>.</p>\n"
},
{
"answer_id": 234237,
"author": "rice",
"author_id": 23933,
"author_profile": "https://Stackoverflow.com/users/23933",
"pm_score": 3,
"selected": false,
"text": "<p>Yes, definitely possible to have the user type C# into a text box, then compile that code and run it from within your app. We do that at my work to allow for custom business logic.</p>\n\n<p>Here is an article (I haven't more than skimmed it) which should get you started:</p>\n\n<p><a href=\"http://www.c-sharpcorner.com/UploadFile/ChrisBlake/RunTimeCompiler12052005045037AM/RunTimeCompiler.aspx\" rel=\"noreferrer\">http://www.c-sharpcorner.com/UploadFile/ChrisBlake/RunTimeCompiler12052005045037AM/RunTimeCompiler.aspx</a></p>\n"
},
{
"answer_id": 234303,
"author": "Brian Schmitt",
"author_id": 30492,
"author_profile": "https://Stackoverflow.com/users/30492",
"pm_score": 4,
"selected": false,
"text": "<p>You might try this: <a href=\"http://weblogs.asp.net/pwelter34/archive/2007/05/05/calculator-net-calculator-that-evaluates-math-expressions.aspx\" rel=\"noreferrer\">Calculator.Net</a></p>\n\n<p>It will evaluate a math expression.</p>\n\n<p>From the posting it will support the following:</p>\n\n<pre><code>MathEvaluator eval = new MathEvaluator();\n//basic math\ndouble result = eval.Evaluate(\"(2 + 1) * (1 + 2)\");\n//calling a function\nresult = eval.Evaluate(\"sqrt(4)\");\n//evaluate trigonometric \nresult = eval.Evaluate(\"cos(pi * 45 / 180.0)\");\n//convert inches to feet\nresult = eval.Evaluate(\"12 [in->ft]\");\n//use variable\nresult = eval.Evaluate(\"answer * 10\");\n//add variable\neval.Variables.Add(\"x\", 10); \nresult = eval.Evaluate(\"x * 10\");\n</code></pre>\n\n<p><a href=\"http://www.loresoft.com/Applications/Calculator/Download/default.aspx\" rel=\"noreferrer\">Download Page</a>\nAnd is distributed under the BSD license.</p>\n"
},
{
"answer_id": 234361,
"author": "Jon Norton",
"author_id": 4797,
"author_profile": "https://Stackoverflow.com/users/4797",
"pm_score": 2,
"selected": false,
"text": "<p>I've done this using CSharpCodeProvider by creating the boiler plate class and function stuff as a const string inside my generator class. Then I insert the user code into the boiler plate and compile.</p>\n\n<p>It was fairly straightforward to do, but the danger to this approach is that the user entering the equation could enter just about anything which could be a security issue depending on your application.</p>\n\n<p>If security is at all a concern, I would recommend using Lambda Expression Trees, but if not, using CSharpCodeProvider is a fairly robust option.</p>\n"
},
{
"answer_id": 234698,
"author": "baretta",
"author_id": 30052,
"author_profile": "https://Stackoverflow.com/users/30052",
"pm_score": 3,
"selected": false,
"text": "<p>You can also create a System.Xml.XPath.XPathNavigator from an empty, \"dummy\" XML stream,\nand evaluate expressions using the XPath evaluator:</p>\n\n<pre><code>static object Evaluate ( string xp )\n{\n return _nav.Evaluate ( xp );\n}\nstatic readonly System.Xml.XPath.XPathNavigator _nav\n = new System.Xml.XPath.XPathDocument (\n new StringReader ( \"<r/>\" ) ).CreateNavigator ( );\n</code></pre>\n\n<p>If you want to register variables to use within this expression,\nyou can dynamically build XML that you can pass in the Evaluate overload\nthat takes a XPathNodeIterator.</p>\n\n<pre><code><context>\n <x>2.151</x>\n <y>231.2</y>\n</context>\n</code></pre>\n\n<p>You can then write expressions like \"x / 2 * 0.07914\" and then x\nis the value of the node in your XML context.\nAnother good thing is, you will have access to all XPath core functions,\nwhich includes mathematics and string manipulation methods, and more stuff.</p>\n\n<p>If you want to take it further, you can even build your own XsltCustomContext(or ill post here on demand)\nwhere you can resolve references to extension functions and variables:</p>\n\n<pre><code>object result = Evaluate ( \"my:func(234) * $myvar\" );\n</code></pre>\n\n<p>my:func is mapped to a C#/.NET method which takes a double or int as parameter.\nmyvar is registered as a variable within the XSLT context.</p>\n"
},
{
"answer_id": 235057,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If all else fails, there are classes under the System.Reflection.Emit namespace which you can use to produce new assemblies, classes, and methods.</p>\n"
},
{
"answer_id": 375737,
"author": "pyon",
"author_id": 46571,
"author_profile": "https://Stackoverflow.com/users/46571",
"pm_score": -1,
"selected": false,
"text": "<p>I don't know if it's possible to implement your <code>ConvertEquationToCode</code> function, however, you can generate a data structure that represents the calculation you need to perform.</p>\n\n<p>For example, you could build a tree whose leaf nodes represent the input for your calculation, whose non-leaf nodes represent intermediate results, and whose root node represents the whole calculation.</p>\n\n<p>It has some advantages. For example, if you're doing what-if analysis and want to change the value of one input at a time, you can recalculate the results that depend on the value that you have changed, while retaining the results that don't.</p>\n"
},
{
"answer_id": 1438653,
"author": "Roel",
"author_id": 173732,
"author_profile": "https://Stackoverflow.com/users/173732",
"pm_score": 1,
"selected": false,
"text": "<p>Try Vici.Parser: <a href=\"http://viciproject.com/wiki/projects/parser/home\" rel=\"nofollow noreferrer\">download it here (free)</a> , it's the most flexible expression parser/evaluator I've found so far. </p>\n"
},
{
"answer_id": 2196645,
"author": "Hannoun Yassir",
"author_id": 72443,
"author_profile": "https://Stackoverflow.com/users/72443",
"pm_score": -1,
"selected": false,
"text": "<p>you can use <code>system.CodeDom</code> to generate code and compile it on the fly \nhave a look <a href=\"http://msdn.microsoft.com/en-us/library/system.codedom.codecompileunit.aspx\" rel=\"nofollow noreferrer\">here</a> </p>\n"
},
{
"answer_id": 2196677,
"author": "Erik van Brakel",
"author_id": 909,
"author_profile": "https://Stackoverflow.com/users/909",
"pm_score": 0,
"selected": false,
"text": "<p>You could implement a <a href=\"http://resume.technoplaza.net/java/postfix-calc.php\" rel=\"nofollow noreferrer\">postfix stack calculator</a>. Basically what you have to do is convert the expression to postfix notation, and then simply iterate over the tokens in your postfix to calculate.</p>\n"
},
{
"answer_id": 7013086,
"author": "GreyCloud",
"author_id": 397268,
"author_profile": "https://Stackoverflow.com/users/397268",
"pm_score": 2,
"selected": false,
"text": "<p>Have you seen <a href=\"http://ncalc.codeplex.com\" rel=\"nofollow\">http://ncalc.codeplex.com</a> ? </p>\n\n<p>It's extensible, fast (e.g. has its own cache) enables you to provide custom functions and varaibles at run time by handling EvaluateFunction/EvaluateParameter events. Example expressions it can parse: </p>\n\n<pre><code>Expression e = new Expression(\"Round(Pow(Pi, 2) + Pow([Pi2], 2) + X, 2)\"); \n\n e.Parameters[\"Pi2\"] = new Expression(\"Pi * Pi\"); \n e.Parameters[\"X\"] = 10; \n\n e.EvaluateParameter += delegate(string name, ParameterArgs args) \n { \n if (name == \"Pi\") \n args.Result = 3.14; \n }; \n\n Debug.Assert(117.07 == e.Evaluate()); \n</code></pre>\n\n<p>It also handles unicode & many data type natively. It comes with an antler file if you want to change the grammer. There is also a fork which supports MEF to load new functions. </p>\n"
},
{
"answer_id": 10457244,
"author": "raven",
"author_id": 4228,
"author_profile": "https://Stackoverflow.com/users/4228",
"pm_score": 5,
"selected": true,
"text": "<p>Yes! Using methods found in the <a href=\"http://msdn.microsoft.com/en-us/library/microsoft.csharp.aspx\">Microsoft.CSharp</a>, <a href=\"http://msdn.microsoft.com/en-us/library/system.codedom.compiler.aspx\">System.CodeDom.Compiler</a>, and <a href=\"http://msdn.microsoft.com/en-us/library/system.reflection.aspx\">System.Reflection</a> name spaces. Here is a simple console app that compiles a class (\"SomeClass\") with one method (\"Add42\") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.</p>\n\n<pre><code>using Microsoft.CSharp;\nusing System;\nusing System.CodeDom.Compiler;\nusing System.Reflection;\n\nnamespace RuntimeCompilationTest {\n class Program\n {\n static void Main(string[] args) {\n string sourceCode = @\"\n public class SomeClass {\n public int Add42 (int parameter) {\n return parameter += 42;\n }\n }\";\n var compParms = new CompilerParameters{\n GenerateExecutable = false, \n GenerateInMemory = true\n };\n var csProvider = new CSharpCodeProvider();\n CompilerResults compilerResults = \n csProvider.CompileAssemblyFromSource(compParms, sourceCode);\n object typeInstance = \n compilerResults.CompiledAssembly.CreateInstance(\"SomeClass\");\n MethodInfo mi = typeInstance.GetType().GetMethod(\"Add42\");\n int methodOutput = \n (int)mi.Invoke(typeInstance, new object[] { 1 }); \n Console.WriteLine(methodOutput);\n Console.ReadLine();\n }\n }\n}\n</code></pre>\n"
},
{
"answer_id": 50430964,
"author": "Kent",
"author_id": 1583763,
"author_profile": "https://Stackoverflow.com/users/1583763",
"pm_score": 1,
"selected": false,
"text": "<p>Here a more modern library for simple expressions: System.Linq.Dynamic.Core.\nIt's compatible with .NET Standard/.NET Core, it's available through NuGet, and the source is available.</p>\n\n<p><a href=\"https://system-linq-dynamic-core.azurewebsites.net/html/de47654c-7ae4-9302-3061-ea6307706cb8.htm\" rel=\"nofollow noreferrer\">https://system-linq-dynamic-core.azurewebsites.net/html/de47654c-7ae4-9302-3061-ea6307706cb8.htm</a>\n<a href=\"https://github.com/StefH/System.Linq.Dynamic.Core\" rel=\"nofollow noreferrer\">https://github.com/StefH/System.Linq.Dynamic.Core</a>\n<a href=\"https://www.nuget.org/packages/System.Linq.Dynamic.Core/\" rel=\"nofollow noreferrer\">https://www.nuget.org/packages/System.Linq.Dynamic.Core/</a></p>\n\n<p>This is a very lightweight and dynamic library.</p>\n\n<p>I wrote a simple wrapper class for this library that let's me do things like this:</p>\n\n<pre><code> string sExpression = \"(a == 0) ? 5 : 10\";\n ExpressionEvaluator<int> exec = new ExpressionEvaluator<int>(sExpression);\n exec.AddParameter(\"a\", 0);\n int n0 = exec.Invoke();\n</code></pre>\n\n<p>Once the expression is compiled, you can simply update the parameter values and re-invoke the expression.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4228/"
] |
**Note: Mathematical expression evaluation is not the focus of this question. I want to compile and execute new code at runtime in .NET.** That being said...
I would like to allow the user to enter any equation, like the following, into a text box:
```
x = x / 2 * 0.07914
x = x^2 / 5
```
And have that equation applied to incoming data points. The incoming data points are represented by **x** and each data point is processed by the user-specified equation. I did this years ago, but I didn't like the solution because it required parsing the text of the equation for every calculation:
```
float ApplyEquation (string equation, float dataPoint)
{
// parse the equation string and figure out how to do the math
// lots of messy code here...
}
```
When you're processing boatloads of data points, this introduces quite a bit of overhead. I would like to be able to translate the equation into a function, on the fly, so that it only has to be parsed once. It would look something like this:
```
FunctionPointer foo = ConvertEquationToCode(equation);
....
x = foo(x); // I could then apply the equation to my incoming data like this
```
Function ConvertEquationToCode would parse the equation and return a pointer to a function that applies the appropriate math.
The app would basically be writing new code at run time. Is this possible with .NET?
|
Yes! Using methods found in the [Microsoft.CSharp](http://msdn.microsoft.com/en-us/library/microsoft.csharp.aspx), [System.CodeDom.Compiler](http://msdn.microsoft.com/en-us/library/system.codedom.compiler.aspx), and [System.Reflection](http://msdn.microsoft.com/en-us/library/system.reflection.aspx) name spaces. Here is a simple console app that compiles a class ("SomeClass") with one method ("Add42") and then allows you to invoke that method. This is a bare-bones example that I formatted down to prevent scroll bars from appearing in the code display. It is just to demonstrate compiling and using new code at run time.
```
using Microsoft.CSharp;
using System;
using System.CodeDom.Compiler;
using System.Reflection;
namespace RuntimeCompilationTest {
class Program
{
static void Main(string[] args) {
string sourceCode = @"
public class SomeClass {
public int Add42 (int parameter) {
return parameter += 42;
}
}";
var compParms = new CompilerParameters{
GenerateExecutable = false,
GenerateInMemory = true
};
var csProvider = new CSharpCodeProvider();
CompilerResults compilerResults =
csProvider.CompileAssemblyFromSource(compParms, sourceCode);
object typeInstance =
compilerResults.CompiledAssembly.CreateInstance("SomeClass");
MethodInfo mi = typeInstance.GetType().GetMethod("Add42");
int methodOutput =
(int)mi.Invoke(typeInstance, new object[] { 1 });
Console.WriteLine(methodOutput);
Console.ReadLine();
}
}
}
```
|
234,231 |
<p>How do you create an application shortcut (.lnk file) in C# or using the .NET framework?</p>
<p>The result would be a .lnk file to the specified application or URL.</p>
|
[
{
"answer_id": 234543,
"author": "Charley Rathkopf",
"author_id": 10119,
"author_profile": "https://Stackoverflow.com/users/10119",
"pm_score": 7,
"selected": true,
"text": "<p>It's not as simple as I'd have liked, but there is a great class call <a href=\"http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Creating_and_Modifying_Shortcuts/ShellLink_Code.html\" rel=\"nofollow noreferrer\">ShellLink.cs</a> at \n<a href=\"http://www.vbaccelerator.com/home/index.html\" rel=\"nofollow noreferrer\">vbAccelerator</a></p>\n\n<p>This code uses interop, but does not rely on WSH.</p>\n\n<p>Using this class, the code to create the shortcut is:</p>\n\n<pre><code>private static void configStep_addShortcutToStartupGroup()\n{\n using (ShellLink shortcut = new ShellLink())\n {\n shortcut.Target = Application.ExecutablePath;\n shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);\n shortcut.Description = \"My Shorcut Name Here\";\n shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;\n shortcut.Save(STARTUP_SHORTCUT_FILEPATH);\n }\n}\n</code></pre>\n"
},
{
"answer_id": 2736786,
"author": "Anuraj",
"author_id": 38024,
"author_profile": "https://Stackoverflow.com/users/38024",
"pm_score": 4,
"selected": false,
"text": "<p>I found something like this:</p>\n\n<pre><code>private void appShortcutToDesktop(string linkName)\n{\n string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);\n\n using (StreamWriter writer = new StreamWriter(deskDir + \"\\\\\" + linkName + \".url\"))\n {\n string app = System.Reflection.Assembly.GetExecutingAssembly().Location;\n writer.WriteLine(\"[InternetShortcut]\");\n writer.WriteLine(\"URL=file:///\" + app);\n writer.WriteLine(\"IconIndex=0\");\n string icon = app.Replace('\\\\', '/');\n writer.WriteLine(\"IconFile=\" + icon);\n writer.Flush();\n }\n}\n</code></pre>\n\n<p>Original code at <a href=\"http://www.sorrowman.org/c-sharp-programmer/url-link-to-desktop.html\" rel=\"noreferrer\">sorrowman's article \"url-link-to-desktop\"</a></p>\n"
},
{
"answer_id": 19914018,
"author": "IS4",
"author_id": 1424244,
"author_profile": "https://Stackoverflow.com/users/1424244",
"pm_score": 6,
"selected": false,
"text": "<p>Nice and clean. (<strong>.NET 4.0</strong>)</p>\n\n<pre><code>Type t = Type.GetTypeFromCLSID(new Guid(\"72C24DD5-D70A-438B-8A42-98424B88AFB8\")); //Windows Script Host Shell Object\ndynamic shell = Activator.CreateInstance(t);\ntry{\n var lnk = shell.CreateShortcut(\"sc.lnk\");\n try{\n lnk.TargetPath = @\"C:\\something\";\n lnk.IconLocation = \"shell32.dll, 1\";\n lnk.Save();\n }finally{\n Marshal.FinalReleaseComObject(lnk);\n }\n}finally{\n Marshal.FinalReleaseComObject(shell);\n}\n</code></pre>\n\n<p>That's it, no additional code needed. <em>CreateShortcut</em> can even load shortcut from file, so properties like <em>TargetPath</em> return existing information. <a href=\"http://msdn.microsoft.com/en-us/library/f5y78918%28v=vs.84%29.aspx\">Shortcut object properties</a>.</p>\n\n<p>Also possible this way for versions of .NET unsupporting dynamic types. (<strong>.NET 3.5</strong>)</p>\n\n<pre><code>Type t = Type.GetTypeFromCLSID(new Guid(\"72C24DD5-D70A-438B-8A42-98424B88AFB8\")); //Windows Script Host Shell Object\nobject shell = Activator.CreateInstance(t);\ntry{\n object lnk = t.InvokeMember(\"CreateShortcut\", BindingFlags.InvokeMethod, null, shell, new object[]{\"sc.lnk\"});\n try{\n t.InvokeMember(\"TargetPath\", BindingFlags.SetProperty, null, lnk, new object[]{@\"C:\\whatever\"});\n t.InvokeMember(\"IconLocation\", BindingFlags.SetProperty, null, lnk, new object[]{\"shell32.dll, 5\"});\n t.InvokeMember(\"Save\", BindingFlags.InvokeMethod, null, lnk, null);\n }finally{\n Marshal.FinalReleaseComObject(lnk);\n }\n}finally{\n Marshal.FinalReleaseComObject(shell);\n}\n</code></pre>\n"
},
{
"answer_id": 20695964,
"author": "AZ_",
"author_id": 185022,
"author_profile": "https://Stackoverflow.com/users/185022",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"http://originaldll.com/file/interop.iwshruntimelibrary.dll/20842.html\" rel=\"nofollow noreferrer\">Donwload IWshRuntimeLibrary</a></p>\n\n<p>You also need to import of COM library <code>IWshRuntimeLibrary</code>. Right click on your project -> add reference -> COM -> IWshRuntimeLibrary -> add and then use the following code snippet.</p>\n\n<pre><code>private void createShortcutOnDesktop(String executablePath)\n{\n // Create a new instance of WshShellClass\n\n WshShell lib = new WshShellClass();\n // Create the shortcut\n\n IWshRuntimeLibrary.IWshShortcut MyShortcut;\n\n\n // Choose the path for the shortcut\n string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);\n MyShortcut = (IWshRuntimeLibrary.IWshShortcut)lib.CreateShortcut(@deskDir+\"\\\\AZ.lnk\");\n\n\n // Where the shortcut should point to\n\n //MyShortcut.TargetPath = Application.ExecutablePath;\n MyShortcut.TargetPath = @executablePath;\n\n\n // Description for the shortcut\n\n MyShortcut.Description = \"Launch AZ Client\";\n\n StreamWriter writer = new StreamWriter(@\"D:\\AZ\\logo.ico\");\n Properties.Resources.system.Save(writer.BaseStream);\n writer.Flush();\n writer.Close();\n // Location for the shortcut's icon \n\n MyShortcut.IconLocation = @\"D:\\AZ\\logo.ico\";\n\n\n // Create the shortcut at the given path\n\n MyShortcut.Save();\n\n}\n</code></pre>\n"
},
{
"answer_id": 23848146,
"author": "Ohad Schneider",
"author_id": 67824,
"author_profile": "https://Stackoverflow.com/users/67824",
"pm_score": 1,
"selected": false,
"text": "<p>After surveying all possibilities I found on SO I've settled on <a href=\"http://msjogren.webhost4life.com/dotnet/eng/samples/dotnet_shelllink.asp\" rel=\"nofollow\">ShellLink</a>:</p>\n\n<pre><code>//Create new shortcut\nusing (var shellShortcut = new ShellShortcut(newShortcutPath)\n{\n Path = path\n WorkingDirectory = workingDir,\n Arguments = args,\n IconPath = iconPath,\n IconIndex = iconIndex,\n Description = description,\n})\n{\n shellShortcut.Save();\n}\n\n//Read existing shortcut\nusing (var shellShortcut = new ShellShortcut(existingShortcut))\n{\n path = shellShortcut.Path;\n args = shellShortcut.Arguments;\n workingDir = shellShortcut.WorkingDirectory;\n ...\n}\n</code></pre>\n\n<p>Apart of being simple and effective, the author (Mattias Sjögren, MS MVP) is some sort of COM/PInvoke/Interop guru, and perusing his code I believe it is more robust than the alternatives.</p>\n\n<p>It should be mentioned that shortcut files can also be created by several commandline utilities (which in turn can be easily invoked from C#/.NET). I never tried any of them, but I'd start with <a href=\"http://www.nirsoft.net/utils/nircmd.html\" rel=\"nofollow\">NirCmd</a> (NirSoft have SysInternals-like quality tools).</p>\n\n<p>Unfortunately NirCmd can't <em>parse</em> shortcut files (only create them), but for that purpose <a href=\"https://www.tzworks.net/prototype_page.php?proto_id=11\" rel=\"nofollow\">TZWorks lp</a> seems capable. It can even format its output as csv. <a href=\"https://code.google.com/p/lnk-parser/\" rel=\"nofollow\">lnk-parser</a> looks good too (it can output both HTML and CSV).</p>\n"
},
{
"answer_id": 28417360,
"author": "Steven Jeuris",
"author_id": 590790,
"author_profile": "https://Stackoverflow.com/users/590790",
"pm_score": 0,
"selected": false,
"text": "<p>Similar to <a href=\"https://stackoverflow.com/a/19914018/590790\">IllidanS4's answer</a>, using the <a href=\"https://msdn.microsoft.com/en-us/library/ec0wcxh3(v=vs.84).aspx\" rel=\"nofollow noreferrer\">Windows Script Host</a> proved the be the easiest solution for me (tested on Windows 8 64 bit).</p>\n\n<p>However, rather than importing the COM type manually through code, it is easier to just add the COM type library as a reference. Choose <code>References->Add Reference...</code>, <code>COM->Type Libraries</code> and find and add <em>\"Windows Script Host Object Model\"</em>.</p>\n\n<p>This imports the namespace <code>IWshRuntimeLibrary</code>, from which you can access:</p>\n\n<pre><code>WshShell shell = new WshShell();\nIWshShortcut link = (IWshShortcut)shell.CreateShortcut(LinkPathName);\nlink.TargetPath=TargetPathName;\nlink.Save();\n</code></pre>\n\n<p><a href=\"http://www.codeproject.com/Articles/3905/Creating-Shell-Links-Shortcuts-in-NET-Programs-Usi\" rel=\"nofollow noreferrer\">Credit goes to Jim Hollenhorst</a>.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10119/"
] |
How do you create an application shortcut (.lnk file) in C# or using the .NET framework?
The result would be a .lnk file to the specified application or URL.
|
It's not as simple as I'd have liked, but there is a great class call [ShellLink.cs](http://www.vbaccelerator.com/home/NET/Code/Libraries/Shell_Projects/Creating_and_Modifying_Shortcuts/ShellLink_Code.html) at
[vbAccelerator](http://www.vbaccelerator.com/home/index.html)
This code uses interop, but does not rely on WSH.
Using this class, the code to create the shortcut is:
```
private static void configStep_addShortcutToStartupGroup()
{
using (ShellLink shortcut = new ShellLink())
{
shortcut.Target = Application.ExecutablePath;
shortcut.WorkingDirectory = Path.GetDirectoryName(Application.ExecutablePath);
shortcut.Description = "My Shorcut Name Here";
shortcut.DisplayMode = ShellLink.LinkDisplayMode.edmNormal;
shortcut.Save(STARTUP_SHORTCUT_FILEPATH);
}
}
```
|
234,239 |
<p>C# .NET 3.5. I'm trying to understand the intrinsic limitation of the C# Action object. Within the lamda (are those, in fact, lamdas?), we can perform assignments, call functions, even execute a ternary operation, but we can't execute a multi-statement operation.</p>
<p>Is this because the single-statement execution is just syntactic sugar for wrapping it in a delegate? Why does the first example below not work?</p>
<pre><code>public class MyClass
{
private int m_Count = 0;
public void Test()
{
int value = 0;
// Does not work, throws compile error
Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; }
// Works
Action action2 = () => value = delegate(){
if(m_Count < 10)
m_Count++;
return m_Count;
};
// Works
Action action3 = () => value = m_Count;
// Works
Action action4 = () => value = m_Count < 10 ? m_Count++ : 0;
// Works
Action action5 = () => value = Increment();
}
public int Increment()
{
if (m_Count < 10)
m_Count++;
return m_Count;
}
}
</code></pre>
<p>EDIT: Grr, sorry for the noise. Originally, I had </p>
<pre><code>Action action = () => if(m_Count < 10) m_Count++; value = m_Count;
</code></pre>
<p>Which threw a compile error, but then right before the post I thought I'd try wrapping it in braces</p>
<pre><code>Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; }
</code></pre>
<p>Which also threw a compile error, so I jumped to conclusions that it was the same problem. It works, though, if I toss in a semi-colon after the braces</p>
<pre><code>Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; };
</code></pre>
<p>Sorry for the noise!</p>
<p>EDIT 2: Thanks cfeduke, you posted that at the same time as my edit above - went ahead and marked as answer. </p>
|
[
{
"answer_id": 234266,
"author": "cfeduke",
"author_id": 5645,
"author_profile": "https://Stackoverflow.com/users/5645",
"pm_score": 5,
"selected": true,
"text": "<p>You are missing a semi-colon, it compiles:</p>\n\n<pre><code> Action action = () => { if (m_Count < 10) m_Count++; value = m_Count; };\n</code></pre>\n\n<p>When you say <code>type name = statement;</code> you need a semicolon even if you use braces for a code block.</p>\n"
},
{
"answer_id": 234286,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 3,
"selected": false,
"text": "<p>cfeduke has posted the solution to getting your code to compile.</p>\n\n<p>Note that you can't convert statement-block lambda expressions into expression trees, even though you can convert them into delegates. There are <a href=\"http://csharpindepth.com/ViewNote.aspx?NoteID=68\" rel=\"noreferrer\">other limitations</a> on what you can convert into expression trees.</p>\n\n<p>Going back to delegates, there are <em>some</em> limitations there - you can't write an iterator block within a lambda expression, for example. (I've wanted to do that before now - it gets weird when you try to get your head round it. You can't do it though.) For the most part, you can do almost anything you can do in a method.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234239",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17803/"
] |
C# .NET 3.5. I'm trying to understand the intrinsic limitation of the C# Action object. Within the lamda (are those, in fact, lamdas?), we can perform assignments, call functions, even execute a ternary operation, but we can't execute a multi-statement operation.
Is this because the single-statement execution is just syntactic sugar for wrapping it in a delegate? Why does the first example below not work?
```
public class MyClass
{
private int m_Count = 0;
public void Test()
{
int value = 0;
// Does not work, throws compile error
Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; }
// Works
Action action2 = () => value = delegate(){
if(m_Count < 10)
m_Count++;
return m_Count;
};
// Works
Action action3 = () => value = m_Count;
// Works
Action action4 = () => value = m_Count < 10 ? m_Count++ : 0;
// Works
Action action5 = () => value = Increment();
}
public int Increment()
{
if (m_Count < 10)
m_Count++;
return m_Count;
}
}
```
EDIT: Grr, sorry for the noise. Originally, I had
```
Action action = () => if(m_Count < 10) m_Count++; value = m_Count;
```
Which threw a compile error, but then right before the post I thought I'd try wrapping it in braces
```
Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; }
```
Which also threw a compile error, so I jumped to conclusions that it was the same problem. It works, though, if I toss in a semi-colon after the braces
```
Action action = () => { if(m_Count < 10) m_Count++; value = m_Count; };
```
Sorry for the noise!
EDIT 2: Thanks cfeduke, you posted that at the same time as my edit above - went ahead and marked as answer.
|
You are missing a semi-colon, it compiles:
```
Action action = () => { if (m_Count < 10) m_Count++; value = m_Count; };
```
When you say `type name = statement;` you need a semicolon even if you use braces for a code block.
|
234,241 |
<blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo">Reference: Comparing PHP's print and echo</a> </p>
</blockquote>
<p>Is there any major and fundamental difference between these two functions in PHP?</p>
|
[
{
"answer_id": 234255,
"author": "dl__",
"author_id": 28565,
"author_profile": "https://Stackoverflow.com/users/28565",
"pm_score": 9,
"selected": true,
"text": "<p>From:\n<a href=\"http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40\" rel=\"noreferrer\">http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40</a></p>\n\n<ol>\n<li><p>Speed. There is a difference between the two, but speed-wise it\nshould be irrelevant which one you use. echo is marginally faster \nsince it doesn't set a return value if you really want to get down to the\nnitty gritty. </p></li>\n<li><p>Expression. <code>print()</code> behaves like a function in that you can do: \n<code>$ret = print \"Hello World\"</code>; And <code>$ret</code> will be <code>1</code>. That means that print\ncan be used as part of a more complex expression where echo cannot. An\nexample from the PHP Manual:</p></li>\n</ol>\n\n<pre class=\"lang-php prettyprint-override\"><code>$b ? print \"true\" : print \"false\";\n</code></pre>\n\n<p>print is also part of the precedence table which it needs to be if it \nis to be used within a complex expression. It is just about at the bottom\nof the precedence list though. Only <code>,</code> <code>AND</code> <code>OR</code> <code>XOR</code> are lower.</p>\n\n<ol start=\"3\">\n<li>Parameter(s). The grammar is: <code>echo expression [, expression[,\nexpression] ... ]</code> But <code>echo ( expression, expression )</code> is not valid. \nThis would be valid: <code>echo (\"howdy\"),(\"partner\")</code>; the same as: <code>echo\n\"howdy\",\"partner\"</code>; (Putting the brackets in that simple example \nserves\nno purpose since there is no operator precedence issue with a single\nterm like that.)</li>\n</ol>\n\n<p>So, echo without parentheses can take multiple parameters, which get\nconcatenated:</p>\n\n<pre><code> echo \"and a \", 1, 2, 3; // comma-separated without parentheses\n echo (\"and a 123\"); // just one parameter with parentheses\n</code></pre>\n\n<p><code>print()</code> can only take one parameter:</p>\n\n<pre><code> print (\"and a 123\");\n print \"and a 123\";\n</code></pre>\n"
},
{
"answer_id": 234258,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>As the PHP.net manual suggests, take a read of <a href=\"http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40\" rel=\"nofollow noreferrer\">this discussion</a>.</p>\n\n<p>One major difference is that <code>echo</code> can take multiple parameters to output. E.g.:</p>\n\n<pre><code>echo 'foo', 'bar'; // Concatenates the 2 strings\nprint('foo', 'bar'); // Fatal error\n</code></pre>\n\n<p>If you're looking to evaluate the outcome of an output statement (as below) use <code>print</code>. If not, use <code>echo</code>.</p>\n\n<pre><code>$res = print('test');\nvar_dump($res); //bool(true)\n</code></pre>\n"
},
{
"answer_id": 234263,
"author": "seanyboy",
"author_id": 1726,
"author_profile": "https://Stackoverflow.com/users/1726",
"pm_score": 6,
"selected": false,
"text": "<p>They are: </p>\n\n<ul>\n<li>print only takes one parameter, while echo can have multiple parameters. </li>\n<li>print returns a value (1), so can be used as an expression. </li>\n<li>echo is slightly faster. </li>\n</ul>\n"
},
{
"answer_id": 447548,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<p>To add to the answers above, while print can only take one parameter, it will allow for concatenation of multiple values, ie:</p>\n\n<pre><code>$count = 5;\n\nprint \"This is \" . $count . \" values in \" . $count/5 . \" parameter\";\n</code></pre>\n\n<p>This is 5 values in 1 parameter </p>\n"
},
{
"answer_id": 663347,
"author": "grilix",
"author_id": 74814,
"author_profile": "https://Stackoverflow.com/users/74814",
"pm_score": 3,
"selected": false,
"text": "<p>I think <code>print()</code> is slower than <code>echo</code>.</p>\n\n<p>I like to use <code>print()</code> only for situations like:</p>\n\n<pre><code> echo 'Doing some stuff... ';\n foo() and print(\"ok.\\n\") or print(\"error: \" . getError() . \".\\n\");\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234241",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26823/"
] |
>
> **Possible Duplicate:**
>
> [Reference: Comparing PHP's print and echo](https://stackoverflow.com/questions/7094118/reference-comparing-phps-print-and-echo)
>
>
>
Is there any major and fundamental difference between these two functions in PHP?
|
From:
<http://web.archive.org/web/20090221144611/http://faqts.com/knowledge_base/view.phtml/aid/1/fid/40>
1. Speed. There is a difference between the two, but speed-wise it
should be irrelevant which one you use. echo is marginally faster
since it doesn't set a return value if you really want to get down to the
nitty gritty.
2. Expression. `print()` behaves like a function in that you can do:
`$ret = print "Hello World"`; And `$ret` will be `1`. That means that print
can be used as part of a more complex expression where echo cannot. An
example from the PHP Manual:
```php
$b ? print "true" : print "false";
```
print is also part of the precedence table which it needs to be if it
is to be used within a complex expression. It is just about at the bottom
of the precedence list though. Only `,` `AND` `OR` `XOR` are lower.
3. Parameter(s). The grammar is: `echo expression [, expression[,
expression] ... ]` But `echo ( expression, expression )` is not valid.
This would be valid: `echo ("howdy"),("partner")`; the same as: `echo
"howdy","partner"`; (Putting the brackets in that simple example
serves
no purpose since there is no operator precedence issue with a single
term like that.)
So, echo without parentheses can take multiple parameters, which get
concatenated:
```
echo "and a ", 1, 2, 3; // comma-separated without parentheses
echo ("and a 123"); // just one parameter with parentheses
```
`print()` can only take one parameter:
```
print ("and a 123");
print "and a 123";
```
|
234,249 |
<p>I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".</p>
<p>I've written the following test program</p>
<pre><code>public static void main(String[] args) {
Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z");
boolean one = fileExtensionPattern.matcher("foo.bar").matches();
boolean two = fileExtensionPattern.matcher("foo.b").matches();
boolean three = fileExtensionPattern.matcher("foo.").matches();
boolean four = fileExtensionPattern.matcher("foo").matches();
System.out.println(one + " " + two + " " + three + " " + four);
}
</code></pre>
<p>I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?</p>
<p>Cheers,
Don</p>
|
[
{
"answer_id": 234283,
"author": "Adam Rosenfield",
"author_id": 9530,
"author_profile": "https://Stackoverflow.com/users/9530",
"pm_score": 4,
"selected": true,
"text": "<p>The <a href=\"http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()\" rel=\"noreferrer\">Matcher.matches()</a> function tries to match the pattern against the entire input. Thus, you have to add <code>.*</code> to the beginning of your regex (and the <code>\\\\Z</code> at the end is superfluous, too), or use the <a href=\"http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#find()\" rel=\"noreferrer\">find()</a> method.</p>\n"
},
{
"answer_id": 234427,
"author": "Bill K",
"author_id": 12943,
"author_profile": "https://Stackoverflow.com/users/12943",
"pm_score": 3,
"selected": false,
"text": "<pre><code>public boolean isFilename(String filename) {\n int i=filename.lastInstanceOf(\".\");\n return(i != -1 && i != filename.length - 1)\n}\n</code></pre>\n\n<p>Would be significantly faster and regardless of what you do, putting it in a method would be more readable.</p>\n"
},
{
"answer_id": 11826665,
"author": "hanisa",
"author_id": 1578951,
"author_profile": "https://Stackoverflow.com/users/1578951",
"pm_score": 0,
"selected": false,
"text": "<pre><code>package regularexpression;\n\nimport java.io.File;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class RegularFile {\n public static void main(String[] args) {\n new RegularFile();\n }\n\n public RegularFile() {\n\n String fileName = null;\n boolean bName = false;\n int iCount = 0;\n File dir = new File(\"C:/regularfolder\");\n File[] files = dir.listFiles();\n System.out.println(\"List Of Files ::\");\n\n for (File f : files) {\n\n fileName = f.getName();\n System.out.println(fileName);\n\n Pattern uName = Pattern.compile(\".*l.zip.*\");\n Matcher mUname = uName.matcher(fileName);\n bName = mUname.matches();\n if (bName) {\n iCount++;\n\n }\n }\n System.out.println(\"File Count In Folder ::\" + iCount);\n\n }\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234249",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2648/"
] |
I'm trying to come up with a Java regex that will match a filename only if it has a valid extension. For example it should match "foo.bar" and "foo.b", but neither "foo." nor "foo".
I've written the following test program
```
public static void main(String[] args) {
Pattern fileExtensionPattern = Pattern.compile("\\.\\w+\\z");
boolean one = fileExtensionPattern.matcher("foo.bar").matches();
boolean two = fileExtensionPattern.matcher("foo.b").matches();
boolean three = fileExtensionPattern.matcher("foo.").matches();
boolean four = fileExtensionPattern.matcher("foo").matches();
System.out.println(one + " " + two + " " + three + " " + four);
}
```
I expect this to print "true true false false", but instead it prints false for all 4 cases. Where am I going wrong?
Cheers,
Don
|
The [Matcher.matches()](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#matches()) function tries to match the pattern against the entire input. Thus, you have to add `.*` to the beginning of your regex (and the `\\Z` at the end is superfluous, too), or use the [find()](http://java.sun.com/javase/6/docs/api/java/util/regex/Matcher.html#find()) method.
|
234,268 |
<p>When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings? </p>
<p>Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.</p>
|
[
{
"answer_id": 234327,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 3,
"selected": false,
"text": "<p>Not sure why you want to create a new one, but if you create it yourself, you'll need to read the web config and get the values yourself to pass to Initialize() as this is done outside the class. I'm sure, though, that there is already a section handler for this section so it should be just a matter of doing:</p>\n\n<pre><code>MembershipSection section = WebConfigurationManager.GetSection(\"membership\");\n</code></pre>\n\n<p>Then find your provider and accessing its properties to construct the NameValueCollection. I don't think you will have to write any code to parse the configuration section.</p>\n\n<p>Here is the <a href=\"http://msdn.microsoft.com/en-us/library/system.web.configuration.membershipsection.aspx\" rel=\"noreferrer\">MembershipSection</a> documentation at MSDN. Drill down from there.</p>\n"
},
{
"answer_id": 235274,
"author": "JHORN",
"author_id": 30848,
"author_profile": "https://Stackoverflow.com/users/30848",
"pm_score": 5,
"selected": true,
"text": "<p>tvanfosson- Thanks for the help. (if I had the 15 points necessary I would vote you up) </p>\n\n<p>From your link I was able to figure it out. It turns out the second parameter to the Initialize proceedure was the list of parameters from the provider and could be reached in the following way:</p>\n\n<pre><code>string configPath = \"~/web.config\";\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(configPath);\nMembershipSection section = (MembershipSection)config.GetSection(\"system.web/membership\");\nProviderSettingsCollection settings = section.Providers;\nNameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;\nInitialize(section.DefaultProvider, membershipParams);\n</code></pre>\n"
},
{
"answer_id": 21371499,
"author": "Nazar Mandzyk",
"author_id": 2704968,
"author_profile": "https://Stackoverflow.com/users/2704968",
"pm_score": 0,
"selected": false,
"text": "<p>In any case you shouldn't create instance of MembershipProvider. It is creating and initializating by standard asp.net infrastructure. You can access to it by code like this one:</p>\n\n<p>var customerMembership = Membership.Provider; </p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234268",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30848/"
] |
When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings?
Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls.
I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.
|
tvanfosson- Thanks for the help. (if I had the 15 points necessary I would vote you up)
From your link I was able to figure it out. It turns out the second parameter to the Initialize proceedure was the list of parameters from the provider and could be reached in the following way:
```
string configPath = "~/web.config";
Configuration config = WebConfigurationManager.OpenWebConfiguration(configPath);
MembershipSection section = (MembershipSection)config.GetSection("system.web/membership");
ProviderSettingsCollection settings = section.Providers;
NameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;
Initialize(section.DefaultProvider, membershipParams);
```
|
234,289 |
<p>From everything I've read, it seemed that adding paging to a ListView control should be dead simple, but it's not working for me. After adding the ListView and DataPager controls to the form and wiring them together, I'm getting very odd behavior. The DataPager correctly limits the ListView's page size, but clicking the paging buttons doesn't affect the ListView at all. The paging buttons seem to think they are doing they're job, as the last button is disabled when you go to the last page, etc., but the ListView never changes. Also, it takes two clicks on the DataPager to get it to do anything, i.e., clicking on Last once does nothing, but clicking it a second time causes the DataPager to react as if the last page is now selected.</p>
<p>The only thing I can think of is that I'm binding the DataSource at runtime (to a LINQ object), not using a LinqDataSource control or anything. Has anyone seen this behavior? Am I doing something wrong? Here's the code I'm using:</p>
<pre><code><asp:DataPager ID="HistoryDataPager" runat="server" PagedControlID="HistoryListView" PageSize="10">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true" />
</Fields>
</asp:DataPager>
<asp:ListView ID="HistoryListView" runat="server">
...
</asp:ListView>
</code></pre>
<p>In the code-behind:</p>
<pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
HistoryListView.DataSource = From x in myContext.myTables ...
DataBind()
End If
End Sub
</code></pre>
|
[
{
"answer_id": 237036,
"author": "MartinHN",
"author_id": 2972,
"author_profile": "https://Stackoverflow.com/users/2972",
"pm_score": 2,
"selected": true,
"text": "<p>Take a look at the ListViewPagedDataSource.</p>\n\n<pre><code>private ListViewPagedDataSource GetProductsAsPagedDataSource(DataView dv)\n{\n// Limit the results through a PagedDataSource\nListViewPagedDataSource pagedData = new ListViewPagedDataSource();\npagedData.DataSource = dv;\npagedData.MaximumRows = dv.Table.Rows.Count;\npagedData.TotalRowCount = dpTop.PageSize;\n\nif (Request.QueryString[dpTop.QueryStringField] != null)\n pagedData.StartRowIndex = (Convert.ToInt32(Request.QueryString[dpTop.QueryStringField]) - 1) * dpTop.PageSize;\nelse\n pagedData.StartRowIndex = 0;\n\nreturn pagedData;\n}\n</code></pre>\n\n<p>Though, I have a problem viewing the last page. The DataPager jumps back to the first page, but the data displayed is the last page.</p>\n"
},
{
"answer_id": 399104,
"author": "Syam",
"author_id": 50016,
"author_profile": "https://Stackoverflow.com/users/50016",
"pm_score": 5,
"selected": false,
"text": "<p>We need to databind list view again in OnPreRender event. </p>\n\n<pre><code>protected override void OnPreRender(EventArgs e)\n {\n ListView1.DataBind();\n base.OnPreRender(e);\n }\n</code></pre>\n\n<p>--Update</p>\n\n<p>After working on a few list views with asp.net ajax, I saw a solution that makes more sense than the above one. You would normally data bind Listview on page load method or a button click event handler and when there is post back the data binding would be lost as described above in the problem. So, we need to data bind again on page properties changed event handler for the list view.</p>\n\n<pre><code>ListView_PagePropertiesChanged(object sender, EventArgs e)\n{\nListView.DataSource=someDatasource;\nListView.DataBind()\n}\n</code></pre>\n"
},
{
"answer_id": 2041929,
"author": "Kaz Fernandes",
"author_id": 289399,
"author_profile": "https://Stackoverflow.com/users/289399",
"pm_score": 1,
"selected": false,
"text": "<p>Also, if the data source of your ListView is changed (e.g. if displaying data based on search parameters), don't forget to reset the pager every time the data source is updated. With a ListView this is not as straightforward as some other data-bound controls (e.g. GridView):</p>\n\n<pre><code>private void ResetListViewPager()\n{\n DataPager pager = (DataPager)ListViewMembers.FindControl(\"DataPager1\");\n if (pager != null)\n {\n CommandEventArgs commandEventArgs = new CommandEventArgs(DataControlCommands.FirstPageCommandArgument, \"\");\n // MAKE SURE THE INDEX IN THE NEXT LINE CORRESPONDS TO THE CORRECT FIELD IN YOUR PAGER\n NextPreviousPagerField nextPreviousPagerField = pager.Fields[0] as NextPreviousPagerField;\n if (nextPreviousPagerField != null)\n {\n nextPreviousPagerField.HandleEvent(commandEventArgs);\n }\n\n // THIS COMMENTED-OUT SECTION IS HOW IT WOULD BE DONE IF USING A NUMERIC PAGER RATHER THAN A NEXT/PREVIOUS PAGER\n //commandEventArgs = new CommandEventArgs(\"0\", \"\");\n //NumericPagerField numericPagerField = pager.Fields[0] as NumericPagerField;\n //if (numericPagerField != null)\n //{\n // numericPagerField.HandleEvent(commandEventArgs);\n //}\n }\n}\n</code></pre>\n"
},
{
"answer_id": 8448849,
"author": "arsamaga",
"author_id": 1090150,
"author_profile": "https://Stackoverflow.com/users/1090150",
"pm_score": 1,
"selected": false,
"text": "<p>Bind the listview at datapager's pre render event not at page load. Please see the <a href=\"https://stackoverflow.com/questions/1130439/asp-net-datapager-control-always-a-step-behind-with-paging\">solution here</a></p>\n"
},
{
"answer_id": 13338848,
"author": "Mustafa Iqbal",
"author_id": 1814109,
"author_profile": "https://Stackoverflow.com/users/1814109",
"pm_score": 2,
"selected": false,
"text": "<p><strong>One More Solution</strong>, Its Simple, Just Get \"ID\" in \"QUERY-STRING\" from the Database, Now Set it to the Pager Control Property as [ QueryStringField=\"ID\" ] like:</p>\n\n<pre><code><asp:DataPager ID=\"DataPagerProducts\" runat=\"server\" QueryStringField=\"ID\" PageSize=\"3\">\n <Fields>\n <asp:NextPreviousPagerField ShowFirstPageButton=\"True\" ShowNextPageButton=\"False\" />\n <asp:NumericPagerField />\n <asp:NextPreviousPagerField ShowLastPageButton=\"True\" ShowPreviousPageButton=\"False\" />\n </Fields>\n </asp:DataPager>\n</code></pre>\n\n<p><strong>Note:</strong> if not woking, then set also <code>[ PagedControlID=\"ListView_Name\" ]</code>.</p>\n"
},
{
"answer_id": 15440735,
"author": "y.lahrbi",
"author_id": 2175357,
"author_profile": "https://Stackoverflow.com/users/2175357",
"pm_score": 0,
"selected": false,
"text": "<pre><code><asp:ListView ID=\"ListView1\" runat=\"server\" DataSourceID=\"sdsImages\">\n <ItemTemplate>\n <div class=\"photo sample12\">\n <asp:Image ID=\"img_Galerie\" runat=\"server\" ImageUrl='<%# \"~/imageHandler.ashx?ID=\" + Eval(\"ImageID\") %>' />\n </div>\n </ItemTemplate>\n</asp:ListView>\n<asp:DataPager ID=\"DataPager1\" runat=\"server\" PagedControlID=\"ListView1\" PageSize=\"3\" QueryStringField=\"ImageID\">\n <Fields>\n <asp:NextPreviousPagerField ShowFirstPageButton=\"True\" ShowNextPageButton=\"False\" />\n <asp:NumericPagerField />\n <asp:NextPreviousPagerField ShowLastPageButton=\"True\" ShowPreviousPageButton=\"False\" />\n </Fields>\n</asp:DataPager>\n<asp:SqlDataSource ID=\"sdsImages\" runat=\"server\"\n ConnectionString=\"<%$ ConnectionStrings:DBCS %>\"\n SelectCommand=\"SELECT ImageID FROM Images \">\n</code></pre>\n\n<p></p>\n"
},
{
"answer_id": 19823036,
"author": "Masoumeh Karvar",
"author_id": 1937517,
"author_profile": "https://Stackoverflow.com/users/1937517",
"pm_score": 0,
"selected": false,
"text": "<p>try this:</p>\n\n<pre><code>protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)\n{\n DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);\n ListView1.DataSource = productList;\n ListView1.DataBind();\n DataPager1.DataBind();\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23935/"
] |
From everything I've read, it seemed that adding paging to a ListView control should be dead simple, but it's not working for me. After adding the ListView and DataPager controls to the form and wiring them together, I'm getting very odd behavior. The DataPager correctly limits the ListView's page size, but clicking the paging buttons doesn't affect the ListView at all. The paging buttons seem to think they are doing they're job, as the last button is disabled when you go to the last page, etc., but the ListView never changes. Also, it takes two clicks on the DataPager to get it to do anything, i.e., clicking on Last once does nothing, but clicking it a second time causes the DataPager to react as if the last page is now selected.
The only thing I can think of is that I'm binding the DataSource at runtime (to a LINQ object), not using a LinqDataSource control or anything. Has anyone seen this behavior? Am I doing something wrong? Here's the code I'm using:
```
<asp:DataPager ID="HistoryDataPager" runat="server" PagedControlID="HistoryListView" PageSize="10">
<Fields>
<asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true" />
</Fields>
</asp:DataPager>
<asp:ListView ID="HistoryListView" runat="server">
...
</asp:ListView>
```
In the code-behind:
```
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
HistoryListView.DataSource = From x in myContext.myTables ...
DataBind()
End If
End Sub
```
|
Take a look at the ListViewPagedDataSource.
```
private ListViewPagedDataSource GetProductsAsPagedDataSource(DataView dv)
{
// Limit the results through a PagedDataSource
ListViewPagedDataSource pagedData = new ListViewPagedDataSource();
pagedData.DataSource = dv;
pagedData.MaximumRows = dv.Table.Rows.Count;
pagedData.TotalRowCount = dpTop.PageSize;
if (Request.QueryString[dpTop.QueryStringField] != null)
pagedData.StartRowIndex = (Convert.ToInt32(Request.QueryString[dpTop.QueryStringField]) - 1) * dpTop.PageSize;
else
pagedData.StartRowIndex = 0;
return pagedData;
}
```
Though, I have a problem viewing the last page. The DataPager jumps back to the first page, but the data displayed is the last page.
|
234,291 |
<p>I don´t know why, but my form isn´t calling Form_Load event when it loads.</p>
<p>Any ideas why this might be happening?</p>
|
[
{
"answer_id": 234342,
"author": "itsmatt",
"author_id": 7862,
"author_profile": "https://Stackoverflow.com/users/7862",
"pm_score": 3,
"selected": false,
"text": "<p>Do you have the event handler set up?</p>\n\n<p>Ultimately, there is going to be a line of code that looks something like this:</p>\n\n<pre><code>this.Load += new System.EventHandler(this.Form1_Load);\n</code></pre>\n\n<p>That might be something you code yourself, or is generated by double-clicking the Load event for the form from within Visual Studio.</p>\n"
},
{
"answer_id": 13119223,
"author": "littlecodefarmer758",
"author_id": 1687981,
"author_profile": "https://Stackoverflow.com/users/1687981",
"pm_score": 0,
"selected": false,
"text": "<p>go to the btnSave\nfind \"Click\"\nset \"btnSave_Click\"\nthen works</p>\n"
},
{
"answer_id": 26351997,
"author": "Matthew Lock",
"author_id": 74585,
"author_profile": "https://Stackoverflow.com/users/74585",
"pm_score": 1,
"selected": false,
"text": "<p>Perhaps an exception is being thrown in Initialize_Component(); which prevents the on load method being called?</p>\n\n<p><a href=\"http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/\" rel=\"nofollow\">http://blog.paulbetts.org/index.php/2010/07/20/the-case-of-the-disappearing-onload-exception-user-mode-callback-exceptions-in-x64/</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22869/"
] |
I don´t know why, but my form isn´t calling Form\_Load event when it loads.
Any ideas why this might be happening?
|
Do you have the event handler set up?
Ultimately, there is going to be a line of code that looks something like this:
```
this.Load += new System.EventHandler(this.Form1_Load);
```
That might be something you code yourself, or is generated by double-clicking the Load event for the form from within Visual Studio.
|
234,333 |
<p>I am displaying a texture that I want to manipulate without out affecting the image data. I want to be able to clamp the texel values so that anything below the lower value becomes 0, anything above the upper value becomes 0, and anything between is linearly mapped from 0 to 1. </p>
<p>Originally, to display my image I was using glDrawPixels. And to solve the problem above I would create a color map using glPixelMap. This worked beautifully. However, for performance reasons I have begun using textures to display my image. The glPixelMap approach no longer seems to work. Well that approach may work but I was unable to get it working. </p>
<p>I then tried using glPixelTransfer to set scales and bias'. This seemed to have some sort of effect (not necessarily the desired) on first pass, but when the upper and lower constraints were changed no effect was visible. </p>
<p>I was then told that fragment shaders would work. But after a call to glGetString(GL_EXTENSIONS), I found that GL_ARB_fragment_shader was not supported. Plus, a call to glCreateShaderObjectARB cause a nullreferenceexception.</p>
<p>So now I am at a loss. What should I do? Please Help.</p>
<hr>
<p>What ever might work I am willing to try. The vendor is Intel and the renderer is Intel 945G. I am unfortunately confined to a graphics card that is integrated on the motherboard, and only has gl 1.4.</p>
<p>Thanks for your response thus far.</p>
|
[
{
"answer_id": 235529,
"author": "Menkboy",
"author_id": 29539,
"author_profile": "https://Stackoverflow.com/users/29539",
"pm_score": 3,
"selected": true,
"text": "<p>Unless you have a pretty old graphics-card, it's surprising that you don't have fragment-shader support. I'd suggest you try double-checking using <a href=\"http://www.realtech-vr.com/glview/\" rel=\"nofollow noreferrer\">this</a>.</p>\n\n<p>Also, are you sure you want anything above the max value to be 0? Perhaps you meant 1? If you did mean 1 and not 0 then are quite long-winded ways to do what you're asking. </p>\n\n<p>The condensed answer is that you use multiple rendering-passes. First you render the image at normal intensity. Then you use subtractive blending (look up glBlendEquation) to subtract your minimum value. Then you use additive blending to multiply everything up by 1/(max-min) (which may need multiple passes).</p>\n\n<p>If you really want to do this, please post back the <code>GL_VENDOR</code> and <code>GL_RENDERER</code> for your graphics-card.</p>\n\n<p><strong>Edit:</strong> Hmm. Intel 945G don't have <code>ARB_fragment_shader</code>, but it does have <code>ARB_fragment_program</code> which will also do the trick.</p>\n\n<p>Your fragment-code should look something like this (but it's been a while since I wrote any so it's probably bugged)</p>\n\n<pre><code>!!ARBfp1.0\nATTRIB tex = fragment.texcoord[0]\nPARAM cbias = program.local[0]\nPARAM cscale = program.local[1]\nOUTPUT cout = result.color\n\nTEMP tmp\nTXP tmp, tex, texture[0], 2D\nSUB tmp, tmp, cbias\nMUL cout, tmp, cscale\n\nEND \n</code></pre>\n\n<p>You load this into OpenGL like so:</p>\n\n<pre><code>GLuint prog;\nglEnable(GL_FRAGMENT_PROGRAM_ARB);\nglGenProgramsARB(1, &prog);\nglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);\nglProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(src), src);\nglDisable(GL_FRAGMENT_PROGRAM_ARB);\n</code></pre>\n\n<p>Then, before rendering your geometry, you do this:</p>\n\n<pre><code>glEnable(GL_FRAGMENT_PROGRAM_ARB);\nglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);\ncolour4f cbias = cmin;\ncolour4f cscale = 1.0f / (cmax-cmin);\nglProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, cbias.r, cbias.g, cbias.b, cbias.a);\nglProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, cscale.r, cscale.g, cscale.b, cscale.a);\n\n//Draw your textured geometry\n\nglDisable(GL_FRAGMENT_PROGRAM_ARB);\n</code></pre>\n"
},
{
"answer_id": 235615,
"author": "Corey Ross",
"author_id": 5927,
"author_profile": "https://Stackoverflow.com/users/5927",
"pm_score": 0,
"selected": false,
"text": "<p>Also see if the <code>GL_ARB_fragment_program</code> extension is supported. That extension supports the ASM style fragment programs. That is supposed to be supported in OpenGL 1.4. </p>\n"
},
{
"answer_id": 237160,
"author": "Larry Gritz",
"author_id": 3832,
"author_profile": "https://Stackoverflow.com/users/3832",
"pm_score": -1,
"selected": false,
"text": "<p>It's really unfortunate that you're using such an ancient version of OpenGL. Can you upgrade with your card?</p>\n\n<p>For a more modern OGL 2.x, this is exactly the kind of program that GLSL is for. Great documentation can be found here:</p>\n\n<p><a href=\"http://opengl.org/documentation/\" rel=\"nofollow noreferrer\">OpenGL Documentation</a></p>\n\n<p><a href=\"http://opengl.org/documentation/glsl/\" rel=\"nofollow noreferrer\">OpenGL Shading Langauge</a></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234333",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/55638/"
] |
I am displaying a texture that I want to manipulate without out affecting the image data. I want to be able to clamp the texel values so that anything below the lower value becomes 0, anything above the upper value becomes 0, and anything between is linearly mapped from 0 to 1.
Originally, to display my image I was using glDrawPixels. And to solve the problem above I would create a color map using glPixelMap. This worked beautifully. However, for performance reasons I have begun using textures to display my image. The glPixelMap approach no longer seems to work. Well that approach may work but I was unable to get it working.
I then tried using glPixelTransfer to set scales and bias'. This seemed to have some sort of effect (not necessarily the desired) on first pass, but when the upper and lower constraints were changed no effect was visible.
I was then told that fragment shaders would work. But after a call to glGetString(GL\_EXTENSIONS), I found that GL\_ARB\_fragment\_shader was not supported. Plus, a call to glCreateShaderObjectARB cause a nullreferenceexception.
So now I am at a loss. What should I do? Please Help.
---
What ever might work I am willing to try. The vendor is Intel and the renderer is Intel 945G. I am unfortunately confined to a graphics card that is integrated on the motherboard, and only has gl 1.4.
Thanks for your response thus far.
|
Unless you have a pretty old graphics-card, it's surprising that you don't have fragment-shader support. I'd suggest you try double-checking using [this](http://www.realtech-vr.com/glview/).
Also, are you sure you want anything above the max value to be 0? Perhaps you meant 1? If you did mean 1 and not 0 then are quite long-winded ways to do what you're asking.
The condensed answer is that you use multiple rendering-passes. First you render the image at normal intensity. Then you use subtractive blending (look up glBlendEquation) to subtract your minimum value. Then you use additive blending to multiply everything up by 1/(max-min) (which may need multiple passes).
If you really want to do this, please post back the `GL_VENDOR` and `GL_RENDERER` for your graphics-card.
**Edit:** Hmm. Intel 945G don't have `ARB_fragment_shader`, but it does have `ARB_fragment_program` which will also do the trick.
Your fragment-code should look something like this (but it's been a while since I wrote any so it's probably bugged)
```
!!ARBfp1.0
ATTRIB tex = fragment.texcoord[0]
PARAM cbias = program.local[0]
PARAM cscale = program.local[1]
OUTPUT cout = result.color
TEMP tmp
TXP tmp, tex, texture[0], 2D
SUB tmp, tmp, cbias
MUL cout, tmp, cscale
END
```
You load this into OpenGL like so:
```
GLuint prog;
glEnable(GL_FRAGMENT_PROGRAM_ARB);
glGenProgramsARB(1, &prog);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);
glProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(src), src);
glDisable(GL_FRAGMENT_PROGRAM_ARB);
```
Then, before rendering your geometry, you do this:
```
glEnable(GL_FRAGMENT_PROGRAM_ARB);
glBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);
colour4f cbias = cmin;
colour4f cscale = 1.0f / (cmax-cmin);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, cbias.r, cbias.g, cbias.b, cbias.a);
glProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, cscale.r, cscale.g, cscale.b, cscale.a);
//Draw your textured geometry
glDisable(GL_FRAGMENT_PROGRAM_ARB);
```
|
234,367 |
<p>As a software developer, I have done many web page applications and been doing blog for my programming experiences. I would like to use pictures in many cases. <strong>Pictures worth thousand words and they are universal language</strong>!</p>
<p>You could create your own clip art images or download graphics(actually many are open clip art/image libraries available, <a href="http://openclipart.org/media/view/media/home" rel="nofollow noreferrer">Open Clip Art Library</a> as example). However your time and art skill are limited and you can only keep limited library of images.</p>
<p>I wish if there is any open art/image library web sites with permanent references available so that you just add a simple reference in your html page like this just like a way that you could use other people or web site's graphics:</p>
<pre><code><img src="http://OpenArtLibray.net/icon/work/DoItYourself.png".../>
</code></pre>
<p>In this way, there is no need to waste time to download and upload images and no waste on your and other computer's disk spaces(no duplication). Just one place with a huge amount of variety of images available, and open for people to use, or with some reasonable fees. People may vote the popularity of art/images as well.</p>
<p>Is there any such kind of web site available?</p>
|
[
{
"answer_id": 234569,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 1,
"selected": false,
"text": "<p>Typically sites discourage this. What this really does is shift the bandwidth cost to the hosting site. There have been cases where sites with pictures have analyzed the referrer to determine if images are linked to from other sites, then servering an image with text claiming the image is being 'stolen'.</p>\n\n<p>The point of that, is the idea isn't very well liked.</p>\n\n<p>However, some sites like w3c, allow you to link to their certification images. It all depends on what you are linking to.</p>\n\n<p>It is hard to think of a business doing this, as there doesn't seem to be a revenue aspect.</p>\n\n<p>Even if some were charged fees, there's a lot of work involved in checking/verifying who has paid, via referrer texts. Maybe you have a new business plan.</p>\n\n<p>Update:\nOh, I have a friend who always sends me emails with links to flickr. Maybe their license lets you link to images on their site. Something for you to check out.</p>\n\n<p>Update:\nThis text, \"photo hosting sites\", makes for an interesting, relevant google search.</p>\n"
},
{
"answer_id": 235010,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 0,
"selected": false,
"text": "<p>Thanks for <a href=\"https://stackoverflow.com/users/15578/chris\">Chris</a> explanation. I could accept it as a answer. However, I raised this question because I really don't like to \"steal\" images. I can see it is hard to charge fees, but there are some many open resources available on the web. Actually, I found one <a href=\"http://openclipart.org/media/view/media/home\" rel=\"nofollow noreferrer\">Open Clip Art Library</a>, which allow people to contribute and share images. I found many good pictures there and downloaded. I may contribute some when I create images for my blog so I'll let people to use my.</p>\n\n<p>Flickre is an open social place for people store and sharing pictures. As long as pictures are shared there, specially by people, I think you can use and link images there. Still you have to do the work: creating and uploading. Actually, I tried another open social site called as <a href=\"https://www.getdropbox.com/home\" rel=\"nofollow noreferrer\">DropBox</a>. I can create a public folder there and add my pictures for sharing. All those sites have one common problem: personal account and may not be available if inactive for certain period of time (90 days for DropBox?).</p>\n\n<p>That's why I asked this question here in StackOverFlow. I hope some people may know some hosts available or any other alternative options available. Maybe it is just like Chris said, \"the idea isn't very well liked\".</p>\n"
},
{
"answer_id": 247481,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, I realize that Open Clip Art Library I mentioned in my previous email does provide image hosting-like service. If you click on any one's picture download link, it will open a new tab or window to display the graphic. The display has its URL. I have created a new user name and submitted my picture. It works well. I can include the graphics in my test web page. Not sure how long the URL will be there. It looks like permanent one.</p>\n"
},
{
"answer_id": 597917,
"author": "random",
"author_id": 9314,
"author_profile": "https://Stackoverflow.com/users/9314",
"pm_score": 0,
"selected": false,
"text": "<p>Try <a href=\"http://search.creativecommons.org/\" rel=\"nofollow noreferrer\">searching Creative Commons licensed</a> works. People will often upload and share photos on such places as Flickr under a Creative Commons license which allows you to remix, reference or use on your own projects, blogs or site.</p>\n\n<p>There are different types of licenses under the CC with some asking you to not use their works if you're going to be making money from it or if you're engaging in commercial activity. </p>\n\n<p>You just have to nod back to the original author when using items under CC and if you link back to them, that's just good karma.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234367",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/62776/"
] |
As a software developer, I have done many web page applications and been doing blog for my programming experiences. I would like to use pictures in many cases. **Pictures worth thousand words and they are universal language**!
You could create your own clip art images or download graphics(actually many are open clip art/image libraries available, [Open Clip Art Library](http://openclipart.org/media/view/media/home) as example). However your time and art skill are limited and you can only keep limited library of images.
I wish if there is any open art/image library web sites with permanent references available so that you just add a simple reference in your html page like this just like a way that you could use other people or web site's graphics:
```
<img src="http://OpenArtLibray.net/icon/work/DoItYourself.png".../>
```
In this way, there is no need to waste time to download and upload images and no waste on your and other computer's disk spaces(no duplication). Just one place with a huge amount of variety of images available, and open for people to use, or with some reasonable fees. People may vote the popularity of art/images as well.
Is there any such kind of web site available?
|
Typically sites discourage this. What this really does is shift the bandwidth cost to the hosting site. There have been cases where sites with pictures have analyzed the referrer to determine if images are linked to from other sites, then servering an image with text claiming the image is being 'stolen'.
The point of that, is the idea isn't very well liked.
However, some sites like w3c, allow you to link to their certification images. It all depends on what you are linking to.
It is hard to think of a business doing this, as there doesn't seem to be a revenue aspect.
Even if some were charged fees, there's a lot of work involved in checking/verifying who has paid, via referrer texts. Maybe you have a new business plan.
Update:
Oh, I have a friend who always sends me emails with links to flickr. Maybe their license lets you link to images on their site. Something for you to check out.
Update:
This text, "photo hosting sites", makes for an interesting, relevant google search.
|
234,388 |
<p>I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.</p>
<pre><code>#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<char> deck;
char suit[] = {'h','d','c','s'};
char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};
for (int j=0; j<13; j++) {
for (int i=0; i<4; i++) {
deck.push_back(card[j] suit[i]);
}
}
return 0;
}
</code></pre>
<p>I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.</p>
|
[
{
"answer_id": 234393,
"author": "Dave",
"author_id": 21294,
"author_profile": "https://Stackoverflow.com/users/21294",
"pm_score": 3,
"selected": false,
"text": "<p>Use 'T' instead of 10.</p>\n"
},
{
"answer_id": 234394,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 3,
"selected": false,
"text": "<p>Have you tried replacing J with 11, Q with 12 and K with 13? Then you could use <code>int</code>egers rather than <code>char</code>acters. Replace 11-13 with the appropriate letter later on.</p>\n"
},
{
"answer_id": 234407,
"author": "JtR",
"author_id": 30958,
"author_profile": "https://Stackoverflow.com/users/30958",
"pm_score": 5,
"selected": true,
"text": "<p>Try to create class of Card with suit and card as a member and set it as a type of vector. Like</p>\n\n<pre><code>public class Card {\n public:\n Card(char suit, char card);\n char suit, card;\n};\n\nint main() {\n vector<Card> deck;\n char suit[] = {'h','d','c','s'};\n char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'};\n for (int j=0; j<13; j++) {\n for (int i=0; i<4; i++) {\n deck.push_back(new Card(card[j],suit[i]));\n } \n }\n return 0;\n}\n</code></pre>\n\n<p>also using enums instead of chars in suit and card would make it clearer.</p>\n"
},
{
"answer_id": 234414,
"author": "FOR",
"author_id": 27826,
"author_profile": "https://Stackoverflow.com/users/27826",
"pm_score": 2,
"selected": false,
"text": "<p>As mentioned by others, you can use 'T' for ten, J, Q, and K for the figures.\nAs far as push_back.. since deck is a vector of chars, you can pass only one char to push_back as argument. Passing both the card value (1...9, T, J, Q, K) and its suite doesn't work.</p>\n\n<p>I personally would create a little struct, to represent a Card, with a Value and a Suite property. Then, you can make your deck a vector of Cards .</p>\n\n<p>Edited: fixing last word since vector (less-than) Card (greater-than) was rendered as vector (nothing).</p>\n"
},
{
"answer_id": 234416,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 2,
"selected": false,
"text": "<p>Well, first of all, deck[0] is one char, yet you are trying, to stuff \"2h\" into it. (for the moment, we'll ignore that how you are doing that is wrong.)</p>\n\n<p>Basically, you'll need to make deck a <code>vector<std::string></code>. Make card an array of const char*s, and convert the elements to string.</p>\n\n<p>then use: </p>\n\n<pre><code>deck.push_back(std::string(card[j]) + suit[i]);\n</code></pre>\n"
},
{
"answer_id": 234422,
"author": "Kevin",
"author_id": 4599,
"author_profile": "https://Stackoverflow.com/users/4599",
"pm_score": 5,
"selected": false,
"text": "<p>I think what you are looking to use is an enumeration. It will make your code clearer and resolve your problem.</p>\n\n<pre><code>enum SUIT { HEART, CLUB, DIAMOND, SPADE }; \nenum VALUE { ONE, TWO, THREE, ..., TEN, JACK, QUEEN, KING};\n</code></pre>\n"
},
{
"answer_id": 234437,
"author": "Drek",
"author_id": 31236,
"author_profile": "https://Stackoverflow.com/users/31236",
"pm_score": 1,
"selected": false,
"text": "<p>Since this is a blackjack program, you will be adding and comparing the value of the cards.</p>\n\n<p>That being the case, you can save yourself some additional programming and pain by giving the cards <em>int</em> values (1-13) instead of <em>char</em> values.</p>\n"
},
{
"answer_id": 234456,
"author": "Steve Fallows",
"author_id": 18882,
"author_profile": "https://Stackoverflow.com/users/18882",
"pm_score": 0,
"selected": false,
"text": "<p>I would go with Ross's suggestion to use integers. Most card games will involve some bits of math so that's a better representation.</p>\n\n<p>Convert to 'A' or 'ACE' etc. on output.</p>\n"
},
{
"answer_id": 234517,
"author": "benjismith",
"author_id": 22979,
"author_profile": "https://Stackoverflow.com/users/22979",
"pm_score": 3,
"selected": false,
"text": "<p>The way you model it really depends on what you're trying to do.</p>\n\n<p>Are you creating an actual game, and the data structures just need to support the gameplay?</p>\n\n<p>If so, I'd create a card class, with an enum field for the suit and a numeric type (with values 1 - 13) for the face value.</p>\n\n<p>On the other hand, if you're building an analysis application or an AI player, then the model might be a little bit different.</p>\n\n<p>A few years ago, I wrote a simulator to calculate probabilities in various Texas Holdem scenarios, and I wanted it to crunch numbers REALLY quickly. I started out with a very straightforward model (card class, suit enum, etc) but after a lot of profiling and optimization, I ended up with a bitwise representation.</p>\n\n<p>Each card was a sixteen-bit value, with the thirteen high-order bits representing the face value, the two low order bits representing the suit, and with bit[2] as a special flag indicating an ace (used only in cases where the ace might appear in an A2345 straight).</p>\n\n<p>Here are a few examples:</p>\n\n<pre><code>0000000000001001 <---- Two of hearts\n0100000000000011 <---- King of spades\n1000000000000110 <---- Ace of diamonds\n\n^^^^^^^^^^^^^ (\"face-value\" bits)\n ^ (\"low-ace\" flag)\n ^^ (\"suit\" bits)\n</code></pre>\n\n<p>You can imagine how, with a design like this, it's lighting fast to look for pairs, threes-of-a-kind, and straights (flushes are slightly more tricky).</p>\n\n<p>I won't go into all the particular operations, but suffice it to say that this kind of model supports millions of operations per second...</p>\n\n<p>Of course, keep in mind, I'm not actually advocating that you use a design like this in a straightforward game implementation. The only reason I ended up with this design is because I needed to conduct massive statistical simulations.</p>\n\n<p>So think carefully about how you want to model:</p>\n\n<ul>\n<li>Each card</li>\n<li>A player's hand</li>\n<li>The entire deck</li>\n<li>The state of the table... including all player hands (including players who have split their initial hand), maybe a six-deck shoe, the discard pile, etc</li>\n</ul>\n\n<p>The overall application model, and the goals of the application in general, will determine to a large extent the types of data structures that'll be most appropriate.</p>\n\n<p>Have fun!!!</p>\n"
},
{
"answer_id": 234805,
"author": "dlamblin",
"author_id": 459,
"author_profile": "https://Stackoverflow.com/users/459",
"pm_score": 0,
"selected": false,
"text": "<p>Since this is homework for C++ I am going to guess you are expected to use classes.\nOtherwise use the enums, and if this were C use a struct or something.</p>\n\n<p>And for some games, apart from points value, you'd want to store some kind of rank for the card, which would depend on the current mode of play.</p>\n\n<p>I haven't done plain C in forever, but I mean something like this:</p>\n\n<pre><code>typedef struct struct_card {\n unsigned short int suit:2;\n unsigned short int card:4;\n// unsigned short int valu:4;\n} card;\n\nint main() {\n card a_card;\n card std_deck[52];\n const unsigned short int rummy_value[13] = {1,2,3,4,5,6,7,8,9,10,10,10,10};\n const char *std_card_name[13] = {\"Ace\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\n \"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Jack\",\"Queen\",\"King\"};\n const char *std_suit_name[4] = {\"Spades\",\"Clubs\",\"Hearts\",\"Diamonds\"};\n\n int j, k, i=0;\n for(j=0; j<4; j++){\n for(k=0; k<13; k++){\n a_card.suit=j; a_card.card=k;\n std_deck[i++] = a_card;\n }\n }\n\n //check our work\n printf(\"In a game of rummy:\\n\");\n for(i=0;i<52;i++){\n printf(\" %-5s of %-8s is worth %2d points.\\n\",\n std_card_name[std_deck[i].card],\n std_suit_name[std_deck[i].suit],\n rummy_value[std_deck[i].card]);\n }\n\n //a different kind of game.\n enum round_mode {SHEILD_TRUMP, FLOWER_TRUMP, BELL_TRUMP, ACORN_TRUMP, BOCK, GEISS} mode;\n const card jass_deck[36]={\n {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},\n {1,1},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},\n {2,2},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},\n {3,3},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},\n };\n#define JASS_V {11,0,0,0,0,10,2,3,4}\n const unsigned short int jass_value[9] = JASS_V;\n#define JASS_TRUMP_V {11,0,0,0,14,10,20,3,4}\n const unsigned short int jass_trump_value[9] = JASS_TRUMP_V;\n#define JASS_BOCK_V {11,0,0,8,0,10,2,3,4}\n const unsigned short int jass_bock_value[9] = JASS_BOCK_V;\n#define JASS_GEISS_V {0,11,0,8,0,10,2,3,4}\n const unsigned short int jass_geiss_value[9] = JASS_GEISS_V;\n const char *jass_card_name[9] = {\"Ace\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Banner\",\n \"Under\",\"Ober\",\"King\"};\n const char *jass_suit_name[4] = {\"Sheilds\",\"Flowers\",\"Bells\",\"Acorns\"};\n const unsigned short int jass_all_value[6][4][9] = {\n { JASS_TRUMP_V, JASS_V, JASS_V, JASS_V },\n { JASS_V, JASS_TRUMP_V, JASS_V, JASS_V },\n { JASS_V, JASS_V, JASS_TRUMP_V, JASS_V },\n { JASS_V, JASS_V, JASS_V, JASS_TRUMP_V },\n { JASS_BOCK_V, JASS_BOCK_V, JASS_BOCK_V, JASS_BOCK_V },\n { JASS_GEISS_V, JASS_GEISS_V, JASS_GEISS_V, JASS_GEISS_V }\n };\n\n //check our work 2: work goes on summer vacation\n printf(\"In a game of jass with trump (Sheilds | Flowers | Bells | Acorns) | Bock | Geiss\\n\");\n for(i=0;i<36;i++){\n printf(\" %-6s of %-7s is worth %8d%10d%8d%9d%8d%8d\\n\",\n jass_card_name[jass_deck[i].card],\n jass_suit_name[jass_deck[i].suit],\n jass_all_value[SHEILD_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[FLOWER_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[BELL_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[ACORN_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[BOCK][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[GEISS][jass_deck[i].suit][jass_deck[i].card]);\n }\n return 0;\n}\n</code></pre>\n\n<p>Output looks like:</p>\n\n<pre><code>In a game of rummy:\n Ace of Spades is worth 1 points.\n Two of Spades is worth 2 points.\n Three of Spades is worth 3 points.\n Four of Spades is worth 4 points.\n Five of Spades is worth 5 points.\n...\n Nine of Diamonds is worth 9 points.\n Ten of Diamonds is worth 10 points.\n Jack of Diamonds is worth 10 points.\n Queen of Diamonds is worth 10 points.\n King of Diamonds is worth 10 points.\nIn a game of jass with trump (Sheilds | Flowers | Bells | Acorns) | Bock | Geiss\n Ace of Sheilds is worth 11 11 11 11 11 0\n Six of Sheilds is worth 0 0 0 0 0 11\n Seven of Sheilds is worth 0 0 0 0 0 0\n Eight of Sheilds is worth 0 0 0 0 8 8\n Nine of Sheilds is worth 14 0 0 0 0 0\n Banner of Sheilds is worth 10 10 10 10 10 10\n...\n Under of Acorns is worth 2 2 2 20 2 2\n Ober of Acorns is worth 3 3 3 3 3 3\n King of Acorns is worth 4 4 4 4 4 4\n</code></pre>\n\n<p>Blackjack is boring.\nThis code does compile.</p>\n"
},
{
"answer_id": 235769,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>This might not compile, but here is the approach I would (and have used). You're going to want to use ints to represent your cards, but you can easily abstract this in a class. Which I'll write for you.</p>\n\n<pre><code>class Card\n{\npublic:\n enum ESuit\n {\n kSuit_Heart,\n kSuit_Club,\n kSuit_Diamond,\n kSuit_Spade,\n kSuit_Count\n };\n\n enum ERank\n {\n kRank_Ace,\n kRank_Two,\n kRank_Three,\n kRank_Four,\n kRank_Five,\n kRank_Six,\n kRank_Seven,\n kRank_Eight,\n kRank_Nine,\n kRank_Ten,\n kRank_Jack,\n kRank_Queen,\n kRank_King,\n kRank_Count\n };\n\n static int const skNumCards = kSuit_Count * kRank_Count;\n\n Card( int cardIndex )\n : mSuit( static_cast<ESuit>( cardIndex / kRank_Count ) )\n , mRank( static_cast<ERank>( cardIndex % kRank_Count ) )\n {}\n\n ESuit GetSuit() const { return mSuit );\n ERank GetRank() const { return mRank );\n\nprivate:\n ESuit mSuit;\n ERank mRank;\n}\n</code></pre>\n\n<p>Now its very simple to add to this class to get everything you want out of it.\nTo generate the list its as simple as below.</p>\n\n<pre><code>rstl::vector<Card> mCards;\nmCards.reserve( Card::skNumCards );\n\nfor ( int cardValue = 0; cardValue < Card::skNumCards; ++cardValue )\n{\n mCards.push_back( Card( cardValue ) );\n}\n</code></pre>\n\n<p>Do you need to shuffle?</p>\n\n<pre><code>#include <algorithm>\nstd::random_shuffle( mCards.begin(), mCards.end() );\n</code></pre>\n\n<p>How about see what the value of the first card is?</p>\n\n<pre><code>if ( mCards[0].GetSuit() == Card::kRank_Club && mCards[0].GetRank() == Card::kRank_Ace )\n{\n std::cout << \"ACE OF CLUBS!\" << std::endl;\n}\n</code></pre>\n\n<p>I didn't compile any of this, but it should be close.</p>\n"
},
{
"answer_id": 10475743,
"author": "Travis Weston",
"author_id": 833696,
"author_profile": "https://Stackoverflow.com/users/833696",
"pm_score": 1,
"selected": false,
"text": "<p>When I created <a href=\"http://www.binpress.com/app/anubis-cppcards/525?ad=1229\" rel=\"nofollow\">my C++ Deck of cards class</a>, I ran into a few problems of my own. First off I was trying to convert <a href=\"http://www.binpress.com/app/anubis-phpcards/518?ad=1229\" rel=\"nofollow\">my PHP deck of cards class</a> to C++, with minimal luck. I decided to sit down and just put it on paper. I decided to go with an Object Oriented setup, mostly because I feel it's the easiest to use for expansion. I use the objects <strong>Card</strong> and <strong>Deck</strong>, so, for instance, if you want to put 10 decks into the <strong>Shoe</strong> of your blackjack game, you could create 10 decks, which would be simple enough, because I decided to make everything self contained. In fact, it's so self contained, to create your shoe the code would be:</p>\n\n<pre><code>#include \"AnubisCards.cpp\"\n\nint main() {\n\n Deck *shoe = new Deck(10);\n\n}\n</code></pre>\n\n<p>But, that was for simplicity, not exactly necessary in smaller games where you only need a single deck.</p>\n\n<p>ANYWAY, How <strong>I</strong> generated the deck was by creating an array of 52 Card objects. Decks are easy enough, because you know that you have <strong>4 Suits</strong> and <strong>13 Cards in each suit</strong>, you also know that you have <strong>2,3,4,5,6,7,8,9,10,Jack,Queen,King,Ace in every single suit</strong>. Those will never change. So I used two loops, one for the <strong>Suit</strong> and the other for the <strong>Value</strong>.</p>\n\n<p>It was something like this:</p>\n\n<pre><code>for(int suit = 1; suit <= 4; suit++){\n for(int card = 1; card <= 13; card++){\n // Add card to array\n }\n}\n</code></pre>\n\n<p>Now, you'll notice in every single one of those loops, I use an integer value. The reason is simple, cards are numbers. 4 suits. 13 values. Even the numerical value in the game of Blackjack. Face value, until you hit Face cards, which are numerical value 10 until you hit Ace which is numerical value 1 or 11. Everything is numbers. So you can use those numbers to not only assign the value of the card, but the suit of the card, and the number in the numerical sequence.</p>\n\n<p>One idea would be to store a map in the Card class, with the char or String names of the cards, with 1,2,3... being the indexes for each.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38/"
] |
I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.
```
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<char> deck;
char suit[] = {'h','d','c','s'};
char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'};
for (int j=0; j<13; j++) {
for (int i=0; i<4; i++) {
deck.push_back(card[j] suit[i]);
}
}
return 0;
}
```
I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push\_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.
|
Try to create class of Card with suit and card as a member and set it as a type of vector. Like
```
public class Card {
public:
Card(char suit, char card);
char suit, card;
};
int main() {
vector<Card> deck;
char suit[] = {'h','d','c','s'};
char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'};
for (int j=0; j<13; j++) {
for (int i=0; i<4; i++) {
deck.push_back(new Card(card[j],suit[i]));
}
}
return 0;
}
```
also using enums instead of chars in suit and card would make it clearer.
|
234,439 |
<p>Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.</p>
<p>Consider the following situation :</p>
<pre><code>var query =
from c in db.Customers
where (c.ContactFirstName.Contains("BlackListed") ||
c.ContactLastName.Contains("BlackListed") ||
c.Address.Contains("BlackListed"))
select c;
</code></pre>
<p>The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?</p>
<p>An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.</p>
|
[
{
"answer_id": 234523,
"author": "James Curran",
"author_id": 12725,
"author_profile": "https://Stackoverflow.com/users/12725",
"pm_score": 3,
"selected": false,
"text": "<pre><code>var query = from C in db.Customers select c;\n\nif (seachFirstName)\n query = query.Where(c=>c.ContactFirstname.Contains(\"Blacklisted\"));\n\nif (seachLastName)\n query = query.Where(c=>c.ContactLastname.Contains(\"Blacklisted\"));\n\nif (seachAddress)\n query = query.Where(c=>c.Address.Contains(\"Blacklisted\"));\n</code></pre>\n\n<p>Note that they aren't mutually exclusive.</p>\n"
},
{
"answer_id": 237108,
"author": "Omer van Kloeten",
"author_id": 4979,
"author_profile": "https://Stackoverflow.com/users/4979",
"pm_score": 0,
"selected": false,
"text": "<p>Since this is not LINQ to Objects, but rather LINQ to SQL, you have no other alternative beside using either Expressions or a stored procedure.</p>\n"
},
{
"answer_id": 237120,
"author": "Aaron Powell",
"author_id": 11388,
"author_profile": "https://Stackoverflow.com/users/11388",
"pm_score": 4,
"selected": false,
"text": "<p>@Geoff has the best option, justing Dynamic LINQ.</p>\n\n<p>If you want to go the way of building queries at runtime using Lambda though I'd recomment that you use the PredicateBuilder (<a href=\"http://www.albahari.com/nutshell/predicatebuilder.aspx\" rel=\"noreferrer\">http://www.albahari.com/nutshell/predicatebuilder.aspx</a>) and have something such as this:</p>\n\n<pre><code>Expression<Fun<T,bool>> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T \nif(blacklistFirstName){\n pred = p => p.ContactFirstName.Contains(\"Blacklisted\");\n}\nif(blacklistLastName){\n if(pred == null){\n pred = p => p.ContactLastName.Contains(\"Blacklisted\"); //if it doesn't exist just assign it\n }else{\n pred = pred.And(p => p.ContactLastName.Contains(\"Blacklisted\"); //otherwise we add it as an And clause\n }\n}\n</code></pre>\n\n<p>And so on for all the columns you want to include. When you get to your query you just need something like this:</p>\n\n<pre><code>var results = db.Customers.Where(pred).Select(c => c);\n</code></pre>\n\n<p>I've used this to do building of LINQ for searching where there are about 20 different options and it produces really good SQL.</p>\n"
},
{
"answer_id": 9516029,
"author": "timothy",
"author_id": 1210530,
"author_profile": "https://Stackoverflow.com/users/1210530",
"pm_score": 2,
"selected": false,
"text": "<p>You can turn your where clauses on and off using some logic expressions.</p>\n\n<pre><code>//Turn on all where clauses\nbool ignoreFirstName = false;\nbool ignoreLastName = false;;\nbool ignoreAddress = false;\n\n//Decide which WHERE clauses we are going to turn off because of something.\nif(something)\n ignoreFirstName = true; \n\n//Create the query\nvar queryCustomers = from c in db.Customers \n where (ignoreFirstName || (c.ContactFirstName.Contains(\"BlackListed\")))\n where (ignoreLastName || (c.ContactLastName.Contains(\"BlackListed\")))\n where (ignoreAddress || (c.Address.Contains(\"BlackListed\"))\n select j; \n</code></pre>\n\n<p>If ignoreFirstName is true in the query then the condition on the other side of the or statement will be ignored.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234439",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9178/"
] |
Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.
Consider the following situation :
```
var query =
from c in db.Customers
where (c.ContactFirstName.Contains("BlackListed") ||
c.ContactLastName.Contains("BlackListed") ||
c.Address.Contains("BlackListed"))
select c;
```
The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?
An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.
|
@Geoff has the best option, justing Dynamic LINQ.
If you want to go the way of building queries at runtime using Lambda though I'd recomment that you use the PredicateBuilder (<http://www.albahari.com/nutshell/predicatebuilder.aspx>) and have something such as this:
```
Expression<Fun<T,bool>> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T
if(blacklistFirstName){
pred = p => p.ContactFirstName.Contains("Blacklisted");
}
if(blacklistLastName){
if(pred == null){
pred = p => p.ContactLastName.Contains("Blacklisted"); //if it doesn't exist just assign it
}else{
pred = pred.And(p => p.ContactLastName.Contains("Blacklisted"); //otherwise we add it as an And clause
}
}
```
And so on for all the columns you want to include. When you get to your query you just need something like this:
```
var results = db.Customers.Where(pred).Select(c => c);
```
I've used this to do building of LINQ for searching where there are about 20 different options and it produces really good SQL.
|
234,458 |
<p>I recently stumbled across <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="noreferrer">this entry in the google testing blog</a> about guidelines for writing more testable code. I was in agreement with the author until this point:</p>
<blockquote>
<p>Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test.</p>
</blockquote>
<p>I simply cannot wrap my head around that. I can understand using polymorphism instead of RTTI (or DIY-RTTI, as the case may be), but that seems like such a broad statement that I can't imagine it actually being used effectively in production code. It seems to me, rather, that it would be easier to add additional test cases for methods which have switch statements, rather than breaking down the code into dozens of separate classes.</p>
<p>Also, I was under the impression that polymorphism can lead to all sorts of other subtle bugs and design issues, so I'm curious to know if the tradeoff here would be worth it. Can someone explain to me exactly what is meant by this testing guideline?</p>
|
[
{
"answer_id": 234491,
"author": "Martin York",
"author_id": 14065,
"author_profile": "https://Stackoverflow.com/users/14065",
"pm_score": 7,
"selected": true,
"text": "<p>Actually this makes testing and code easier to write.</p>\n\n<p>If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them).</p>\n\n<p>By using polymorphism you can use virtual functions to get the same functionality and because a new case is a new class you don't have to search your code for things that need to be checked it is all isolated for each class.</p>\n\n<pre><code>class Animal\n{\n public:\n Noise warningNoise();\n Noise pleasureNoise();\n private:\n AnimalType type;\n};\n\nNoise Animal::warningNoise()\n{\n switch(type)\n {\n case Cat: return Hiss;\n case Dog: return Bark;\n }\n}\nNoise Animal::pleasureNoise()\n{\n switch(type)\n {\n case Cat: return Purr;\n case Dog: return Bark;\n }\n}\n</code></pre>\n\n<p>In this simple case every new animal causes requires both switch statements to be updated.<br>\nYou forget one? What is the default? BANG!!</p>\n\n<p>Using polymorphism </p>\n\n<pre><code>class Animal\n{\n public:\n virtual Noise warningNoise() = 0;\n virtual Noise pleasureNoise() = 0;\n};\n\nclass Cat: public Animal\n{\n // Compiler forces you to define both method.\n // Otherwise you can't have a Cat object\n\n // All code local to the cat belongs to the cat.\n\n};\n</code></pre>\n\n<p>By using polymorphism you can test the Animal class.<br>\nThen test each of the derived classes separately.</p>\n\n<p>Also this allows you to ship the Animal class (<strong>Closed for alteration</strong>) as part of you binary library. But people can still add new Animals (<strong>Open for extension</strong>) by deriving new classes derived from the Animal header. If all this functionality had been captured inside the Animal class then all animals need to be defined before shipping (Closed/Closed).</p>\n"
},
{
"answer_id": 234506,
"author": "QBziZ",
"author_id": 11572,
"author_profile": "https://Stackoverflow.com/users/11572",
"pm_score": 2,
"selected": false,
"text": "<p>Polymorphism is one of the corner stones of OO and certainly is very useful.\nBy dividing concerns over multiple classes you create isolated and testable units.\nSo instead of doing a switch...case where you call methods on several different types or implemenations you create a unified interface, having multiple implementations. \nWhen you need to add an implementation, you do not need to modify the clients, as is the case with switch...case. Very important as this helps to avoid regression.</p>\n\n<p>You can also simplify your client algorithm by dealing with just one type : the interface.</p>\n\n<p>Very important to me is that polymorphism is best used with a pure interface/implementation pattern ( like the venerable Shape <- Circle etc... ) . \nYou can also have polymorphism in concrete classes with template-methods ( aka hooks ), but its effectiveness decreases as complexity increases.</p>\n\n<p>Polymorphism is the foundation on which our company's codebase is built, so I consider it very practical.</p>\n"
},
{
"answer_id": 234510,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 3,
"selected": false,
"text": "<p>Unit testing an OO program means testing each class as a unit. A principle that you want to learn is \"Open to extension, closed to modification\". I got that from Head First Design Patterns. But it basically says that you want to have the ability to easily extend your code without modifying existing tested code.</p>\n\n<p>Polymorphism makes this possible by eliminating those conditional statements. Consider this example:</p>\n\n<p>Suppose you have a Character object that carries a Weapon. You can write an attack method like this:</p>\n\n<pre><code>If (weapon is a rifle) then //Code to attack with rifle else\nIf (weapon is a plasma gun) //Then code to attack with plasma gun\n</code></pre>\n\n<p>etc.</p>\n\n<p>With polymorphism the Character does not have to \"know\" the type of weapon, simply </p>\n\n<pre><code>weapon.attack()\n</code></pre>\n\n<p>would work. What happens if a new weapon was invented? Without polymorphism you will have to modify your conditional statement. With polymorphism you will have to add a new class and leave the tested Character class alone.</p>\n"
},
{
"answer_id": 234511,
"author": "JohnMcG",
"author_id": 1674,
"author_profile": "https://Stackoverflow.com/users/1674",
"pm_score": 3,
"selected": false,
"text": "<p>Not an expert in the implications for test cases, but from a software development perspective:</p>\n\n<ul>\n<li><p><strong>Open-closed principle</strong> -- Classes should be closed to alteration, but open to extension. If you manage conditional operations via a conditional construct, then if a new condition is added, your class needs to change. If you use polymorphism, the base class need not change.</p></li>\n<li><p><strong>Don't repeat yourself</strong> -- An important part of the guideline is the \"<em>same</em> if condition.\" That indicates that your class has some distinct modes of operation that can be factored into a class. Then, that condition appears in one place in your code -- when you instantiate the object for that mode. And again, if a new one comes along, you only need to change one piece of code.</p></li>\n</ul>\n"
},
{
"answer_id": 234549,
"author": "Nick Fortescue",
"author_id": 5346,
"author_profile": "https://Stackoverflow.com/users/5346",
"pm_score": 1,
"selected": false,
"text": "<p>This is mainly to do with encapsulation of knowledge. Let's start with a really obvious example - toString(). This is Java, but easily transfers to C++. Suppose you want to print a human friendly version of an object for debugging purposes. You could do:</p>\n\n<pre><code>switch(obj.type): {\ncase 1: cout << \"Type 1\" << obj.foo <<...; break; \ncase 2: cout << \"Type 2\" << ...\n</code></pre>\n\n<p>This would however clearly be silly. Why should one method somewhere know how to print everything. It will often be better for the object itself to know how to print itself, eg:</p>\n\n<pre><code>cout << object.toString();\n</code></pre>\n\n<p>That way the toString() can access member fields without needing casts. They can be tested independently. They can be changed easily.</p>\n\n<p>You could argue however, that how an object prints shouldn't be associated with an object, it should be associated with the print method. In this case, another design pattern comes in helpful, which is the Visitor pattern, used to fake Double Dispatch. Describing it fully is too long for this answer, but you can <a href=\"http://en.wikipedia.org/wiki/Visitor_pattern\" rel=\"nofollow noreferrer\">read a good description here</a>.</p>\n"
},
{
"answer_id": 234552,
"author": "coppro",
"author_id": 16855,
"author_profile": "https://Stackoverflow.com/users/16855",
"pm_score": -1,
"selected": false,
"text": "<p>It really depends on your style of programming. While this may be correct in Java or C#, I don't agree that automatically deciding to use polymorphism is correct. You can split your code into lots of little functions and perform an array lookup with function pointers (initialized at compile time), for instance. In C++, polymorphism and classes are often overused - probably the biggest design mistake made by people coming from strong OOP languages into C++ is that everything goes into a class - this is not true. A class should only contain the minimal set of things that make it work as a whole. If a subclass or friend is necessary, so be it, but they shouldn't be the norm. Any other operations on the class should be free functions in the same namespace; ADL will allow these functions be used without lookup.</p>\n\n<p>C++ is not an OOP language, don't make it one. It's as bad as programming C in C++.</p>\n"
},
{
"answer_id": 234638,
"author": "rice",
"author_id": 23933,
"author_profile": "https://Stackoverflow.com/users/23933",
"pm_score": 3,
"selected": false,
"text": "<p>I'm a bit of a skeptic: I believe inheritance often adds more complexity than it removes.</p>\n\n<p>I think you are asking a good question, though, and one thing I consider is this:</p>\n\n<p>Are you splitting into multiple classes because you are dealing with different <em>things</em>? Or is it really the same thing, acting in a different <em>way</em>?</p>\n\n<p>If it's really a new <strong>type</strong>, then go ahead and create a new class. But if it's just an option, I generally keep it in the same class.</p>\n\n<p>I believe the default solution is the single-class one, and the onus is on the programmer proposing inheritance to prove their case.</p>\n"
},
{
"answer_id": 234737,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>It works very well <strong>if you understand it</strong>.</p>\n\n<p>There are also 2 flavors of polymorphism. The first is very easy to understand in java-esque:</p>\n\n<pre><code>interface A{\n\n int foo();\n\n}\n\nfinal class B implements A{\n\n int foo(){ print(\"B\"); }\n\n}\n\nfinal class C implements A{\n\n int foo(){ print(\"C\"); }\n\n}\n</code></pre>\n\n<p>B and C share a common interface. B and C in this case can't be extended, so you're always sure which foo() you're calling. Same goes for C++, just make A::foo pure virtual.</p>\n\n<p>Second, and trickier is run-time polymorphism. It doesn't look too bad in pseudo-code.</p>\n\n<pre><code>class A{\n\n int foo(){print(\"A\");}\n\n}\n\nclass B extends A{\n\n int foo(){print(\"B\");}\n\n}\n\nclass C extends B{\n\n int foo(){print(\"C\");}\n\n}\n\n...\n\nclass Z extends Y{\n\n int foo(){print(\"Z\");\n\n}\n\nmain(){\n\n F* f = new Z();\n A* a = f;\n a->foo();\n f->foo();\n\n}\n</code></pre>\n\n<p>But it is a lot trickier. Especially if you're working in C++ where some of the foo declarations may be virtual, and some of the inheritance might be virtual. Also the answer to this:</p>\n\n<pre><code>A* a = new Z;\nA a2 = *a;\na->foo();\na2.foo();\n</code></pre>\n\n<p>might not be what you expect.</p>\n\n<p>Just keep keenly aware of what you do and don't know if you're using run-time polymorphism. Don't get overconfident, and if you're not sure what something is going to do at run-time, then test it.</p>\n"
},
{
"answer_id": 235028,
"author": "paercebal",
"author_id": 14089,
"author_profile": "https://Stackoverflow.com/users/14089",
"pm_score": 5,
"selected": false,
"text": "<h2>Do not fear...</h2>\n<p>I guess your problem lies with familiarity, not technology. Familiarize yourself with C++ OOP.</p>\n<h2>C++ is an OOP language</h2>\n<p>Among its multiple paradigms, it has OOP features and is more than able to support comparison with most pure OO language.</p>\n<p>Don't let the "C part inside C++" make you believe C++ can't deal with other paradigms. C++ can handle a lot of programming paradigms quite graciously. And among them, OOP C++ is the most mature of C++ paradigms after procedural paradigm (i.e. the aforementioned "C part").</p>\n<h2>Polymorphism is Ok for production</h2>\n<p>There is no "subtle bugs" or "not suitable for production code" thing. There are developers who remain set in their ways, and developers who'll learn how to use tools and use the best tools for each task.</p>\n<h2>switch and polymorphism are [almost] similar...</h2>\n<p>... But polymorphism removed most errors.</p>\n<p>The difference is that you must handle the switches manually, whereas polymorphism is more natural, once you get used with inheritance method overriding.</p>\n<p>With switches, you'll have to compare a type variable with different types, and handle the differences. With polymorphism, the variable itself knows how to behave. You only have to organize the variables in logical ways, and override the right methods.</p>\n<p>But in the end, if you forget to handle a case in switch, the compiler won't tell you, whereas you'll be told if you derive from a class without overriding its pure virtual methods. Thus most switch-errors are avoided.</p>\n<p>All in all, the two features are about making choices. But Polymorphism enable you to make more complex and in the same time more natural and thus easier choices.</p>\n<h2>Avoid using RTTI to find an object's type</h2>\n<p>RTTI is an interesting concept, and can be useful. But most of the time (i.e. 95% of the time), method overriding and inheritance will be more than enough, and most of your code should not even know the exact type of the object handled, but trust it to do the right thing.</p>\n<p>If you use RTTI as a glorified switch, you're missing the point.</p>\n<p>(Disclaimer: I am a great fan of the RTTI concept and of dynamic_casts. But one must use the right tool for the task at hand, and most of the time RTTI is used as a glorified switch, which is wrong)</p>\n<h2>Compare dynamic vs. static polymorphism</h2>\n<p>If your code does not know the exact type of an object at compile time, then use dynamic polymorphism (i.e. classic inheritance, virtual methods overriding, etc.)</p>\n<p>If your code knows the type at compile time, then perhaps you could use static polymorphism, i.e. the CRTP pattern <a href=\"http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern\" rel=\"noreferrer\">http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern</a></p>\n<p>The CRTP will enable you to have code that smells like dynamic polymorphism, but whose every method call will be resolved statically, which is ideal for some very critical code.</p>\n<h2>Production code example</h2>\n<p>A code similar to this one (from memory) is used on production.</p>\n<p>The easier solution revolved around a the procedure called by message loop (a WinProc in Win32, but I wrote a simplier version, for simplicity's sake). So summarize, it was something like:</p>\n<pre><code>void MyProcedure(int p_iCommand, void *p_vParam)\n{\n // A LOT OF CODE ???\n // each case has a lot of code, with both similarities\n // and differences, and of course, casting p_vParam\n // into something, depending on hoping no one\n // did a mistake, associating the wrong command with\n // the wrong data type in p_vParam\n\n switch(p_iCommand)\n {\n case COMMAND_AAA: { /* A LOT OF CODE (see above) */ } break ;\n case COMMAND_BBB: { /* A LOT OF CODE (see above) */ } break ;\n // etc.\n case COMMAND_XXX: { /* A LOT OF CODE (see above) */ } break ;\n case COMMAND_ZZZ: { /* A LOT OF CODE (see above) */ } break ;\n default: { /* call default procedure */} break ;\n }\n}\n</code></pre>\n<p>Each addition of command added a case.</p>\n<p>The problem is that some commands where similar, and shared partly their implementation.</p>\n<p>So mixing the cases was a risk for evolution.</p>\n<p>I resolved the problem by using the Command pattern, that is, creating a base Command object, with one process() method.</p>\n<p>So I re-wrote the message procedure, minimizing the dangerous code (i.e. playing with void *, etc.) to a minimum, and wrote it to be sure I would never need to touch it again:</p>\n<pre><code>void MyProcedure(int p_iCommand, void *p_vParam)\n{\n switch(p_iCommand)\n {\n // Only one case. Isn't it cool?\n case COMMAND:\n {\n Command * c = static_cast<Command *>(p_vParam) ;\n c->process() ;\n }\n break ;\n default: { /* call default procedure */} break ;\n }\n}\n</code></pre>\n<p>And then, for each possible command, instead of adding code in the procedure, and mixing (or worse, copy/pasting) the code from similar commands, I created a new command, and derived it either from the Command object, or one of its derived objects:</p>\n<p>This led to the hierarchy (represented as a tree):</p>\n<pre><code>[+] Command\n |\n +--[+] CommandServer\n | |\n | +--[+] CommandServerInitialize\n | |\n | +--[+] CommandServerInsert\n | |\n | +--[+] CommandServerUpdate\n | |\n | +--[+] CommandServerDelete\n |\n +--[+] CommandAction\n | |\n | +--[+] CommandActionStart\n | |\n | +--[+] CommandActionPause\n | |\n | +--[+] CommandActionEnd\n |\n +--[+] CommandMessage\n</code></pre>\n<p>Now, all I needed to do was to override process for each object.</p>\n<p>Simple, and easy to extend.</p>\n<p>For example, say the CommandAction was supposed to do its process in three phases: "before", "while" and "after". Its code would be something like:</p>\n<pre><code>class CommandAction : public Command\n{\n // etc.\n virtual void process() // overriding Command::process pure virtual method\n {\n this->processBefore() ;\n this->processWhile() ;\n this->processAfter() ;\n }\n\n virtual void processBefore() = 0 ; // To be overriden\n \n virtual void processWhile()\n {\n // Do something common for all CommandAction objects\n }\n \n virtual void processAfter() = 0 ; // To be overriden\n\n} ;\n</code></pre>\n<p>And, for example, CommandActionStart could be coded as:</p>\n<pre><code>class CommandActionStart : public CommandAction\n{\n // etc.\n virtual void processBefore()\n {\n // Do something common for all CommandActionStart objects\n }\n\n virtual void processAfter()\n {\n // Do something common for all CommandActionStart objects\n }\n} ;\n</code></pre>\n<p>As I said: Easy to understand (if commented properly), and very easy to extend.</p>\n<p>The switch is reduced to its bare minimum (i.e. if-like, because we still needed to delegate Windows commands to Windows default procedure), and no need for RTTI (or worse, in-house RTTI).</p>\n<p>The same code inside a switch would be quite amusing, I guess (if only judging by the amount of "historical" code I saw in our app at work).</p>\n"
},
{
"answer_id": 365595,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>If you are using switch statements everywhere you run into the possibility that when upgrading you miss one place thats needs an update.</p>\n"
},
{
"answer_id": 458256,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "<p>I must re-iterate that finding all switch statments can be a non trivial processes in a mature code base. If you miss any then the application is likely to crash because of an unmatched case statement unless you have default set.</p>\n\n<p>Also check out \"Martin Fowlers\" book on \"Refactoring\"<br>\nUsing a switch instead of polymorphism is a code smell.</p>\n"
},
{
"answer_id": 15389260,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 2,
"selected": false,
"text": "<p>Switches and polymorphism does the same thing. </p>\n\n<p>In polymorphism (and in class-based programming in general) you group the functions by their type. When using switches you group the types by function. Decide which view is good for you.</p>\n\n<p>So if your interface is fixed and you only add new types, polymorphism is your friend. \nBut if you add new functions to your interface you will need to update all implementations.</p>\n\n<p>In certain cases, you may have a fixed amount of types, and new functions can come, then switches are better. But adding new types makes you update every switch.</p>\n\n<p>With switches you are duplicating sub-type lists. With polymorphism you are duplicating operation lists. You traded a problem to get a different one. This is the so called <a href=\"http://c2.com/cgi/wiki?ExpressionProblem\" rel=\"nofollow\">expression problem</a>, which is not solved by any programming paradigm I know. The root of the problem is the one-dimensional nature of the text used to represent the code.</p>\n\n<p>Since pro-polymorphism points are well discussed here, let me provide a pro-switch point.</p>\n\n<p>OOP has design patterns to avoid common pitfalls. Procedural programming has design patterns too (but no one have wrote it down yet AFAIK, we need another new Gang of N to make a bestseller book of those...). One design pattern could be <em>always include a default case</em>.</p>\n\n<p>Switches can be done right:</p>\n\n<pre><code>switch (type)\n{\n case T_FOO: doFoo(); break;\n case T_BAR: doBar(); break;\n default:\n fprintf(stderr, \"You, who are reading this, add a new case for %d to the FooBar function ASAP!\\n\", type);\n assert(0);\n}\n</code></pre>\n\n<p>This code will point your favorite debugger to the location where you forgot to handle a case. A compiler can force you to implement your interface, but this <em>forces</em> you to test your code thoroughly (at least to see the new case is noticed). </p>\n\n<p>Of course if a particular switch would be used more than one places, it's cut out into a function (<em>don't repeat yourself</em>).</p>\n\n<p>If you want to extend these switches just do a <code>grep 'case[ ]*T_BAR' rn .</code> (on Linux) and it will spit out the locations worth looking at. Since you need to look at the code, you will see some context which helps you how to add the new case correctly. When you use polymorphism the call sites are hidden inside the system, and you depend on the correctness of the documentation, if it exists at all.</p>\n\n<p>Extending switches does not break the OCP too, since you does not alter the existing cases, just add a new case.</p>\n\n<p>Switches also help the next guy trying to get accustomed to and understand the code: </p>\n\n<ul>\n<li>The possible cases are before your eyes. That's a good thing when reading code (less jumping around).</li>\n<li>But virtual method calls are just like normal method calls. One can never know if a call is virtual or normal (without looking up the class). That's bad.</li>\n<li>But if the call is virtual, possible cases are not obvious (without finding all derived classes). That's also bad.</li>\n</ul>\n\n<p>When you provide an interface to a thirdparty, so they can add behavior and user data to a system, then that's a different matter. (They can set callbacks and pointers to user-data, and you give them handles)</p>\n\n<p>Further debate can be found here: <a href=\"http://c2.com/cgi/wiki?SwitchStatementsSmell\" rel=\"nofollow\">http://c2.com/cgi/wiki?SwitchStatementsSmell</a></p>\n\n<p><em>I'm afraid my \"C-hacker's syndrome\" and anti-OOPism will eventually burn all my reputation here. But whenever I needed or had to hack or bolt something into a procedural C system, I found it quite easy, the lack of constraints, forced encapsulation and less abstraction layers makes me \"just do it\". But in a C++/C#/Java system where tens of abstraction layers stacked on the top of each other in the software's lifetime, I need to spend many hours sometimes days to find out how to correctly work around all the constraints and limitations that other programmers built into their system to avoid others \"messing with their class\".</em></p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
I recently stumbled across [this entry in the google testing blog](http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html) about guidelines for writing more testable code. I was in agreement with the author until this point:
>
> Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test.
>
>
>
I simply cannot wrap my head around that. I can understand using polymorphism instead of RTTI (or DIY-RTTI, as the case may be), but that seems like such a broad statement that I can't imagine it actually being used effectively in production code. It seems to me, rather, that it would be easier to add additional test cases for methods which have switch statements, rather than breaking down the code into dozens of separate classes.
Also, I was under the impression that polymorphism can lead to all sorts of other subtle bugs and design issues, so I'm curious to know if the tradeoff here would be worth it. Can someone explain to me exactly what is meant by this testing guideline?
|
Actually this makes testing and code easier to write.
If you have one switch statement based on an internal field you probably have the same switch in multiple places doing slightly different things. This causes problems when you add a new case as you have to update all the switch statements (if you can find them).
By using polymorphism you can use virtual functions to get the same functionality and because a new case is a new class you don't have to search your code for things that need to be checked it is all isolated for each class.
```
class Animal
{
public:
Noise warningNoise();
Noise pleasureNoise();
private:
AnimalType type;
};
Noise Animal::warningNoise()
{
switch(type)
{
case Cat: return Hiss;
case Dog: return Bark;
}
}
Noise Animal::pleasureNoise()
{
switch(type)
{
case Cat: return Purr;
case Dog: return Bark;
}
}
```
In this simple case every new animal causes requires both switch statements to be updated.
You forget one? What is the default? BANG!!
Using polymorphism
```
class Animal
{
public:
virtual Noise warningNoise() = 0;
virtual Noise pleasureNoise() = 0;
};
class Cat: public Animal
{
// Compiler forces you to define both method.
// Otherwise you can't have a Cat object
// All code local to the cat belongs to the cat.
};
```
By using polymorphism you can test the Animal class.
Then test each of the derived classes separately.
Also this allows you to ship the Animal class (**Closed for alteration**) as part of you binary library. But people can still add new Animals (**Open for extension**) by deriving new classes derived from the Animal header. If all this functionality had been captured inside the Animal class then all animals need to be defined before shipping (Closed/Closed).
|
234,479 |
<p>I'm writing a config file and I need to define if the process expects a windows format file or a unix format file. I've got a copy of the expected file - is there a way I can check if it uses \n or \r\n without exiting emacs?</p>
|
[
{
"answer_id": 234495,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 0,
"selected": false,
"text": "<p>Open the file in emacs using find-file-literally. If lines have ^M symbols at the end, it expects a windows format text file.</p>\n"
},
{
"answer_id": 234557,
"author": "Jouni K. Seppänen",
"author_id": 26575,
"author_profile": "https://Stackoverflow.com/users/26575",
"pm_score": 4,
"selected": true,
"text": "<p>If it says (DOS) on the modeline when you open the file on Unix, the line endings are Windows-style. If it says (Unix) when you open the file on Windows, the line endings are Unix-style.</p>\n\n<p>From the Emacs 22.2 manual (Node: Mode Line):</p>\n\n<blockquote>\n <p>If the buffer's file uses\n carriage-return linefeed, the colon\n changes to either a backslash ('\\') or\n '(DOS)', depending on the operating\n system. If the file uses just\n carriage-return, the colon indicator\n changes to either a forward slash\n ('/') or '(Mac)'. On some systems,\n Emacs displays '(Unix)' instead of the\n colon for files that use newline as\n the line separator.</p>\n</blockquote>\n\n<p>Here's a function that – I think – shows how to check from elisp what Emacs has determined to be the type of line endings. If it looks inordinately complicated, perhaps it is.</p>\n\n<pre><code>(defun describe-eol ()\n (interactive)\n (let ((eol-type (coding-system-eol-type buffer-file-coding-system)))\n (when (vectorp eol-type)\n (setq eol-type (coding-system-eol-type (aref eol-type 0))))\n (message \"Line endings are of type: %s\"\n (case eol-type\n (0 \"Unix\") (1 \"DOS\") (2 \"Mac\") (t \"Unknown\")))))\n</code></pre>\n"
},
{
"answer_id": 234692,
"author": "Chris Conway",
"author_id": 1412,
"author_profile": "https://Stackoverflow.com/users/1412",
"pm_score": 0,
"selected": false,
"text": "<p>The following Elisp function will return <code>nil</code> if no <code>\"\\r\\n\"</code> terminators appear in a file (otherwise it returns the point of the first occurrence). You can put it in your <code>.emacs</code> and call it with <code>M-x check-eol</code>.</p>\n\n<pre><code>(defun check-eol (FILE)\n (interactive \"fFile: \")\n (set-buffer (generate-new-buffer \"*check-eol*\"))\n (insert-file-contents-literally FILE)\n (let ((point (search-forward \"\\r\\n\")))\n (kill-buffer nil)\n point))\n</code></pre>\n"
},
{
"answer_id": 234998,
"author": "stephanea",
"author_id": 8776,
"author_profile": "https://Stackoverflow.com/users/8776",
"pm_score": 2,
"selected": false,
"text": "<p>If you go in hexl-mode (M-x hexl-mode), you shoul see the line termination bytes.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234479",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26880/"
] |
I'm writing a config file and I need to define if the process expects a windows format file or a unix format file. I've got a copy of the expected file - is there a way I can check if it uses \n or \r\n without exiting emacs?
|
If it says (DOS) on the modeline when you open the file on Unix, the line endings are Windows-style. If it says (Unix) when you open the file on Windows, the line endings are Unix-style.
From the Emacs 22.2 manual (Node: Mode Line):
>
> If the buffer's file uses
> carriage-return linefeed, the colon
> changes to either a backslash ('\') or
> '(DOS)', depending on the operating
> system. If the file uses just
> carriage-return, the colon indicator
> changes to either a forward slash
> ('/') or '(Mac)'. On some systems,
> Emacs displays '(Unix)' instead of the
> colon for files that use newline as
> the line separator.
>
>
>
Here's a function that – I think – shows how to check from elisp what Emacs has determined to be the type of line endings. If it looks inordinately complicated, perhaps it is.
```
(defun describe-eol ()
(interactive)
(let ((eol-type (coding-system-eol-type buffer-file-coding-system)))
(when (vectorp eol-type)
(setq eol-type (coding-system-eol-type (aref eol-type 0))))
(message "Line endings are of type: %s"
(case eol-type
(0 "Unix") (1 "DOS") (2 "Mac") (t "Unknown")))))
```
|
234,482 |
<p>I have a collection of elements that I need to operate over, calling member functions on the collection:</p>
<pre><code>std::vector<MyType> v;
... // vector is populated
</code></pre>
<p>For calling functions with no arguments it's pretty straight-forward:</p>
<pre><code>std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc));
</code></pre>
<p>A similar thing can be done if there's one argument to the function I wish to call.</p>
<p>My problem is that I want to call a function on elements in the vector if it meets some condition. <code>std::find_if</code> returns an iterator to the first element meeting the conditions of the predicate. </p>
<pre><code>std::vector<MyType>::iterator it =
std::find_if(v.begin(), v.end(), MyPred());
</code></pre>
<p>I wish to find <strong>all</strong> elements meeting the predicate and operate over them.</p>
<p>I've been looking at the STL algorithms for a "<code>find_all</code>" or "<code>do_if</code>" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.</p>
|
[
{
"answer_id": 234525,
"author": "Marcin",
"author_id": 22724,
"author_profile": "https://Stackoverflow.com/users/22724",
"pm_score": 3,
"selected": false,
"text": "<p>Is it ok to change the vector? You may want to look at the partition algorithm.\n<br>\n<a href=\"http://www.cplusplus.com/reference/algorithm/partition.html\" rel=\"nofollow noreferrer\">Partition algorithm</a></p>\n\n<p>Another option would be to change your <code>MyType::myfunc</code> to either check the element, or to take a predicate as a parameter and use it to test the element it's operating on.</p>\n"
},
{
"answer_id": 234556,
"author": "John Dibling",
"author_id": 241536,
"author_profile": "https://Stackoverflow.com/users/241536",
"pm_score": 4,
"selected": false,
"text": "<p>I wrote a <code>for_each_if()</code> and a <code>for_each_equal()</code> which do what I think you're looking for.</p>\n\n<p><code>for_each_if()</code> takes a predicate functor to evaluate equality, and <code>for_each_equal()</code> takes a value of any type and does a direct comparison using <code>operator ==</code>. In both cases, the function you pass in is called on each element that passes the equality test.</p>\n\n<pre><code>/* ---\n\n For each\n 25.1.1\n\n template< class InputIterator, class Function, class T>\n Function for_each_equal(InputIterator first, InputIterator last, const T& value, Function f)\n\n template< class InputIterator, class Function, class Predicate >\n Function for_each_if(InputIterator first, InputIterator last, Predicate pred, Function f)\n\n Requires: \n\n T is of type EqualityComparable (20.1.1) \n\n Effects: \n\n Applies f to each dereferenced iterator i in the range [first, last) where one of the following conditions hold:\n\n 1: *i == value\n 2: pred(*i) != false\n\n Returns: \n\n f\n\n Complexity: \n\n At most last - first applications of f\n\n --- */\n\n template< class InputIterator, class Function, class Predicate >\n Function for_each_if(InputIterator first, \n InputIterator last, \n Predicate pred, \n Function f)\n {\n for( ; first != last; ++first)\n {\n if( pred(*first) )\n f(*first);\n }\n return f;\n };\n\n template< class InputIterator, class Function, class T>\n Function for_each_equal(InputIterator first, \n InputIterator last, \n const T& value, \n Function f)\n {\n for( ; first != last; ++first)\n {\n if( *first == value )\n f(*first);\n }\n return f;\n };\n</code></pre>\n"
},
{
"answer_id": 234566,
"author": "Greg Rogers",
"author_id": 5963,
"author_profile": "https://Stackoverflow.com/users/5963",
"pm_score": 0,
"selected": false,
"text": "<p>For what its worth <a href=\"http://www.crystalclearsoftware.com/cgi-bin/boost_wiki/wiki.pl?STLAlgorithmExtensions/ForEachIf\" rel=\"nofollow noreferrer\">for_each_if</a> is being considered as an eventual addition to boost. It isn't hard to implement your own.</p>\n"
},
{
"answer_id": 234593,
"author": "oz10",
"author_id": 14069,
"author_profile": "https://Stackoverflow.com/users/14069",
"pm_score": 5,
"selected": true,
"text": "<p>Boost Lambda makes this easy.</p>\n\n<pre><code>#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/if.hpp>\n\nstd::for_each( v.begin(), v.end(), \n if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] \n );\n</code></pre>\n\n<p>You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant \"is divisible by 2\":</p>\n\n<pre><code>std::for_each( v.begin(), v.end(), \n if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]\n );\n</code></pre>\n\n<p><hr/>\n<strong>Update:</strong>\nDoing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):</p>\n\n<pre><code>std::for_each( v.begin(), v.end(),\n [](MyType& mt ) mutable\n {\n if( mt % 2 == 0)\n { \n mt.myfunc(); \n }\n } );\n</code></pre>\n\n<p>At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality. </p>\n"
},
{
"answer_id": 234618,
"author": "computinglife",
"author_id": 17224,
"author_profile": "https://Stackoverflow.com/users/17224",
"pm_score": 0,
"selected": false,
"text": "<p>Lamda functions - the idea is to do something like this</p>\n\n<pre><code>for_each(v.begin(), v.end(), [](MyType& x){ if (Check(x) DoSuff(x); }) \n</code></pre>\n\n<p>Origial post <a href=\"http://softwareramblings.com/2008/04/c-lambda-functions.html\" rel=\"nofollow noreferrer\">here</a>. </p>\n"
},
{
"answer_id": 235036,
"author": "Ferruccio",
"author_id": 4086,
"author_profile": "https://Stackoverflow.com/users/4086",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"http://www.boost.org/doc/libs/1_36_0/doc/html/foreach.html\" rel=\"nofollow noreferrer\">Boost.Foreach</a>:</p>\n\n<pre><code>BOOST_FOREACH (vector<...>& x, v)\n{\n if (Check(x)\n DoStuff(x);\n}\n</code></pre>\n"
},
{
"answer_id": 235491,
"author": "Max Lybbert",
"author_id": 10593,
"author_profile": "https://Stackoverflow.com/users/10593",
"pm_score": 1,
"selected": false,
"text": "<pre><code>std::vector<int> v, matches;\nstd::vector<int>::iterator i = v.begin();\nMyPred my_pred;\nwhile(true) {\n i = std::find_if(i, v.end(), my_pred);\n if (i == v.end())\n break;\n matches.push_back(*i);\n}\n</code></pre>\n\n<p>For the record, while I have seen an implementation where calling <code>end()</code> on a <code>list</code> was O(n), I haven't seen any STL implementations where calling <code>end()</code> on a <code>vector</code> was anything other than O(1) -- mainly because <code>vector</code>s are guaranteed to have random-access iterators.</p>\n\n<p>Even so, if you are worried about an inefficient <code>end()</code>, you can use this code:</p>\n\n<pre><code>std::vector<int> v, matches;\nstd::vector<int>::iterator i = v.begin(), end = v.end();\nMyPred my_pred;\nwhile(true) {\n i = std::find_if(i, v.end(), my_pred);\n if (i == end)\n break;\n matches.push_back(*i);\n}\n</code></pre>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234482",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24263/"
] |
I have a collection of elements that I need to operate over, calling member functions on the collection:
```
std::vector<MyType> v;
... // vector is populated
```
For calling functions with no arguments it's pretty straight-forward:
```
std::for_each(v.begin(), v.end(), std::mem_fun(&MyType::myfunc));
```
A similar thing can be done if there's one argument to the function I wish to call.
My problem is that I want to call a function on elements in the vector if it meets some condition. `std::find_if` returns an iterator to the first element meeting the conditions of the predicate.
```
std::vector<MyType>::iterator it =
std::find_if(v.begin(), v.end(), MyPred());
```
I wish to find **all** elements meeting the predicate and operate over them.
I've been looking at the STL algorithms for a "`find_all`" or "`do_if`" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.
|
Boost Lambda makes this easy.
```
#include <boost/lambda/lambda.hpp>
#include <boost/lambda/bind.hpp>
#include <boost/lambda/if.hpp>
std::for_each( v.begin(), v.end(),
if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ]
);
```
You could even do away with defining MyPred(), if it is simple. This is where lambda really shines. E.g., if MyPred meant "is divisible by 2":
```
std::for_each( v.begin(), v.end(),
if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]
);
```
---
**Update:**
Doing this with the C++0x lambda syntax is also very nice (continuing with the predicate as modulo 2):
```
std::for_each( v.begin(), v.end(),
[](MyType& mt ) mutable
{
if( mt % 2 == 0)
{
mt.myfunc();
}
} );
```
At first glance this looks like a step backwards from boost::lambda syntax, however, it is better because more complex functor logic is trivial to implement with c++0x syntax... where anything very complicated in boost::lambda gets tricky quickly. Microsoft Visual Studio 2010 beta 2 currently implements this functionality.
|
234,507 |
<p>This was something originally discussed during a presentation given by Charles Brian Quinn of the <a href="http://www.bignerdranch.com/" rel="noreferrer">Big Nerd Ranch</a> at <a href="http://www.actsasconference.com" rel="noreferrer">acts_as_conference</a>. He was discussing what he had learned from instructing a Ruby on Rails Bootcamp to many people both new to programming and new to Rails.</p>
<p>One particular slide that stood out was along the lines of <strong>never using foo and bar as examples when trying to teach someone to program</strong>. His reasoning was very simple.</p>
<p>Which is easier to understand?</p>
<pre><code>baz = foo + bar
</code></pre>
<p>or</p>
<pre><code>answer = first_number + second_number
</code></pre>
<p>It's happened many times myself when explaining something and I immediately jump to the go to foo bar placeholders but then realize my mistake and make the example make a lot more sense by using a real world scenario. </p>
<p>This is especially applicable when trying to teach someone who has had no programming exposure and you end up needing explain foo and bar before explaining what you're actually trying to teach.</p>
<p>However, using foo and bar for experienced programmers seems OK, though I personally think, along with Charles, that it's something that needs to change.</p>
<p>A quick SO search for "foo" returns over 20 pages of results with foo being used in more ways that I can comprehend. And in some cases where I'm reading a question on a particular language and I'm doing so to help understand that language better. If applicable variable names are used instead of foo and bar, it makes it much easier to understand and interpret the problem. So for seasoned developers, the construct seems a bit flawed as well.</p>
<p>Is this a habit that will ever be able to be kicked? Why do you choose to foo bar or to not foo bar?</p>
|
[
{
"answer_id": 234529,
"author": "Niniki",
"author_id": 4155,
"author_profile": "https://Stackoverflow.com/users/4155",
"pm_score": 4,
"selected": false,
"text": "<p>I can see the point when talking to non programmers, but when you're at a whiteboard discussing a problem with some team members .. I would miss my foos and my bars. I think the prevalence of foo/bar is an example of the ability of most programmers to think abstractly. </p>\n\n<p>Probably more of an issue if you're in the training arena.</p>\n"
},
{
"answer_id": 234534,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": false,
"text": "<p>I use them sometimes. But only if a \"real\" name is not relevant.</p>\n"
},
{
"answer_id": 234538,
"author": "Santiago Palladino",
"author_id": 12791,
"author_profile": "https://Stackoverflow.com/users/12791",
"pm_score": 6,
"selected": true,
"text": "<p>It strictly depends on what are you trying to teach. Sometimes, when showing a programming example, you have to declare a few things just for the snippet to be \"complete\", and those few things are not the core of what you are showing. </p>\n\n<p>For example, if you want to show how to throw an exception, I believe it is ok to present a snippet like</p>\n\n<pre><code>public void foo() { \n\n // Do some things\n\n if (errorCondition) {\n throw new Exception(\"Error message\");\n }\n\n}\n</code></pre>\n\n<p>Since the point in it is showing exceptions, there is no point in caring about the method name, so foo is \"legal\" in this context, or at least for me.</p>\n\n<p>What I would not accept (in this same example) would be</p>\n\n<pre><code>public void foo() { \n\n // Do some things\n\n if (bar) {\n throw new Exception(baz);\n }\n\n}\n</code></pre>\n\n<p>as it is obscuring what you are trying to teach.</p>\n"
},
{
"answer_id": 234544,
"author": "tom.dietrich",
"author_id": 15769,
"author_profile": "https://Stackoverflow.com/users/15769",
"pm_score": 1,
"selected": false,
"text": "<p>I choose not to foo and bar whenever my audience is familiar enough with the concept at hand that it would prove a detriment to their understanding.</p>\n\n<p>The only time Foo and Bar should be used is when you are talking about something so abstract that adding a context would require additional discussion. Then Foo and Bar are much more readable and created code that is more followable than the alternatives, like x, y and z. </p>\n"
},
{
"answer_id": 234571,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 2,
"selected": false,
"text": "<p>I use them when demonstrating that any values of 'foo' and 'bar' will suffice, like \"you can get the size of an object with sizeof(foo).\" It's handy for getting people to understand the general concept and not just the particulars. For instance, if I'd said \"you can get the size of an object with something like sizeof(int)\", then it's almost guaranteed that someone would ask if that also works for floats.</p>\n"
},
{
"answer_id": 418239,
"author": "user51498",
"author_id": 51498,
"author_profile": "https://Stackoverflow.com/users/51498",
"pm_score": 0,
"selected": false,
"text": "<p>I am new to programming, and more or less self taught. I read a lot of example code online and at the beginning found myself replacing foo and bar &c. with more relevant names, such as the firstnumber and secondnumber examples above.</p>\n\n<p>I now prefer x,y,z,i... because foo and bar seem to spark linguistic impulses in my mind and can distract me from the routine, and I've developed, somewhat, the ability to hold a whole bunch of different variables in my head and remember what they are. But I would still definitely recommend using relevant naming when teaching someone else, especially when explaining code to someone that doesn't program but needs to understand how the program works.</p>\n"
},
{
"answer_id": 418268,
"author": "Jim C",
"author_id": 21706,
"author_profile": "https://Stackoverflow.com/users/21706",
"pm_score": 1,
"selected": false,
"text": "<p>I think it is due to mildly, or maybe not so mildly, sarcastic nature of many programmers. While many people have tried to place different meanings on foo/bar most , or at least many, of us think of \"FUBAR\", F**K Up Beyond All Recognition. Its a way for \"experienced\" people to make a snide comment about everyone else. </p>\n\n<p>Because of this I never use it for non programmer and seldom use it even with experienced programmers. If I do use you can bet I am making a veiled reference to the subject at hand.</p>\n"
},
{
"answer_id": 418311,
"author": "too much php",
"author_id": 28835,
"author_profile": "https://Stackoverflow.com/users/28835",
"pm_score": 1,
"selected": false,
"text": "<p>On top of avoiding nonsensical words like foo & bar, I've found it's much more important to provide code examples for real-world scenarios which have the same relationships. This really helps a learner to understand a topic properly and prevents misunderstandings. E.g., if I'm teaching about Dependency Injection and show example code where an instance of the Car class is injected into the Driver class, no one's going to get confused and think \"So that means the Car controls the Driver then?\".</p>\n"
},
{
"answer_id": 866044,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<p>For totaly new programmer I have to say that terms foo and bar might not be known. I thought that they were something language specific (namely C), but after cheking Wikipedia I now know they are just abstract place holders.\nSo if your audience consist of people who don't know meanings of them, something else is much clearer. Also first_number and so tells that those are numbers how ever they are presented and not something else.</p>\n"
},
{
"answer_id": 11070739,
"author": "Matt Montag",
"author_id": 264970,
"author_profile": "https://Stackoverflow.com/users/264970",
"pm_score": 1,
"selected": false,
"text": "<p>I think there is another important reason for using <code>foo</code> and <code>bar</code> in examples. These names make it clear that you are not invoking any magic keywords. Whenever I am reading some documentation or code examples, I like the arbitrary parts of the example to be clearly distinguished from the necessary parts.</p>\n\n<p>If you substituted the nonsense word for what it generically represents in the example code, you might end up with some names that look a lot like the keywords, classes, or methods you're trying to explain. The \"my\" prefix, as in <code>myNumber</code>, <code>myFunction</code>, is a good compromise that makes names stand out as being arbitrary.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234507",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23909/"
] |
This was something originally discussed during a presentation given by Charles Brian Quinn of the [Big Nerd Ranch](http://www.bignerdranch.com/) at [acts\_as\_conference](http://www.actsasconference.com). He was discussing what he had learned from instructing a Ruby on Rails Bootcamp to many people both new to programming and new to Rails.
One particular slide that stood out was along the lines of **never using foo and bar as examples when trying to teach someone to program**. His reasoning was very simple.
Which is easier to understand?
```
baz = foo + bar
```
or
```
answer = first_number + second_number
```
It's happened many times myself when explaining something and I immediately jump to the go to foo bar placeholders but then realize my mistake and make the example make a lot more sense by using a real world scenario.
This is especially applicable when trying to teach someone who has had no programming exposure and you end up needing explain foo and bar before explaining what you're actually trying to teach.
However, using foo and bar for experienced programmers seems OK, though I personally think, along with Charles, that it's something that needs to change.
A quick SO search for "foo" returns over 20 pages of results with foo being used in more ways that I can comprehend. And in some cases where I'm reading a question on a particular language and I'm doing so to help understand that language better. If applicable variable names are used instead of foo and bar, it makes it much easier to understand and interpret the problem. So for seasoned developers, the construct seems a bit flawed as well.
Is this a habit that will ever be able to be kicked? Why do you choose to foo bar or to not foo bar?
|
It strictly depends on what are you trying to teach. Sometimes, when showing a programming example, you have to declare a few things just for the snippet to be "complete", and those few things are not the core of what you are showing.
For example, if you want to show how to throw an exception, I believe it is ok to present a snippet like
```
public void foo() {
// Do some things
if (errorCondition) {
throw new Exception("Error message");
}
}
```
Since the point in it is showing exceptions, there is no point in caring about the method name, so foo is "legal" in this context, or at least for me.
What I would not accept (in this same example) would be
```
public void foo() {
// Do some things
if (bar) {
throw new Exception(baz);
}
}
```
as it is obscuring what you are trying to teach.
|
234,512 |
<p>I have a string which is like this:</p>
<p>this is [bracket test] "and quotes test "</p>
<p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p>
<p>['this','is','bracket test','and quotes test '] </p>
|
[
{
"answer_id": 234645,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a simplistic solution that works with your test input:</p>\n\n<pre><code>import re\nre.findall('\\[[^\\]]*\\]|\\\"[^\\\"]*\\\"|\\S+',s)\n</code></pre>\n\n<p>This will return any code that matches either </p>\n\n<ul>\n<li>a open bracket followed by zero or more non-close-bracket characters followed by a close bracket, </li>\n<li>a double-quote followed by zero or more non-quote characters followed by a quote,</li>\n<li>any group of non-whitespace characters</li>\n</ul>\n\n<p>This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.</p>\n"
},
{
"answer_id": 234674,
"author": "ddaa",
"author_id": 11549,
"author_profile": "https://Stackoverflow.com/users/11549",
"pm_score": 1,
"selected": false,
"text": "<p>Here's a simplistic parser (tested against your example input) that introduces the State design pattern.</p>\n\n<p>In real world, you probably want to build a real parser using something like <a href=\"http://www.dabeaz.com/ply/\" rel=\"nofollow noreferrer\">PLY</a>.</p>\n\n<pre><code>class SimpleParser(object):\n\n def __init__(self):\n self.mode = None\n self.result = None\n\n def parse(self, text):\n self.initial_mode()\n self.result = []\n for word in text.split(' '):\n self.mode.handle_word(word)\n return self.result\n\n def initial_mode(self):\n self.mode = InitialMode(self)\n\n def bracket_mode(self):\n self.mode = BracketMode(self)\n\n def quote_mode(self):\n self.mode = QuoteMode(self)\n\n\nclass InitialMode(object):\n\n def __init__(self, parser):\n self.parser = parser\n\n def handle_word(self, word):\n if word.startswith('['):\n self.parser.bracket_mode()\n self.parser.mode.handle_word(word[1:])\n elif word.startswith('\"'):\n self.parser.quote_mode()\n self.parser.mode.handle_word(word[1:])\n else:\n self.parser.result.append(word)\n\n\nclass BlockMode(object):\n\n end_marker = None\n\n def __init__(self, parser):\n self.parser = parser\n self.result = []\n\n def handle_word(self, word):\n if word.endswith(self.end_marker):\n self.result.append(word[:-1])\n self.parser.result.append(' '.join(self.result))\n self.parser.initial_mode()\n else:\n self.result.append(word)\n\nclass BracketMode(BlockMode):\n end_marker = ']'\n\nclass QuoteMode(BlockMode):\n end_marker = '\"'\n</code></pre>\n"
},
{
"answer_id": 234855,
"author": "Sanjaya R",
"author_id": 9353,
"author_profile": "https://Stackoverflow.com/users/9353",
"pm_score": -1,
"selected": false,
"text": "<p>Works for quotes only. </p>\n\n<pre><code>rrr = []\nqqq = s.split('\\\"')\n[ rrr.extend( qqq[x].split(), [ qqq[x] ] )[ x%2]) for x in range( len( qqq ) )]\nprint rrr\n</code></pre>\n"
},
{
"answer_id": 234957,
"author": "Kirk Strauser",
"author_id": 32538,
"author_profile": "https://Stackoverflow.com/users/32538",
"pm_score": 0,
"selected": false,
"text": "<p>Here's a more procedural approach:</p>\n\n<pre><code>#!/usr/bin/env python\n\na = 'this is [bracket test] \"and quotes test \"'\n\nwords = a.split()\nwordlist = []\n\nwhile True:\n try:\n word = words.pop(0)\n except IndexError:\n break\n if word[0] in '\"[':\n buildlist = [word[1:]]\n while True:\n try:\n word = words.pop(0)\n except IndexError:\n break\n if word[-1] in '\"]':\n buildlist.append(word[:-1])\n break\n buildlist.append(word)\n wordlist.append(' '.join(buildlist))\n else:\n wordlist.append(word)\n\nprint wordlist\n</code></pre>\n"
},
{
"answer_id": 235412,
"author": "PhE",
"author_id": 31335,
"author_profile": "https://Stackoverflow.com/users/31335",
"pm_score": 3,
"selected": false,
"text": "<p>To complete Bryan post and match exactly the answer :</p>\n\n<pre><code>>>> import re\n>>> txt = 'this is [bracket test] \"and quotes test \"'\n>>> [x[1:-1] if x[0] in '[\"' else x for x in re.findall('\\[[^\\]]*\\]|\\\"[^\\\"]*\\\"|\\S+', txt)]\n['this', 'is', 'bracket test', 'and quotes test ']\n</code></pre>\n\n<p>Don't misunderstand the whole syntax used : This is not several statments on a single line but a single functional statment (more bugproof).</p>\n"
},
{
"answer_id": 238476,
"author": "zvoase",
"author_id": 31600,
"author_profile": "https://Stackoverflow.com/users/31600",
"pm_score": 0,
"selected": false,
"text": "<p>Well, I've encountered this problem quite a few times, which led me to write my own system for parsing any kind of syntax.</p>\n\n<p>The result of this can be found <a href=\"http://gist.github.com/19929\" rel=\"nofollow noreferrer\">here</a>; note that this may be overkill, and it will provide you with something that lets you parse statements with both brackets and parentheses, single and double quotes, as nested as you want. For example, you could parse something like this (example written in Common Lisp):</p>\n\n<pre><code>(defun hello_world (&optional (text \"Hello, World!\"))\n (format t text))\n</code></pre>\n\n<p>You can use nesting, brackets (square) and parentheses (round), single- and double-quoted strings, and it's very extensible.</p>\n\n<p>The idea is basically a configurable implementation of a Finite State Machine which builds up an abstract syntax tree character-by-character. I recommend you look at the source code (see link above), so that you can get an idea of how to do it. It's capable via regular expressions, but try writing a system using REs and then trying to extend it (or even understand it) later.</p>\n"
}
] |
2008/10/24
|
[
"https://Stackoverflow.com/questions/234512",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31256/"
] |
I have a string which is like this:
this is [bracket test] "and quotes test "
I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:
['this','is','bracket test','and quotes test ']
|
Here's a simplistic solution that works with your test input:
```
import re
re.findall('\[[^\]]*\]|\"[^\"]*\"|\S+',s)
```
This will return any code that matches either
* a open bracket followed by zero or more non-close-bracket characters followed by a close bracket,
* a double-quote followed by zero or more non-quote characters followed by a quote,
* any group of non-whitespace characters
This works with your example, but might fail for many real-world strings you may encounter. For example, you didn't say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.