qid int64 4 19.1M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
358,350 | <p>I have a list, and each item is linked, is there a way I can alternate the background colors for each item?</p>
<pre><code><ul>
<li><a href="link">Link 1</a></li>
<li><a href="link">Link 2</a></li>
<li><a href="link">Link 3</a></li>
<li><a href="link">Link 4</a></li>
<li><a href="link">Link 5</a></li>
</ul>
</code></pre>
| [
{
"answer_id": 358357,
"author": "sblundy",
"author_id": 4893,
"author_profile": "https://Stackoverflow.com/users/4893",
"pm_score": -1,
"selected": false,
"text": "li, li + li + li, li + li + li + li + li {\n background-color: black;\n}\n\nli + li, li + li + li + li {\n background-color: white;\n}\n"
},
{
"answer_id": 358358,
"author": "Chris Van Opstal",
"author_id": 7264,
"author_profile": "https://Stackoverflow.com/users/7264",
"pm_score": 3,
"selected": false,
"text": "<ul>\n <li class=\"odd\"><a href=\"link\">Link 1</a></li>\n <li><a href=\"link\">Link 2</a></li>\n <li class=\"odd\"><a href=\"link\">Link 2</a></li>\n <li><a href=\"link\">Link 2</a></li>\n</ul>\n li { backgorund:white; }\nli.odd { background:silver; }\n $(document).ready(function() {\n $('table tbody tr:odd').addClass('odd');\n});\n"
},
{
"answer_id": 358366,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 1,
"selected": false,
"text": "row0 row1 for ($i = 0; $i < 10; ++$i) {\n echo '<tr class=\"row' . ($i % 2) . '\">...</tr>';\n}\n $('table tr:odd').addClass('row1');\n tr li table ul"
},
{
"answer_id": 358368,
"author": "Phil.Wheeler",
"author_id": 15609,
"author_profile": "https://Stackoverflow.com/users/15609",
"pm_score": 6,
"selected": false,
"text": "<ul>\n <li class=\"alternate\"><a href=\"link\">Link 1</a></li>\n <li><a href=\"link\">Link 2</a></li>\n <li class=\"alternate\"><a href=\"link\">Link 3</a></li>\n <li><a href=\"link\">Link 4</a></li>\n <li class=\"alternate\"><a href=\"link\">Link 5</a></li>\n</ul>\n <li> <ul id=\"myList\">\n <li><a href=\"link\">Link 1</a></li>\n <li><a href=\"link\">Link 2</a></li>\n <li><a href=\"link\">Link 3</a></li>\n <li><a href=\"link\">Link 4</a></li>\n <li><a href=\"link\">Link 5</a></li>\n</ul>\n $(document).ready(function(){\n $('#myList li:nth-child(odd)').addClass('alternate');\n});\n"
},
{
"answer_id": 358376,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<ul>\n <li class=\"even\"><a href=\"link\">Link 1</a></li>\n <li class=\"odd\"><a href=\"link\">Link 2</a></li>\n <li class=\"even\"><a href=\"link\">Link 3</a></li>\n <li class=\"odd\"><a href=\"link\">Link 4</a></li>\n <li class=\"even\"><a href=\"link\">Link 5</a></li>\n</ul>\n li.even { background-color: red; }\nli.odd { background-color: blue; }\n"
},
{
"answer_id": 2477586,
"author": "Adam C",
"author_id": 219451,
"author_profile": "https://Stackoverflow.com/users/219451",
"pm_score": 9,
"selected": true,
"text": "li { background: green; }\nli:nth-child(odd) { background: red; }\n"
},
{
"answer_id": 22502488,
"author": "Augusto Triste",
"author_id": 2371734,
"author_profile": "https://Stackoverflow.com/users/2371734",
"pm_score": 1,
"selected": false,
"text": "$(document).ready(function(){\n$('#myList li:nth-child(odd)').addClass('alternate');\n});\n .alternate {\nbackground: black;\n}\n li:nth-child(odd) {\n background: black;\n}\n"
},
{
"answer_id": 48419817,
"author": "Avanish Kumar",
"author_id": 4813631,
"author_profile": "https://Stackoverflow.com/users/4813631",
"pm_score": 2,
"selected": false,
"text": " li:nth-child(odd) { background: #ffffff; }\n li:nth-child(even) { background: #80808030; }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358350",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26130/"
] |
358,387 | <p>Basically what the title says...</p>
<p>I need to have an image that when clicked, I call script.php for instance and in that PHP script file, I get the image coordinates where the mouse was clicked.</p>
<p>Is this possible?</p>
<p><strong>EDIT:</strong><br />
After a couple of answers I realized I didn't describe my problem correctly... The thing is, I don't have total control over the HTML. The control I have for the image and the image link is the control BBCode provides me.</p>
<p>Basically want I want to do is to have a forum signature with links to various sections on my website. You could argue I could use multiple images but most forums limit how much you can type for the signature, which is not enough for multiple images.</p>
<p>So, I will only be able to do something like this:<br /></p>
<pre><code>[url=http://www.mydomain.com/script.php]
[img]http://www.mydomain.com/signature.jpg[/img]
[/url]
</code></pre>
<p>Which translates to something like this:<br /></p>
<pre><code><a href="http://www.mydomain.com/script.php">
<img src="http://www.mydomain.com/signature.jpg" />
</a>
</code></pre>
| [
{
"answer_id": 358401,
"author": "jmucchiello",
"author_id": 44065,
"author_profile": "https://Stackoverflow.com/users/44065",
"pm_score": 2,
"selected": false,
"text": "name=\"foo\" $\\_POST['foo\\_x'] $\\_POST['foo\\_y']"
},
{
"answer_id": 358512,
"author": "recursive",
"author_id": 44743,
"author_profile": "https://Stackoverflow.com/users/44743",
"pm_score": 0,
"selected": false,
"text": "<a href=\"link.html\"><img src=\"shapes.jpg\" alt=\"Shapes\" ismap=\"ismap\"/></a>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358387",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40480/"
] |
358,389 | <p>I just finished watching the Google clean code video on YouTube (see <a href="http://googletesting.blogspot.com/" rel="nofollow noreferrer">link</a>, first article) about removing <code>if</code> statements from your code and using polymorphism instead. </p>
<p>After watching the video I had a look at some code that I was writing before watching the video and noticed some places where I could use this method, mainly places where the same kind of logic was implemented many times. So a example:</p>
<p>I have some code like this.</p>
<pre><code>public int Number
{
get
{
string returnValue;
if (this.internalTableNumber == null)
returnValue = this.RunTableInfoCommand(internalTableName,
TableInfoEnum.TAB_INFO_NUM);
else
returnValue = this.RunTableInfoCommand(internalTableNumber.Value,
TableInfoEnum.TAB_INFO_NUM);
return Convert.ToInt32(returnValue);
}
}
</code></pre>
<p>What RunTableInfoCommand does isn't really important,but the main thing is that I have many properties with exactly the same <code>if</code> statments the only thing that changes is the TableInfoEnum.</p>
<p>I was wondering if someone could help me refactor this so that it still does the same thing but without any <code>if</code> statements?</p>
| [
{
"answer_id": 358403,
"author": "Andrew Kennan",
"author_id": 22506,
"author_profile": "https://Stackoverflow.com/users/22506",
"pm_score": 0,
"selected": false,
"text": "public class Thing\n{\n public IValueFetcher ValueFetcher { get; set; }\n\n public int Number \n { \n get \n {\n return this.ValueFetcher.GetValue<int>(/* parameters to identify the value to fetch */);\n }\n }\n}\n"
},
{
"answer_id": 358404,
"author": "Vincent Ramdhanie",
"author_id": 27439,
"author_profile": "https://Stackoverflow.com/users/27439",
"pm_score": 2,
"selected": false,
"text": "public int Number\n {\n get\n {\n\n return this.tableInfoCommand.runTableInfoCommand();\n }\n }\n"
},
{
"answer_id": 358409,
"author": "sven",
"author_id": 46,
"author_profile": "https://Stackoverflow.com/users/46",
"pm_score": 0,
"selected": false,
"text": "internTableName InternalTableNumber this.RunTableInfoCommand public int Number\n {\n get\n {\n string returnValue;\n internalTableClass myinstance(parameters);\n return Convert.ToInt32(this.RunTableInfoCommand(myinstance, TableInfoEnum.TAB_INFO_NUM));\n }\n }\n giveInternalTableIdentifier public int Number\n {\n get\n {\n string returnValue;\n internalTableClass myinstance(parameters);\n return Convert.ToInt32(this.RunTableInfoCommand(myinstance.giveInternalTableIdentifier, TableInfoEnum.TAB_INFO_NUM));\n }\n }\n"
},
{
"answer_id": 358414,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 0,
"selected": false,
"text": " private int? internalTableNumber;\n private int InternalTableNumber\n {\n get\n {\n if (!internalTableNumber.HasValue)\n {\n internalTableNumber = GetValueFromTableName( internalTableName );\n }\n return internalTableNumber;\n }\n set\n {\n internalTableNumber = value;\n }\n }\n\n public int Number\n {\n get\n {\n string value = this.RunTableInfoCommand(InternalTableNumber,\n TableInfoEnum.TAB_INFO_NUM);\n return Convert.ToInt32( value );\n }\n }\n public interface IFoo\n{\n int Number { get; }|\n\n}\n\npublic class FooWithName : IFoo\n{\n private string tableName;\n public FooWithName( string name )\n {\n this.tableName = name;\n }\n\n public int Number\n {\n get { return this.RunTableInfoCommand(this.tableName,\n TableInfoEnum.TAB_INFO_NUM);\n }\n\n ... rest of class, including RunTableInfoCommand(string,int);\n}\n\npublic class FooWithNumber : IFoo\n{\n private int tableNumber;\n public FooWithNumber( int number )\n {\n this.tableNumber = number;\n }\n\n public int Number\n {\n get { return this.RunTableInfoCommand(this.tableNumber,\n TableInfoEnum.TAB_INFO_NUM);\n }\n\n ... rest of class, including RunTableInfoCommand(int,int);\n}\n IFoo foo;\n\nif (tableNumber.HasValue)\n{\n foo = new FooWithNumber( tableNumber.Value );\n}\nelse\n{\n foo = new FooWithName( tableName );\n}\n\nint number = foo.Number;\n"
},
{
"answer_id": 358418,
"author": "ieure",
"author_id": 45224,
"author_profile": "https://Stackoverflow.com/users/45224",
"pm_score": 0,
"selected": false,
"text": "table = this.internalTableNumber == null ? internalTableName : internalTableNumber.Value;\nreturn Convert.ToInt32(this.RunTableInfoCommand(table, TableInfoEnum.TAB_INFO_NUM));\n"
},
{
"answer_id": 358472,
"author": "Michael Burr",
"author_id": 12711,
"author_profile": "https://Stackoverflow.com/users/12711",
"pm_score": 0,
"selected": false,
"text": "RunTableInfoCommand() RunTableInfoCommand() internalTableNumber internalTableName RunTableInfoCommand() TableInfoEnum RunTableInfoCommand() private string RunTableInfoCommand( TableInfoEnum infoEnum)\n{\n if (this.internalTableNumber == null) {\n return this.RunTableInfoCommand( internalTableName, infoEnum);\n }\n\n return this.RunTableInfoCommand( internalTableNumber.Value, infoEnum);\n}\n if returnValue = this.RunTableInfoCommand( TableInfoEnum.TAB_INFO_NUM); \n // or whatever enum is appropriate\n"
},
{
"answer_id": 358555,
"author": "Steven A. Lowe",
"author_id": 9345,
"author_profile": "https://Stackoverflow.com/users/9345",
"pm_score": 0,
"selected": false,
"text": "(internalTableNumber == null) ==> \n internalTableName else internalTableNumber.Value\n public int Number\n{\n get\n {\n return iTable.RunTableInfoCommand(TableInfoEnum.TAB_INFO_NUM);\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358389",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6335/"
] |
358,397 | <p><strong>Is it possible for some Javascript to detect whether Skype is installed or not?</strong></p>
<p>The reason I ask is that I'd like to change a link's href based on that: if Skype isn't installed, show a popup explaining what Skype is and how to install it, if it is installed, change the link to <code>skype:my.contact.name?call</code> so the click will start a call. Real estate issues means that I'd prefer to only have one link shown.</p>
| [
{
"answer_id": 358421,
"author": "some",
"author_id": 36866,
"author_profile": "https://Stackoverflow.com/users/36866",
"pm_score": 3,
"selected": false,
"text": "function isSkypeInstalled(str) {\n try {\n /*@cc_on\n //The Microsoft way, thanks to the conditional comments only run in IE\n if (new ActiveXObject(\"Skype.Detection\")) return true;\n @*/\n\n //Tested for firefox on win\n if (navigator.mimeTypes[\"application/x-skype\"]) return true;\n }\n catch(e){}\n return false;\n}\n"
},
{
"answer_id": 358427,
"author": "KristoferA",
"author_id": 11241,
"author_profile": "https://Stackoverflow.com/users/11241",
"pm_score": 2,
"selected": false,
"text": "<SPAN onmouseup=\"..\" class=\"skype_tb_injection\" onmousedown=\"...\" id=\"softomate_highlight_0\" onmouseover=\"...\" title=\"Call this phone number in Thailand with Skype: +66812341234\" onclick=\"...\" onmouseout=\"...\" durex=\"0\" context=\"+66 8 1234 1234\" IamRTL=\"0\">\n <SPAN class=\"skype_tb_nop\"> </SPAN>\n <SPAN onmouseup=\"...\" class=\"skype_tb_imgA_flex\" onmousedown=\"...\" id=\"skype_tb_droppart_0\" onmouseover=\"...\" title=\"Skype actions\" style=\"...\" onclick=\"...\" onmouseout=\"...\">\n \n <SPAN class=\"skype_tb_nop\"> </SPAN>\n <SPAN class=\"skype_tb_imgFlag\" id=\"skype_tb_img_f0\" style=\"...\"> </SPAN>\n \n <SPAN class=\"skype_tb_nop\"> </SPAN>\n </SPAN>\n <SPAN class=\"skype_tb_imgS\" id=\"skype_tb_img_s0\" style=\"...\"> </SPAN>\n <SPAN class=\"skype_tb_injectionIn\" id=\"skype_tb_text0\" style=\"...\">\n <SPAN class=\"skype_tb_innerText\" id=\"skype_tb_innerText0\"> +6...</SPAN>\n </SPAN>\n <SPAN class=\"skype_tb_imgR\" id=\"skype_tb_img_r0\" style=\"...\"> \n <SPAN class=\"skype_tb_nop\"> </SPAN>\n </SPAN>\n</SPAN>\n"
},
{
"answer_id": 358553,
"author": "nickf",
"author_id": 9021,
"author_profile": "https://Stackoverflow.com/users/9021",
"pm_score": 5,
"selected": false,
"text": "jQuery.extend({\n skype : function(failureFunction) {\n var $ = jQuery;\n\n if ($.browser.safari || $.browser.opera) {\n return true;\n } else if ($.browser.msie) {\n try {\n if (new ActiveXObject(\"Skype.Detection\")) return true;\n } catch(e) { }\n } else {\n if (typeof(navigator.mimeTypes[\"application/x-skype\"]) == \"object\") {\n return true;\n }\n }\n $('a[href^=\"skype:\"]').click(function() {\n failureFunction();\n return false;\n });\n return false;\n }\n});\n <a href=\"skype:your.skype.username?call\">Call me</a>\n<a href=\"skype:your.skype.username?add\">Add me</a>\n jQuery(function($) {\n $.skype(function() {\n // this function gets called if they don't have skype.\n alert(\"Looks like you don't have skype. Bummer.\");\n });\n});\n $.skype"
},
{
"answer_id": 2295382,
"author": "gu.",
"author_id": 276860,
"author_profile": "https://Stackoverflow.com/users/276860",
"pm_score": 0,
"selected": false,
"text": "<a href=\"callto:<phone_number>\"><phone_number></a>\n"
},
{
"answer_id": 10935842,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "<!-- the links -->\n<a href=\"tel:+15035551212\" data-skype=\"yourskypeusername\" title=\"Call\">Call</a>\n\n/* the javascript*/\nfunction hasSkype() {\n if ($.browser.safari || $.browser.opera) {\n return true;\n } else if ($.browser.msie) {\n try {\n if (new ActiveXObject(\"Skype.Detection\")) return true;\n } catch(e) { }\n } else {\n if (typeof(navigator.mimeTypes[\"application/x-skype\"]) == \"object\") {\n return true;\n }\n }\n return false;\n}\n\n$('a[href^=\"tel:\"]').each(function() {\n if(hasSkype()) {\n // if Skype is available, update the link to use Skype\n $(this).attr('href','skype:'+$(this).attr('data-skype')+'?call');\n }\n});\n"
},
{
"answer_id": 25542180,
"author": "Egor Kashlinov",
"author_id": 3985514,
"author_profile": "https://Stackoverflow.com/users/3985514",
"pm_score": 0,
"selected": false,
"text": "mimeTypes navigator.mimeTypes navigator.mimeTypes jQuery.extend({checkPlugin: function(mimetype_substr) {\n for (var i = 0; i < navigator.mimeTypes.length; i++) {\n if (navigator.mimeTypes[i]['type'].toLowerCase().indexOf(mimetype_substr) >= 0) {\n console.log(\"Gotcha! Here it is: \"+navigator.mimeTypes[i]['type']);\n return true;\n }\n }\n return false;\n}});\n $.checkPlugin(\"skype\"); true false navigator.plugins navigator.mimeTypes"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358397",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9021/"
] |
358,398 | <p>I have a class called myClass which defines post() and get() methods. </p>
<p>From <em>index.html</em>, I have a form with an action that calls myClass.post() which grabs some data from the data base, sets a couple variables and sends the user to <em>new.html</em>. </p>
<p>now, <em>new.html</em> has a form which calls myClass.get(). </p>
<p><strong>I want the get() method to know the value of the variables I got in post().</strong> That is is main point here.</p>
<p>I figure the submit from new.html creates a separate instance of myClass created by the submit from index.html. </p>
<p>Is there a way to access the "post instance" somehow? </p>
<p>Is there a workaround for this? If I have to, is there an established way to send the value from post to "new.html" and send it back with the get-submit? </p>
<p>more generally, I guess I don't understand the life of my instances when web-programming. In a normal interactive environment, I know when the instance is created and destroyed, but I don't get that when I'm only using the class through calls to its methods. Are those classes even instantiated unless their methods are called? </p>
| [
{
"answer_id": 358613,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 1,
"selected": false,
"text": "def save_foo(request):\n if request.method == 'POST':\n save(request.POST)\n return HttpRedirect(reverse(\n 'Some_Target',\n {'bar': 'baz', 'foo': request.POST['foo']}))\n else:\n # do something else\n Some_Target foo cookies"
},
{
"answer_id": 359034,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 2,
"selected": false,
"text": "?sessionid=SomeSessionGUID"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1179/"
] |
358,410 | <p>Can anybody let me know the query to find all the tables that has a date columns on it.</p>
<p>Thanks</p>
| [
{
"answer_id": 358424,
"author": "RobS",
"author_id": 18471,
"author_profile": "https://Stackoverflow.com/users/18471",
"pm_score": 4,
"selected": false,
"text": " select distinct c.TABLE_NAME \n from INFORMATION_SCHEMA.COLUMNS as c\n where c.DATA_TYPE = 'datetime'\n select tbl.name as 'Table', c.name as 'Column Name', t.name as 'Type'\nfrom sys.columns as c\ninner join sys.tables as tbl\non tbl.object_id = c.object_id\ninner join sys.types as t\non c.system_type_id = t.system_type_id\nwhere t.name in ('datetime', 'date')\norder by tbl.name\n"
},
{
"answer_id": 358433,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 5,
"selected": false,
"text": "select\n so.name table_name\n ,sc.name column_name\n ,st.name data_type\nfrom sysobjects so\ninner join syscolumns sc on (so.id = sc.id)\ninner join systypes st on (st.type = sc.type)\nwhere so.type = 'U'\nand st.name IN ('DATETIME', 'DATE', 'TIME', 'SMALLDATETIME')\n"
},
{
"answer_id": 9512970,
"author": "Misiu",
"author_id": 965722,
"author_profile": "https://Stackoverflow.com/users/965722",
"pm_score": 0,
"selected": false,
"text": "SELECT\n DISTINCT OBJECT_NAME(col.OBJECT_ID) AS [TableName]\nFROM\n sys.all_columns col\n INNER JOIN sys.types typ\n ON col.user_type_id = typ.user_type_id\nWHERE\n col.user_type_id IN (61)\n SELECT\n OBJECT_NAME(col.OBJECT_ID) AS [TableName]\n ,col.[name] AS [ColName]\n ,typ.[name] AS [TypeName]\nFROM\n sys.all_columns col\n INNER JOIN sys.types typ\n ON col.user_type_id = typ.user_type_id\nWHERE\n col.user_type_id IN (61)\n AND\n OBJECT_NAME(col.OBJECT_ID) = 'TABLE_NAME'\n"
},
{
"answer_id": 11191776,
"author": "HKM",
"author_id": 1001349,
"author_profile": "https://Stackoverflow.com/users/1001349",
"pm_score": 2,
"selected": false,
"text": "select s.name as 'SchemaName',\ntbl.name as 'Table', c.name as 'Column Name', t.name as 'Type'\nfrom sys.columns as c\ninner join sys.tables as tbl\non tbl.object_id = c.object_id\ninner join sys.types as t\non c.system_type_id = t.system_type_id\ninner join sys.schemas s\non tbl.schema_id = s.schema_id\nwhere t.name in ('datetime', 'date')\norder by s.name, tbl.name\n"
},
{
"answer_id": 19643986,
"author": "ManOVision",
"author_id": 1152738,
"author_profile": "https://Stackoverflow.com/users/1152738",
"pm_score": 4,
"selected": false,
"text": "SELECT TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, COLUMN_NAME, DATA_TYPE\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE DATA_TYPE LIKE '%date%' OR DATA_TYPE LIKE '%time%'\n"
},
{
"answer_id": 57571774,
"author": "Divyesh Jani",
"author_id": 5859743,
"author_profile": "https://Stackoverflow.com/users/5859743",
"pm_score": 1,
"selected": false,
"text": "SELECT DISTINCT(TABLE_NAME) \nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE \nDATA_TYPE='datetime'\n SELECT DISTINCT(TABLE_NAME) \nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE \nDATA_TYPE IN ('datatype1','datatype2')\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358410",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,430 | <p>I want to implement a simple 2 part FormWizard.
Form 1 will by dynamically generated something like this:</p>
<pre><code>class BuyAppleForm(forms.Form):
creditcard = forms.ChoiceField(widget = forms.RadioSelect)
type = forms.ChoiceField(widget = forms.RadioSelect)
def __init__(self,*args, **kwargs):
user = kwargs['user']
del kwargs['user']
super(BuyAppleForm, self).__init__(*args, **kwargs)
credit_cards = get_credit_cards(user)
self.fields['creditcard'].choices = [(card.id,str(card)) for card in credit_cards]
apple_types= get_types_packages()
self.fields['type'].choices = [(type.id,str(type)) for type in apple_types]
</code></pre>
<p>This will dynamically create a form with lists of available choices.</p>
<p>My second form, I actually want no input. I just want to display a confirmation screen containing the credit card info, apple info, and money amounts (total, tax, shipping). Once user clicks OK, I want the apple purchase to commence.</p>
<p>I was able to implement the single form way by passing in the request.user object in the kwargs. However, with the FormWizard, I cannot figure this out.</p>
<p>Am I approaching the problem wrong and is the FormWizard not the proper way to do this? If it is, how can the Form <code>__init__</code> method access the user object from the HTTP request? </p>
| [
{
"answer_id": 358556,
"author": "Krystian Cybulski",
"author_id": 45226,
"author_profile": "https://Stackoverflow.com/users/45226",
"pm_score": 1,
"selected": true,
"text": "buy_apples buy_apples_confirm buy_apples_confirm"
},
{
"answer_id": 4858044,
"author": "Zak Patterson",
"author_id": 597745,
"author_profile": "https://Stackoverflow.com/users/597745",
"pm_score": 2,
"selected": false,
"text": "def form_setup(**kwargs):\n def makeform(data, prefix=None, initial=None):\n form = FormLev2(data, prefix, initial)\n for k, v in kwargs.items():\n if k == 'some_list':\n form.fields['some_list'].choices = v\n ...\n return form\n return makeform\n def process_step(self, request, process, step):\n if step == 1\n if form.is_valid(): #form from step 1\n objs = Table.objects.filter(...) #based on last form \n self.form_list[1] = form_setup(some_list=[(o.id,o.name) for o in objs]) #(*)\n ...\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358430",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45226/"
] |
358,443 | <p>I'm trying to get some WPF concepts down, so I've put together a simple example of what I'm trying to do. I would like to set a custom property of a user control, and have it be used by an element within the control.</p>
<p>I've been researching and experimenting, but I'm not fully understanding everything here. Any help would be appreciated.</p>
<p>The user control for this example is a simple square with a circle inside of it:</p>
<pre><code><UserControl x:Class="CircleInSquare"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="100" Height="100" >
<Grid Background="#000000">
<Ellipse Name="Circle"
Margin="10"
Fill="?????????"
>
</Ellipse>
</Grid>
</UserControl>
</code></pre>
<p>The VB Code Behind it:</p>
<pre><code>Partial Public Class CircleInSquare
Private _CircleColor As Color
Public Property CircleColor() As Color
Get
Return _CircleColor
End Get
Set(ByVal value As Color)
_CircleColor = value
End Set
End Property
End Class
</code></pre>
<p>When I use this user control, how can I apply a CircleColor to the control, and have it be shown as the Ellipse's fill color? Even better... can I give it a default color that shows up in the VS2008 Designer?</p>
<p>So... if I place one of these into my window XAML like this:</p>
<pre><code><app:CircleInSquare CircleColor="Blue" />
</code></pre>
<p>I would like the circle to display as Blue (or any other color I choose for that instance)</p>
| [
{
"answer_id": 358458,
"author": "bendewey",
"author_id": 37881,
"author_profile": "https://Stackoverflow.com/users/37881",
"pm_score": 0,
"selected": false,
"text": "<Ellipse app:CircleInSquare.CircleColor=\"Blue\" />\n"
},
{
"answer_id": 358535,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": " <Ellipse Name=\"Circle\"\n Margin=\"10\"\n Fill=\"{Binding Path= CircleColor}\"\n >\n </Ellipse>\n"
},
{
"answer_id": 359603,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 0,
"selected": false,
"text": "Public Shared ReadOnly MouseOverBrushProperty As DependencyProperty = DependencyProperty.Register(\"MouseOverBrush\", GetType(Brush), GetType(BrushableComboBox), New UIPropertyMetadata())\nPublic Property MouseOverBrush() As Brush\n Get\n Return CType(GetValue(MouseOverBrushProperty), Brush)\n End Get\n Set(ByVal value As Brush)\n SetValue(MouseOverBrushProperty, value)\n End Set\nEnd Property\n Background=\"{TemplateBinding MouseOverBrush}\"\n <Style TargetType=\"{x:Type local:BrushableComboBox}\">\n <Setter Property=\"MouseOverBrush\" Value=\"Blue\" />\n ...\n"
},
{
"answer_id": 360700,
"author": "bendewey",
"author_id": 37881,
"author_profile": "https://Stackoverflow.com/users/37881",
"pm_score": 3,
"selected": true,
"text": "<Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:WpfApplicationVB1\"\n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Grid>\n <app:CircleInSquare Height=\"50\" Width=\"50\" CircleColor=\"Blue\" SquareColor=\"Red\" />\n </Grid>\n</Window>\n Partial Public Class CircleInSquare\n Public Property CircleColor() As Brush\n Get\n Return GetValue(CircleColorProperty)\n End Get\n\n Set(ByVal value As Brush)\n SetValue(CircleColorProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly CircleColorProperty As DependencyProperty = _\n DependencyProperty.Register(\"CircleColor\", _\n GetType(Brush), GetType(CircleInSquare), _\n New FrameworkPropertyMetadata(Brushes.Black))\n\n\n Public Property SquareColor() As Brush\n Get\n Return GetValue(SquareColorProperty)\n End Get\n\n Set(ByVal value As Brush)\n SetValue(SquareColorProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly SquareColorProperty As DependencyProperty = _\n DependencyProperty.Register(\"SquareColor\", _\n GetType(Brush), GetType(CircleInSquare), _\n New FrameworkPropertyMetadata(Brushes.Gray))\n\nEnd Class\n <UserControl x:Class=\"CircleInSquare\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:app=\"clr-namespace:WpfApplicationVB1\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <UserControl.Template>\n <ControlTemplate>\n <Border x:Name=\"PART_Square\" Height=\"{TemplateBinding Height}\" Width=\"{TemplateBinding Width}\" Background=\"{TemplateBinding app:CircleInSquare.SquareColor}\">\n <Ellipse x:Name=\"PART_Ellipse\" Height=\"{TemplateBinding Height}\"\n Width=\"{TemplateBinding Width}\" Fill=\"{TemplateBinding app:CircleInSquare.CircleColor}\" />\n </Border>\n </ControlTemplate>\n </UserControl.Template>\n</UserControl>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/641985/"
] |
358,449 | <p>When using ASP.NET protected configuration, how can I encrypt the config with just the public key?</p>
<p>I can export a public key file. I would like to then use this public key to encrypt the configuration files on another server for later deployment. However, I can't figure out how to get aspnet_regiis to use the exported public key.</p>
<p>Basically, I tried importing just the public key into a container, and then encrypt it. However, when I do that, instead of using the existing key to encrypt, it creates an entirely new key pair, overwriting the existing public key. In the script below, if you rename each of the copied files back to connections.config, and try to decrypt them, the first one (connectionstring_server.encrypted) will fail, while the second (connectionstring_build.encrypted) will succeed), proving that a new keypair was created.</p>
<p>Here is a batch file that demonstrates the approach I have tried (edit: this is just an example to test the aspnet_regiis capabilities. My actual usage of it would, obviously, be slightly different) :</p>
<pre><code>REM delete container in case it already exists
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pz "MyKeys"
REM create container
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pc "MyKeys"
REM export key
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -px "MyKeys" "publicKey.xml"
REM encrypt file
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" . -prov "MyProvider"
REM copy encrypted file for later comparison
copy connections.config connectionstring_server.encrypted
pause
REM decrypt file
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pdf "connectionStrings" .
REM delete continer
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pz "MyKeys"
REM import public key
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pi "MyKeys" publicKey.xml
REM encrypt file with just public key - THIS DOES NOT WORK CORRECTLY, it creates a new keypair
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pef "connectionStrings" . -prov "MyProvider"
REM copy back encrypted file
copy connections.config connectionstring_build.encrypted
pause
REM decrypt file
\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_regiis -pdf "connectionStrings" .
</code></pre>
<p>And here is a sample web.config</p>
<pre><code><?xml version="1.0"?>
<configuration>
<configProtectedData>
<providers>
<add name="MyProvider" keyContainerName="MyKeys" type="System.Configuration.RsaProtectedConfigurationProvider, System.Configuration, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" useMachineContainer="true" />
</providers>
</configProtectedData>
<connectionStrings configSource="connections.config" />
</configuration>
</code></pre>
<p>And the corresponding connections.config:</p>
<pre><code><connectionStrings>
<add name="SomConnectionName" connectionString="Data Source=somedatasource; Initial Catalog=somedatabase; Integrated Security=SSPI; Persist Security Info=False;" providerName="System.Data.SqlClient" />
</connectionStrings>
</code></pre>
<p><strong>Edit:</strong>
Answer suggested below that I could export the private key as well. That would indeed allow the encryption to work, but I shouldn't need the private key to encrypt. What I want to do is leave the private key just on the server that will use the config file, and store the public key in a more accessible place. Is the inability to do this simply a limitation of aspnet_regiis?</p>
| [
{
"answer_id": 358458,
"author": "bendewey",
"author_id": 37881,
"author_profile": "https://Stackoverflow.com/users/37881",
"pm_score": 0,
"selected": false,
"text": "<Ellipse app:CircleInSquare.CircleColor=\"Blue\" />\n"
},
{
"answer_id": 358535,
"author": "Jobi Joy",
"author_id": 8091,
"author_profile": "https://Stackoverflow.com/users/8091",
"pm_score": 0,
"selected": false,
"text": " <Ellipse Name=\"Circle\"\n Margin=\"10\"\n Fill=\"{Binding Path= CircleColor}\"\n >\n </Ellipse>\n"
},
{
"answer_id": 359603,
"author": "Bryan Anderson",
"author_id": 21186,
"author_profile": "https://Stackoverflow.com/users/21186",
"pm_score": 0,
"selected": false,
"text": "Public Shared ReadOnly MouseOverBrushProperty As DependencyProperty = DependencyProperty.Register(\"MouseOverBrush\", GetType(Brush), GetType(BrushableComboBox), New UIPropertyMetadata())\nPublic Property MouseOverBrush() As Brush\n Get\n Return CType(GetValue(MouseOverBrushProperty), Brush)\n End Get\n Set(ByVal value As Brush)\n SetValue(MouseOverBrushProperty, value)\n End Set\nEnd Property\n Background=\"{TemplateBinding MouseOverBrush}\"\n <Style TargetType=\"{x:Type local:BrushableComboBox}\">\n <Setter Property=\"MouseOverBrush\" Value=\"Blue\" />\n ...\n"
},
{
"answer_id": 360700,
"author": "bendewey",
"author_id": 37881,
"author_profile": "https://Stackoverflow.com/users/37881",
"pm_score": 3,
"selected": true,
"text": "<Window x:Class=\"Window1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:app=\"clr-namespace:WpfApplicationVB1\"\n Title=\"Window1\" Height=\"300\" Width=\"300\">\n <Grid>\n <app:CircleInSquare Height=\"50\" Width=\"50\" CircleColor=\"Blue\" SquareColor=\"Red\" />\n </Grid>\n</Window>\n Partial Public Class CircleInSquare\n Public Property CircleColor() As Brush\n Get\n Return GetValue(CircleColorProperty)\n End Get\n\n Set(ByVal value As Brush)\n SetValue(CircleColorProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly CircleColorProperty As DependencyProperty = _\n DependencyProperty.Register(\"CircleColor\", _\n GetType(Brush), GetType(CircleInSquare), _\n New FrameworkPropertyMetadata(Brushes.Black))\n\n\n Public Property SquareColor() As Brush\n Get\n Return GetValue(SquareColorProperty)\n End Get\n\n Set(ByVal value As Brush)\n SetValue(SquareColorProperty, value)\n End Set\n End Property\n\n Public Shared ReadOnly SquareColorProperty As DependencyProperty = _\n DependencyProperty.Register(\"SquareColor\", _\n GetType(Brush), GetType(CircleInSquare), _\n New FrameworkPropertyMetadata(Brushes.Gray))\n\nEnd Class\n <UserControl x:Class=\"CircleInSquare\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:app=\"clr-namespace:WpfApplicationVB1\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\">\n <UserControl.Template>\n <ControlTemplate>\n <Border x:Name=\"PART_Square\" Height=\"{TemplateBinding Height}\" Width=\"{TemplateBinding Width}\" Background=\"{TemplateBinding app:CircleInSquare.SquareColor}\">\n <Ellipse x:Name=\"PART_Ellipse\" Height=\"{TemplateBinding Height}\"\n Width=\"{TemplateBinding Width}\" Fill=\"{TemplateBinding app:CircleInSquare.CircleColor}\" />\n </Border>\n </ControlTemplate>\n </UserControl.Template>\n</UserControl>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358449",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24954/"
] |
358,457 | <p>I think I shall reframe my question from </p>
<p>Where should you use BlockingQueue Implementations instead of Simple Queue Implementations ?</p>
<p>to </p>
<p><strong>What are the advantages/disadvantages of BlockingQueue over Queue implementations taking into consideration aspects like speed,concurrency or other properties which vary e.g. time to access last element.</strong></p>
<p>I have used both kind of Queues. I know that Blocking Queue is normally used in concurrent application. I was writing simple ByteBuffer pool where I needed some placeholder for ByteBuffer objects. I needed fastest , thread safe queue implementation. Even there are List implementations like ArrayList which has constant access time for elements.</p>
<p>Can anyone discuss about pros and cons of BlockingQueue vs Queue vs List implementations?</p>
<p>Currently I have used ArrayList to hold these ByteBuffer objects.</p>
<p><strong>Which data structure shall I use to hold these objects?</strong></p>
| [
{
"answer_id": 358464,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "BlockingQueue BlockingQueue ThreadPoolExecutor"
},
{
"answer_id": 358558,
"author": "erickson",
"author_id": 3474,
"author_profile": "https://Stackoverflow.com/users/3474",
"pm_score": 6,
"selected": true,
"text": "BlockingQueue OutOfMemoryError LinkedBlockingQueue ConcurrentLinkedQueue LinkedBlockingQueue take poll ConcurrentLinkedQueue ArrayList LinkedList ArrayList"
},
{
"answer_id": 45791041,
"author": "atish shimpi",
"author_id": 1245337,
"author_profile": "https://Stackoverflow.com/users/1245337",
"pm_score": 2,
"selected": false,
"text": "Queue Queue Blocking Queue"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358457",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45232/"
] |
358,471 | <p>I am writing a program that requires the use of XMODEM to transfer data from a sensor device. I'd like to avoid having to write my own XMODEM code, so I was wondering if anyone knew if there was a python XMODEM module available anywhere?</p>
| [
{
"answer_id": 705300,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "def xmodem_send(serial, file):\nt, anim = 0, '|/-\\\\'\nserial.setTimeout(1)\nwhile 1:\n if serial.read(1) != NAK:\n t = t + 1\n print anim[t%len(anim)],'\\r',\n if t == 60 : return False\n else:\n break\n\np = 1\ns = file.read(128)\nwhile s:\n s = s + '\\xFF'*(128 - len(s))\n chk = 0\n for c in s:\n chk+=ord(c)\n while 1:\n serial.write(SOH)\n serial.write(chr(p))\n serial.write(chr(255 - p))\n serial.write(s)\n serial.write(chr(chk%256))\n serial.flush()\n\n answer = serial.read(1)\n if answer == NAK: continue\n if answer == ACK: break\n return False\n s = file.read(128)\n p = (p + 1)%256\n print '.',\nserial.write(EOT)\nreturn True\n"
},
{
"answer_id": 5196623,
"author": "Artem Zankovich",
"author_id": 436980,
"author_profile": "https://Stackoverflow.com/users/436980",
"pm_score": 2,
"selected": false,
"text": "import serial\ntry:\n from cStringIO import StringIO\nexcept:\n from StringIO import StringIO\nfrom xmodem import XMODEM, NAK\nfrom time import sleep\n\ndef readUntil(char = None):\n def serialPortReader():\n while True:\n tmp = port.read(1)\n if not tmp or (char and char == tmp):\n break\n yield tmp\n return ''.join(serialPortReader())\n\ndef getc(size, timeout=1):\n return port.read(size)\n\ndef putc(data, timeout=1):\n port.write(data)\n sleep(0.001) # give device time to prepare new buffer and start sending it\n\nport = serial.Serial(port='COM5',parity=serial.PARITY_NONE,bytesize=serial.EIGHTBITS,stopbits=serial.STOPBITS_ONE,timeout=0,xonxoff=0,rtscts=0,dsrdtr=0,baudrate=115200)\nport.write(\"command that initiates xmodem send from device\\r\\n\")\nsleep(0.02) # give device time to handle command and start sending response\nreadUntil(NAK)\nbuffer = StringIO()\nXMODEM(getc, putc).recv(buffer, crc_mode = 0, quiet = 1)\ncontents = buffer.getvalue()\nbuffer.close()\nreadUntil()\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,495 | <p>I have designing the TabMenu Like following</p>
<pre><code><script type="text/javascript">
$(function() {
$('#container-1').tabs();
$('#container-2').tabs();
}
</script>
.....
<div id="container-1">
<ul>
<li><a href="#fragment-1"><span id="start">First</span></a></li>
</ul>
</div>
<div id="container-2">
<ul>
<li><a href="#fragment-1"><span id="end">Last</span></a></li>
</ul>
</div>
.....
</code></pre>
<p>Is it possible to get the ClickedTab data, instead of the index? Like if ClickTab is first then <code>#fragment1</code>. Else if ClickTab is last, <code>#fragment2</code>.</p>
<p>How can I do this?</p>
| [
{
"answer_id": 358508,
"author": "ChadT",
"author_id": 23300,
"author_profile": "https://Stackoverflow.com/users/23300",
"pm_score": 1,
"selected": false,
"text": "<li><a href=\"#fragment-1\"><span id=\"end\">Last</span></a></li>\n <li><a href=\"#fragment-2\"><span id=\"end\">Last</span></a></li>\n $('.ui-tabs-nav').bind('tabsselect', function(event, ui) {\n//ui.panel is a dom element that contains the contents of the clicked tab.\n}\n"
},
{
"answer_id": 359486,
"author": "Manik",
"author_id": 41381,
"author_profile": "https://Stackoverflow.com/users/41381",
"pm_score": 0,
"selected": false,
"text": " $(document).ready(function() {\n $('#container-1').tabs({\n selected : function(e, ui) {\n if ($($(\"a\", e.target).get(ui.index)).attr('href') == '#fragment-1') {\n alert('First clicked!');\n }\n } \n }); \n });\n ....\n <div id=\"container-1\">\n <ul>\n <li><a href=\"#fragment-1\"><span>Home</span></a></li>\n <li><a href=\"#fragment-2\"><span>Contact</span></a></li>\n\n </ul>\n </div>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358495",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44984/"
] |
358,500 | <p>I want to select a blob col from one table, base64 encode it and insert it into another tables. Is there any way to do this without round tripping the data out of the DB and through my app?</p>
| [
{
"answer_id": 7088614,
"author": "lepe",
"author_id": 196507,
"author_profile": "https://Stackoverflow.com/users/196507",
"pm_score": 3,
"selected": false,
"text": "sys_eval(CONCAT(\"echo '\",myField,\"' | base64\"));\n"
},
{
"answer_id": 12138609,
"author": "WOLFF",
"author_id": 1627144,
"author_profile": "https://Stackoverflow.com/users/1627144",
"pm_score": 4,
"selected": false,
"text": "DELIMITER $$\n\nUSE `YOUR DATABASE`$$\n\nDROP TABLE IF EXISTS core_base64_data$$\nCREATE TABLE core_base64_data (c CHAR(1) BINARY, val TINYINT)$$\nINSERT INTO core_base64_data VALUES \n('A',0), ('B',1), ('C',2), ('D',3), ('E',4), ('F',5), ('G',6), ('H',7), ('I',8), ('J',9),\n('K',10), ('L',11), ('M',12), ('N',13), ('O',14), ('P',15), ('Q',16), ('R',17), ('S',18), ('T',19),\n('U',20), ('V',21), ('W',22), ('X',23), ('Y',24), ('Z',25), ('a',26), ('b',27), ('c',28), ('d',29),\n('e',30), ('f',31), ('g',32), ('h',33), ('i',34), ('j',35), ('k',36), ('l',37), ('m',38), ('n',39),\n('o',40), ('p',41), ('q',42), ('r',43), ('s',44), ('t',45), ('u',46), ('v',47), ('w',48), ('x',49),\n('y',50), ('z',51), ('0',52), ('1',53), ('2',54), ('3',55), ('4',56), ('5',57), ('6',58), ('7',59),\n('8',60), ('9',61), ('+',62), ('/',63), ('=',0) $$\n\nDROP FUNCTION IF EXISTS `BASE64_ENCODE`$$\n\nCREATE DEFINER=`YOUR DATABASE`@`%` FUNCTION `BASE64_ENCODE`(input BLOB) RETURNS BLOB\n DETERMINISTIC\n SQL SECURITY INVOKER\nBEGIN\n DECLARE ret BLOB DEFAULT '';\n DECLARE done TINYINT DEFAULT 0;\n IF input IS NULL THEN\n RETURN NULL;\n END IF;\neach_block:\n WHILE NOT done DO BEGIN\n DECLARE accum_value BIGINT UNSIGNED DEFAULT 0;\n DECLARE in_count TINYINT DEFAULT 0;\n DECLARE out_count TINYINT;\neach_input_char:\n WHILE in_count < 3 DO BEGIN\n DECLARE first_char BLOB(1);\n\n IF LENGTH(input) = 0 THEN\n SET done = 1;\n SET accum_value = accum_value << (8 * (3 - in_count));\n LEAVE each_input_char;\n END IF;\n\n SET first_char = SUBSTRING(input,1,1);\n SET input = SUBSTRING(input,2);\n\n SET accum_value = (accum_value << 8) + ASCII(first_char);\n SET in_count = in_count + 1;\n END; END WHILE;\n\n -- We've now accumulated 24 bits; deaccumulate into base64 characters\n -- We have to work from the left, so use the third byte position and shift left\n CASE\n WHEN in_count = 3 THEN SET out_count = 4;\n WHEN in_count = 2 THEN SET out_count = 3;\n WHEN in_count = 1 THEN SET out_count = 2;\n ELSE RETURN ret;\n END CASE;\n\n WHILE out_count > 0 DO BEGIN\n BEGIN\n DECLARE out_char CHAR(1);\n DECLARE base64_getval CURSOR FOR SELECT c FROM core_base64_data WHERE val = (accum_value >> 18);\n OPEN base64_getval;\n FETCH base64_getval INTO out_char;\n CLOSE base64_getval;\n SET ret = CONCAT(ret,out_char);\n SET out_count = out_count - 1;\n SET accum_value = accum_value << 6 & 0xffffff;\n END;\n END; END WHILE;\n CASE\n WHEN in_count = 2 THEN SET ret = CONCAT(ret,'=');\n WHEN in_count = 1 THEN SET ret = CONCAT(ret,'==');\n ELSE BEGIN END;\n END CASE;\n\n END; END WHILE;\n RETURN ret;\nEND$$\n\nDELIMITER ;\n"
},
{
"answer_id": 37838051,
"author": "Pini Cheyni",
"author_id": 1773972,
"author_profile": "https://Stackoverflow.com/users/1773972",
"pm_score": 4,
"selected": false,
"text": "SELECT `id`,`name`, TO_BASE64(content) FROM `db`.`upload`\n"
},
{
"answer_id": 49152007,
"author": "Bars",
"author_id": 5998363,
"author_profile": "https://Stackoverflow.com/users/5998363",
"pm_score": 2,
"selected": false,
"text": "drop function if exists base64_encode;\ncreate function base64_encode(_data blob)\nreturns text\nbegin\n declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n declare _lim int unsigned default length(_data);\n declare _i int unsigned default 0;\n declare _chk3 char(6) default '';\n declare _chk3int int default 0;\n declare _enc text default '';\n\n while _i < _lim do\n set _chk3 = rpad(hex(binary substr(_data, _i + 1, 3)), 6, '0');\n set _chk3int = conv(_chk3, 16, 10);\n set _enc = concat(\n _enc\n , substr(_alphabet, ((_chk3int >> 18) & 63) + 1, 1)\n , if (_lim-_i > 0, substr(_alphabet, ((_chk3int >> 12) & 63) + 1, 1), '=')\n , if (_lim-_i > 1, substr(_alphabet, ((_chk3int >> 6) & 63) + 1, 1), '=')\n , if (_lim-_i > 2, substr(_alphabet, ((_chk3int >> 0) & 63) + 1, 1), '=')\n );\n set _i = _i + 3;\n end while;\n\n return _enc;\nend;\n\ndrop function if exists base64_decode;\ncreate function base64_decode(_enc text)\nreturns blob\nbegin\n declare _alphabet char(64) default 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';\n declare _lim int unsigned default 0;\n declare _i int unsigned default 0;\n declare _chr1byte tinyint default 0;\n declare _chk4int int default 0;\n declare _chk4int_bits tinyint default 0;\n declare _dec blob default '';\n declare _rem tinyint default 0;\n set _enc = trim(_enc);\n set _rem = if(right(_enc, 3) = '===', 3, if(right(_enc, 2) = '==', 2, if(right(_enc, 1) = '=', 1, 0)));\n set _lim = length(_enc) - _rem;\n\n while _i < _lim\n do\n set _chr1byte = locate(substr(_enc, _i + 1, 1), binary _alphabet) - 1;\n if (_chr1byte > -1)\n then\n set _chk4int = (_chk4int << 6) | _chr1byte;\n set _chk4int_bits = _chk4int_bits + 6;\n\n if (_chk4int_bits = 24 or _i = _lim-1)\n then\n if (_i = _lim-1 and _chk4int_bits != 24)\n then\n set _chk4int = _chk4int << 0;\n end if;\n\n set _dec = concat(\n _dec\n , char((_chk4int >> (_chk4int_bits - 8)) & 0xff)\n , if(_chk4int_bits > 8, char((_chk4int >> (_chk4int_bits - 16)) & 0xff), '\\0')\n , if(_chk4int_bits > 16, char((_chk4int >> (_chk4int_bits - 24)) & 0xff), '\\0')\n );\n set _chk4int = 0;\n set _chk4int_bits = 0;\n end if;\n end if;\n set _i = _i + 1;\n end while;\n\n return substr(_dec, 1, length(_dec) - _rem);\nend;\n convert(base64_decode(base64_encode('ёлка')) using utf8)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358500",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
358,501 | <p>I'm trying to add a custom font as a resource in my application.
I have a "CustomFont" directory in the application and all the fonts inside of it are set to "Resource"</p>
<pre><code><Window.Resources>
<Style x:Key="Gotham-XLight">
<Setter Property="TextElement.FontFamily"
Value="/CustomFonts;Component/#Gotham-XLight" />
</Style>
</Window.Resources>
</code></pre>
<p>And then on my TextBlock I have this: (inside a grid)</p>
<pre><code><TextBlock x:Name="TimeTextBlock" Style="{DynamicResource Gotham-XLight}"
TextAlignment="Center" FontSize="25" FontWeight="Bold"
Foreground="White" Text="TextBlockTimer"
Margin="105,242.974,0,226.975" HorizontalAlignment="Left"
Width="221.919" />
</code></pre>
<p>But I'm not seeing my font as people say. Am I doing something wrong?</p>
| [
{
"answer_id": 358511,
"author": "joshperry",
"author_id": 30587,
"author_profile": "https://Stackoverflow.com/users/30587",
"pm_score": 3,
"selected": false,
"text": "<Window.Resources>\n <Style x:Key=\"Gotham-XLight\">\n <Setter Property=\"TextElement.FontFamily\" Value=\"CustomFonts/#Gotham-XLight\" />\n </Style>\n</Window.Resources>\n {StaticResource Gotham-XLight}"
},
{
"answer_id": 16732727,
"author": "sdd",
"author_id": 2028846,
"author_profile": "https://Stackoverflow.com/users/2028846",
"pm_score": 2,
"selected": false,
"text": " <Button Grid.Column=\"1\" Grid.RowSpan=\"2\" Name=\"start\" Margin=\"5\" Click=\"start_Click\">\n <TextBlock Name=\"test\" FontFamily=\"pack://application:,,,/Y_Yoga;Component/Resources/#FontAwesome\"></TextBlock>\n </Button>\n"
},
{
"answer_id": 60171307,
"author": "Alexandru Dicu",
"author_id": 1140388,
"author_profile": "https://Stackoverflow.com/users/1140388",
"pm_score": 1,
"selected": false,
"text": " <ItemGroup>\n <Resource Include=\"Fonts\\*.ttf\" />\n </ItemGroup>\n <Window x:Class=\"Namespace.MainWindow\"\n ...\n FontFamily=\"/Fonts/#[FONT NAME]\"\n Title=\"\">\n <Grid>\n ...\n </Grid>\n</Window>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358501",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/22451/"
] |
358,533 | <p>I am curious to learn <a href="http://www.boost.org/" rel="noreferrer">Boost</a>. But I wanted to ask:</p>
<ul>
<li>How important is it to make the effort to learn Boost?</li>
<li>What prerequisites should one have before jumping on Boost?</li>
</ul>
<p>Why I am curious to know about Boost is that many people are talking about Boost on IRC's channels and here in StackOverflow.</p>
| [
{
"answer_id": 358691,
"author": "Anteru",
"author_id": 39912,
"author_profile": "https://Stackoverflow.com/users/39912",
"pm_score": 2,
"selected": false,
"text": "shared_ptr"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358533",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38038/"
] |
358,538 | <p>I'm trying to develop an application that will use getImageData in javascript in Firefox 3, but I am getting a "<code>NS_ERROR_DOM_SECURITY_ERR</code>" on the getImageData call. The javascript and the image are both currently being served from by hard drive, which is apparently a security violation? When this is live they will both be served from the same domain, so it won't be a problem, but how can I develop in the meantime?</p>
| [
{
"answer_id": 366493,
"author": "Justin Love",
"author_id": 30203,
"author_profile": "https://Stackoverflow.com/users/30203",
"pm_score": 3,
"selected": false,
"text": " var data;\n try {\n try {\n data = context.getImageData(sx, sy, sw, sh).data;\n } catch (e) {\n netscape.security.PrivilegeManager.enablePrivilege(\"UniversalBrowserRead\");\n data = context.getImageData(sx, sy, sw, sh).data;\n }\n } catch (e) {\n throw new Error(\"unable to access image data: \" + e);\n }\n"
},
{
"answer_id": 10265079,
"author": "nodehi",
"author_id": 673998,
"author_profile": "https://Stackoverflow.com/users/673998",
"pm_score": 1,
"selected": false,
"text": "getImageData http://mySite.com\n http://www.mySite.com\n .htaccess www. RewriteEngine On\nRewriteCond %{HTTP_HOST} ^mySite\\.com$ [NC]\nRewriteRule ^(.*)$ http://www.mySite.com/$1 [L,R=301]\n NS_ERROR_DOM_SECURITY_ERR"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358538",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2652/"
] |
358,542 | <p>How to find fifth highest salary in a single query in SQL Server</p>
| [
{
"answer_id": 358547,
"author": "Jayden",
"author_id": 44873,
"author_profile": "https://Stackoverflow.com/users/44873",
"pm_score": 5,
"selected": false,
"text": "select\n *\nfrom\n(\n Select\n SalesOrderID, CustomerID, Row_Number() Over (Order By SalesOrderID) as RunningCount\n From\n Sales.SalesOrderHeader\n Where\n SalesOrderID > 10000\n Order By\n SalesOrderID \n) ranked\nwhere \n RunningCount = 5\n"
},
{
"answer_id": 358548,
"author": "recursive",
"author_id": 44743,
"author_profile": "https://Stackoverflow.com/users/44743",
"pm_score": 2,
"selected": false,
"text": "DECLARE @result int\n\nSELECT TOP 5 @result = Salary FROM Employees ORDER BY Salary DESC\n SELECT MIN(Salary) FROM (\n SELECT TOP 5 Salary FROM Employees ORDER BY Salary DESC\n) AS TopFive\n"
},
{
"answer_id": 358836,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "select salary\nfrom Employees a\nwhere 5=(select count(distinct salary)\n from Employees b\n where a.salary > b.salary)\norder by salary desc\n"
},
{
"answer_id": 959190,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "SELECT TOP 1 salary\nFROM (\n SELECT DISTINCT TOP n salary\n FROM employee\n ORDER BY salary DESC) a\nORDER BY salary\nwhere n > 1 -- (n is always greater than one)\n"
},
{
"answer_id": 1142338,
"author": "Yagnesh84",
"author_id": 140040,
"author_profile": "https://Stackoverflow.com/users/140040",
"pm_score": 0,
"selected": false,
"text": "select top 1 salary \nfrom (select top 5 salary\n from tbl_Employee\n order by salary desc) as tbl \norder by salary asc\n"
},
{
"answer_id": 2756688,
"author": "Bell",
"author_id": 331216,
"author_profile": "https://Stackoverflow.com/users/331216",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP 1 salary FROM (\n SELECT DISTINCT min(salary) salary\n FROM emp where salary > (select salary from emp where empname = 'John Hell') \n ) a \nORDER BY salary\n"
},
{
"answer_id": 3320568,
"author": "Nilesh",
"author_id": 400494,
"author_profile": "https://Stackoverflow.com/users/400494",
"pm_score": 0,
"selected": false,
"text": "select * from employee2 e\nwhere 2=(select count(distinct salary) from employee2\n where e.salary<=salary)\n"
},
{
"answer_id": 4942110,
"author": "Ritesh Kumar",
"author_id": 609326,
"author_profile": "https://Stackoverflow.com/users/609326",
"pm_score": 1,
"selected": false,
"text": "select MIN(esal) from (\n select top 5 esal from tbemp order by esal desc) as sal\n"
},
{
"answer_id": 5482728,
"author": "user683393",
"author_id": 683393,
"author_profile": "https://Stackoverflow.com/users/683393",
"pm_score": 1,
"selected": false,
"text": "SELECT MIN(Salary) FROM (\n SELECT TOP 2 Salary FROM empa ORDER BY Salary DESC\n) AS TopFive\n"
},
{
"answer_id": 70146617,
"author": "Bhaskar Ranjan",
"author_id": 8485644,
"author_profile": "https://Stackoverflow.com/users/8485644",
"pm_score": 1,
"selected": false,
"text": "SELECT MIN(Salary) FROM (\nSELECT Salary FROM empa ORDER BY Salary DESC limit 5\n)TopFive\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358542",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45241/"
] |
358,546 | <p>Sorry, I thought this was an inheritance question: it was an ArrayList question all along!</p>
<p>Ok, my problem is more specific than I thought. So I have two families of classes. Cards, and Zones. Zones are boxes for holding card. </p>
<p>The first two subClasses of Zone, ZoneList and ZoneMap are meant to be two different ways of storing Cards. Further subclasses, such as Hand, and PokerHand, have their own specific ways of dealing with the cards they store. </p>
<p>Where it gets complicated is that Card also has subClasses, such as PokerCard, and that the subclasses of ZoneList and ZoneMap are meant to organize those. </p>
<p>So in ZoneList I have <code>protected ArrayList<Card> cardBox;</code> and in PokerHand I expected to be able to declare <code>cardBox = new ArrayList<PokerCard>();</code> since PokerCard is a Card. The error I am getting is that I apparently can't cast between Card and GangCard when it comes to ArrayLists... So I was trying to fix this by just redeclaring cardBox as <code>private ArrayList<PokerCard> cardBox;</code> inside PokerHand, but that resulted in the hiding that was bugging up my program.</p>
<p>SO really, the question is about casting between ArrayLists? Java tells me I can't, so any ideas on how I can?</p>
<p>z.</p>
| [
{
"answer_id": 358579,
"author": "Scanningcrew",
"author_id": 45219,
"author_profile": "https://Stackoverflow.com/users/45219",
"pm_score": 1,
"selected": false,
"text": "Zonelist this super"
},
{
"answer_id": 358610,
"author": "Marc Novakowski",
"author_id": 27020,
"author_profile": "https://Stackoverflow.com/users/27020",
"pm_score": 4,
"selected": false,
"text": "protected ArrayList<? extends Card> getCardBox();\n"
},
{
"answer_id": 358612,
"author": "refrus",
"author_id": 37267,
"author_profile": "https://Stackoverflow.com/users/37267",
"pm_score": 5,
"selected": true,
"text": "public class ZoneList<T extends Card> {\n protected List<T> cardBox;\n}\n\npublic class PokerHand extends ZoneList<PokerCard> {\n public PokerHand() {\n cardBox = new ArrayList<PokerCard>();\n }\n}\n"
},
{
"answer_id": 358620,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": false,
"text": "List<Banana> bananaBunch = new ArrayList<Banana>();\nList<Fruit> fruitBowl = bananBunch;\nfruitBowl.add(new Apple());\n List<Fruit>"
},
{
"answer_id": 358815,
"author": "Markus",
"author_id": 45064,
"author_profile": "https://Stackoverflow.com/users/45064",
"pm_score": 3,
"selected": false,
"text": "ArrayList<PokerCard> ArrayList<Card> ArrayList<PokerCard> ArrayList<? extends Card> List<? extends Card> protected ArrayList<? extends Card> getCardBox();\n List<? extends Card> list = new ArrayList<Card>(); protected ArrayList<? extends Card> getCardBox() {\n List<Card> list = new ArrayList<Card>();\n list.add(pokerCard1);\n list.add(pokerCard2);\n return java.util.Collections.unmodifiableList(list);\n}\n"
},
{
"answer_id": 25233504,
"author": "Steven Lizarazo",
"author_id": 589132,
"author_profile": "https://Stackoverflow.com/users/589132",
"pm_score": 3,
"selected": false,
"text": "ArrayList<Card> cards = (ArrayList<Card>)(ArrayList<?>) (pokerCardObjects);\n ArrayList<Card> cards = pokerCardObjects.stream().collect(Collectors.toCollection(ArrayList::new);\n ArrayList<Card> cards = new ArrayList<>(pokerCardObjects);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29182/"
] |
358,601 | <p>There are 2 radiobutton and a hyperlink.
if select 'radiobutton1' the hyperlink is enabled.
if select 'radiobutton2' the hyperlink is disabled.
i can use jquery to disable the hyperlink, but can't enable it.
How to enable the hyperlink with jquery?</p>
| [
{
"answer_id": 358665,
"author": "seanb",
"author_id": 3354,
"author_profile": "https://Stackoverflow.com/users/3354",
"pm_score": 2,
"selected": false,
"text": "$(\"#hyperlink1\").click(function(){ \n // return true or false based on your radio buttons \n return enableLink; \n});\n"
},
{
"answer_id": 358773,
"author": "miceuz",
"author_id": 24443,
"author_profile": "https://Stackoverflow.com/users/24443",
"pm_score": 0,
"selected": false,
"text": "$(\"#radioDisable\").click(function() {\n $(“hyperlink”).click(function(){\n return false;\n });\n $(“hyperlink”).addClass(“disabled”);\n});\n\n$(\"#radioEnable\").click(function() {\n $(“hyperlink”).click(function(){\n return true;\n });\n $(“hyperlink”).removeClass(“disabled”);\n});\n"
},
{
"answer_id": 411717,
"author": "Frank Schwieterman",
"author_id": 32203,
"author_profile": "https://Stackoverflow.com/users/32203",
"pm_score": 0,
"selected": false,
"text": "if (!$(\"#ContinueButton\")[0].disabled) { \n UserContinue(); \n}\n $(\"#ContinueButton\")[0].disabled = !canContinue; \n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,603 | <p>I have a problem I have got stuck on. </p>
<p>I want to export my Access table to an Excel file. Currently, I do that using <code>DoCmd.TransferSpreadsheet</code>, but I want some kind of formatting to be done on the exported data. Can I format that data I am sending to Excel or do I have to write a macro in Excel that will format that data after it has been exported from Access?</p>
| [
{
"answer_id": 358935,
"author": "Berzerk",
"author_id": 37599,
"author_profile": "https://Stackoverflow.com/users/37599",
"pm_score": 2,
"selected": false,
"text": "Sub Makro1()\n''\nConst sDB = \"c:\\db1.mdb\"\nConst sSQL = \"SELECT * FROM Table1\"\n\n With ActiveSheet.QueryTables.Add(Connection:= _\n \"ODBC;DSN=MS Access-database;DBQ=\" + sDB + \";FIL=MS Access;MaxBufferSize=2048;PageTimeout=5;\" _\n , Destination:=Range(\"A1\"))\n .CommandText = Array(sSQL)\n .Name = \"Query1\"\n .FieldNames = True\n .RowNumbers = False\n .FillAdjacentFormulas = False\n .PreserveFormatting = True\n .RefreshOnFileOpen = False\n .BackgroundQuery = True\n .RefreshStyle = xlInsertDeleteCells\n .SavePassword = True\n .SaveData = True\n .AdjustColumnWidth = True\n .RefreshPeriod = 0\n .PreserveColumnInfo = True\n .Refresh BackgroundQuery:=False\n End With\nEnd Sub\n"
},
{
"answer_id": 362325,
"author": "Philippe Grondier",
"author_id": 11436,
"author_profile": "https://Stackoverflow.com/users/11436",
"pm_score": 2,
"selected": false,
"text": "Public Function ExportToExcel(x_frm as Form)\n\nDim ctl As Control, _\n xlApp As Excel.Application, _\n xlBook As Excel.Workbook, _\n xlSheet As Excel.Worksheet, _\n columnName() As String, _\n columnCount as Integer\n\n'suppose Excel is not opened. You can add an extra control for that'\nSet xlApp = CreateObject(\"Excel.Application\")\n\n'create an Excel workbook, declare the first sheet'\nSet xlBook = xlApp.Workbooks.Add\nSet xlSheet = xlBook.Worksheets(1)\nxlApp.Visible = False\n\ncolumnCount = fc().section(0).Controls.Count\n\n'use array columnName() to collect the column names of detail section in tabbed order'\nReDim columnName(columnCount)\n\nFor Each ctl In fc().section(0).Controls\n columnName(ctl.TabIndex) = ctl.Name\nNext ctl\n\n'This function will add a title to the excel sheet with my favorite formating'\n'I can for example decide this title to be bold/Arial/16 on cell(B2)'\naddTitleToExcelSheet xlSheet, x_frm.Name\n\n'This function will add the column names to my Excel sheet with my favorite formating'\n'for example column names will be added on row 4, columns B to B + columnCount'\naddColumnNameToExcelSheet xlSheet, columnName()\n\n'This function will add the column values to my Excel sheet with specific format (date, number, etc)'\n'Data will be added to the range defined by '\n'row 5 to row 5 + x_frm.recordset.recordcount, '\n'columns B to B + columnCount.'\n'Recordset values will have to be read according to tab order'\n'exported data can depend on recordset filter and orderBy property: your choice'\naddColumnValueToExcelSheet xlSheet, columnName(), x_frm.Recordset\n\n'The Excel sheet is made visible and saved under the current folder with the forms name'\nxlApp.Visible = True\nxlBook.SaveAs x_frm.Name & \".xls\"\n\nSet xlBook = Nothing\nSet xlSheet = Nothing\nSet xlApp = Nothing\n\nEnd Function\n"
},
{
"answer_id": 1207040,
"author": "Knox",
"author_id": 4873,
"author_profile": "https://Stackoverflow.com/users/4873",
"pm_score": 1,
"selected": false,
"text": "DoCmd.TransferSpreadsheet DoCmd.TransferSpreadsheet DoCmd.TransferSpreadsheet DoCmd.TransferSpreadsheet"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358603",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,609 | <p>I am developing a Tool in vb.net and need find out Activex Controls from MS Access DB forms. I am able to conut number of controls in form, but unable to get the Activex Controls only from the form. Can any one have any idea how to achieve this, please suggest. </p>
| [
{
"answer_id": 359240,
"author": "Gary Kindel",
"author_id": 44597,
"author_profile": "https://Stackoverflow.com/users/44597",
"pm_score": 0,
"selected": false,
"text": "Dim oAccess As Access.Application\n\n' Start a new instance of Access for Automation:\noAccess = New Access.ApplicationClass()\n\n' Open a database in exclusive mode:\noAccess.OpenCurrentDatabase(filepath:=\"c:\\mydb.mdb\", Exclusive:=True)\n\noAccess.DoCmd.OpenForm(FormName:=\"Employees\")\n"
},
{
"answer_id": 359308,
"author": "Fionnuala",
"author_id": 2548,
"author_profile": "https://Stackoverflow.com/users/2548",
"pm_score": 2,
"selected": true,
"text": "ActiveXCount = 0\nFor Each ctl In Screen.ActiveForm\n If ctl.ControlType = 119 Then 'Custom control'\n 'Debug.Print ctl.Class'\n ActiveXCount = ActiveXCount + 1\n End If\nNext\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358609",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45255/"
] |
358,617 | <p>How can I create a file dsn for connecting to an AS400 system using the iSeries ODBC driver?</p>
<p>The iSeries ODBC driver allows many settings to be configured. Where can I find a list of all properties that can be set in the file DSN?</p>
| [
{
"answer_id": 358628,
"author": "Gustavo Rubio",
"author_id": 14533,
"author_profile": "https://Stackoverflow.com/users/14533",
"pm_score": 2,
"selected": false,
"text": "[ODBC]\nDRIVER=iSeries Access ODBC Driver\nSystem=server;\nUid=user;\nPwd=password;\nInitial Catalog=library;\n"
},
{
"answer_id": 358666,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 2,
"selected": false,
"text": "Driver={Client Access ODBC Driver (32-bit)};System=my_system_name;\nUid=myUsername;Pwd=myPassword;\n Driver={iSeries Access ODBC Driver};System=my_system_name;\nUid=myUsername;Pwd=myPassword;\n DataSource=myServerAddress;UserID=myUsername;\nPassword=myPassword; DataCompression=True;\n Provider=IBMDA400;Data Source=MY_SYSTEM_NAME;\nUser Id=myUsername;Password=myPassword;\n Provider=IBMDA400;Data Source=MY_SYSTEM_NAME;User Id=myUsername;\nPassword=myPassword;Default Collection=MY_LIBRARY;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358617",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,645 | <p>In IIS7 for Vista, you can select your machine and it gives you several options in which you can use to configure your system. Where is this file stored at? It seems like there's a big master.config file which stores all my settings like the "Connection Strings" which are inherited by the webpages. </p>
<p>Supposedly it's some file named machine.config but nothing I change in the IIS manager for my machine changes there. </p>
| [
{
"answer_id": 358653,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\CONFIG"
},
{
"answer_id": 358664,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 2,
"selected": false,
"text": "windows\\microsoft.net\\framework\\v2.0.50727\\config\\machine.config web.config"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358645",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
358,654 | <p>I need to specify path to dlls referenced by assembly in .config file.
Problem is that path can be found in env. variable.
Is it possible to use some sort of %DLLPATH% macro in .config file?</p>
| [
{
"answer_id": 358678,
"author": "Prensen",
"author_id": 43633,
"author_profile": "https://Stackoverflow.com/users/43633",
"pm_score": 5,
"selected": false,
"text": "<configuration>\n <appSettings>\n <add key=\"mypath\" value=\"%DLLPATH%\\foo\\bar\"/>\n </appSettings>\n</configuration>\n var pathFromConfig = ConfigurationManager.AppSettings[\"mypath\"];\nvar expandedPath = Environment.ExpandEnvironmentVariables(pathFromConfig);\n ExpandEnvironmentVariables(string s)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358654",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35425/"
] |
358,663 | <p>this question can create a misunderstanding: I know I have to use CSS to validate successfully my document as XHTML 1.0 Transitional. The fact is that I have to embed in my webpage a picture composed by zeros and ones created with <a href="http://www.text-image.com/index.html" rel="noreferrer" title="text image">text image</a>, and the problem is that the code uses deprecated tag font and looks like this</p>
<pre><code><!-- IMAGE BEGINS HERE -->
<pre>
<font size="-3">
<font color="#000000">0001100000101101100011</font>
<font color="#010000">00</font>
<font color="#020101">0</font>
<font color="#040101">0</font>
<font color="#461919">1</font>
<font color="#b54f4f">1</font>
...etc.etc...
</font>
</pre>
<!-- IMAGE ENDS HERE -->
</code></pre>
<p>(In this code example I inserted a newline after each couple of tags to make it more readable, but the original code is all in one line because of the <code><pre></code> tag).
The font's color changes at least thousands times so I never considered to create a field in the CSS for each combination.Hope someone knows at least where to find a solution, I searched everywhere :)
Thanks</p>
| [
{
"answer_id": 358667,
"author": "Ryan Doherty",
"author_id": 956,
"author_profile": "https://Stackoverflow.com/users/956",
"pm_score": 6,
"selected": true,
"text": "<font color=\"#000000\">0001100000101101100011</font> <span style=\"color:#000000\">0001100000101101100011</span>"
},
{
"answer_id": 358703,
"author": "BraveSirFoobar",
"author_id": 39263,
"author_profile": "https://Stackoverflow.com/users/39263",
"pm_score": 2,
"selected": false,
"text": "<script>\nvalues = [1, 0, 0, 1, ... ]\ncolors = [\"010000\", \"020101\", ...]\n\nfor (i = 0; i < values.length; i++) {\n span = createElement(\"span\"); // use a portable function for creating elements\n span.setAttribute(\"style\", \"color:#\"+colors[i]);\n txtNode = document.createTextNode(values[i]); \n span.appendChild(txtNode);\n document.appendChild(span);\n}\n</script>\n"
},
{
"answer_id": 358765,
"author": "gc5",
"author_id": 41977,
"author_profile": "https://Stackoverflow.com/users/41977",
"pm_score": 2,
"selected": false,
"text": "<!-- IMAGE BEGINS HERE -->\n<div style=\"font-size:x-small;font-family:monospace\">\n <span style=\"color:#000000\">0001100000101101100011</span>\n <span style=\"color:#010000\">00</span>\n ...etc.etc...\n</div>\n<!-- IMAGE ENDS HERE -->\n"
},
{
"answer_id": 358766,
"author": "Dylan Beattie",
"author_id": 5017,
"author_profile": "https://Stackoverflow.com/users/5017",
"pm_score": 0,
"selected": false,
"text": "<span style=\"color:#ff00ff;\">00</span> <!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 3.2 Final//EN\">"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358663",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41977/"
] |
358,681 | <p>I'm trying to generate my models from a schema.xml file on OSX 10.5 with the latest versions of PHP & Propel 1.3 & Phing. All the model classes actually get created, then it just dies, right at the last step. I have already tried </p>
<blockquote>
<p>chmod -R 777 ./application/config</p>
</blockquote>
<p>but that didn't help. I have also tried both </p>
<blockquote>
<p>propel-gen ./ reverse</p>
</blockquote>
<p>and </p>
<blockquote>
<p>propel-gen ./ creole</p>
</blockquote>
<p>Both produced the same error. This error: </p>
<pre><code>propel > convert-conf:
[echo] Output file: models-conf.php
[echo] XMLFile: /application/config/runtime-conf.xml
Execution of target "convert-conf" failed for the following reason: pear/data/propel_generator/build-propel.xml:514:20: No valid xmlConfFile specified.
[phingcall] /pear/data/propel_generator/build-propel.xml:514:20: No valid xmlConfFile specified.
Execution of target "main" failed for the following reason:
pear/data/propel_generator/build-propel.xml:94:18: Execution of the target buildfile failed. Aborting.
[phing] pear/data/propel_generator/build-propel.xml:94:18: Execution of the target buildfile failed. Aborting.
BUILD FINISHED
</code></pre>
<p>Here is my build.properties file:</p>
<pre><code>propel.project = models
propel.database = mysql
propel.database.encoding = utf8
propel.database.url = mysql:host=localhost;dbname={$myDBName}
propel.database.user = {$myDBuser}
propel.database.password = {$myDBpass}
propel.output.dir = /application
propel.php.dir = ${propel.output.dir}/
propel.sql.dir = ${propel.output.dir}/models/sql
propel.schema.dir = ${propel.output.dir}/config
propel.conf.dir = ${propel.output.dir}/config
propel.phpconf.dir = ${propel.output.dir}/config
propel.addGenericAccessors = true
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 360603,
"author": "lo_fye",
"author_id": 3407,
"author_profile": "https://Stackoverflow.com/users/3407",
"pm_score": 2,
"selected": true,
"text": "<datasource id=\"models\"> <!-- this ID must match <database name=\"\"> in schema.xml -->\n"
},
{
"answer_id": 3248287,
"author": "user391799",
"author_id": 391799,
"author_profile": "https://Stackoverflow.com/users/391799",
"pm_score": 2,
"selected": false,
"text": "propel.runtime.conf.file=runtime-config.xml\n build.properties"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3407/"
] |
358,687 | <p>I currently have a database that is 20GB in size.
I've run a few scripts which show on each tables size (and other incredibly useful information such as index stuff) and the biggest table is 1.1 million records which takes up 150MB of data. We have less than 50 tables most of which take up less than 1MB of data.</p>
<p>After looking at the size of each table I don't understand why the database shouldn't be 1GB in size after a shrink. The amount of available free space that SqlServer (2005) reports is 0%. The log mode is set to simple. At this point my main concern is I feel like I have 19GB of unaccounted for used space. Is there something else I should look at?</p>
<p>Normally I wouldn't care and would make this a passive research project except this particular situation calls for us to do a backup and restore on a weekly basis to put a copy on a satellite (which has no internet, so it must be done manually). I'd much rather copy 1GB (or even if it were down to 5GB!) than 20GB of data each week.</p>
<p>sp_spaceused reports the following:</p>
<pre><code>Navigator-Production 19184.56 MB 3.02 MB
</code></pre>
<p>And the second part of it:</p>
<pre><code>19640872 KB 19512112 KB 108184 KB 20576 KB
</code></pre>
<p>while I've found a few other scripts (such as the one from two of the server database size questions here, they all report the same information either found above or below).
The script I am using is from SqlTeam. Here is the header info:</p>
<pre><code>* BigTables.sql
* Bill Graziano (SQLTeam.com)
* graz@<email removed>
* v1.11
</code></pre>
<p>The top few tables show this (table, rows, reserved space, data, index, unused, etc):</p>
<pre><code>Activity 1143639 131 MB 89 MB 41768 KB 1648 KB 46% 1%
EventAttendance 883261 90 MB 58 MB 32264 KB 328 KB 54% 0%
Person 113437 31 MB 15 MB 15752 KB 912 KB 103% 3%
HouseholdMember 113443 12 MB 6 MB 5224 KB 432 KB 82% 4%
PostalAddress 48870 8 MB 6 MB 2200 KB 280 KB 36% 3%
</code></pre>
<p>The rest of the tables are either the same in size or smaller. No more than 50 tables.</p>
<p>Update 1:
- All tables use unique identifiers. Usually an int incremented by 1 per row.</p>
<ul>
<li><p>I've also re-indexed everything.</p></li>
<li><p>I ran the dbcc shrink command as well as updating the usage before and after. And over and over. An interesting thing I found is that when I restarted the server and confirmed <em>no one</em> was using it (and no maintenance procs are running, this is a very new application -- under a week old) and when I went to run the shrink, every now and then it would say something about data changed. Googling yielded too few useful answers with the obvious not applying (it was 1am and I disconnected everyone, so it seems impossible that was really the case). The data was migrated via C# code which basically looked at another server and brought things over. The quantity of deletes, at this point in time, are probably under 50k in rows. Even if those rows were the biggest rows, that wouldn't be more than 100M I would imagine.</p></li>
<li><p>When I go to shrink via the GUI it reports 0% available to shrink, indicating that I've already gotten it as small as it thinks it can go.</p></li>
</ul>
<p>Update 2:</p>
<ul>
<li><p>sp_spaceused 'Activity' yields this (which seems right on the money):</p>
<p>Activity 1143639 134488 KB 91072 KB 41768 KB 1648 KB</p></li>
<li><p>Fill factor was 90.</p></li>
<li><p>All primary keys are ints.</p></li>
<li><p>Here is the command I used to 'updateusage':</p>
<p>DBCC UPDATEUSAGE(0);</p></li>
</ul>
<p>Update 3:</p>
<ul>
<li>Per Edosoft's request:
Image 111975 2407773 19262184
It appears as though the image table believes it's the 19GB portion.
I don't understand what this means though.
Is it <em>really</em> 19GB or is it misrepresented?</li>
</ul>
<p>Update 4:</p>
<ul>
<li>Talking to a co-worker and I found out that it's because of the pages, as someone else here has also state the potential for that. The only index on the image table is a clustered PK. Is this something I can fix or do I just have to deal with it?
The regular script shows the Image table to be 6MB in size.</li>
</ul>
<p>Update 5:</p>
<ul>
<li>I think I'm just going to have to deal with it after further research. The images have been resized to be roughly 2-5KB each and on a normal file system doesn't consume much space but on SqlServer it seems to consume considerably more. The real answer, in the long run, will likely be separating that table in to another partition or something similar.</li>
</ul>
| [
{
"answer_id": 358707,
"author": "Bernhard Hofmann",
"author_id": 39722,
"author_profile": "https://Stackoverflow.com/users/39722",
"pm_score": 1,
"selected": false,
"text": "DECLARE @DbName NVARCHAR(128)\nSET @DbName = DB_NAME(DB_ID())\nDBCC UPDATEUSAGE(@DbName)\n"
},
{
"answer_id": 359546,
"author": "edosoft",
"author_id": 6399,
"author_profile": "https://Stackoverflow.com/users/6399",
"pm_score": 2,
"selected": true,
"text": "SELECT object_name(object_id) AS name, rows, total_pages, \n total_pages * 8192 / 1024 as [Size(Kb)]\nFROM sys.partitions p\nINNER JOIN sys.allocation_units a\n ON p.partition_id = a.container_id\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358687",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18217/"
] |
358,700 | <p>I have 3 projects in my VS solution. One of them is a Web app, the second one is a Windows Service and the last one a Setup project for my Web app. </p>
<p>What I want is by the end of the installation of the web app in my setup project, within my custom action to try and install my windows service given that I have the location of the assembly by then.</p>
| [
{
"answer_id": 358704,
"author": "lakshmanaraj",
"author_id": 44541,
"author_profile": "https://Stackoverflow.com/users/44541",
"pm_score": 5,
"selected": false,
"text": "System.Configuration.Install exeFileName public static void InstallService(string exeFilename)\n{\n string[] commandLineOptions = new string[1] { \"/LogFile=install.log\" };\n\n System.Configuration.Install.AssemblyInstaller installer = new System.Configuration.Install.AssemblyInstaller(exeFilename, commandLineOptions);\n\n installer.UseNewContext = true; \n installer.Install(null); \n installer.Commit(null);\n\n}\n public static void UninstallService(string exeFilename)\n{\n string[] commandLineOptions = new string[1] { \"/LogFile=uninstall.log\" };\n\n System.Configuration.Install.AssemblyInstaller installer = new System.Configuration.Install.AssemblyInstaller(exeFilename, commandLineOptions);\n\n installer.UseNewContext = true; \n installer.Uninstall(null);\n\n}\n"
},
{
"answer_id": 637728,
"author": "Konstantinos",
"author_id": 17443,
"author_profile": "https://Stackoverflow.com/users/17443",
"pm_score": 7,
"selected": true,
"text": "//Installs and starts the service\nServiceInstaller.InstallAndStart(\"MyServiceName\", \"MyServiceDisplayName\", \"C:\\\\PathToServiceFile.exe\");\n\n//Removes the service\nServiceInstaller.Uninstall(\"MyServiceName\");\n\n//Checks the status of the service\nServiceInstaller.GetServiceStatus(\"MyServiceName\");\n\n//Starts the service\nServiceInstaller.StartService(\"MyServiceName\");\n\n//Stops the service\nServiceInstaller.StopService(\"MyServiceName\");\n\n//Check if service is installed\nServiceInstaller.ServiceIsInstalled(\"MyServiceName\");\n"
},
{
"answer_id": 1172111,
"author": "Lars A. Brekken",
"author_id": 6120,
"author_profile": "https://Stackoverflow.com/users/6120",
"pm_score": 7,
"selected": false,
"text": "public static class ServiceInstaller\n{\n private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;\n private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;\n\n [StructLayout(LayoutKind.Sequential)]\n private class SERVICE_STATUS\n {\n public int dwServiceType = 0;\n public ServiceState dwCurrentState = 0;\n public int dwControlsAccepted = 0;\n public int dwWin32ExitCode = 0;\n public int dwServiceSpecificExitCode = 0;\n public int dwCheckPoint = 0;\n public int dwWaitHint = 0;\n }\n\n #region OpenSCManager\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenSCManagerW\", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]\n static extern IntPtr OpenSCManager(string machineName, string databaseName, ScmAccessRights dwDesiredAccess);\n #endregion\n\n #region OpenService\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceAccessRights dwDesiredAccess);\n #endregion\n\n #region CreateService\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceAccessRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);\n #endregion\n\n #region CloseServiceHandle\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool CloseServiceHandle(IntPtr hSCObject);\n #endregion\n\n #region QueryServiceStatus\n [DllImport(\"advapi32.dll\")]\n private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);\n #endregion\n\n #region DeleteService\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool DeleteService(IntPtr hService);\n #endregion\n\n #region ControlService\n [DllImport(\"advapi32.dll\")]\n private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);\n #endregion\n\n #region StartService\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int StartService(IntPtr hService, int dwNumServiceArgs, int lpServiceArgVectors);\n #endregion\n\n public static void Uninstall(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Service not installed.\");\n\n try\n {\n StopService(service);\n if (!DeleteService(service))\n throw new ApplicationException(\"Could not delete service \" + Marshal.GetLastWin32Error());\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static bool ServiceIsInstalled(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);\n\n if (service == IntPtr.Zero)\n return false;\n\n CloseServiceHandle(service);\n return true;\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void InstallAndStart(string serviceName, string displayName, string fileName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);\n\n if (service == IntPtr.Zero)\n service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null);\n\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Failed to install service.\");\n\n try\n {\n StartService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void StartService(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Start);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Could not open service.\");\n\n try\n {\n StartService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void StopService(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Stop);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Could not open service.\");\n\n try\n {\n StopService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n private static void StartService(IntPtr service)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n StartService(service, 0, 0);\n var changedStatus = WaitForServiceStatus(service, ServiceState.StartPending, ServiceState.Running);\n if (!changedStatus)\n throw new ApplicationException(\"Unable to start service\");\n }\n\n private static void StopService(IntPtr service)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n ControlService(service, ServiceControl.Stop, status);\n var changedStatus = WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);\n if (!changedStatus)\n throw new ApplicationException(\"Unable to stop service\");\n }\n\n public static ServiceState GetServiceStatus(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);\n if (service == IntPtr.Zero)\n return ServiceState.NotFound;\n\n try\n {\n return GetServiceStatus(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n private static ServiceState GetServiceStatus(IntPtr service)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n\n if (QueryServiceStatus(service, status) == 0)\n throw new ApplicationException(\"Failed to query service status.\");\n\n return status.dwCurrentState;\n }\n\n private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n\n QueryServiceStatus(service, status);\n if (status.dwCurrentState == desiredStatus) return true;\n\n int dwStartTickCount = Environment.TickCount;\n int dwOldCheckPoint = status.dwCheckPoint;\n\n while (status.dwCurrentState == waitStatus)\n {\n // Do not wait longer than the wait hint. A good interval is\n // one tenth the wait hint, but no less than 1 second and no\n // more than 10 seconds.\n\n int dwWaitTime = status.dwWaitHint / 10;\n\n if (dwWaitTime < 1000) dwWaitTime = 1000;\n else if (dwWaitTime > 10000) dwWaitTime = 10000;\n\n Thread.Sleep(dwWaitTime);\n\n // Check the status again.\n\n if (QueryServiceStatus(service, status) == 0) break;\n\n if (status.dwCheckPoint > dwOldCheckPoint)\n {\n // The service is making progress.\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = status.dwCheckPoint;\n }\n else\n {\n if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)\n {\n // No progress made within the wait hint\n break;\n }\n }\n }\n return (status.dwCurrentState == desiredStatus);\n }\n\n private static IntPtr OpenSCManager(ScmAccessRights rights)\n {\n IntPtr scm = OpenSCManager(null, null, rights);\n if (scm == IntPtr.Zero)\n throw new ApplicationException(\"Could not connect to service control manager.\");\n\n return scm;\n }\n}\n\n\npublic enum ServiceState\n{\n Unknown = -1, // The state cannot be (has not been) retrieved.\n NotFound = 0, // The service is not known on the host server.\n Stopped = 1,\n StartPending = 2,\n StopPending = 3,\n Running = 4,\n ContinuePending = 5,\n PausePending = 6,\n Paused = 7\n}\n\n[Flags]\npublic enum ScmAccessRights\n{\n Connect = 0x0001,\n CreateService = 0x0002,\n EnumerateService = 0x0004,\n Lock = 0x0008,\n QueryLockStatus = 0x0010,\n ModifyBootConfig = 0x0020,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | Connect | CreateService |\n EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)\n}\n\n[Flags]\npublic enum ServiceAccessRights\n{\n QueryConfig = 0x1,\n ChangeConfig = 0x2,\n QueryStatus = 0x4,\n EnumerateDependants = 0x8,\n Start = 0x10,\n Stop = 0x20,\n PauseContinue = 0x40,\n Interrogate = 0x80,\n UserDefinedControl = 0x100,\n Delete = 0x00010000,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |\n QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |\n Interrogate | UserDefinedControl)\n}\n\npublic enum ServiceBootFlag\n{\n Start = 0x00000000,\n SystemStart = 0x00000001,\n AutoStart = 0x00000002,\n DemandStart = 0x00000003,\n Disabled = 0x00000004\n}\n\npublic enum ServiceControl\n{\n Stop = 0x00000001,\n Pause = 0x00000002,\n Continue = 0x00000003,\n Interrogate = 0x00000004,\n Shutdown = 0x00000005,\n ParamChange = 0x00000006,\n NetBindAdd = 0x00000007,\n NetBindRemove = 0x00000008,\n NetBindEnable = 0x00000009,\n NetBindDisable = 0x0000000A\n}\n\npublic enum ServiceError\n{\n Ignore = 0x00000000,\n Normal = 0x00000001,\n Severe = 0x00000002,\n Critical = 0x00000003\n}\n"
},
{
"answer_id": 4405482,
"author": "Brian Low",
"author_id": 46039,
"author_profile": "https://Stackoverflow.com/users/46039",
"pm_score": 3,
"selected": false,
"text": "MyService.exe install\n"
},
{
"answer_id": 11619451,
"author": "Newtopian",
"author_id": 25812,
"author_profile": "https://Stackoverflow.com/users/25812",
"pm_score": 4,
"selected": false,
"text": "ManagedInstallerClass.InstallHelper(new string[] { \n Assembly.GetExecutingAssembly().Location });\n ManagedInstallerClass.InstallHelper(new string[] { \"/u\", \n Assembly.GetExecutingAssembly().Location });\n System.Environment.UserInteractive"
},
{
"answer_id": 18447185,
"author": "Tayfur Yılmaz",
"author_id": 1222187,
"author_profile": "https://Stackoverflow.com/users/1222187",
"pm_score": 1,
"selected": false,
"text": " [DllImport(\"advapi32.dll\", EntryPoint = \"CreateServiceA\")]\n\n private static extern IntPtr CreateService(IntPtr hSCManager, string\n\n lpServiceName, string lpDisplayName, ServiceRights dwDesiredAccess, int\n\n dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl,\n\n string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string\n\n lpDependencies, string lp, string lpPassword); \n"
},
{
"answer_id": 27177669,
"author": "mJay",
"author_id": 2165019,
"author_profile": "https://Stackoverflow.com/users/2165019",
"pm_score": 3,
"selected": false,
"text": "InstallAndStart lp lpPassword public static void InstallAndStart(\n string serviceName, \n string displayName, \n string fileName, \n string username, \n string password)\n{\n IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);\n\n try\n {\n IntPtr service = OpenService(\n scm, \n serviceName, \n ServiceAccessRights.AllAccess);\n\n if (service == IntPtr.Zero)\n service = CreateService(\n scm, \n serviceName, \n displayName, \n ServiceAccessRights.AllAccess, \n SERVICE_WIN32_OWN_PROCESS, \n ServiceBootFlag.AutoStart, \n ServiceError.Normal, \n fileName, \n null, \n IntPtr.Zero, \n null, \n username, \n password);\n\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Failed to install service.\");\n\n try\n {\n StartService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n}\n"
},
{
"answer_id": 36011424,
"author": "Mahsh Nikam",
"author_id": 3262774,
"author_profile": "https://Stackoverflow.com/users/3262774",
"pm_score": 0,
"selected": false,
"text": "public void InstallWinService(string winServicePath)\n{\n try\n {\n ManagedInstallerClass.InstallHelper(new string[] { winServicePath});\n }\n catch (Exception)\n {\n\n throw;\n }\n}\n"
},
{
"answer_id": 61347817,
"author": "Ali Sharafi",
"author_id": 1871733,
"author_profile": "https://Stackoverflow.com/users/1871733",
"pm_score": 2,
"selected": false,
"text": " public static class ServiceHelper\n {\n private const int STANDARD_RIGHTS_REQUIRED = 0xF0000;\n private const int SERVICE_WIN32_OWN_PROCESS = 0x00000010;\n\n [StructLayout(LayoutKind.Sequential)]\n private class SERVICE_STATUS\n {\n public int dwServiceType = 0;\n public ServiceState dwCurrentState = 0;\n public int dwControlsAccepted = 0;\n public int dwWin32ExitCode = 0;\n public int dwServiceSpecificExitCode = 0;\n public int dwCheckPoint = 0;\n public int dwWaitHint = 0;\n }\n\n #region OpenSCManager\n [DllImport(\"advapi32.dll\", EntryPoint = \"OpenSCManagerW\", ExactSpelling = true, CharSet = CharSet.Unicode, SetLastError = true)]\n static extern IntPtr OpenSCManager(string machineName, string databaseName, ScmAccessRights dwDesiredAccess);\n #endregion\n\n #region OpenService\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n static extern IntPtr OpenService(IntPtr hSCManager, string lpServiceName, ServiceAccessRights dwDesiredAccess);\n #endregion\n\n #region CreateService\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Auto)]\n private static extern IntPtr CreateService(IntPtr hSCManager, string lpServiceName, string lpDisplayName, ServiceAccessRights dwDesiredAccess, int dwServiceType, ServiceBootFlag dwStartType, ServiceError dwErrorControl, string lpBinaryPathName, string lpLoadOrderGroup, IntPtr lpdwTagId, string lpDependencies, string lp, string lpPassword);\n #endregion\n\n #region CloseServiceHandle\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n static extern bool CloseServiceHandle(IntPtr hSCObject);\n #endregion\n\n #region QueryServiceStatus\n [DllImport(\"advapi32.dll\")]\n private static extern int QueryServiceStatus(IntPtr hService, SERVICE_STATUS lpServiceStatus);\n #endregion\n\n #region DeleteService\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n [return: MarshalAs(UnmanagedType.Bool)]\n private static extern bool DeleteService(IntPtr hService);\n #endregion\n\n #region ControlService\n [DllImport(\"advapi32.dll\")]\n private static extern int ControlService(IntPtr hService, ServiceControl dwControl, SERVICE_STATUS lpServiceStatus);\n #endregion\n\n #region StartService\n [DllImport(\"advapi32.dll\", SetLastError = true)]\n private static extern int StartService(IntPtr hService, int dwNumServiceArgs, string[] lpServiceArgVectors);\n #endregion\n\n public static void Uninstall(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Service not installed.\");\n\n try\n {\n StopService(service);\n if (!DeleteService(service))\n throw new ApplicationException(\"Could not delete service \" + Marshal.GetLastWin32Error());\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static bool ServiceIsInstalled(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);\n\n if (service == IntPtr.Zero)\n return false;\n\n CloseServiceHandle(service);\n return true;\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void InstallAndStart(string serviceName, string displayName, string fileName,string[] args)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.AllAccess);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.AllAccess);\n\n if (service == IntPtr.Zero)\n service = CreateService(scm, serviceName, displayName, ServiceAccessRights.AllAccess, SERVICE_WIN32_OWN_PROCESS, ServiceBootFlag.AutoStart, ServiceError.Normal, fileName, null, IntPtr.Zero, null, null, null);\n\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Failed to install service.\");\n\n try\n {\n StartService(service,args);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void StartService(string serviceName,string[] args)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Start);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Could not open service.\");\n\n try\n {\n StartService(service,args);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n public static void StopService(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus | ServiceAccessRights.Stop);\n if (service == IntPtr.Zero)\n throw new ApplicationException(\"Could not open service.\");\n\n try\n {\n StopService(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n private static void StartService(IntPtr service,string[] args)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n StartService(service, args.Length, args);\n var changedStatus = WaitForServiceStatus(service, ServiceState.StartPending, ServiceState.Running);\n if (!changedStatus)\n throw new ApplicationException(\"Unable to start service\");\n }\n\n private static void StopService(IntPtr service)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n ControlService(service, ServiceControl.Stop, status);\n var changedStatus = WaitForServiceStatus(service, ServiceState.StopPending, ServiceState.Stopped);\n if (!changedStatus)\n throw new ApplicationException(\"Unable to stop service\");\n }\n\n public static ServiceState GetServiceStatus(string serviceName)\n {\n IntPtr scm = OpenSCManager(ScmAccessRights.Connect);\n\n try\n {\n IntPtr service = OpenService(scm, serviceName, ServiceAccessRights.QueryStatus);\n if (service == IntPtr.Zero)\n return ServiceState.NotFound;\n\n try\n {\n return GetServiceStatus(service);\n }\n finally\n {\n CloseServiceHandle(service);\n }\n }\n finally\n {\n CloseServiceHandle(scm);\n }\n }\n\n private static ServiceState GetServiceStatus(IntPtr service)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n\n if (QueryServiceStatus(service, status) == 0)\n throw new ApplicationException(\"Failed to query service status.\");\n\n return status.dwCurrentState;\n }\n\n private static bool WaitForServiceStatus(IntPtr service, ServiceState waitStatus, ServiceState desiredStatus)\n {\n SERVICE_STATUS status = new SERVICE_STATUS();\n\n QueryServiceStatus(service, status);\n if (status.dwCurrentState == desiredStatus) return true;\n\n int dwStartTickCount = Environment.TickCount;\n int dwOldCheckPoint = status.dwCheckPoint;\n\n while (status.dwCurrentState == waitStatus)\n {\n // Do not wait longer than the wait hint. A good interval is\n // one tenth the wait hint, but no less than 1 second and no\n // more than 10 seconds.\n\n int dwWaitTime = status.dwWaitHint / 10;\n\n if (dwWaitTime < 1000) dwWaitTime = 1000;\n else if (dwWaitTime > 10000) dwWaitTime = 10000;\n\n Thread.Sleep(dwWaitTime);\n\n // Check the status again.\n\n if (QueryServiceStatus(service, status) == 0) break;\n\n if (status.dwCheckPoint > dwOldCheckPoint)\n {\n // The service is making progress.\n dwStartTickCount = Environment.TickCount;\n dwOldCheckPoint = status.dwCheckPoint;\n }\n else\n {\n if (Environment.TickCount - dwStartTickCount > status.dwWaitHint)\n {\n // No progress made within the wait hint\n break;\n }\n }\n }\n return (status.dwCurrentState == desiredStatus);\n }\n\n private static IntPtr OpenSCManager(ScmAccessRights rights)\n {\n IntPtr scm = OpenSCManager(null, null, rights);\n if (scm == IntPtr.Zero)\n throw new ApplicationException(\"Could not connect to service control manager.\");\n\n return scm;\n }\n }\n\n\n public enum ServiceState\n {\n Unknown = -1, // The state cannot be (has not been) retrieved.\n NotFound = 0, // The service is not known on the host server.\n Stopped = 1,\n StartPending = 2,\n StopPending = 3,\n Running = 4,\n ContinuePending = 5,\n PausePending = 6,\n Paused = 7\n }\n\n [Flags]\n public enum ScmAccessRights\n {\n Connect = 0x0001,\n CreateService = 0x0002,\n EnumerateService = 0x0004,\n Lock = 0x0008,\n QueryLockStatus = 0x0010,\n ModifyBootConfig = 0x0020,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | Connect | CreateService |\n EnumerateService | Lock | QueryLockStatus | ModifyBootConfig)\n }\n\n [Flags]\n public enum ServiceAccessRights\n {\n QueryConfig = 0x1,\n ChangeConfig = 0x2,\n QueryStatus = 0x4,\n EnumerateDependants = 0x8,\n Start = 0x10,\n Stop = 0x20,\n PauseContinue = 0x40,\n Interrogate = 0x80,\n UserDefinedControl = 0x100,\n Delete = 0x00010000,\n StandardRightsRequired = 0xF0000,\n AllAccess = (StandardRightsRequired | QueryConfig | ChangeConfig |\n QueryStatus | EnumerateDependants | Start | Stop | PauseContinue |\n Interrogate | UserDefinedControl)\n }\n\n public enum ServiceBootFlag\n {\n Start = 0x00000000,\n SystemStart = 0x00000001,\n AutoStart = 0x00000002,\n DemandStart = 0x00000003,\n Disabled = 0x00000004\n }\n\n public enum ServiceControl\n {\n Stop = 0x00000001,\n Pause = 0x00000002,\n Continue = 0x00000003,\n Interrogate = 0x00000004,\n Shutdown = 0x00000005,\n ParamChange = 0x00000006,\n NetBindAdd = 0x00000007,\n NetBindRemove = 0x00000008,\n NetBindEnable = 0x00000009,\n NetBindDisable = 0x0000000A\n }\n\n public enum ServiceError\n {\n Ignore = 0x00000000,\n Normal = 0x00000001,\n Severe = 0x00000002,\n Critical = 0x00000003\n }\n"
},
{
"answer_id": 67962471,
"author": "Zohar",
"author_id": 2630035,
"author_profile": "https://Stackoverflow.com/users/2630035",
"pm_score": 0,
"selected": false,
"text": " System.Diagnostics.Process process = new System.Diagnostics.Process();\n System.Diagnostics.ProcessStartInfo startInfo = new \n System.Diagnostics.ProcessStartInfo();\n startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;\n startInfo.FileName = \"cmd.exe\";\n startInfo.Arguments = \"/C sc create MyService binpath=\\\"c:\\\\...\\\\MyService.exe\\\"\";\n process.StartInfo = startInfo;\n process.Start();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358700",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17443/"
] |
358,714 | <p>I know that in C#, if you write <code>~MyClass()</code>, this basically translates to <code>override System.Object.Finalize()</code>. So, whether you write the <em>destructor</em> or not, every type in CLR will have a <code>Finalize()</code> method in it (of <code>System.Object</code> at least).</p>
<p>1] So, does it mean that, every object, by default, <strong>has</strong> a finalizer ?</p>
<p>2] What is the basis for the CLR to decide that an object should be put through finalization queue ? </p>
<p>I'm asking this, because, I had a class, say <code>ManagedResourceHolder</code> that implemented <code>IDisposable</code>, but did not call <code>GC.SuppressFinalize(this)</code> in its <code>IDisposable.Dispose()</code> method. The class did not hold any unmanaged resources, and there was no need for the <code>~ManagedResourceHolder()</code> method, which in turn meant no need for the <code>GC.SuppressFinalize(this)</code> call as there was no <em>finalizer</em>.</p>
<p>3] In context of the above scenario, is it <strong>always</strong> necessary to provide a finalizer when you implement IDisposable ? (even on a class that holds no unmanaged resources)</p>
<p>The FxCop rule <a href="http://msdn.microsoft.com/en-us/library/ms182269.aspx" rel="noreferrer">CA1816</a> was giving me a violation on this and the response I got <a href="http://social.msdn.microsoft.com/Forums/en-US/vstscode/thread/4e8a3155-6f12-4888-9ca1-f6762761e038" rel="noreferrer">here</a> when I asked in the CA forum on MSDN confused me.</p>
<p>Thanks.</p>
| [
{
"answer_id": 358715,
"author": "mmx",
"author_id": 33708,
"author_profile": "https://Stackoverflow.com/users/33708",
"pm_score": 0,
"selected": false,
"text": "Finalize()"
},
{
"answer_id": 358716,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "base.Finalize() System.Object.Finalize() Finalize base.Finalize FileStream IDisposable Dispose() FileStream"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358714",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42913/"
] |
358,718 | <p>I have a fairly expensive array calculation (SpectralResponse) which I like to keep to a minimum. I figured the best way is to store them and bring it back up when same array is needed again in the future. The decision is made using BasicParameters.</p>
<p>So right now, I use a LinkedList of object for the arrays of SpectralResponse, and another LinkedList for the BasicParameter. And the BasicParameters has a isParamsEqualTo(BasicParameters) method to compare the parameter set.</p>
<pre><code>LinkedList<SpectralResponse> responses
LinkedList<BasicParameters> fitParams
LinkedList<Integer> responseNumbers
</code></pre>
<p>So to look up, I just go through the list of BasicParameters, check for match, if matched, return the SpectralResponse. If no match, then calculate the SpectralResponse. </p>
<p>Here's is the for loop I used to lookup. </p>
<pre><code>size: LinkedList size, limited to a reasonable value
responseNumber: just another variable to distinguish the SpectralResponse.
for ( i = size-1; i > 0 ; i--) {
if (responseNumbers.get(i) == responseNum)
{
tempFit = fitParams.get(i);
if (tempFit.isParamsEqualTo(fit))
{
return responses.get(i);
}
}
}
</code></pre>
<p>But somehow, doing it this way no only take out lots of memory, it's actually slower than just calculating SpectralResponse straight. Much slower.</p>
<p>So it is my implementation that's wrong, or I was mistaken that precalculating and lookup is faster?</p>
| [
{
"answer_id": 376220,
"author": "Nicholas White",
"author_id": 42543,
"author_profile": "https://Stackoverflow.com/users/42543",
"pm_score": 0,
"selected": false,
"text": "if (responseNumbers.get(i) == responseNum) responseNumbers.get(i)"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358718",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9774/"
] |
358,721 | <p>I have a scenario when I start 3..10 threads with ThreadPool.
Each thread does its job and returns to the ThreadPool.
What are possible options to be notified in main thread when all background threads have finished?</p>
<p>Currently I'm using a homegrown method with incrementing a variable for each of created threads and decrementing it when a background thread is about to finish.
This works just fine, but I was curious if there are better options.</p>
| [
{
"answer_id": 358733,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 5,
"selected": true,
"text": "Interlocked.Decrement Parallel.ForEach"
},
{
"answer_id": 358879,
"author": "DonkeyMaster",
"author_id": 5178,
"author_profile": "https://Stackoverflow.com/users/5178",
"pm_score": 0,
"selected": false,
"text": " int length = 10;\n ManualResetEvent[] waits = new ManualResetEvent[length];\n for ( int i = 0; i < length; i++ ) {\n waits[i] = new ManualResetEvent( false );\n ThreadPool.QueueUserWorkItem( (obj) => {\n try {\n\n } finally {\n waits[i].Set();\n }\n } );\n }\n\n for ( int i = 0; i < length; i++ ) {\n if ( !waits[i].WaitOne() )\n break;\n }\n"
},
{
"answer_id": 359038,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 2,
"selected": false,
"text": "List<WaitHandle> events = new List<WaitHandle>();\nfor (int i = 0; i < 64; i++)\n{\n ManualResetEvent mre = new ManualResetEvent(false);\n ThreadPool.QueueUserWorkItem(\n delegate(object o)\n {\n Thread.Sleep(TimeSpan.FromMinutes(1));\n ((ManualResetEvent)o).Set();\n },mre);\n events.Add(mre);\n}\nWaitHandle.WaitAll(events.ToArray());\n"
},
{
"answer_id": 8366322,
"author": "user1078733",
"author_id": 1078733,
"author_profile": "https://Stackoverflow.com/users/1078733",
"pm_score": 2,
"selected": false,
"text": "using (var poolGuard = new PoolGuard())\n{\n for (int i = 0; i < ...\n {\n ThreadPool.QueueUserWorkItem(ChildThread, poolGuard);\n }\n // Do stuff.\n poolGuard.WaitOne();\n // Do stuff that required the child threads to have ended.\n\nvoid ChildThread(object state)\n{\n var poolGuard = state as PoolGuard;\n if (poolGuard.TryEnter())\n {\n try\n {\n // Do stuff.\n }\n finally\n {\n poolGuard.Exit();\n }\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358721",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/430254/"
] |
358,730 | <p>I have a jsp page with two radio tags. </p>
<p>The page contains a struts2 form. When I submit the form one of two radio must be automatically checked.</p>
<p>Is it possible to do that?</p>
| [
{
"answer_id": 358749,
"author": "annakata",
"author_id": 13018,
"author_profile": "https://Stackoverflow.com/users/13018",
"pm_score": 3,
"selected": true,
"text": "checked=\"checked\""
},
{
"answer_id": 358750,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 0,
"selected": false,
"text": "<html:radio property=\"foo\" value=\"yes\"/>\n getFoo()"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39339/"
] |
358,760 | <p>I am implementing a database design that has a vehicle table, vehicle engine and vehicle gear table with SQL 2005.</p>
<p>Each table has an ID that is a SQL identity number, and each engine and gear has a relation with the vehicle ID.
So before I create a vehicle I must create an engine and gear.</p>
<p>How could I know the vehicle identity number when creating the engine and gear? The vehicle row hasn't yet been created because of the foreign key constraint with the engine and gear tables?</p>
<p>Should I implement an automatic trigger that on a creation of a vehicle creates an empty row for the engine and gear linked to the vehicle? But again how could I know the vehicle ID?</p>
| [
{
"answer_id": 358863,
"author": "Carl",
"author_id": 2136,
"author_profile": "https://Stackoverflow.com/users/2136",
"pm_score": 0,
"selected": false,
"text": "CREATE VIEW VehicleComplete AS SELECT * FROM Vehicle INNER JOIN VehicleEngine USING(VehicleID)\n\nUPDATE VehicleComplete SET Rego = 'ABC 123', EngineModel = '380' WHERE VehicleID = 1\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358760",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38963/"
] |
358,764 | <p>I need to exclude files with the following pattern:</p>
<p>ProjectFoo.Data[0-9]{14}.lgp</p>
<p>How can I use RegEx for (Visual)SVN ignore list?</p>
| [
{
"answer_id": 358928,
"author": "Bert Huijben",
"author_id": 2094,
"author_profile": "https://Stackoverflow.com/users/2094",
"pm_score": 4,
"selected": true,
"text": "ProjectFoo.Data[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].lgp\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358764",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2104/"
] |
358,772 | <p>With Symfony's Action Security if a user has not been identified he will be forwarded to the default login action as defined in the applications settings.yml file. How would I forward the user to the originally requested action after the user is successfully authenticated?</p>
| [
{
"answer_id": 364228,
"author": "deresh",
"author_id": 11851,
"author_profile": "https://Stackoverflow.com/users/11851",
"pm_score": 4,
"selected": true,
"text": "if(!$this->getUser()->hasParameter('referer'))\n{\n $this->getUser()->setParameter('referer',$this->getRequest()->getReferer());\n}\n $this->redirect($this->getUser()->getParameter('referer'));\n"
},
{
"answer_id": 1397690,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 1,
"selected": false,
"text": "$this->getUser()->setReferer($this->getRequest()->getReferer());\n setReferer($referer)\n{\n if (!$this->hasAttribute('referer'))\n $this->setAttribute('referer', $referer);\n}\n"
},
{
"answer_id": 6863430,
"author": "Druckles",
"author_id": 840714,
"author_profile": "https://Stackoverflow.com/users/840714",
"pm_score": 0,
"selected": false,
"text": "if ($this->getUser()->hasFlash('referer'))\n{\n $this->getUser()->setFlash('referer', $this->getUser()->getFlash('referer'));\n}\nelse\n{ \n $this->getUser()->setFlash('referer', $this->getRequest()->getReferer());\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358772",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/200521/"
] |
358,780 | <p>I have a method, which will accept a parameter of a JQuery Object and will calculate totals for a section. So if you give it a JQuery Object of a div containing the section it will calculate a total for it</p>
<p>so you can do this:</p>
<p>var $totalcompletion = CalculateSectionCompletion(jQuery("#Section1"));</p>
<p>Now I have multiple divs with the class of section container. I want to be able to call the above method on any div with that class.</p>
<p>I'm doing this:</p>
<p>jQuery("div.SectionContainer").each(
function(i, valueOfElement){<br>
CalculateSectionCompletion(valueOfElement);<br>
});</p>
<p>The problem is the valueOfElement is actually the DOM object and not the JQuery Object, so I can't pass this in to my method.</p>
<p>Is there anyway I can loop through all JQuery Objects selected by a query, without writing some dirty code to extract the Id from the DOM object, and call JQuery(valueOfElement.id) and pass it in?</p>
| [
{
"answer_id": 358806,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 3,
"selected": true,
"text": "jQuery(\"div.SectionContainer\").each( function(i, valueOfElement){\n CalculateSectionCompletion($(valueOfElement));\n});\n"
},
{
"answer_id": 358862,
"author": "roborourke",
"author_id": 42147,
"author_profile": "https://Stackoverflow.com/users/42147",
"pm_score": 2,
"selected": false,
"text": "jQuery(\"div.SectionContainer\").each(function(){\n CalculateSectionCompletion(jQuery(this));\n});\n jQuery(\"div.SectionContainer\").each(function(){\n CalculateSectionCompletion(this);\n});\n\nfunction CalculateSectionCopletion(e){\n jQuery(e).dostuff();\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45279/"
] |
358,783 | <p>I have a script which uses pexpect to start a CLI program. It works a bit like a shell where you get a prompt where you can enter some commands.</p>
<p>The problem I have, I think, is that this program uses a coloured prompt.</p>
<p>This is what I do </p>
<pre><code>import pprint
import pexpect
1 a = pexpect.spawn('program')
2 a.expect("prompt>")
3 print "---------start------------"
4 print(a.before)
5 a.sendline("command")
6 a.expect("prompt>")
7 print "---------before------------"
8 pprint.pprint(a.before)
9 print "---------after------------"
10 pprint.pprint(a.after)
</code></pre>
<p>This is the output:</p>
<pre><code>> python borken.py
---------start------------
A lot of text here from the enjoying programs start-up, lorem ipsum ...
---------before------------
' \x1b[0m\x1b[8D\x1b[K\x1b[1m\x1b[34m'
---------after------------
'prompt>'
</code></pre>
<p>For some reason the first prompt colour coding borkens up things and a.before at line 8 is garbled, normal print does not work, even if I see that the command at line 5 actually produced a lot of output.</p>
<p>Does someone know what the problem could be, or is it possible to set the terminal type in pexpect to avoid the colours?</p>
<p>I am using tcsh shell</p>
| [
{
"answer_id": 358794,
"author": "csl",
"author_id": 21028,
"author_profile": "https://Stackoverflow.com/users/21028",
"pm_score": 2,
"selected": false,
"text": "shell_cmd = 'ls -l | grep LOG > log_list.txt'\nchild = pexpect.spawn('/bin/bash', ['-c', shell_cmd])\nchild.expect(pexpect.EOF)\n child = pexpect.spawn('TERM=vt100 /bin/bash', ['-c', shell_cmd])\n"
},
{
"answer_id": 359241,
"author": "Rickard Lindroth",
"author_id": 12126,
"author_profile": "https://Stackoverflow.com/users/12126",
"pm_score": 4,
"selected": true,
"text": "a = pexpect.spawn('program', env = {\"TERM\": \"dumb\"})\n import os\nos.environ[\"TERM\"] = \"dumb\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358783",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12126/"
] |
358,786 | <p>What are the patterns and dos and don'ts when one is writing tests for <a href="http://javolution.org/" rel="nofollow noreferrer">Javolution</a> tests? In particular I was wondering:</p>
<ul>
<li>TestCase.execute() does not allow throwing of exceptions. How to deal with them? Rethrow as RuntimeException or store in a variable and assert in TestCase.validate() or something?</li>
<li>Are there any graphical runners that show you the tests that fail, i.e. in Eclipse? Perhaps someone wrote a JUnit-Wrapper such that I could use the Eclipse JUnit Runner?</li>
</ul>
| [
{
"answer_id": 385911,
"author": "Hans-Peter Störr",
"author_id": 21499,
"author_profile": "https://Stackoverflow.com/users/21499",
"pm_score": 0,
"selected": false,
"text": "protected final javolution.testing.TestCase test;\n\npublic JavolutionJUnit4Adapter(javolution.testing.TestCase testcase) {\n this.test = testcase;\n}\n\n@org.junit.Test\npublic void executeTest() throws Exception {\n enter(REGRESSION);\n try {\n new javolution.testing.TestSuite() {\n @Override\n public void run() {\n test(test);\n }\n }.run();\n } finally {\n exit();\n }\n}\n\n@Parameters\npublic static Collection<javolution.testing.TestCase[]> data() {\n javolution.testing.TestSuite fp = new WhateverSuiteYouWantToRun();\n List<javolution.testing.TestCase> tests = fp.getTestCases();\n Collection<javolution.testing.TestCase[]> res = new ArrayList<javolution.testing.TestCase[]>();\n for (javolution.testing.TestCase t : tests) {\n res.add(new javolution.testing.TestCase[] { t });\n }\n return res;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358786",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21499/"
] |
358,788 | <p>I've problem with sending HTML mails with <a href="http://phpmailer.worxware.com/index.php?pg=phpmailer" rel="nofollow noreferrer">PHPMailer</a>. I make a <a href="http://en.wikipedia.org/wiki/Smarty" rel="nofollow noreferrer">Smarty</a> template and I got all the HTML code from it. But when I send mail, I got the mail without included CSS (it's only background-color, font or something like that). In PHPMailer I set that the mail is HTML.</p>
<p>Is there any way to send HTML mail with included CSS?</p>
| [
{
"answer_id": 2209829,
"author": "useless",
"author_id": 267351,
"author_profile": "https://Stackoverflow.com/users/267351",
"pm_score": 3,
"selected": false,
"text": " $body = <<< YOUR_HTML_WITH_CSS_STYLE_TAGS\n<html>\n<head>\n <style>\n body * {width:1px;}\n #adiv {padding:2px;}\n .aclass {margin:3px;}\n </style>\n</head>\n<body>\n <div>\n some html\n </div>\n <div id=\"adiv\">\n <p class=\"aclass\">\n </p>\n </div>\n</body>\n</html>\nYOUR_HTML_WITH_CSS_STYLE_TAGS;\n $doc = new DOMDocument();\n @$doc->loadHTML($body);\n $xpd = new DOMXPath($doc);\n 0&&$node = new DOMElement();\n $result = $xpd->query('//img');\n foreach($result as $node){\n $attr = $node->getAttribute('src');\n $re = '/(http:\\/\\/.*?)?(\\/.*+)/i';\n if(preg_match_all($re, $attr, $matches)){\n if(!empty($matches[1][0])&&0)\n continue;\n $attr = 'http://'.$_SERVER['HTTP_HOST'].$matches[2][0];\n }\n $node->setAttribute('src',$attr);\n }\n false&&$node=new DOMElement()&&$child=new DOMElement();\n $result = $xpd->query('//style/..');\n foreach($result as $node){\n foreach($node->childNodes as $child){\n if(strtolower($child->nodeName)=='style'){\n $node->removeChild($child);\n $css = $child->textContent;\n $re = '/(.*?)\\{([^}]+)\\}/';\n if(preg_match_all($re, $css, $matches)){\n foreach($matches[1] as $idx=>$css_selector){\n $css_text = $matches[2][$idx];\n $css_text = preg_replace('/\\s+/',' ',$css_text);\n $css = new CSSQuery($doc);\n foreach($css->query($css_selector) as $selected_node){\n $style = $selected_node->getAttribute('style');\n $selected_node->setAttribute('style', $style?$css_text:$style.';'.$css_text);\n }\n }\n }\n }\n }\n }\n $body = $doc->saveHTML();\n <html>\n<head>\n</head>\n<body>\n <div style=\"width:1px;\">\n some html\n </div>\n <div id=\"adiv\" style=\"width:1px;padding:2px;\">\n <p class=\"aclass\" style=\"width:1px;margin:3px;\">\n </p>\n </div>\n</body>\n</html>\n CSSQuery"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358788",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/461736/"
] |
358,789 | <p>We are having a problem where IE6 (the only browser we have noticed this happening on) seems to be caching an empty version of our main stylesheet. The only way to resolve the problem is to request the stylesheet directly by typing the its url directly into the browser, and then when you refresh the page, it will appear with the styles. About a week or so later, it will happen again.</p>
<p>This isn't happening to all users, but we can't figure out why it is happening.</p>
<p>We are running IIS on Server 2003, and this problem started happening a couple of months ago (never had any problems before that).</p>
<p>I appreciate any help you can offer.</p>
<p>Paul</p>
<p>*I have looked closer and now it is doing the same for certain Javascripts as well.</p>
<ul>
<li>12-12-2008</li>
</ul>
<p>Thanks for the help Grant, IE is fairly locked down, but have checked what can be changed and it is fine, and no extra plug-ins are installed.</p>
<p>If you Ctrl-F5 or kill the temp files it doesn't seem to do anything. It's not until you request the file directly that it actually it actually fixes the problem which does indicate that there is a problem with IE caching a broken or empty version. Unfortunately, I must now wait until it happens again and I'm going to check the log files on the server.</p>
<p>Again thanks for the help.</p>
| [
{
"answer_id": 360240,
"author": "Grant Wagner",
"author_id": 9254,
"author_profile": "https://Stackoverflow.com/users/9254",
"pm_score": 1,
"selected": false,
"text": "Content-type last-modified If-Modified-Since Pragma"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358789",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,791 | <pre><code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
<link href="Stylesheet.css" rel="stylesheet" type="text/css" />
</head>
<body>
<table style="height: 100%; width: 100%;">
<tr>
<td colspan="2" style="height: 100px;">Header</td>
</tr>
<tr>
<td style="width: 180px;">Links</td>
<td>Content</td>
</tr>
<tr>
<td colspan="2" style="height: 25px;">Footer</td>
</tr>
</table>
</body>
</html>
</code></pre>
<p>Stylesheet.css looks as follows:</p>
<pre><code>*
{
margin: 0;
padding: 0;
}
html, body
{
height: 100%;
width: 100%;
}
</code></pre>
<p>Row 1 and 3 above have fixed heights. Row 3 is not filling the remaining space. If i omit the doctype, it works as expected. I need to use this doctype.</p>
| [
{
"answer_id": 358811,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "<div>"
},
{
"answer_id": 453478,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 1,
"selected": false,
"text": "Transitional DOCTYPE Strict DOCTYPE https://developer.mozilla.org/en/Gecko's_%22Almost_Standards%22_Mode\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358791",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,792 | <p>I'm writing a DLL which talks to Excel via its IDispatch interface. From VBA I pass in a Variant containing <code>Application.Caller</code> from which I draw the IDispatch pointer via <code>.pDispVal</code>. </p>
<p>What I'd like to know is how to query the interface via that IDispatch pointer. I want to set up a connection point container, and from there find a connection point to Excel. The ultimate goal is to tie things to Excel's Calculate event and be able to manipulate the Excel data.</p>
| [
{
"answer_id": 358811,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 1,
"selected": false,
"text": "<div>"
},
{
"answer_id": 453478,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 1,
"selected": false,
"text": "Transitional DOCTYPE Strict DOCTYPE https://developer.mozilla.org/en/Gecko's_%22Almost_Standards%22_Mode\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358792",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/426/"
] |
358,793 | <p>I am looking for a specific desgin pattern.</p>
<p>For example i have an article class, clsArticle. This class contains member variables like Id, title, author, article, and so on. Imagine i want to show all the articles in a list. So somewhere i have to create a method getAllArticles(). Since clsArticle is not responsible for getting all the articles, i have to put this method in another class, clsArticleFact (Where Fact stands for Factory).</p>
<p>Does someone know how this pattern is called? Is this way of working a design pattern?</p>
| [
{
"answer_id": 358817,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 3,
"selected": true,
"text": "ArticleFactory.getAll(): Article[]\n WindowsArticleFactory\n OSXArticleFactory\n ArticleDao.getAll(): Article[]\n XmlArticleDao // Return a list of articles from an XML\n DatabaseArticleDao // return the list from the database.\n class Article { \n static Article[] getAll() {\n // do whatever is neede here...\n }\n }\n"
},
{
"answer_id": 358858,
"author": "Claymore",
"author_id": 7510,
"author_profile": "https://Stackoverflow.com/users/7510",
"pm_score": 0,
"selected": false,
"text": "public static class clsArticles\n{\n public static clsArticles[] GetAllArticles() { /* actual code */ }\n}\n"
},
{
"answer_id": 358905,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 1,
"selected": false,
"text": "public class clsArticle\n{\n public static clsArticle[] findAll() { /*... */ }\n\n // the other regular code here;\n}\n\n// client code\nforeach(clsArticle obArticle in clsArticle.findAll())\n{\n list.add(clsArticle)\n}\n"
},
{
"answer_id": 358908,
"author": "Llyle",
"author_id": 27765,
"author_profile": "https://Stackoverflow.com/users/27765",
"pm_score": 0,
"selected": false,
"text": "public class clsClass\n{\n public int ID;\n public string title;\n public string author;\n public string article;\n}\n\n\npublic class BookGateway\n{\n public List<clsClass> GetAllArticles()\n {\n var result = new List<clsClass>();\n\n // Add items here.\n // Can call database and populate each new clsClass\n // and add to result object.\n\n return result;\n }\n}\n"
},
{
"answer_id": 358980,
"author": "eljenso",
"author_id": 30316,
"author_profile": "https://Stackoverflow.com/users/30316",
"pm_score": 0,
"selected": false,
"text": "public interface ArticleService {\n Article[] getAllArticles() throws ServiceException();\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358793",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40676/"
] |
358,797 | <p>I am working on an application where i need to transfer mails from a mailbox to anoter one.I can not send these mails using smtp because this willchange the header information .I am using C# and out look api to process mails . is thre any way i can transfer mails to other mail box without changing mail header.</p>
<hr>
<p>By Transfer I mean, I need to take a mail from one mail box and move this to another mailbox without changing any header information. If I use smtp , header information will be changed. I have heared that using MAPI mail can be moved from one mail box to another mail box. any pointers.</p>
| [
{
"answer_id": 360354,
"author": "Oliver Giesen",
"author_id": 9784,
"author_profile": "https://Stackoverflow.com/users/9784",
"pm_score": 0,
"selected": false,
"text": "MailItem.Move"
},
{
"answer_id": 374136,
"author": "Kapil",
"author_id": 45280,
"author_profile": "https://Stackoverflow.com/users/45280",
"pm_score": 2,
"selected": false,
"text": " rdoSession.LogonExchangeMailbox(\"TEST\", \"ServerName\");\n RDOExchangeMailboxStore mailBoxStore = (Redemption.RDOExchangeMailboxStore)\n rdoSession.Stores.DefaultStore;\n RDOFolder inboxFolder = null;\n\n foreach (RDOFolder rdoFolder in mailBoxStore.IPMRootFolder.Folders)\n {\n if (rdoFolder.Name.Equals(\"Inbox\", StringComparison.InvariantCultureIgnoreCase))\n {\n inboxFolder = rdoFolder;\n break;\n }\n }\n rdoMail.CopyTo(inboxFolder);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358797",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45280/"
] |
358,802 | <p>In our project I have several <a href="http://www.junit.org/" rel="noreferrer">JUnit</a> tests that e.g. take every file from a directory and run a test on it. If I implement a <code>testEveryFileInDirectory</code> method in the <code>TestCase</code> this shows up as only one test that may fail or succeed. But I am interested in the results on each individual file. How can I write a <code>TestCase</code> / <code>TestSuite</code> such that each file shows up as a separate test e.g. in the graphical TestRunner of Eclipse? (Coding an explicit test method for each file is not an option.)</p>
<p>Compare also the question <a href="https://stackoverflow.com/questions/385925/parameterizedtest-with-a-name-in-eclipse-testrunner">ParameterizedTest with a name in Eclipse Testrunner</a>.</p>
| [
{
"answer_id": 358884,
"author": "Michael Borgwardt",
"author_id": 16883,
"author_profile": "https://Stackoverflow.com/users/16883",
"pm_score": 2,
"selected": false,
"text": "TestSuite tests() TestCase"
},
{
"answer_id": 358926,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 8,
"selected": true,
"text": "@RunWith(Parameterized.class)\n Collection @Parameters\n @RunWith(Parameterized.class)\npublic class ParameterizedTest {\n\n private File file;\n\n public ParameterizedTest(File file) {\n this.file = file;\n }\n\n @Test\n public void test1() throws Exception { }\n\n @Test\n public void test2() throws Exception { }\n\n @Parameters\n public static Collection<Object[]> data() {\n // load the files as you want\n Object[] fileArg1 = new Object[] { new File(\"path1\") };\n Object[] fileArg2 = new Object[] { new File(\"path2\") };\n\n Collection<Object[]> data = new ArrayList<Object[]>();\n data.add(fileArg1);\n data.add(fileArg2);\n return data;\n }\n}\n"
},
{
"answer_id": 359004,
"author": "McDowell",
"author_id": 304,
"author_profile": "https://Stackoverflow.com/users/304",
"pm_score": 5,
"selected": false,
"text": "public class XTest extends TestCase {\n\n public File file;\n\n public XTest(File file) {\n super(file.toString());\n this.file = file;\n }\n\n public void testX() {\n fail(\"Failed: \" + file);\n }\n\n}\n\npublic class XTestSuite extends TestSuite {\n\n public static Test suite() {\n TestSuite suite = new TestSuite(\"XTestSuite\");\n File[] files = new File(\".\").listFiles();\n for (File file : files) {\n suite.addTest(new XTest(file));\n }\n return suite;\n }\n\n}\n import org.junit.Test;\nimport org.junit.runner.RunWith;\nimport org.junit.runners.Parameterized;\nimport org.junit.runners.Parameterized.Parameters;\n\n@RunWith(Parameterized.class)\npublic class TestY {\n\n @Parameters\n public static Collection<Object[]> getFiles() {\n Collection<Object[]> params = new ArrayList<Object[]>();\n for (File f : new File(\".\").listFiles()) {\n Object[] arr = new Object[] { f };\n params.add(arr);\n }\n return params;\n }\n\n private File file;\n\n public TestY(File file) {\n this.file = file;\n }\n\n @Test\n public void testY() {\n fail(file.toString());\n }\n\n}\n"
},
{
"answer_id": 24794033,
"author": "Ben Hutchison",
"author_id": 979493,
"author_profile": "https://Stackoverflow.com/users/979493",
"pm_score": 1,
"selected": false,
"text": "public class FileTest {\n\n @DataProvider(name=\"files\")\n public File[][] getFiles(){\n return new File[][] {\n { new File(\"file1\") },\n { new File(\"file2\") }\n };\n // or scan a directory\n }\n\n @Test(dataProvider=\"files\")\n public void testFile(File file){\n //run tests on file\n }\n}\n PASSED: testFile(file1)\nPASSED: testFile(file2)\n\n===============================================\n Default test\n Tests run: 2, Failures: 0, Skips: 0\n===============================================\n"
},
{
"answer_id": 30360402,
"author": "falsarella",
"author_id": 1064325,
"author_profile": "https://Stackoverflow.com/users/1064325",
"pm_score": 2,
"selected": false,
"text": "@org.junit.runner.RunWith(junitparams.JUnitParamsRunner.class)\npublic class ParameterizedTest {\n\n @org.junit.Test\n @junitparams.Parameters(method = \"data\")\n public void test1(File file) throws Exception { }\n\n @org.junit.Test\n @junitparams.Parameters(method = \"data\")\n public void test2(File file) throws Exception { }\n\n public static File[] data() {\n return new File[] { new File(\"path1\"), new File(\"path2\") };\n }\n}\n @org.junit.runner.RunWith(junitparams.JUnitParamsRunner.class)\npublic class ParameterizedTest {\n\n @org.junit.Test\n @junitparams.Parameters(value = { \"path1\", \"path2\" })\n public void test1(String path) throws Exception {\n File file = new File(path);\n }\n\n @org.junit.Test\n @junitparams.Parameters(value = { \"path1\", \"path2\" })\n public void test2(String path) throws Exception {\n File file = new File(path);\n }\n}\n"
},
{
"answer_id": 43055729,
"author": "avandeursen",
"author_id": 165292,
"author_profile": "https://Stackoverflow.com/users/165292",
"pm_score": 4,
"selected": false,
"text": "@ParameterizedTest\n@MethodSource(\"fileProvider\")\nvoid testFile(File f) {\n // Your test comes here\n}\n\nstatic Stream<File> fileProvider() {\n return Arrays.asList(new File(\".\").list()).stream();\n}\n DynamicTest @TestFactory dynamicTest import org.junit.jupiter.api.DynamicTest;\nimport org.junit.jupiter.api.TestFactory;\nimport static org.junit.jupiter.api.DynamicTest.dynamicTest;\n\nimport java.util.stream.Stream;\n\n@TestFactory\npublic Stream<DynamicTest> testFiles() {\n return Arrays.asList(new File(\".\").list())\n .stream()\n .map((file) -> dynamicTest(\n \"Test for file: \" + file,\n () -> { /* Your test comes here */ }));\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358802",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21499/"
] |
358,821 | <p>I've just started to use linq to sql and have run into a problem with inserting a record with an auto incrementing field.</p>
<p>I have created a new instance of a company object defined by linq. it has initialised an auto incrementing field 'companyID' to 0.
InsertOnSubmit() fails with the following invalidOperationException.</p>
<blockquote>
<p>Incorrect autosync specification for
member 'companyID'</p>
</blockquote>
<p>the column attribute IsDbGenerated is true for the companyID property.
I am using sql server 2000.</p>
<p>Edit: Auto-sync is set to OnIsert. The dataype is BigInt in TSQL, long in c#.</p>
<p>Does anyone know why this error is occuring and how it can be resolved?</p>
<p>thanks</p>
| [
{
"answer_id": 4000204,
"author": "ingamx",
"author_id": 484589,
"author_profile": "https://Stackoverflow.com/users/484589",
"pm_score": 2,
"selected": false,
"text": "\"OnInsert\""
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358821",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18966/"
] |
358,826 | <p>I've been trying to fix this for two hours straight and I can't figure it out.</p>
<pre><code>onclick = "location='exceltest.asp?vanjaar=<%=vanjaar%>&vanmaand=<%=vanmaand%>&vandag=<%=vandag%>&totjaar=<%=totjaar%>&totmaand=<%=totmaand%>&totdag=<%=totdag%>'"
</code></pre>
<p>That line of code is in an < input type="button" /> attribute. The button links to a page where an Excel download should be triggered. The values in the URL are from- and to-date-parts. (year, month, day)</p>
<p>this:</p>
<pre><code>onclick = "location='exceltest.asp?fromdate=<%=fromdate%>&todate=<%=todate%>'" />
</code></pre>
<p>does not work, because somehow IE7 reads the date (eg. 2008/1/1) wrong. Something to do with the slashes I think. </p>
<p>But when I try to click the button in IE and thus download the generated file, Internet explorer tries do download the file </p>
<blockquote>
<p>exceltest.asp?vanjaar=2008vanmaand=1vandag=1totjaar=2008totmaand=2totdag=1</p>
</blockquote>
<p>instead of the excel file I want.<br>
FF offers to download the excelfile, but gives (in that excelfile) an overview of an htmlpage with an errormessage telling me my query is wrong (Item cannot be found in the collection corresponding to the requested name or ordinal.) But that CAN'T be, I'm using that exact same query elsewhere, using the same (but restarted) connection.</p>
<p>This is the bit of code I use to instantiate the download of the file:</p>
<pre><code>Response.Buffer = TRUE
Response.ContentType = "application/vnd.ms-excel"
Response.AddHeader "content-disposition", "attachment; filename=overicht.xls"
</code></pre>
<p>There might actually being to things going on here, but I am most insterested in why IE wants to download the asp page and FF offers the right download.</p>
| [
{
"answer_id": 358853,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 2,
"selected": false,
"text": "& onclick=\"\" &"
},
{
"answer_id": 358861,
"author": "Jonathan Lonowski",
"author_id": 15031,
"author_profile": "https://Stackoverflow.com/users/15031",
"pm_score": 1,
"selected": true,
"text": "Server.URLEncode fromdate=<%=Server.URLEncode(fromdate)%>\n Recordset.Fields()"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358826",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42389/"
] |
358,834 | <p>If I want to create a .NET object in the powershell I write something like the following:</p>
<pre><code>[System.Reflection.Assembly]::LoadWithPartialName("System.Xml") | out-null"
$doc = new-object -typename System.Xml.XmlDocument"
</code></pre>
<p>If I want to call a static .Net method I use a command similar to the following line:</p>
<pre><code>$path = [System.String]::Format("{0} {1}", "Hello", "World")
</code></pre>
<p>I don't see the rule behind that. If it works in the first example, why can't I use <code>System.String.Format</code> in the second one?</p>
| [
{
"answer_id": 358919,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 2,
"selected": false,
"text": "// type \"Assembly\" in the \"System.Reflection\" namespace\n[System.Reflection.Assembly] \n\n// member method \"LoadWithPartialName\" of type \"Assembly\"\n[System.Reflection.Assembly]::LoadWithPartialName \n\n// type \"String\" in the \"System\" namespace\n[System.String] \n\n// member method \"Format\" of type \"String\"\n[System.String]::Format\n"
},
{
"answer_id": 359879,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$doc = new-object -typename \"System.Xml.XmlDocument\"\n"
},
{
"answer_id": 359915,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 0,
"selected": false,
"text": "$doc = new-object -typename \"System.Xml.XmlDocument\"\n $doc = new-object -typename \"TypeThatDoesntExsit\" \n"
},
{
"answer_id": 361710,
"author": "Andy Schneider",
"author_id": 45571,
"author_profile": "https://Stackoverflow.com/users/45571",
"pm_score": 3,
"selected": true,
"text": "PS C:\\> $i = [int]\"1\"\nPS C:\\> $i.gettype().Name\nInt32\nPS C:\\> $j = \"1\"\nPS C:\\> $j.gettype().Name\nString\nPS C:\\>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358834",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
358,835 | <p>Assuming the following hypothetical inheritance hierarchy:</p>
<pre><code>public interface IA
{
int ID { get; set; }
}
public interface IB : IA
{
string Name { get; set; }
}
</code></pre>
<p>Using reflection and making the following call: </p>
<pre><code>typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance)
</code></pre>
<p>will only yield the properties of interface <code>IB</code>, which is "<code>Name</code>". </p>
<p>If we were to do a similar test on the following code,</p>
<pre><code>public abstract class A
{
public int ID { get; set; }
}
public class B : A
{
public string Name { get; set; }
}
</code></pre>
<p>the call <code>typeof(B).GetProperties(BindingFlags.Public | BindingFlags.Instance)</code> will return an array of <code>PropertyInfo</code> objects for "<code>ID</code>" and "<code>Name</code>".</p>
<p>Is there an easy way to find all the properties in the inheritance hierarchy for interfaces as in the first example?</p>
| [
{
"answer_id": 358857,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 4,
"selected": false,
"text": "interface ILow { void Low();}\ninterface IFoo : ILow { void Foo();}\ninterface IBar { void Bar();}\ninterface ITest : IFoo, IBar { void Test();}\n\nstatic class Program\n{\n static void Main()\n {\n List<Type> considered = new List<Type>();\n Queue<Type> queue = new Queue<Type>();\n considered.Add(typeof(ITest));\n queue.Enqueue(typeof(ITest));\n while (queue.Count > 0)\n {\n Type type = queue.Dequeue();\n Console.WriteLine(\"Considering \" + type.Name);\n foreach (Type tmp in type.GetInterfaces())\n {\n if (!considered.Contains(tmp))\n {\n considered.Add(tmp);\n queue.Enqueue(tmp);\n }\n }\n foreach (var member in type.GetMembers())\n {\n Console.WriteLine(member.Name);\n }\n }\n }\n}\n"
},
{
"answer_id": 358865,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 2,
"selected": false,
"text": "PropertyInfo[] pis = typeof(IB).GetProperties(BindingFlags.Public | BindingFlags.Instance);\nType[] tt = typeof(IB).GetInterfaces();\nPropertyInfo[] pis2 = tt[0].GetProperties(BindingFlags.Public | BindingFlags.Instance);\n"
},
{
"answer_id": 2444090,
"author": "mythz",
"author_id": 85785,
"author_profile": "https://Stackoverflow.com/users/85785",
"pm_score": 8,
"selected": true,
"text": "public static PropertyInfo[] GetPublicProperties(this Type type)\n{\n if (type.IsInterface)\n {\n var propertyInfos = new List<PropertyInfo>();\n\n var considered = new List<Type>();\n var queue = new Queue<Type>();\n considered.Add(type);\n queue.Enqueue(type);\n while (queue.Count > 0)\n {\n var subType = queue.Dequeue();\n foreach (var subInterface in subType.GetInterfaces())\n {\n if (considered.Contains(subInterface)) continue;\n\n considered.Add(subInterface);\n queue.Enqueue(subInterface);\n }\n\n var typeProperties = subType.GetProperties(\n BindingFlags.FlattenHierarchy \n | BindingFlags.Public \n | BindingFlags.Instance);\n\n var newPropertyInfos = typeProperties\n .Where(x => !propertyInfos.Contains(x));\n\n propertyInfos.InsertRange(0, newPropertyInfos);\n }\n\n return propertyInfos.ToArray();\n }\n\n return type.GetProperties(BindingFlags.FlattenHierarchy\n | BindingFlags.Public | BindingFlags.Instance);\n}\n"
},
{
"answer_id": 13880766,
"author": "Derek Strickland",
"author_id": 1218029,
"author_profile": "https://Stackoverflow.com/users/1218029",
"pm_score": 1,
"selected": false,
"text": " var props = bindingContext.ModelType.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance).ToList();\n\n bindingContext.ModelType.GetInterfaces()\n .ToList()\n .ForEach(i => props.AddRange(i.GetProperties()));\n\n foreach (var property in props)\n"
},
{
"answer_id": 26766221,
"author": "Douglas",
"author_id": 1149773,
"author_profile": "https://Stackoverflow.com/users/1149773",
"pm_score": 7,
"selected": false,
"text": "Type.GetInterfaces public static IEnumerable<PropertyInfo> GetPublicProperties(this Type type)\n{\n if (!type.IsInterface)\n return type.GetProperties();\n\n return (new Type[] { type })\n .Concat(type.GetInterfaces())\n .SelectMany(i => i.GetProperties());\n}\n"
},
{
"answer_id": 47277547,
"author": "sjb-sjb",
"author_id": 6090828,
"author_profile": "https://Stackoverflow.com/users/6090828",
"pm_score": 2,
"selected": false,
"text": " static public IEnumerable<PropertyInfo> GetPropertiesAndInterfaceProperties(this Type type, BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Instance)\n {\n if (!type.IsInterface) {\n return type.GetProperties( bindingAttr);\n }\n\n return type.GetInterfaces().Union(new Type[] { type }).SelectMany(i => i.GetProperties(bindingAttr)).Distinct();\n }\n static public PropertyInfo GetPropertyOrInterfaceProperty(this Type type, string propertyName, BindingFlags bindingAttr = BindingFlags.Public|BindingFlags.Instance)\n {\n if (!type.IsInterface) {\n return type.GetProperty(propertyName, bindingAttr);\n }\n\n return type.GetInterfaces().Union(new Type[] { type }).Select(i => i.GetProperty( propertyName, bindingAttr)).Distinct().Where(propertyInfo => propertyInfo != null).Single();\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358835",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31770/"
] |
358,874 | <p>I'm currently adding verbose tooltips to our site, and I'd like (without having to resort to a whizz-bang jQuery plugin, I know there are many!) to use carriage returns to format the tooltip.</p>
<p>To add the tip I'm using the <code>title</code> attribute. I've looked around the usual sites and using the basic template of:</p>
<pre><code><a title='Tool?Tip?On?New?Line'>link with tip</a>
</code></pre>
<p>I've tried replacing the <code>?</code> with:</p>
<ul>
<li><code><br /></code></li>
<li><code>&013; / &#13;</code></li>
<li><code>\r\n</code></li>
<li><code>Environment.NewLine</code> (I'm using C#)</li>
</ul>
<p>None of the above works. Is it possible?</p>
| [
{
"answer_id": 358880,
"author": "Stefan Mai",
"author_id": 13257,
"author_profile": "https://Stackoverflow.com/users/13257",
"pm_score": 7,
"selected": false,
"text": " title <a href=\"#\" title=\"Line 1 Line 2 Line 3\">Hover for multi-line title</a>"
},
{
"answer_id": 358885,
"author": "Greg Dean",
"author_id": 1200558,
"author_profile": "https://Stackoverflow.com/users/1200558",
"pm_score": 3,
"selected": false,
"text": " "
},
{
"answer_id": 358903,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 9,
"selected": true,
"text": "<a href=\"#\" title='Tool\nTip\nOn\nNew\nLine'>link with tip</a>"
},
{
"answer_id": 358929,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 8,
"selected": false,
"text": " # ;"
},
{
"answer_id": 2523128,
"author": "Juan",
"author_id": 302493,
"author_profile": "https://Stackoverflow.com/users/302493",
"pm_score": 3,
"selected": false,
"text": "
"
},
{
"answer_id": 10319221,
"author": "amurra",
"author_id": 299592,
"author_profile": "https://Stackoverflow.com/users/299592",
"pm_score": 5,
"selected": false,
"text": " <span title=\"First line Second line\">Test</span>\n"
},
{
"answer_id": 12957569,
"author": "Anil Bharadia",
"author_id": 411871,
"author_profile": "https://Stackoverflow.com/users/411871",
"pm_score": 4,
"selected": false,
"text": "$(td).attr(\"title\", \"One \\n Two \\n Three\");\n"
},
{
"answer_id": 13205056,
"author": "cprcrack",
"author_id": 423171,
"author_profile": "https://Stackoverflow.com/users/423171",
"pm_score": 6,
"selected": false,
"text": "divElement.setAttribute(\"title\", \"Line one Line two\"); divElement.setAttribute(\"title\", \"Line one\\x0ALine two\");"
},
{
"answer_id": 13585406,
"author": "Morten Repsdorph Husfeldt",
"author_id": 1844764,
"author_profile": "https://Stackoverflow.com/users/1844764",
"pm_score": 6,
"selected": false,
"text": " "
},
{
"answer_id": 22684105,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<a title='Tool
Tip
On
New
Line'>link with tip</a>\n 
"
},
{
"answer_id": 26717080,
"author": "Ricardo Zea",
"author_id": 321555,
"author_profile": "https://Stackoverflow.com/users/321555",
"pm_score": 3,
"selected": false,
"text": "<a href=\"#\" title=\"First Line
Second Line\">Multiline Tooltip</a>\n<br>\n<br>\n<a href=\"#\" title=\"List:\n • List item here\n • Another list item here\n • Aaaand another list item, lol\">Unordered list tooltip</a>\n"
},
{
"answer_id": 37927995,
"author": "Welshboy",
"author_id": 1408110,
"author_profile": "https://Stackoverflow.com/users/1408110",
"pm_score": 3,
"selected": false,
"text": "document.getElementById(\"ElementID\").title = 'First Line text \\n Second line text'\n"
},
{
"answer_id": 38185862,
"author": "Youans",
"author_id": 1460591,
"author_profile": "https://Stackoverflow.com/users/1460591",
"pm_score": 3,
"selected": false,
"text": " white-space: pre-line;"
},
{
"answer_id": 39593467,
"author": "Juan Cortés",
"author_id": 363262,
"author_profile": "https://Stackoverflow.com/users/363262",
"pm_score": 4,
"selected": false,
"text": "
 	 <button title=\"My to-do list:
	-Item 2
	-Item 3
	-Item 4
		-Subitem 1\">TEST</button>"
},
{
"answer_id": 39658112,
"author": "Zameer Ansari",
"author_id": 2404470,
"author_profile": "https://Stackoverflow.com/users/2404470",
"pm_score": 3,
"selected": false,
"text": "document.getElementById(\"tooltip\").setAttribute(\"title\", \"Tool\\x0ATip\\x0AOn\\x0ANew\\x0ALine\") <p title='Tool\nTip\nOn\nNew\nLine'>Tooltip with <pre>\n new\n line</pre> Works in all browsers</p>\n<hr/>\n\n<p title=\"Tool Tip On New Line\">Tooltip with <code>&#13;</code> Not works Firefox browsers</p>\n<hr/>\n\n<p title='Tool Tip On New Line'>Tooltip with <code>&#10;</code> Works in some browsers</p>\n<hr/>\n\n<p title='Tool
Tip
On
New
Line'>Tooltip with <code>&#xD;</code> May work in some browsers</p>\n<hr/>\n\n<p id='tooltip'>Tooltip with <code>document.getElementById(\"tooltip\").setAttribute(\"title\", \"Tool\\x0ATip\\x0AOn\\x0ANew\\x0ALine\")</code> May work in some browsers</p>\n<hr/>\n\n\n<p title=\"List:\n • List item here\n • Another list item here\n • Aaaand another list item, lol\">Tooltip with <code>• </code>Unordered list tooltip</p>\n<hr/>\n\n\n<p title='Tool\\nTip\\nOn\\nNew\\nLine'>Tooltip with <code>\\n</code> May not work in modern browsers</p>\n<hr/>\n\n<p title='Tool\\tTip\\tOn\\tNew\\tLine'>Tooltip with <code>\\t</code> May not work in modern browsers</p>\n<hr/>\n\n<p title='Tool
Tip
On
New
Line'>Tooltip with <code>&#013;</code> Works in most browsers</p>\n<hr/>"
},
{
"answer_id": 43687205,
"author": "Fstarocka Burns",
"author_id": 5597612,
"author_profile": "https://Stackoverflow.com/users/5597612",
"pm_score": 0,
"selected": false,
"text": " etc\n"
},
{
"answer_id": 45103463,
"author": "Shelby115",
"author_id": 1467644,
"author_profile": "https://Stackoverflow.com/users/1467644",
"pm_score": 2,
"selected": false,
"text": "\\r\\n @{\n var logTooltip = \"Sunday\\r\\nMonday\\r\\netc.\";\n}\n\n<h3 title=\"@logTooltip\">Logs</h3>\n"
},
{
"answer_id": 49875979,
"author": "csandreas1",
"author_id": 6041389,
"author_profile": "https://Stackoverflow.com/users/6041389",
"pm_score": 3,
"selected": false,
"text": "
 data-html=\"true\" data-content <div title=\"Hello 
World\">hover here</div>"
},
{
"answer_id": 50952278,
"author": "Chris",
"author_id": 1308967,
"author_profile": "https://Stackoverflow.com/users/1308967",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<style>\n.tooltip {\n position: relative;\n display: inline-block;\n border-bottom: 1px dotted black;\n}\n\n.tooltip .tooltiptext {\n visibility: hidden;\n width: 120px;\n background-color: #555;\n color: #fff;\n text-align: center;\n border-radius: 6px;\n padding: 5px 0;\n position: absolute;\n z-index: 1;\n bottom: 125%;\n left: 50%;\n margin-left: -60px;\n opacity: 0;\n transition: opacity 0.3s;\n}\n\n.tooltip .tooltiptext::after {\n content: \"\";\n position: absolute;\n top: 100%;\n left: 50%;\n margin-left: -5px;\n border-width: 5px;\n border-style: solid;\n border-color: #555 transparent transparent transparent;\n}\n\n.tooltip:hover .tooltiptext {\n visibility: visible;\n opacity: 1;\n}\n</style>\n<body style=\"text-align:center;\">\n\n<h2>Tooltip</h2>\n<p>Move the mouse <a href=\"#\" title=\"some text\nmore and then some\">over</a> the text below:</p>\n\n<div class=\"tooltip\">Hover over me\n<span class=\"tooltiptext\">Tooltip text\nsome <b>more</b><br/>\n<i>and</i> more</span>\n</div>\n\n<div class=\"tooltip\">Each tooltip is independent\n<span class=\"tooltiptext\">Other tooltip text\nsome more<br/>\nand more</span>\n</div>\n\n</body>\n</html>\n"
},
{
"answer_id": 52184677,
"author": "Nithin C",
"author_id": 5648505,
"author_profile": "https://Stackoverflow.com/users/5648505",
"pm_score": -1,
"selected": false,
"text": "data-html=\"true\" <br>"
},
{
"answer_id": 58724030,
"author": "Niket Joshi",
"author_id": 8693964,
"author_profile": "https://Stackoverflow.com/users/8693964",
"pm_score": 0,
"selected": false,
"text": " "
},
{
"answer_id": 59654766,
"author": "David Vielhuber",
"author_id": 2068362,
"author_profile": "https://Stackoverflow.com/users/2068362",
"pm_score": 4,
"selected": false,
"text": " "
},
{
"answer_id": 61534004,
"author": "user3416126",
"author_id": 3416126,
"author_profile": "https://Stackoverflow.com/users/3416126",
"pm_score": 0,
"selected": false,
"text": "
 <CR> <option title=\"Constraint PSC/SCS/Activity\nDefinition Constraint Checker\nDatabase Start Notifier\">CnCk\n"
},
{
"answer_id": 66701407,
"author": "Luís Alves",
"author_id": 11719390,
"author_profile": "https://Stackoverflow.com/users/11719390",
"pm_score": 0,
"selected": false,
"text": "function customTitle(event, textHeader, text){\n let eventOrigin = event.target || event.srcElement;\n eventOrigin.title = textHeader + '\\n\\n' + text;\n}\n onmouseover=\"customTitle(event, 'Some Caput', 'Some more or less complete description');\"\n"
},
{
"answer_id": 70243600,
"author": "Siddhesh T",
"author_id": 3070768,
"author_profile": "https://Stackoverflow.com/users/3070768",
"pm_score": 0,
"selected": false,
"text": "title={`First line of text ${varOne} Second line of text ${varTwo} Third line of text ${varThree}`}\n title={`First line of text ${varOne}\nSecond line of text ${varTwo}\nThird line of text ${varThree}`}\n"
},
{
"answer_id": 71127085,
"author": "john2002",
"author_id": 18213515,
"author_profile": "https://Stackoverflow.com/users/18213515",
"pm_score": 1,
"selected": false,
"text": "
 
 <a href=\"javascript:;\" title=\"Tooltip Line One Tooltip Line Two Tooltip Line Three\">Tooltip</a>"
},
{
"answer_id": 71275172,
"author": "Mostafa Arian Nejad",
"author_id": 8551764,
"author_profile": "https://Stackoverflow.com/users/8551764",
"pm_score": 1,
"selected": false,
"text": "data-toggle=\"tooltip\" data-html=\"true\" title <br> <i class=\"bi bi-x-circle\" data-toggle=\"tooltip\" data-placement=\"top\" title=\"test1 <br> test2\"></i>\n <i class=\"bi bi-x-circle\" data-toggle=\"tooltip\" data-html=\"true\" data-placement=\"top\" title=\"test1 <br> test2\"></i>\n \\n <br> nl2br(\"string\")"
},
{
"answer_id": 71822195,
"author": "Zahid Rouf",
"author_id": 3464564,
"author_profile": "https://Stackoverflow.com/users/3464564",
"pm_score": 1,
"selected": false,
"text": "<span onmouseover=\"getInfo(this,'06-APR-22')\" data-html=\"true\">Day</span>\n <script>\nfunction getInfo(x, dateVal) { \n var html = $.ajax({\n type: \"POST\",\n url: \"report/get-info.php\",\n data: { \n 'dateVal': dateVal,\n }, \n success: function(response) {\n x.setAttribute('title', response );\n }\n });\n}\n</script>\n <?php\n$tmp = $_POST['dateVal']; \n$dateVal = date(\"m/d/Y\", strtotime($tmp));\n\n$querySelectCode = \"SELECT INFO_ID, INFO_NAME FROM INFORMATION\n WHERE TRUNC(DP.DATE_TIME) = TO_DATE('$dateVal','MM/DD/YYYY') \"; \n$stmtSelectcode = oci_parse($dbConn, $querySelectCode);\nif ( ! oci_execute($stmtSelectcode) ){\n $err = oci_error($stmtSelectcode);\n trigger_error('Query failed: ' . $err['message'], E_USER_ERROR);\n}\n$INFO_ID = array();\nwhile(oci_fetch($stmtSelectcode)){\n $INFO_ID[] = oci_result($stmtSelectcode, 'INFO_ID');\n $INFO_NAME[] = oci_result($stmtSelectcode, 'INFO_NAME'); \n}\nfor($index=0 ; $index < count($INFO_ID) ; $index++)\n{\n echo $INFO_NAME[$index ] . \"\\x0A\" ; \n}\n?>\n"
},
{
"answer_id": 72753753,
"author": "Danil S",
"author_id": 10302109,
"author_profile": "https://Stackoverflow.com/users/10302109",
"pm_score": 0,
"selected": false,
"text": "<!DOCTYPE html>\n<html>\n<body>\n <select title=\"Line 1 : Line 2\">\n <option value=\"0\">test</option>\n </select>\n</body>\n</html> Line 1 : title=\"Line 1 : Line 2\" Line 1 : "
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358874",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32027/"
] |
358,891 | <p>I want another developer to run a Perl script I have written. The script uses many CPAN modules that have to be installed before the script can be run. Is it possible to make the script (or the <code>perl</code> binary) to dump a list of all the missing modules? Perl prints out the missing modules’ names when I attempt to run the script, but this is verbose and does not list all the missing modules at once. I’d like to do something like:</p>
<pre><code>$ cpan -i `said-script --list-deps`
</code></pre>
<p>Or even:</p>
<pre><code>$ list-deps said-script > required-modules # on my machine
$ cpan -i `cat required-modules` # on his machine
</code></pre>
<p>Is there a simple way to do it? This is not a show stopper, but I would like to make the other developer’s life easier. (The required modules are sprinkled across several files, so that it’s not easy for me to make the list by hand without missing anything. I know about <a href="http://search.cpan.org/~smueller/PAR-0.983/lib/PAR.pm" rel="noreferrer">PAR</a>, but it seems a bit too complicated for what I want.)</p>
<hr/>
<p><strong>Update:</strong> Thanks, Manni, that will do. I did not know about <code>%INC</code>, I only knew about <code>@INC</code>. I settled with something like this:</p>
<pre><code>print join("\n", map { s|/|::|g; s|\.pm$||; $_ } keys %INC);
</code></pre>
<p>Which prints out:</p>
<pre><code>Moose::Meta::TypeConstraint::Registry
Moose::Meta::Role::Application::ToClass
Class::C3
List::Util
Imager::Color
…
</code></pre>
<p>Looks like this will work.</p>
| [
{
"answer_id": 358959,
"author": "innaM",
"author_id": 7498,
"author_profile": "https://Stackoverflow.com/users/7498",
"pm_score": 5,
"selected": true,
"text": "%INC"
},
{
"answer_id": 360423,
"author": "brian d foy",
"author_id": 2766176,
"author_profile": "https://Stackoverflow.com/users/2766176",
"pm_score": 4,
"selected": false,
"text": "%INC"
},
{
"answer_id": 5899098,
"author": "rjbs",
"author_id": 10478,
"author_profile": "https://Stackoverflow.com/users/10478",
"pm_score": 3,
"selected": false,
"text": "scan-perl-prereqs %INC"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358891",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17279/"
] |
358,894 | <p>I am wondering if Unittesting and using statements can really go hand in hand as there is no way to mock the disposable object instantiated in the using statement. How would I be able to effectively unittest a method containing the following using statement?</p>
<pre>
public void MyMethod()
{
using(MyDisposableClass disp = new MyDisposableClass())
{
...
}
}
</pre>
<p>Are using statements simply forbidden when you are unit-testing?</p>
<p>Any comments appreciated.</p>
| [
{
"answer_id": 359013,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "interface IResource : IDisposable\n{\n void DoSomething();\n}\n\nclass DisposableResource : IResource\n{\n public void Dispose() { Console.WriteLine(\"That's it. I'm outta here!\"); }\n public void DoSomething() { Console.WriteLine(\"Hard work this\"); }\n}\n class MyClass\n{\n protected virtual IResource GetResource()\n {\n return new DisposableResource();\n }\n public void MyMethod1()\n {\n using (IResource r = GetResource())\n {\n r.DoSomething();\n }\n }\n}\n class MySubClassForTest : MyClass\n{\n protected override IResource GetResource()\n {\n return new MockResource();\n }\n}\nclass MockResource : IResource // or use a mock framework to create one\n{\n public void DoSomething() { Console.WriteLine(\"Me work?\"); }\n public void Dispose() { Console.WriteLine(\"Disposed Mock!\"); }\n}\n MyClass obj = new MyClass(); // production code\n obj.MyMethod1();\n\n obj = new MySubClassForTest(); // test code\n obj.MyMethod1();\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358894",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32313/"
] |
358,912 | <p>I have a string. I need to replace all instances of a given array of strings from this original string - how would I do that?</p>
<p>Currently I am using...</p>
<pre><code>var inputString = "this is my original string.";
var replacement = "";
var pattern = string.Join("|", arrayOfStringsToRemove);
Regex.Replace(inputString, pattern, replacement);
</code></pre>
<p>This works fine, but unfortunately it breaks down when someone tries to remove a character that has a special meaning in the regex.</p>
<p>How should I do this? Is there a better way?</p>
| [
{
"answer_id": 358917,
"author": "adam",
"author_id": 33604,
"author_profile": "https://Stackoverflow.com/users/33604",
"pm_score": 0,
"selected": false,
"text": "\\\n \\\\\n"
},
{
"answer_id": 358923,
"author": "muhuk",
"author_id": 42188,
"author_profile": "https://Stackoverflow.com/users/42188",
"pm_score": 0,
"selected": false,
"text": "var str_to_replace = \"removing \\[this\\]\\(link\\)\";\n"
},
{
"answer_id": 358978,
"author": "gimel",
"author_id": 6491,
"author_profile": "https://Stackoverflow.com/users/6491",
"pm_score": 3,
"selected": true,
"text": "StringBuilder pattern = new StringBuilder();\nforeach (string s in arrayOfStringsToRemove)\n{\n pattern.Append(\"(\");\n pattern.Append(Regex.Escape(s));\n pattern.Append(\")|\");\n}\nRegex.Replace(inputString, pattern.ToString(0, pattern.Length - 1), // remove trailing |\n replacement);\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358912",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39561/"
] |
358,927 | <p>I have a table called ApprovalTasks... Approvals has a status column</p>
<p>I also have a view called ApprovalsView</p>
<p>When I try a straight update :</p>
<pre><code>update ApprovalTasks set Status = 2 where ApprovalTaskID = 48
</code></pre>
<p>I'm getting this error message: </p>
<pre><code>Msg 2601, Level 14, State 1, Line 1
Cannot insert duplicate key row in object 'dbo.ApprovalsView' with unique index 'IX_ApprovalTaskID'.
The statement has been terminated.
</code></pre>
<p>Any idea why this is happening?</p>
<p>Here is the create table script:</p>
<pre><code>USE [CSPMOSSApplication]
GO
/****** Object: Table [dbo].[ApprovalTasks] Script Date: 12/11/2008 12:41:35 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApprovalTasks](
[ApprovalTaskID] [int] IDENTITY(1,1) NOT NULL,
[ApproverID] [int] NOT NULL,
[DueDate] [datetime] NULL,
[Status] [smallint] NOT NULL,
[ApprovedRejectedDate] [datetime] NULL,
[Reason] [nvarchar](1024) COLLATE Finnish_Swedish_CI_AS NULL,
[OrganizationID] [int] NOT NULL,
[TicketID] [int] NOT NULL,
[Link] [nchar](255) COLLATE Finnish_Swedish_CI_AS NULL,
[GlobalApproverID] [int] NULL,
CONSTRAINT [PK_Approval_Tasks] PRIMARY KEY CLUSTERED
(
[ApprovalTaskID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
USE [CSPMOSSApplication]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_ApprovalTaskStatuses] FOREIGN KEY([Status])
REFERENCES [dbo].[ApprovalTaskStatuses] ([ApprovalTaskStatusID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_ApprovalTaskStatuses]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Organizations] FOREIGN KEY([OrganizationID])
REFERENCES [dbo].[Organizations] ([OrganizationID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Organizations]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Tickets] FOREIGN KEY([TicketID])
REFERENCES [dbo].[Tickets] ([TicketID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Tickets]
GO
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_Users] FOREIGN KEY([ApproverID])
REFERENCES [dbo].[Users] ([UserID])
GO
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_Users]
</code></pre>
<p>PK_Approval_Tasks(Clustered)</p>
<pre><code>USE [CSPMOSSApplication]
GO
/****** Object: Index [PK_Approval_Tasks] Script Date: 12/11/2008 12:45:50 ******/
ALTER TABLE [dbo].[ApprovalTasks] ADD CONSTRAINT [PK_Approval_Tasks] PRIMARY KEY CLUSTERED
(
[ApprovalTaskID] ASC
)WITH (SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
</code></pre>
<p>IX_ApprovalTaskID(Clsutered)</p>
<pre><code>SE [CSPMOSSApplication]
GO
SET ARITHABORT ON
GO
SET CONCAT_NULL_YIELDS_NULL ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
SET ANSI_PADDING ON
GO
SET ANSI_WARNINGS ON
GO
SET NUMERIC_ROUNDABORT OFF
GO
/****** Object: Index [IX_ApprovalTaskID] Script Date: 12/11/2008 12:47:27 ******/
CREATE UNIQUE CLUSTERED INDEX [IX_ApprovalTaskID] ON [dbo].[ApprovalsView]
(
[ApprovalTaskID] ASC
)WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, IGNORE_DUP_KEY = OFF, ONLINE = OFF) ON [PRIMARY]
</code></pre>
<p>Create View Script</p>
<pre><code>USE [CSPMOSSApplication]
GO
-- =============================================
-- Script Template
-- =============================================
-- [ApprovalTasks]: add columns Link, GlobalApproverID
IF NOT EXISTS(SELECT 1 FROM sysobjects,syscolumns WHERE sysobjects.id = syscolumns.id
AND sysobjects.name = 'ApprovalTasks' AND syscolumns.name = 'Link')
BEGIN
ALTER TABLE ApprovalTasks ADD [Link] [nchar] (255) COLLATE Finnish_Swedish_CI_AS NULL
PRINT 'Column ApprovalTasks.Link was added.'
END
IF NOT EXISTS(SELECT 1 FROM sysobjects,syscolumns WHERE sysobjects.id = syscolumns.id
AND sysobjects.name = 'ApprovalTasks' AND syscolumns.name = 'GlobalApproverID')
BEGIN
ALTER TABLE ApprovalTasks ADD [GlobalApproverID] [int] NULL
PRINT 'Column ApprovalTasks.GlobalApproverID was added.'
ALTER TABLE [dbo].[ApprovalTasks] WITH NOCHECK ADD CONSTRAINT [FK_Approval_Tasks_GlobalApproverID] FOREIGN KEY([GlobalApproverID])
REFERENCES [dbo].[Users] ([UserID])
ALTER TABLE [dbo].[ApprovalTasks] CHECK CONSTRAINT [FK_Approval_Tasks_GlobalApproverID]
END
-- [ApprovalsView]
IF EXISTS (SELECT * FROM sys.fulltext_indexes fti WHERE fti.object_id = OBJECT_ID(N'[dbo].[ApprovalsView]'))
BEGIN
DROP FULLTEXT INDEX ON [dbo].[ApprovalsView]
PRINT 'FULLTEXT INDEX on [ApprovalsView] was dropped.'
END
GO
IF EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[ApprovalsView]') AND name = N'IX_ApprovalTaskID')
BEGIN
DROP INDEX IX_ApprovalTaskID ON [dbo].[ApprovalsView] WITH ( ONLINE = OFF )
PRINT 'INDEX IX_ApprovalTaskID was dropped.'
END
GO
IF EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[ApprovalsView]'))
DROP VIEW [dbo].[ApprovalsView]
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE VIEW [dbo].[ApprovalsView]
WITH SCHEMABINDING
AS
SELECT at.ApprovalTaskID,
at.ApproverID,
at.DueDate,
at.Status,
ats.ApprovalTaskStatusTranslationKey AS StatusText,
at.ApprovedRejectedDate,
at.Reason,
at.OrganizationID,
ord.Name AS OrderName,
ord.TotalPrice,
ord.SubmitDate,
ord.OrdererID,
usr.FirstName AS OrdererFirstName,
usr.LastName AS OrdererLastName,
ordi.Items_Name AS ItemName,
ordi.Items_Description AS ItemDescription,
ordi.OtherInformation AS ItemInformation,
oir.RecipientFullName,
CONVERT(nvarchar(250), oir.DeliveryAddress) As DeliveryAddress,
ti.Description
FROM dbo.ApprovalTasks at
INNER JOIN
dbo.ApprovalTaskStatuses ats ON ats.ApprovalTaskStatusID = at.Status
INNER JOIN
dbo.Orders_Items_Recipients oir ON oir.TicketID = at.TicketID
INNER JOIN
dbo.Orders_Items ordi ON ordi.Orders_ItemsID = oir.Orders_ItemsID
INNER JOIN
dbo.Orders ord ON ordi.OrderID = ord.OrderID
INNER JOIN
dbo.Users usr ON ord.OrdererID = usr.UserID
INNER JOIN
dbo.Tickets ti ON ti.TicketID = at.TicketID
GO
CREATE UNIQUE CLUSTERED INDEX [IX_ApprovalTaskID] ON [dbo].[ApprovalsView]
(
[ApprovalTaskID] ASC
)WITH (IGNORE_DUP_KEY = OFF) ON [PRIMARY]
GO
CREATE FULLTEXT INDEX ON [dbo].[ApprovalsView](
[DeliveryAddress] LANGUAGE [Neutral],
[ItemDescription] LANGUAGE [Neutral],
[ItemInformation] LANGUAGE [Neutral],
[ItemName] LANGUAGE [Neutral],
[OrdererFirstName] LANGUAGE [Neutral],
[OrdererLastName] LANGUAGE [Neutral],
[OrderName] LANGUAGE [Neutral],
[Reason] LANGUAGE [Neutral],
[RecipientFullName] LANGUAGE [Neutral])
KEY INDEX [IX_ApprovalTaskID] ON [ApprovalSearchCatalog]
WITH CHANGE_TRACKING AUTO
GO
ALTER FULLTEXT CATALOG [ApprovalSearchCatalog] rebuild
PRINT 'Catalog [ApprovalSearchCatalog] task to rebuild fulltext index was sent.'
-- STORED PROCEDURES
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[ReceiveApprovalTasksFromQueue]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[ReceiveApprovalTasksFromQueue]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Petr Klozik
-- Create date: 19.11.2008
-- Description: Gets approvals which DueDate is over ReferenceDate (now)
-- =============================================
CREATE Procedure [dbo].[ReceiveApprovalTasksFromQueue]
@Limit int
As
BEGIN
SET NOCOUNT ON;
If Not @Limit Is Null Set RowCount @Limit
-- Status: WaitingForApproval = 1
Select Tasks.ApprovalTaskID
From ApprovalTasks Tasks
Where Status = 1 And DueDate < GetDate()
END
'
GO
GRANT EXECUTE ON [dbo].[ReceiveApprovalTasksFromQueue] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[UpdateApprovalTaskInfo]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[UpdateApprovalTaskInfo]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Klozik Petr
-- Create date: 2008-11-25
-- Description: Updates Approval task info to DB
-- =============================================
CREATE PROCEDURE [dbo].[UpdateApprovalTaskInfo]
@ApprovalTaskID int,
@DueDate datetime,
@ApprovalRejectDate datetime,
@Reason nvarchar(1024),
@Status int,
@GlobalApproverID int
AS
BEGIN
SET NOCOUNT ON;
Update ApprovalTasks
Set DueDate = @DueDate,
ApprovedRejectedDate = @ApprovalRejectDate,
Reason = @Reason,
Status = @Status,
GlobalApproverID = @GlobalApproverID
Where ApprovalTaskID = @ApprovalTaskID
END
'
GO
GRANT EXECUTE ON [dbo].[UpdateApprovalTaskInfo] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetUserById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetUserById]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Klozik Petr
-- Create date: 2008-12-04
-- Description: Gets user row by the specified ID.
-- =============================================
CREATE PROCEDURE [dbo].[GetUserById]
(
@UserID int
)
AS
BEGIN
SELECT
UserID,
RTRIM(SID) [SID],
RTRIM(OMTGUID) [OMTGUID],
RTRIM(UserAccount) [UserAccount],
RTRIM(Email) [Email],
RTRIM(FirstName) [FirstName],
RTRIM(LastName) [LastName],
RTRIM(Country) [Country],
RTRIM(City) [City],
RTRIM(PostalNumber) [PostalNumber],
RTRIM(StreetAddress) [StreetAddress],
RTRIM(PhoneNumber) PhoneNumber,
Modified,
Deleted,
Uploaded,
UploadCode,
UploadStatus,
RTRIM(Users.ADUserAccount) AS ADUserAccount
FROM
[dbo].[Users]
WHERE
UserID = @UserID
END
'
GO
GRANT EXECUTE ON [dbo].[GetUserById] TO [OMT_IntegrationRole]
GO
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetApprovalTaskInfoById]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[GetApprovalTaskInfoById]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
EXEC dbo.sp_executesql @statement = N'
-- =============================================
-- Author: Petr Klozik
-- Create date: 19.11.2008
-- Description: Gets approvals which DueDate is over ReferenceDate (now)
-- =============================================
CREATE Procedure [dbo].[GetApprovalTaskInfoById]
@ApprovalTaskID int
As
BEGIN
SET NOCOUNT ON;
Declare @OrganizationID int
Declare @CurrentApproverID int
Declare @NewApproverID int
Declare @NewOrganizationID int
Select @OrganizationID = OrganizationID, @CurrentApproverID = ApproverID
From ApprovalTasks
Where ApprovalTaskID = @ApprovalTaskID
Set @NewApproverID = (
Select Top 1 o.GlobalApproverID
From Organizations o
Inner Join OrganizationDescendants od On od.OrganizationID = o.OrganizationID
Where od.DescendantID = @OrganizationID
And Not(o.GlobalApproverID Is Null)
Order By o.OrganizationLevel Desc
)
If Not(@NewApproverID Is Null)
Begin
Set @NewOrganizationID = (
Select OrganizationID
from Organizations
Where GlobalApproverID = @NewApproverID)
End
Select Tasks.*, Tickets.Description AS TicketDescription,
Tickets.RequestorID, Tickets.OrdererID,
@NewApproverID AS OrgGlobalApproverID,
@NewOrganizationID AS OrgGlobalApproverOrganizationID
From ApprovalTasks Tasks
inner join Tickets Tickets on Tasks.TicketID = Tickets.TicketID
Where ApprovalTaskID = @ApprovalTaskID
END
'
GO
GRANT EXECUTE ON [dbo].[GetApprovalTaskInfoById] TO [OMT_IntegrationRole]
GO
</code></pre>
| [
{
"answer_id": 358962,
"author": "Nick Kavadias",
"author_id": 40067,
"author_profile": "https://Stackoverflow.com/users/40067",
"pm_score": 3,
"selected": true,
"text": "DISABLE TRIGGER ALL ON ApprovalTasks"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358927",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
358,931 | <p>I need to copy a text from a textbox into the clipboard with ASP.NET. I want a code that is comparable with Mozilla Firefox and IE.</p>
| [
{
"answer_id": 358955,
"author": "Strelok",
"author_id": 2788,
"author_profile": "https://Stackoverflow.com/users/2788",
"pm_score": 3,
"selected": true,
"text": "// set the clipboard\nvar x = 'Whatever you want on the clipboard';\nwindow.clipboardData.setData('Text',x);\n\n// get the clipboard data\nwindow.clipboardData.getData('Text');\n"
},
{
"answer_id": 359007,
"author": "sabiland",
"author_id": 44964,
"author_profile": "https://Stackoverflow.com/users/44964",
"pm_score": 0,
"selected": false,
"text": " if(!document.getElementById(flashcopier)) {\n var divholder = document.createElement('div');\n divholder.id = flashcopier;\n document.body.appendChild(divholder);\n }\n\n document.getElementById(flashcopier).innerHTML = '';\n var divinfo = '<embed src=\"_clipboard.swf\" FlashVars=\"clipboard='+encodeURIComponent('YOUR_VALUE_FOR_CLIPBOARD')+'\" width=\"0\" height=\"0\" type=\"application/x-shockwave-flash\"></embed>';\n document.getElementById(flashcopier).innerHTML = divinfo;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358931",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44973/"
] |
358,934 | <pre><code>include("conn.php");
$result = mysql_query("SELECT * FROM sggame");
while($row = mysql_fetch_assoc($result));
{
$id = $row['id'];
echo $id;
echo 'working?';
}
</code></pre>
<p>The above code simply doesn't return anything out of the db. The row name is correct and the loop runs, showing that there is something in the database. However the row is just not echoed out at all. This is code i have used a thousand time before and am rather perplexed as to why it has stopped now! Any help, as always, is much appreciated</p>
| [
{
"answer_id": 358943,
"author": "Aron Rotteveel",
"author_id": 11568,
"author_profile": "https://Stackoverflow.com/users/11568",
"pm_score": 3,
"selected": true,
"text": "while($row = mysql_fetch_assoc($result));\n while($row = mysql_fetch_assoc($result))\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31677/"
] |
358,949 | <p>I am looking in to ways to enable a site to basically have something like:</p>
<p><a href="http://mysite.com/" rel="nofollow noreferrer">http://mysite.com/</a><strong>en-US</strong>/index.aspx`</p>
<p>Where the "en-US" can vary by culture..</p>
<p>This culture in the URL will then basically set the <code>CurrentUICulture</code> for the application..</p>
<p>Basically, we currently have a page where the user explicitly clicks it, but some are favouriting past that, and it is causing some issues..</p>
<p>I know this sort of thing is easily done in ASP.NET MVC, but how about those of us still working in 2.0? Can you guys in all your wisdom offer any suggestions/pointers/ANYTHING that may get me started? This is new to me :)</p>
<p>I'm sure there must be some way to pick up the request and set/bounce as appropriate.. <code>HttpModule</code> maybe?</p>
<h3>Update</h3>
<p>Just had a thought.. May be best to create VirtDirs in IIS and then pull the appropriate part from the Requested URL and set the culture in <code>InitializeCulture</code>?</p>
| [
{
"answer_id": 359024,
"author": "Eduardo Molteni",
"author_id": 2385,
"author_profile": "https://Stackoverflow.com/users/2385",
"pm_score": 1,
"selected": false,
"text": "Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)\n ' Code that runs on application startup\n RegisterRoutes(RouteTable.Routes)\nEnd Sub\n\n\nPublic Sub RegisterRoutes(ByVal routes As RouteCollection)\n Dim reportRoute As Route\n Dim DefaultLang As String = \"es\"\n\n reportRoute = New Route(\"{lang}/{page}\", New LangRouteHandler)\n '* if you want, you can contrain the values\n 'reportRoute.Constraints = New RouteValueDictionary(New With {.lang = \"[a-z]{2}\"})\n reportRoute.Defaults = New RouteValueDictionary(New With {.lang = DefaultLang, .page = \"home\"})\n\n routes.Add(reportRoute)\nEnd Sub\n Public Class LangRouteHandler\n Implements IRouteHandler\n\n Public Function GetHttpHandler(ByVal requestContext As System.Web.Routing.RequestContext) As System.Web.IHttpHandler _\n Implements System.Web.Routing.IRouteHandler.GetHttpHandler\n\n 'Fill the context with the route data, just in case some page needs it\n For Each value In requestContext.RouteData.Values\n HttpContext.Current.Items(value.Key) = value.Value\n Next\n\n Dim VirtualPath As String\n VirtualPath = \"~/\" + requestContext.RouteData.Values(\"page\") + \".aspx\"\n\n Dim redirectPage As IHttpHandler\n redirectPage = BuildManager.CreateInstanceFromVirtualPath(VirtualPath, GetType(Page))\n Return redirectPage\n\n End Function\nEnd Class\n Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs)\n Dim DefaultLang As String = \"es\"\n Dim SupportedLangs As String() = {\"en\", \"es\"}\n Dim BrowserLang As String = Mid(Request.UserLanguages(0).ToString(), 1, 2).ToLower\n If SupportedLangs.Contains(BrowserLang) Then DefaultLang = BrowserLang\n\n Response.Redirect(DefaultLang + \"/\")\nEnd Sub\n"
},
{
"answer_id": 20597838,
"author": "DigitalFox",
"author_id": 896327,
"author_profile": "https://Stackoverflow.com/users/896327",
"pm_score": 0,
"selected": false,
"text": "http://yoursite/yourPage.aspx?lang=en-US\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
358,951 | <p>I have a solution that contains a good deal of projects, </p>
<p>I would like to remove the source control bindings completely, how can I do this?</p>
<p><strong>Update:</strong>
What I really want to do is move one solution and its projects from TFS 2005 -> 2008. Thats why I am removing the bindings, is there a better way to do this?</p>
| [
{
"answer_id": 6137843,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 7,
"selected": false,
"text": "\"Go Offline\n\nThe Team Foundation Server http://some-other-guys-tfs-server/ \nis currently unavailable.\n\nThe solution will be opened offline.\"\n GlobalSection(TeamFoundationVersionControl) = preSolution\n SccNumberOfProjects = 2\n SccEnterpriseProvider = {xxxxx}\n SccTeamFoundationServer = http://some-other-guys-tfs-server/\n SccLocalPath0 = .\n SccProjectUniqueName1 = xxDemo\\\\xxDemo.csproj\n SccProjectName1 = xxDemo\n SccLocalPath1 = xxDemo\nEndGlobalSection\n"
},
{
"answer_id": 21470918,
"author": "EdSF",
"author_id": 304683,
"author_profile": "https://Stackoverflow.com/users/304683",
"pm_score": 3,
"selected": false,
"text": "SccProjectName = \"\"\nSccAuxPath = \"\"\nSccLocalPath = \"\"\nSccProvider = \"\"\n"
},
{
"answer_id": 31993424,
"author": "Mark",
"author_id": 5224411,
"author_profile": "https://Stackoverflow.com/users/5224411",
"pm_score": 2,
"selected": false,
"text": "Go to C:\\Users\\<user>\\AppData\\Local\\Microsoft\\Team Foundation\\2.0\nDelete or rename the Cache folder.\n"
},
{
"answer_id": 43486056,
"author": "code4j",
"author_id": 1022209,
"author_profile": "https://Stackoverflow.com/users/1022209",
"pm_score": 1,
"selected": false,
"text": "File->Source Control->Advanced->Change Source Control C:\\Users\\<user>\\AppData\\Local\\Microsoft\\Team Foundation\\6.0"
},
{
"answer_id": 54592055,
"author": "ASpirin",
"author_id": 514449,
"author_profile": "https://Stackoverflow.com/users/514449",
"pm_score": 3,
"selected": false,
"text": "proj <SccProjectName>SAK</SccProjectName>\n <SccLocalPath>SAK</SccLocalPath>\n <SccAuxPath>SAK</SccAuxPath>\n <SccProvider>SAK</SccProvider>"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358951",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41291/"
] |
358,952 | <p>This one is weird,</p>
<p><a href="http://www.pickledegg.orchardhostings6.co.uk/bug/wp-test.php" rel="nofollow noreferrer">I have a page that consists of a html table in a div called 'rates-viewer'</a>. If you load this page in IE (6 or 7), you will notice that the contents of the table headers is misaligned over to the left.</p>
<p>If you choose a country from the dropdown, it triggers an ajax call to a script. This script returns exactly the same html into the 'rates-viwer' div, to replace the original table.</p>
<p><em>The weird thing is that when it does so, the table header content is correctly aligned.</em> </p>
<p>Why does loading the same html into the same div, cause my table header content to be corrected like this?</p>
<p>I assumed that my html differed slightly, I'm sure its the same.</p>
<p>Can anyone plase help with this one please, its causing me to frown a lot :) I basically need the original html to be lined up correctly, but I'm intrigued as to why this is happening.</p>
<p>The JS is a bit of jquery, and its in the wp-test.php source. My script that is called is rates-viewer-test.php, and the CSS is in main.css...</p>
| [
{
"answer_id": 6137843,
"author": "Matt Frear",
"author_id": 32598,
"author_profile": "https://Stackoverflow.com/users/32598",
"pm_score": 7,
"selected": false,
"text": "\"Go Offline\n\nThe Team Foundation Server http://some-other-guys-tfs-server/ \nis currently unavailable.\n\nThe solution will be opened offline.\"\n GlobalSection(TeamFoundationVersionControl) = preSolution\n SccNumberOfProjects = 2\n SccEnterpriseProvider = {xxxxx}\n SccTeamFoundationServer = http://some-other-guys-tfs-server/\n SccLocalPath0 = .\n SccProjectUniqueName1 = xxDemo\\\\xxDemo.csproj\n SccProjectName1 = xxDemo\n SccLocalPath1 = xxDemo\nEndGlobalSection\n"
},
{
"answer_id": 21470918,
"author": "EdSF",
"author_id": 304683,
"author_profile": "https://Stackoverflow.com/users/304683",
"pm_score": 3,
"selected": false,
"text": "SccProjectName = \"\"\nSccAuxPath = \"\"\nSccLocalPath = \"\"\nSccProvider = \"\"\n"
},
{
"answer_id": 31993424,
"author": "Mark",
"author_id": 5224411,
"author_profile": "https://Stackoverflow.com/users/5224411",
"pm_score": 2,
"selected": false,
"text": "Go to C:\\Users\\<user>\\AppData\\Local\\Microsoft\\Team Foundation\\2.0\nDelete or rename the Cache folder.\n"
},
{
"answer_id": 43486056,
"author": "code4j",
"author_id": 1022209,
"author_profile": "https://Stackoverflow.com/users/1022209",
"pm_score": 1,
"selected": false,
"text": "File->Source Control->Advanced->Change Source Control C:\\Users\\<user>\\AppData\\Local\\Microsoft\\Team Foundation\\6.0"
},
{
"answer_id": 54592055,
"author": "ASpirin",
"author_id": 514449,
"author_profile": "https://Stackoverflow.com/users/514449",
"pm_score": 3,
"selected": false,
"text": "proj <SccProjectName>SAK</SccProjectName>\n <SccLocalPath>SAK</SccLocalPath>\n <SccAuxPath>SAK</SccAuxPath>\n <SccProvider>SAK</SccProvider>"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358952",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26107/"
] |
358,972 | <p>I'm creating a xml-file for display in Excel using _di_IXMLDocument. But for some tags I get an unwanted extra (empty) xmlns attribute witch makes the file unreadable for Excel...
This is what i do:</p>
<pre><code>...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("ss:Name",Now().DateString());
...
</code></pre>
<p>and this is what comes out:</p>
<pre><code><Worksheet xmlns="" ss:Name="2008-12-11">
</code></pre>
<p>Where does xmlns come from? How do I get rid of it?</p>
<p>EDIT:
Some more info: If I try to add a xmlns attribute to Worksheet myself, like this:</p>
<pre><code>...
_di_IXMLNode worksheet = workbook->AddChild("Worksheet");
worksheet->SetAttribute("xlmns","Foo");
worksheet->SetAttribute("ss:Name",Now().DateString());
...
</code></pre>
<p>Then the child nodes of "Worksheet" all get the empty xmlns attributes instead!</p>
<pre><code><Worksheet xmlns="Foo" ss:Name="2008-12-11">
<Table xmlns="">
</code></pre>
| [
{
"answer_id": 359279,
"author": "c0m4",
"author_id": 2079,
"author_profile": "https://Stackoverflow.com/users/2079",
"pm_score": 1,
"selected": true,
"text": "_di_IXMLNode worksheet = workbook->AddChild(\"Worksheet\",\"workbooks-namespace\",false);\nworksheet->SetAttribute(\"ss:Name\",Now().DateString());\n <Worksheet ss:Name=\"2008-12-11\">\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358972",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2079/"
] |
358,973 | <p>In a simple dialog app, using designer, I've set up the usual shortcut keys for cut, copy, paste and delete in the edit menu.</p>
<p>My problem is that I only want to handle delete events when a certain tree control is in focus. Otherwise, in my datagrid control for example, I want delete to work as usual.</p>
<p>What's the best way to do this? Currently I'm getting a delete event in the main form class, but the delete key isn't working in the edit controls in the datagrid control.</p>
<p><b>Edit</b> - specified that the delete key isn't working in edit sub-controls</p>
| [
{
"answer_id": 359075,
"author": "Wolf5",
"author_id": 37643,
"author_profile": "https://Stackoverflow.com/users/37643",
"pm_score": 3,
"selected": true,
"text": "keycombination eventhandler .Handled=false KeyDown keypreview .ShortcutKeyDisplayString"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358973",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11828/"
] |
358,974 | <p>Is there a way to add an attribute to an xml node (which I have the xpath of) using nant?
Tried xmlpoke but it looks like it can only update existing attributes.</p>
<p>thanks.</p>
| [
{
"answer_id": 3982825,
"author": "Christopher Stott",
"author_id": 134595,
"author_profile": "https://Stackoverflow.com/users/134595",
"pm_score": 2,
"selected": false,
"text": "<script language=\"C#\" prefix=\"test\" >\n <references>\n <include name=\"System.Xml.dll\" />\n </references>\n <code>\n <![CDATA[\n [TaskName(\"xmlinsertnode\")]\n public class TestTask : Task {\n #region Private Instance Fields\n private string _filename;\n private string _xpath;\n private string _fragment;\n #endregion Private Instance Fields\n\n #region Public Instance Properties\n [TaskAttribute(\"filename\", Required=true)]\n public string FileName {\n get { return _filename; }\n set { _filename = value; }\n }\n\n [TaskAttribute(\"xpath\", Required=true)]\n public string XPath {\n get { return _xpath; }\n set { _xpath = value; }\n }\n\n [TaskAttribute(\"fragment\", Required=true)]\n public string Fragment {\n get { return _fragment; }\n set { _fragment = value; }\n }\n\n #endregion Public Instance Properties\n\n #region Override implementation of Task\n protected override void ExecuteTask() {\n System.Xml.XmlDocument document = new System.Xml.XmlDocument();\n document.Load(_filename);\n System.Xml.XPath.XPathNavigator navigator = document.CreateNavigator();\n navigator.SelectSingleNode(_xpath).AppendChild(_fragment);\n document.Save(_filename);\n }\n #endregion Override implementation of Task\n }\n ]]>\n </code>\n </script>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358974",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19956/"
] |
358,999 | <p>I need to retrieve the Build Status from TeamCity in the form of XML, RSS format would be ideal.</p>
<p>I am familiar with the RSS feed within Teamcity but that is of no use as it is more of a history view. I am looking for something more like the page generated by the Status Widget but in XML form. (FYI, the status widget page is not XHTML - tried that!)</p>
<p>I wonder if anyone has across anything that could assist?</p>
<p>Kind Regards,
David Christiansen</p>
| [
{
"answer_id": 4600764,
"author": "brasskazoo",
"author_id": 6340,
"author_profile": "https://Stackoverflow.com/users/6340",
"pm_score": 3,
"selected": true,
"text": "Syndication Feed My Settings And Tools http://teamcity:8111/feed.html?buildTypeId=bt2&itemsType=builds&itemsCount=5\n buildTypeId itemsType buildStatus sinceDate /httpAuth/feed.html /guestAuth/feed.html"
},
{
"answer_id": 26777420,
"author": "Alfons",
"author_id": 2771739,
"author_profile": "https://Stackoverflow.com/users/2771739",
"pm_score": 0,
"selected": false,
"text": "curl -k \"https://${SERVER}/guestAuth/app/rest/buildTypes/${BUILDTYPE}/builds/?locator=lookupLimit:1\"|xpath -q -e //build/@status\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/358999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20406/"
] |
359,029 | <p>I'm having an extremely weird problem with a PHP script of mine.</p>
<p>I'm uploading a couple of files and having PHP put them all in one folder.
I've have trouble with random files being sent and random ones not being sent. So I debugged it and I got a very weird result from the $_FILES[] array.</p>
<p>I tried it with 3 files.</p>
<p><code>$_FILES["addFile"]["name"]</code> Holds the names of the 3 files.</p>
<p>You'd expect <code>$_FILES["addFile"]["tmp_name"]</code> to hold the 3 temporary names that PHP uses to copy the files, but it doesn't. It holds just one name. The other 2 are empty strings, which generate an error whilst uploading(which I supress from being displayed)</p>
<p>This is very odd. I've tried mulitple situations and it just keeps on happening.
This must be something in my settings or perhaps even my code.</p>
<p>Here's my code:</p>
<pre><code>$i = 0;
if (!empty($_FILES['addFile'])) {
foreach($_FILES['addFile'] as $addFile) {
$fileToCopy = $_FILES["addFile"]["tmp_name"][$i];
$fileName = $_FILES["addFile"]["name"][$i];
$i++;
if(!empty($fileToCopy)){
$copyTo = $baseDir."/".$fileName;
@copy($fileToCopy, $copyTo) or die("cannot copy ".$fileToCopy." to ".$copyTo);
}
}
exit(0);
}
</code></pre>
<p>Since the tmp_name is empty, the if-value will be false so it's gonna skip the die() function.</p>
<p>Does anybody know what might be causing this?</p>
<p>further info: I'm using Windows XP, running WAMP server. Never had this problem before and I can acces all maps from which I've tried to upload. Security settings of windows can't be the issue I think.</p>
| [
{
"answer_id": 359056,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 1,
"selected": false,
"text": "if (!empty($_FILES['addFile']) && is_array($_FILES['addFile']['name'])) {\n $length = count($_FILES['addFile']['name']);\n for($i = 0; $i < $length; $i++) {\n $result = move_uploaded_file($_FILES['addFile']['tmp_name'][$i],$baseDir.\"/\" . $_FILES['addFile']['name'][$i]);\n if($result === false) {\n echo 'File upload failed. The following error has occurred: ' . $_FILES['addFile']['error'][$i];\n }\n }\n}\n"
},
{
"answer_id": 359088,
"author": "dragonlord21",
"author_id": 44931,
"author_profile": "https://Stackoverflow.com/users/44931",
"pm_score": 2,
"selected": false,
"text": " $i = 0;\n foreach($_FILES['addFile'.$i] as $addFile) {\n if(!empty($addFiles) {\n move_uploaded_file($addFile['temp_name'], 'YOUR DIRECTORY');\n }\n $i++;\n }\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359029",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/11795/"
] |
359,031 | <p>Following are the PHP code lines which I am using to open a PDF file:</p>
<pre><code>$pdf_generartor = new PDFlib();
$doc = $pdf_generartor -> open_pdi_document("Report.pdf", "") or die ("ERROR: " . $pdf_generartor -> get_errmsg());
</code></pre>
<p>Though the file is at required location, every time I receive following error:</p>
<pre><code>ERROR: Couldn't open PDF file 'Report.pdf' for reading (file not found)
</code></pre>
<p>Is anyone familiar with the possible solution?</p>
| [
{
"answer_id": 359049,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 1,
"selected": false,
"text": "echo realpath('Report.pdf');\n"
},
{
"answer_id": 385589,
"author": "Anil",
"author_id": 45284,
"author_profile": "https://Stackoverflow.com/users/45284",
"pm_score": 0,
"selected": false,
"text": " $doc = $pdf_generartor->open_pdi_document(\"D:\\\\Report.pdf\", \"\") or die (\"ERROR:\")\n"
},
{
"answer_id": 3668415,
"author": "pbean",
"author_id": 47045,
"author_profile": "https://Stackoverflow.com/users/47045",
"pm_score": 2,
"selected": false,
"text": "$p = new PDFlib();\n$p->set_parameter(\"SearchPath\", realpath(\"data/\"));\n $indoc = $p->open_pdi_document(realpath($infile), \"\");\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359031",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6561/"
] |
359,036 | <p>My program run fine from anywhere else on my drive apart from the Program Files directory (windows XP), I am logged on as administrator so I have full permissions to the drive. It runs fine from the root of c: the windows directory basically anywhere else apart from Program Files. I have recreated this problem on 4 different machines 2 XP, 2 Vista. </p>
<p>My program is a C# .Net 2.0 program. What on earth could the problem be?</p>
<p>I have even copied my entire project to the Program Files directory and I can't debug it from there it just won't run up, no errors at all.</p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 359066,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 2,
"selected": false,
"text": "LogDebug('before 1');\nStatement1;\nLogDebug('before 2');\nStatement2;\nLogDebug('before 3');\nStatement3;\nLogDebug('after 3');\n"
},
{
"answer_id": 359209,
"author": "Oliver Friedrich",
"author_id": 44532,
"author_profile": "https://Stackoverflow.com/users/44532",
"pm_score": 0,
"selected": false,
"text": "string tempFilePath = Path.Combine(Path.GetTempPath(), Path.GetTempFileName());\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359036",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,041 | <p>I need to create a request for a web page delivered to our web sites, but I need to be able to set the host header information too. I have tried this using HttpWebRequest, but the Header information is read only (Or at least the Host part of it is). I need to do this because we want to perform the initial request for a page before the user can. We have 10 web server which are load balanced, so we need to request the file from each of the web servers. </p>
<p>I have tried the following:</p>
<pre><code>HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://192.168.1.5/filename.htm");
request.Headers.Set("Host", "www.mywebsite.com");
WebResponse response = request.GetResponse();
</code></pre>
<p>Obviously this does not work, as I can't update the header, and I don't know if this is indeed the right way to do it.</p>
| [
{
"answer_id": 359299,
"author": "Xetius",
"author_id": 274,
"author_profile": "https://Stackoverflow.com/users/274",
"pm_score": 4,
"selected": true,
"text": "string getString = \"GET /path/mypage.htm HTTP/1.1\\r\\nHost: www.mysite.mobi\\r\\nConnection: Close\\r\\n\\r\\n\";\nEncoding ASCII = Encoding.ASCII;\nByte[] byteGetString = ASCII.GetBytes(getString);\nByte[] receiveByte = new Byte[256];\nSocket socket = null;\nString strPage = null;\ntry\n{\n IPEndPoint ip = new IPEndPoint(IPAddress.Parse(\"10.23.1.93\"), 80);\n socket = new Socket(ip.AddressFamily, SocketType.Stream, ProtocolType.Tcp);\n socket.Connect(ip);\n}\ncatch (SocketException ex)\n{\n Console.WriteLine(\"Source:\" + ex.Source);\n Console.WriteLine(\"Message:\" + ex.Message);\n}\nsocket.Send(byteGetString, byteGetString.Length, 0);\nInt32 bytes = socket.Receive(receiveByte, receiveByte.Length, 0);\nstrPage = strPage + ASCII.GetString(receiveByte, 0, bytes);\n\nwhile (bytes > 0)\n{\n bytes = socket.Receive(receiveByte, receiveByte.Length, 0);\n strPage = strPage + ASCII.GetString(receiveByte, 0, bytes);\n}\nsocket.Close();\n"
},
{
"answer_id": 2264692,
"author": "Fox",
"author_id": 74177,
"author_profile": "https://Stackoverflow.com/users/74177",
"pm_score": 2,
"selected": false,
"text": "public class MyHeaderCollection:WebHeaderCollection\n{\n public new void Set(string name, string value)\n {\n AddWithoutValidate(name, value);\n }\n //or\n public new string this[string name]\n {\n get { return base[name]; }\n set { AddWithoutValidate(name, value); }\n }\n}\n var http = WebRequest.Create(\"http://example.com/\");\n var headers = new MyHeaderCollection();\n http.Headers = headers;\n\n //Now you can add/override anything you like without validation:\n headers.Set(\"Host\", http.RequestUri.Host);\n //or\n headers[\"Host\"] = http.RequestUri.Host;\n"
},
{
"answer_id": 4421324,
"author": "thedrs",
"author_id": 112937,
"author_profile": "https://Stackoverflow.com/users/112937",
"pm_score": 2,
"selected": false,
"text": "string retVal = \"\";\n // Can't change the 'Host' header property because .NET protects it\n // HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n // request.Headers.Set(HttpRequestHeader.Host, DEPLOYER_HOST);\n // so we must use a workaround\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n request.Proxy = new WebProxy(ip);\n using (WebResponse response = request.GetResponse())\n {\n using (TextReader reader = new StreamReader(response.GetResponseStream()))\n {\n string line;\n while ((line = reader.ReadLine()) != null)\n retVal += line;\n }\n }\n return retVal;\n"
},
{
"answer_id": 7560279,
"author": "L.B",
"author_id": 932418,
"author_profile": "https://Stackoverflow.com/users/932418",
"pm_score": 4,
"selected": false,
"text": "HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(new Uri(\"http://192.168.1.1\"));\nrequest.Headers.GetType().InvokeMember(\"ChangeInternal\", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod, null, request.Headers, new object[] {\"Host\",\"www.mysite.com\"});\n"
},
{
"answer_id": 30910008,
"author": "Will Munn",
"author_id": 752756,
"author_profile": "https://Stackoverflow.com/users/752756",
"pm_score": 2,
"selected": false,
"text": "HttpWebRequest request = (HttpWebRequest)WebRequest.Create(\"http://192.168.1.5/filename.htm\");\nrequest.Host = \"www.mywebstite.com\";\nWebResponse response = request.GetResponse();\n"
},
{
"answer_id": 41257954,
"author": "Stefan Steiger",
"author_id": 155077,
"author_profile": "https://Stackoverflow.com/users/155077",
"pm_score": 0,
"selected": false,
"text": "public class myweb : System.Net.WebClient\n{\n protected override System.Net.WebRequest GetWebRequest(System.Uri address)\n {\n System.Net.WebRequest request = (System.Net.WebRequest)base.GetWebRequest(address);\n //string host = \"redmine.nonexistantdomain.com\";\n\n //request.Headers.GetType().InvokeMember(\"ChangeInternal\",\n // System.Reflection.BindingFlags.NonPublic |\n // System.Reflection.BindingFlags.Instance |\n // System.Reflection.BindingFlags.InvokeMethod, null,\n // request.Headers, new object[] { \"Host\", host }\n //);\n\n //server IP and port\n request.Proxy = new System.Net.WebProxy(\"http://28.14.88.71:80\");\n\n // .NET 4.0 only\n System.Net.HttpWebRequest foo = (System.Net.HttpWebRequest)request;\n //foo.Host = host;\n\n // The below reflection-based operation is not necessary, \n // if the server speaks HTTP 1.1 correctly\n // and the firewall doesn't interfere\n // https://yoursunny.com/t/2009/HttpWebRequest-IP/\n System.Reflection.FieldInfo horribleProxyServicePoint = (typeof(System.Net.ServicePoint))\n .GetField(\"m_ProxyServicePoint\", System.Reflection.BindingFlags.NonPublic |\n System.Reflection.BindingFlags.Instance);\n\n horribleProxyServicePoint.SetValue(foo.ServicePoint, false);\n return foo; // or return request; if you don't neet this\n }\n\n\n }\n myweb wc = new myweb();\nstring str = wc.DownloadString(\"http://redmine.netexistantdomain.com\");\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359041",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/274/"
] |
359,043 | <p>I'm writing code to generate character-based pagination. I have articles in my site that I want to split up based on length.</p>
<p>The code I have so far is working albeit two issues:</p>
<ol>
<li>It's splitting pages in the middle of words and HTML tags; I want it to
only split after a complete word, tag, or a punctuation mark. </li>
<li>In the pagination bar, it's generating the wrong number of pages.</li>
</ol>
<p>In the
pagination bar, it's generating the
wrong number of pages.</p>
<p>Need help addressing these two issues. Code follows:</p>
<pre><code>$text = file_get_contents($View);
$ArticleLength = strlen($text);
$CharsPerPage = 5000;
$NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage);
$CurrentPage = $this->ReturnNeededObject('pagenumber');
$Page = (isset($CurrentPage) && '' !== $CurrentPage) ? $CurrentPage : '1';
$PageText = substr($text, $CharsPerPage*($Page-1), $CharsPerPage);
echo $PageText, '<p>';
for ($i=1; $i<$NoOfPages+1; $i++)
{
if ($i == $CurrentPage)
{
echo '<strong>', $i, '</strong>';
}
else
{
echo '<a href="', $i, '">', $i, '</a>';
}
echo ' | ';
}
echo '</p>';
</code></pre>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 359062,
"author": "benlumley",
"author_id": 39161,
"author_profile": "https://Stackoverflow.com/users/39161",
"pm_score": 0,
"selected": false,
"text": "$NoOfPages = round((double)$ArticleLength / (double)$CharsPerPage);\n"
},
{
"answer_id": 359067,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 0,
"selected": false,
"text": "ceil() round() <div> <p> <table>"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359043",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,047 | <p>How can I detect which request type was used (GET, POST, PUT or DELETE) in PHP?</p>
| [
{
"answer_id": 359050,
"author": "gnud",
"author_id": 27204,
"author_profile": "https://Stackoverflow.com/users/27204",
"pm_score": 12,
"selected": true,
"text": "$_SERVER['REQUEST_METHOD']\n if ($_SERVER['REQUEST_METHOD'] === 'POST') {\n // The request is using the POST method\n}\n"
},
{
"answer_id": 897311,
"author": "neu242",
"author_id": 13365,
"author_profile": "https://Stackoverflow.com/users/13365",
"pm_score": 8,
"selected": false,
"text": "<?php\n$method = $_SERVER['REQUEST_METHOD'];\n$request = explode(\"/\", substr(@$_SERVER['PATH_INFO'], 1));\n\nswitch ($method) {\n case 'PUT':\n do_something_with_put($request); \n break;\n case 'POST':\n do_something_with_post($request); \n break;\n case 'GET':\n do_something_with_get($request); \n break;\n default:\n handle_error($request); \n break;\n}\n"
},
{
"answer_id": 20611054,
"author": "nurettin",
"author_id": 227755,
"author_profile": "https://Stackoverflow.com/users/227755",
"pm_score": 4,
"selected": false,
"text": "$app = new \\Slim\\Slim();\n$app->get('/hello/:name', function ($name) {\n echo \"Hello, $name\";\n});\n$app->run();\n $router = new AltoRouter();\n$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in\n\n// mapping routes\n$router->map('GET|POST','/', 'home#index', 'home');\n$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));\n$router->map('GET','/users/[i:id]', 'users#show', 'users_show');\n$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');\n"
},
{
"answer_id": 31244353,
"author": "Amit Patange",
"author_id": 4112984,
"author_profile": "https://Stackoverflow.com/users/4112984",
"pm_score": 3,
"selected": false,
"text": "$request = new \\Zend\\Http\\PhpEnvironment\\Request();\n$httpMethod = $request->getMethod();\n"
},
{
"answer_id": 33366525,
"author": "Peter",
"author_id": 3169577,
"author_profile": "https://Stackoverflow.com/users/3169577",
"pm_score": 5,
"selected": false,
"text": "REQUEST METHOD $method = $_SERVER['REQUEST_METHOD'];\nif ($method == 'POST'){\n // Method is POST\n} elseif ($method == 'GET'){\n // Method is GET\n} elseif ($method == 'PUT'){\n // Method is PUT\n} elseif ($method == 'DELETE'){\n // Method is DELETE\n} else {\n // Method unknown\n}\n switch if-else GET POST <!-- DELETE method -->\n<form action='' method='POST'>\n <input type=\"hidden\" name'_METHOD' value=\"DELETE\">\n</form>\n\n<!-- PUT method -->\n<form action='' method='POST'>\n <input type=\"hidden\" name'_METHOD' value=\"PUT\">\n</form>\n"
},
{
"answer_id": 34555779,
"author": "Rockers Technology",
"author_id": 5730945,
"author_profile": "https://Stackoverflow.com/users/5730945",
"pm_score": -1,
"selected": false,
"text": "www.example.com?id=2&name=r $_GET['id'] $_REQUEST['id'] <form action='' method='POST'> $_POST $_REQUEST"
},
{
"answer_id": 35796240,
"author": "Artegon",
"author_id": 1315357,
"author_profile": "https://Stackoverflow.com/users/1315357",
"pm_score": 4,
"selected": false,
"text": "getenv $_SERVER getenv('REQUEST_METHOD');\n"
},
{
"answer_id": 37200969,
"author": "HelpNeeder",
"author_id": 720323,
"author_profile": "https://Stackoverflow.com/users/720323",
"pm_score": 4,
"selected": false,
"text": "$request = filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED);\n"
},
{
"answer_id": 43392886,
"author": "Juned Ansari",
"author_id": 1385107,
"author_profile": "https://Stackoverflow.com/users/1385107",
"pm_score": 3,
"selected": false,
"text": "<?php\n$method = $_SERVER['REQUEST_METHOD'];\nswitch ($method) {\n case 'GET':\n //Here Handle GET Request \n break;\n case 'POST':\n //Here Handle POST Request \n break;\n case 'DELETE':\n //Here Handle DELETE Request \n break;\n case 'PUT':\n //Here Handle PUT Request \n break;\n}\n?>\n"
},
{
"answer_id": 46076366,
"author": "Thielicious",
"author_id": 6189002,
"author_profile": "https://Stackoverflow.com/users/6189002",
"pm_score": 1,
"selected": false,
"text": "array count() $m=['GET'=>$_GET,'POST'=>$_POST];\nforeach($m as$k=>$v){\n echo count($v)?\n $k.' was requested.':null;\n}\n"
},
{
"answer_id": 51674335,
"author": "Shaan Ansari",
"author_id": 5641072,
"author_profile": "https://Stackoverflow.com/users/5641072",
"pm_score": 3,
"selected": false,
"text": "<?php\n\n$method = $_SERVER['REQUEST_METHOD'];\n\nswitch ($method) {\n case 'GET':\n //Here Handle GET Request\n echo 'You are using '.$method.' Method';\n break;\n case 'POST':\n //Here Handle POST Request\n echo 'You are using '.$method.' Method';\n break;\n case 'PUT':\n //Here Handle PUT Request\n echo 'You are using '.$method.' Method';\n break;\n case 'PATCH':\n //Here Handle PATCH Request\n echo 'You are using '.$method.' Method';\n break;\n case 'DELETE':\n //Here Handle DELETE Request\n echo 'You are using '.$method.' Method';\n break;\n case 'COPY':\n //Here Handle COPY Request\n echo 'You are using '.$method.' Method';\n break;\n\n case 'OPTIONS':\n //Here Handle OPTIONS Request\n echo 'You are using '.$method.' Method';\n break;\n case 'LINK':\n //Here Handle LINK Request\n echo 'You are using '.$method.' Method';\n break;\n case 'UNLINK':\n //Here Handle UNLINK Request\n echo 'You are using '.$method.' Method';\n break;\n case 'PURGE':\n //Here Handle PURGE Request\n echo 'You are using '.$method.' Method';\n break;\n case 'LOCK':\n //Here Handle LOCK Request\n echo 'You are using '.$method.' Method';\n break;\n case 'UNLOCK':\n //Here Handle UNLOCK Request\n echo 'You are using '.$method.' Method';\n break;\n case 'PROPFIND':\n //Here Handle PROPFIND Request\n echo 'You are using '.$method.' Method';\n break;\n case 'VIEW':\n //Here Handle VIEW Request\n echo 'You are using '.$method.' Method';\n break;\n Default:\n echo 'You are using '.$method.' Method';\n break;\n}\n\n\n?>\n"
},
{
"answer_id": 54257515,
"author": "mahfuz",
"author_id": 2625958,
"author_profile": "https://Stackoverflow.com/users/2625958",
"pm_score": 1,
"selected": false,
"text": "function get_request_method() {\n $request_method = strtolower($_SERVER['REQUEST_METHOD']);\n\n if($request_method != 'get' && $request_method != 'post') {\n return $request_method;\n }\n\n if($request_method == 'post' && isset($_POST['_method'])) {\n return strtolower($_POST['_method']);\n }\n\n return $request_method;\n}\n REST calls html form <form method=\"post\">\n <input name=\"_method\" type=\"hidden\" value=\"delete\" />\n <input type=\"submit\" value=\"Submit\">\n</form>\n"
},
{
"answer_id": 60108892,
"author": "Karol Sobański",
"author_id": 12152493,
"author_profile": "https://Stackoverflow.com/users/12152493",
"pm_score": 2,
"selected": false,
"text": "$_GET GET POST DELETE PUT $_GET"
},
{
"answer_id": 72770169,
"author": "Maik Lowrey",
"author_id": 14807111,
"author_profile": "https://Stackoverflow.com/users/14807111",
"pm_score": 2,
"selected": false,
"text": "$_SERVER $_SERVER['REQUEST_METHOD'] filter_input(INPUT_SERVER, 'REQUEST_METHOD', FILTER_SANITIZE_ENCODED); Symfony\\Component\\HttpFoundation\\Request \\Zend\\Http\\PhpEnvironment\\Request $_SERVER['REQUEST_METHOD']"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359047",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
359,052 | <p>I need to send PUT and DELETE along with POST, GET to a REST API how can I do it?</p>
| [
{
"answer_id": 360112,
"author": "skamradt",
"author_id": 9217,
"author_profile": "https://Stackoverflow.com/users/9217",
"pm_score": 2,
"selected": false,
"text": "function HttpPutBinary(const URL: string; const Data: TStream): Boolean;\nvar\n HTTP: THTTPSend;\nbegin\n HTTP := THTTPSend.Create;\n try\n HTTP.Document.CopyFrom(Data, 0);\n HTTP.MimeType := 'Application/octet-stream';\n Result := HTTP.HTTPMethod('PUT', URL); // changed method from 'POST'\n Data.Size := 0;\n if Result then\n begin\n Data.Seek(0, soFromBeginning);\n Data.CopyFrom(HTTP.Document, 0);\n end;\n finally\n HTTP.Free;\n end;\nend;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
359,087 | <p>If i do jQuery(expr).change( function), then I can get an event function to fire when the user makes a change to the value.</p>
<p>Is it possible to get this to fire if it's changed programatically, ie if I call jQuery(expr).val("moo").</p>
<p>or if some Plain old JavaScript changes it's value?</p>
<p>Thanks for any help.</p>
| [
{
"answer_id": 359129,
"author": "Sander Versluys",
"author_id": 2172,
"author_profile": "https://Stackoverflow.com/users/2172",
"pm_score": 5,
"selected": true,
"text": "jQuery('#element').change();\n"
},
{
"answer_id": 359140,
"author": "Adam Bellaire",
"author_id": 21632,
"author_profile": "https://Stackoverflow.com/users/21632",
"pm_score": 3,
"selected": false,
"text": "setTimeout"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359087",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45279/"
] |
359,099 | <p>I'm trying to refactor a large, old project and one thing I've noticed is a range of different Iterator implementations:</p>
<pre><code>while($iterator->moveNext()) {
$item = $iterator->current();
// do something with $item;
}
for($iterator = getIterator(), $iterator->HasNext()) {
$item = $iterator->Next();
// do something with $item
}
while($item = $iterator->fetch()) {
// do something with item
}
</code></pre>
<p>or even the <a href="http://www.php.net/~helly/php/ext/spl/" rel="nofollow noreferrer">StandardPHPLibrary (SPL)</a> iterator which allows</p>
<pre><code>foreach($iterator as $item) {
// do something with $item
}
</code></pre>
<p>Having so many different Iterators (with different methods for looping over collections) seems like a strong code smell, and I'm inclined to refactor everything to SPL.
Is there a compelling advantage to any of these implementations of Iterator, or is it purely a matter of personal taste? </p>
| [
{
"answer_id": 359117,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 1,
"selected": false,
"text": "for( $object as $i => $v ) \n for( $dbresult->iterator() as $i => $v ){ \n\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20074/"
] |
359,109 | <p>How can I set up GNU screen to allow the mouse's scrollwheel to scroll around in the scrollback buffer? I tried to Google about this, but most hits were on how to allow applications inside screen to use the scrollwheel.</p>
| [
{
"answer_id": 1125947,
"author": "Pistos",
"author_id": 28558,
"author_profile": "https://Stackoverflow.com/users/28558",
"pm_score": 10,
"selected": true,
"text": "~/.screenrc termcapinfo xterm* ti@:te@\n screen -d -r ls screen(1) termcapinfo term terminal-tweaks [window-tweaks]\n [..]\n The first argument specifies which terminal(s) should be affected by this\n definition. You can specify multiple terminal names by separating them with\n `|'s. Use `*' to match all terminals and `vt*' to match all terminals that\n begin with \"vt\".\n [..]\n Some examples:\n\n termcap xterm* LP:hs@\n\n Informs screen that all terminals that begin with `xterm' have firm\n auto-margins that allow the last position on the screen to be updated (LP),\n but they don't really have a status line (no 'hs' - append `@' to turn\n entries off). Note that we assume `LP' for all terminal names that start\n with \"vt\", but only if you don't specify a termcap command for that terminal.\n termcap(5) String capabilities\n [..]\n te End program that uses cursor motion\n ti Begin program that uses cursor motion\n"
},
{
"answer_id": 3474732,
"author": "Tommi R.",
"author_id": 128698,
"author_profile": "https://Stackoverflow.com/users/128698",
"pm_score": 5,
"selected": false,
"text": "XTerm*saveLines: 0\nXTerm*vt100.translations: #override \\n\\\n Ctrl <Btn4Down>: string(0x1b) string(\"[25S\") \\n\\\n Lock Ctrl <Btn4Down>: string(0x1b) string(\"[25S\") \\n\\\n Lock @Num_Lock Ctrl <Btn4Down>: string(0x1b) string(\"[25S\") \\n\\\n @Num_Lock Ctrl <Btn4Down>: string(0x1b) string(\"[25S\") \\n\\\n <Btn4Down>: string(0x1b) string(\"[5S\") \\n\\\n Ctrl <Btn5Down>: string(0x1b) string(\"[25T\") \\n\\\n Lock Ctrl <Btn5Down>: string(0x1b) string(\"[25T\") \\n\\\n Lock @Num_Lock Ctrl <Btn5Down>: string(0x1b) string(\"[25T\") \\n\\\n @Num_Lock Ctrl <Btn5Down>: string(0x1b) string(\"[25T\") \\n\\\n <Btn5Down>: string(0x1b) string(\"[5T\") \\n\\\n Shift <KeyPress> Prior: string(0x1b) string(\"[25S\") \\n\\\n Shift <KeyPress> Next: string(0x1b) string(\"[25T\") \\n\n defscrollback 1000\n\n# Scroll up\nbindkey -d \"^[[5S\" eval copy \"stuff 5\\025\"\nbindkey -m \"^[[5S\" stuff 5\\025\n\n# Scroll down\nbindkey -d \"^[[5T\" eval copy \"stuff 5\\004\"\nbindkey -m \"^[[5T\" stuff 5\\004\n\n# Scroll up more\nbindkey -d \"^[[25S\" eval copy \"stuff \\025\"\nbindkey -m \"^[[25S\" stuff \\025\n\n# Scroll down more\nbindkey -d \"^[[25T\" eval copy \"stuff \\004\"\nbindkey -m \"^[[25T\" stuff \\004\n xterm -e screen\n"
},
{
"answer_id": 7878579,
"author": "edench",
"author_id": 1011229,
"author_profile": "https://Stackoverflow.com/users/1011229",
"pm_score": 4,
"selected": false,
"text": "set mouse=a \" hold shift to copy xterm\nset ttymouse=xterm2 \" necessary for gnu screen & mouse\n"
},
{
"answer_id": 13628522,
"author": "Jesse Crossen",
"author_id": 745831,
"author_profile": "https://Stackoverflow.com/users/745831",
"pm_score": 4,
"selected": false,
"text": "defscrollback 5000\ntermcapinfo xterm* ti@:te@\n"
},
{
"answer_id": 21235819,
"author": "Torbjör Weiland",
"author_id": 1374936,
"author_profile": "https://Stackoverflow.com/users/1374936",
"pm_score": 3,
"selected": false,
"text": "terminfo xterm* ti=:te=\n"
},
{
"answer_id": 26211291,
"author": "lemonsqueeze",
"author_id": 1883178,
"author_profile": "https://Stackoverflow.com/users/1883178",
"pm_score": 3,
"selected": false,
"text": "TERM vt100 xterm .bashrc # make scrollbar / wheel scrolling work when running screen in gnome-terminal (or other)\nif [ \"$TERM\" = \"xterm\" ]; then\n export TERM=vt100\nfi\n .screenrc # Extend the vt100 desciption by some sequences.\ntermcap vt100* ms:AL=\\E[%dL:DL=\\E[%dM:UP=\\E[%dA:DO=\\E[%dB:LE=\\E[%dD:RI=\\E[%dC\nterminfo vt100* ms:AL=\\E[%p1%dL:DL=\\E[%p1%dM:UP=\\E[%p1%dA:DO=\\E[%p1%dB:LE=\\E[%p1%dD:RI=\\E[%p1%dC\n"
},
{
"answer_id": 42235598,
"author": "nachocab",
"author_id": 355567,
"author_profile": "https://Stackoverflow.com/users/355567",
"pm_score": 2,
"selected": false,
"text": "termcapinfo xterm* ti@:te@\n termcapinfo"
},
{
"answer_id": 45254823,
"author": "Malcolm Boekhoff",
"author_id": 1388639,
"author_profile": "https://Stackoverflow.com/users/1388639",
"pm_score": 2,
"selected": false,
"text": "termcapinfo xterm* ti@:te@\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359109",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13051/"
] |
359,120 | <p>for testing purposes i need an recursive directory with some files, that comes to maximum path-length.</p>
<p>The Script used for the creation consists only of two for-loops, as followed:</p>
<pre><code>for /L %%a in (1 1 255) do @(
mkdir %%a
&& cd %%a
&& for /L %%b in (1 1 %random%) do @(
echo %%b >> %%a.txt
)
)
</code></pre>
<p>Now I would like to embed this script as part of another script, since more is to be done, but I can not add any other commands around it or it refuses working. I use this under windows vista, if this is useful to you.</p>
<p>Nor it works if i write <code>"@ECHO OFF</code>" in first line, neither with "<code>echo done</code>" on the last line.</p>
<p>output on commandline is:</p>
<pre><code>X:\Scripte>recursive.cmd
OFFfor /L %a in (1 1 255) do @( mkdir %a
The system cannot find the path specified.
</code></pre>
<p>EDIT:
Seems to be a problem with layer 8, the problem seems to be in the command shell used, if used the bare cmd.exe, it works, with visual studio 2008 command shell it does not work, like stated above.</p>
<p>anyway, thank you.</p>
| [
{
"answer_id": 359135,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 2,
"selected": true,
"text": "@echo OFF\n\nfor /L %%a in (1 1 255) do (\n @echo a = %%a\n mkdir %%a\n cd %%a\n for /L %%b in (1 1 %random%) do (\n echo %%b >> %%a.txt\n )\n)\n\n@echo done\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359120",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44532/"
] |
359,122 | <p>I am looking at depency injection, I can see the benefits but I am having problems with the syntax it creates. I have this example</p>
<pre><code>public class BusinessProducts
{
IDataContext _dx;
BusinessProducts(IDataContext dx)
{
_dx = dx;
}
public List<Product> GetProducts()
{
return dx.GetProducts();
}
}
</code></pre>
<p>The problem is that I don't want to write </p>
<pre><code>BusinessProducts bp = new BusinessProducts(dataContextImplementation);
</code></pre>
<p>I would continue to write </p>
<pre><code>BusinessProducts bp = new BusinessProducts();
</code></pre>
<p>because I feel the first alternative just feels unatural. I dont want to know what the BusinessProduct "depends" on to get the products, also I feel it makes my code more unreadable. </p>
<p>Is there any alternatives to this approach as I would like to keep my original syntax for creating objects but I would like to still be able to fake the dependencies when unit testing or is it this dependecy injection frameworks can do for me?</p>
<p>I am coding in c# but alternatives from other languages is welcome</p>
| [
{
"answer_id": 359146,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 2,
"selected": false,
"text": "new BusinessProducts(dataContextImplementation)\n"
},
{
"answer_id": 359189,
"author": "Szymon Rozga",
"author_id": 7583,
"author_profile": "https://Stackoverflow.com/users/7583",
"pm_score": 1,
"selected": false,
"text": "new SomeObjectO(diContext)\n DIFramework.GetNew<SomeObjectO>();\n DIFramework.Get<SomeObject>();\n"
},
{
"answer_id": 359196,
"author": "tvanfosson",
"author_id": 12950,
"author_profile": "https://Stackoverflow.com/users/12950",
"pm_score": 4,
"selected": true,
"text": "public class BusinessProducts\n{\n private IDataContextFactory DataContextFactory { get; set; } // my interface\n\n public BusinessProducts() : this(null) {}\n\n public BusinessProducts( IDataContextFactory factory )\n {\n this.DataContext = factory ?? new BusinessProductsDataContextFactory();\n }\n\n public void DoSomething()\n {\n using (DataContext dc = this.DataContextFactory().CreateDataContext())\n {\n ...\n }\n }\n"
},
{
"answer_id": 359202,
"author": "Owen",
"author_id": 425,
"author_profile": "https://Stackoverflow.com/users/425",
"pm_score": 3,
"selected": false,
"text": "public class BusinessProducts\n{\n IDataContext _dx;\n\n BusinessProducts()\n {\n _dx = new SolidDataContext();\n }\n\n BusinessProducts(IDataContext dx)\n {\n _dx = dx;\n }\n}\n"
},
{
"answer_id": 359246,
"author": "hangy",
"author_id": 11963,
"author_profile": "https://Stackoverflow.com/users/11963",
"pm_score": 1,
"selected": false,
"text": "public class BusinessProducts\n{\n IDataContext _dx;\n\n BusinessProducts()\n {\n _dx = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<IDataContext>();\n }\n\n public List<Product> GetProducts()\n {\n return dx.GetProducts();\n }\n}\n BusinessProducts bp = Microsoft.Practices.ServiceLocation.ServiceLocator.Current.GetInstance<BusinessProducts>();\n"
},
{
"answer_id": 359463,
"author": "Scott Cowan",
"author_id": 253,
"author_profile": "https://Stackoverflow.com/users/253",
"pm_score": 1,
"selected": false,
"text": "public class BusinessProducts\n{\n IDataContext _dx;\n\n BusinessProducts() : this(new DataContext()) {}\n\n BusinessProducts(IDataContext dx)\n {\n _dx = dx;\n }\n\n public List<Product> GetProducts()\n {\n return dx.GetProducts();\n }\n}\n"
},
{
"answer_id": 359499,
"author": "Chris Marisic",
"author_id": 37055,
"author_profile": "https://Stackoverflow.com/users/37055",
"pm_score": 1,
"selected": false,
"text": "protected void Application_Start(object sender, EventArgs e)\n{\n Application.GetContainer()\n // presenters / controllers are per request \n .RegisterType<IEmployeeController, EmployeeController>(new ContextLifetimeManager<IEmployeeController>())\n\n //Data Providers are Per session \n .RegisterType<IEmployeeDataProvider, EmployeeDataProvider>(new SessionLifetimeManager<IEmployeeDataProvider>())\n\n //Session Factory is life time\n .RegisterType<INHibernateSessionManager, NHibernateSessionManager>(new ContainerControlledLifetimeManager());\n}\n private static void OnPreRequestHandlerExecute(object sender, EventArgs e)\n{\n var handler = HttpContext.Current.Handler;\n HttpContext.Current.Application.GetContainer().BuildUp(handler.GetType(), handler);\n\n // User Controls are ready to be built up after the page initialization is complete\n var page = HttpContext.Current.Handler as Page;\n if (page != null)\n {\n page.InitComplete += OnPageInitComplete;\n }\n}\n public partial class Employees : Page, IEmployeeView\n{\n private EmployeePresenter _presenter;\n\n [Dependency]\n public EmployeePresenter Presenter\n {\n set\n {\n _presenter = value;\n _presenter.View = this;\n }\n }\n}\n public class EmployeePresenter : Presenter<IEmployeeView>\n{\n private readonly IEmployeeController _controller;\n\n [InjectionConstructor]\n }\n public EmployeePresenter(IEmployeeController controller)\n {\n _controller = controller;\n}\n public class EmployeeController : IEmployeeController\n{\n private readonly IEmployeeDataProvider _provider;\n\n [InjectionConstructor]\n public EmployeeController(IEmployeeDataProvider DataProvider)\n {\n _provider = DataProvider;\n }\n}\n public class EmployeeController : IEmployeeController\n{\n private readonly IEmployeeDataProvider _provider;\n\n [InjectionConstructor]\n public EmployeeController(IEmployeeDataProvider DataProvider)\n {\n _provider = DataProvider;\n }\n}\n public class NHibernateSessionManager : INHibernateSessionManager\n{ \n private readonly ISessionFactory _sessionFactory;\n\n public NHibernateSessionManager()\n { \n _sessionFactory = GetSessionFactory();\n }\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29519/"
] |
359,125 | <p>This is a fairly basic question, which for some reason, a proper solution escapes me at the moment. I am dealing with a 3rd-party SDK which declares the following structure:</p>
<pre><code>struct VstEvents
{
VstInt32 numEvents; ///< number of Events in array
VstIntPtr reserved; ///< zero (Reserved for future use)
VstEvent* events[2]; ///< event pointer array, variable size
};
</code></pre>
<p>Even though this is a "variable sized" array, it's declared statically. So obviously, if I make a VstEvents object, set the numEvents to something, and then go through and start adding them to the array, it's going to cause memory corruption.</p>
<p>So how am I supposed to properly deal with a structure like this? Should I allocate my own VstEvent* array and then point events[0] to it?</p>
| [
{
"answer_id": 359136,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 2,
"selected": true,
"text": "struct VstEvents *evnts;\n\nevnts = (struct VstEvents*)malloc(sizeof(struct VstEvents) + \n numEvents*sizeof(VstEvent*));\n"
},
{
"answer_id": 359142,
"author": "Sandeep Datta",
"author_id": 39648,
"author_profile": "https://Stackoverflow.com/users/39648",
"pm_score": 2,
"selected": false,
"text": "struct VstEvents\n{\n VstInt32 numEvents; ///< number of Events in array\n VstIntPtr reserved; ///< zero (Reserved for future use)\n VstEvent* events[2]; ///< event pointer array, variable size\n};\n\n#define numEventsRequired 10\nVstEvents *vstEvents = (VstEvents*)malloc(sizeof(VstEvents) + sizeof(VstEvent*)*(numEventsRequired-2));\n\nvstEvents->numEvents = numEventsRequired;\n"
},
{
"answer_id": 364927,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 0,
"selected": false,
"text": "struct VstEvents\n{\n VstInt32 numEvents; ///< number of Events in array\n VstIntPtr reserved; ///< zero (Reserved for future use)\n VstEvent* events[]; ///< event pointer array, variable size\n};\n\n\nstruct VstEvents *alloc_vst_events(int num_events) {\n struct VstEvents *p = \n malloc(sizeof(*p) + num_events * sizeof(p->events[0]));\n return p;\n}\n #define NELEMS(A) (sizeof(A) / sizeof((A)[0]))\n\nstruct VstEvents *alloc_vst_events(int num_events) {\n struct VstEvents *p;\n int events_needed = num_events - NELEMS(p->events);\n p = malloc(sizeof(*p) + events_needed * sizeof(p->events[0]));\n return p;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359125",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14302/"
] |
359,126 | <p>I'm using Crystal Reports 11 (and VB6) to open a report file, load the data from an Access database and either print the report to a printer or export the report to another .rpt file (for later printing without the database)</p>
<p>Even for small amounts of data the process is somewhat slow. Profiling showed about 1.5 seconds for three records (one page) For about 500 records on 10 pages, it's 1.7 seconds.</p>
<p>Can I do something the speed it up? Can I tweak the data or the report? </p>
| [
{
"answer_id": 359136,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 2,
"selected": true,
"text": "struct VstEvents *evnts;\n\nevnts = (struct VstEvents*)malloc(sizeof(struct VstEvents) + \n numEvents*sizeof(VstEvent*));\n"
},
{
"answer_id": 359142,
"author": "Sandeep Datta",
"author_id": 39648,
"author_profile": "https://Stackoverflow.com/users/39648",
"pm_score": 2,
"selected": false,
"text": "struct VstEvents\n{\n VstInt32 numEvents; ///< number of Events in array\n VstIntPtr reserved; ///< zero (Reserved for future use)\n VstEvent* events[2]; ///< event pointer array, variable size\n};\n\n#define numEventsRequired 10\nVstEvents *vstEvents = (VstEvents*)malloc(sizeof(VstEvents) + sizeof(VstEvent*)*(numEventsRequired-2));\n\nvstEvents->numEvents = numEventsRequired;\n"
},
{
"answer_id": 364927,
"author": "Norman Ramsey",
"author_id": 41661,
"author_profile": "https://Stackoverflow.com/users/41661",
"pm_score": 0,
"selected": false,
"text": "struct VstEvents\n{\n VstInt32 numEvents; ///< number of Events in array\n VstIntPtr reserved; ///< zero (Reserved for future use)\n VstEvent* events[]; ///< event pointer array, variable size\n};\n\n\nstruct VstEvents *alloc_vst_events(int num_events) {\n struct VstEvents *p = \n malloc(sizeof(*p) + num_events * sizeof(p->events[0]));\n return p;\n}\n #define NELEMS(A) (sizeof(A) / sizeof((A)[0]))\n\nstruct VstEvents *alloc_vst_events(int num_events) {\n struct VstEvents *p;\n int events_needed = num_events - NELEMS(p->events);\n p = malloc(sizeof(*p) + events_needed * sizeof(p->events[0]));\n return p;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359126",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23368/"
] |
359,128 | <p>When a ComboBox is clicked this causes it to be selected in the window. Is there a way to perform the equivalent of a javascript blur()</p>
| [
{
"answer_id": 359158,
"author": "arul",
"author_id": 15409,
"author_profile": "https://Stackoverflow.com/users/15409",
"pm_score": 3,
"selected": true,
"text": "comboBox1.TopLevelControl.Focus();\n someControl.Focus();\n"
},
{
"answer_id": 6341225,
"author": "Roey",
"author_id": 314905,
"author_profile": "https://Stackoverflow.com/users/314905",
"pm_score": 0,
"selected": false,
"text": "comboBox1.Enabled = false;\ncomboBox1.Enabled = true;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32055/"
] |
359,147 | <p>Related to this question:
<a href="https://stackoverflow.com/questions/353207/url-characters-replacement-in-jsp-with-urlrewrite">URL characters replacement in JSP with UrlRewrite</a></p>
<p>I want to have masked URLs in this JSP Java EE web project.
For example if I had this:</p>
<pre><code>http://mysite.com/products.jsp?id=42&name=Programming_Book
</code></pre>
<p>I would like to turn that URL into something more User/Google friendly like:</p>
<pre><code>http://mysite.com/product-Programming-Book
</code></pre>
<p>I've been fighting with UrlRewrite, forwarding and RequestDispatcher to accomplish what I want, but I'm kind of lost. I should probably have a filter for all http requests, re format them, and forward the page. </p>
<p>Can anyone give some directions? Tips? </p>
<p>Thanks a lot. </p>
<p><strong>UPDATE:</strong> Servlets did it. Thanks Yuval for your orientation.
I had been using UrlRewrite, as you can see at the first sentence of the question I also asked a question about that. But I couldn't manage to get UrlRewrite work the way I wanted. Servlets did the job.</p>
| [
{
"answer_id": 359306,
"author": "Yuval",
"author_id": 2819,
"author_profile": "https://Stackoverflow.com/users/2819",
"pm_score": 1,
"selected": true,
"text": "http://mysite.com/product-Programming-Book http://mysite.com/products.jsp?id=42&name=Programming_Book"
},
{
"answer_id": 367745,
"author": "tegbains",
"author_id": 19419,
"author_profile": "https://Stackoverflow.com/users/19419",
"pm_score": 2,
"selected": false,
"text": "URLRewrite filter <rule>\n<from>^/some/old/page\\.html$</from>\n<to type=\"redirect\">/very/new/page.html</to>\n</rule>\n <rule>\n<from>^/zebra$</from>\n<to type=\"redirect\">/big/ugly/url/1,23,56,23132.html</to>\n</rule>\n"
},
{
"answer_id": 2932210,
"author": "luis.espinal",
"author_id": 201722,
"author_profile": "https://Stackoverflow.com/users/201722",
"pm_score": 0,
"selected": false,
"text": "http://yoursite/products?isbn=123465\nhttp://yoursite/products?author=johndoe&title=\"the cookbook\" << this assumes the latest edition, or 1 if first.\nhttp://yoursite/products?author=johndoe&title=\"the cookbook\"&edition=3\nhttp://yoursite/products?title=\"the cookbook\"&author=johndoe\nhttp://yoursite/products?edition=3&title=\"the cookbook\"&author=johndoe\n....\n http://yoursite/product/isbn/12345\nhttp://yoursite/product/author/johndoe/the%20cookbook << see the %20 for encoding spaces (not a good idea, but something to take into account)\nhttp://yoursite/product/author/johndoe/the%20cookbook/3\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1492/"
] |
359,206 | <p>I have seen these two approaches for constant declaration which are to be used in the project.</p>
<ol>
<li><p>Constants in a public module. </p></li>
<li><p>Constants in a NonInheritable(Sealed) class </p></li>
</ol>
<p>Does anybody uses any other approach for the constant declartion ?</p>
<p>Is there any difference between these approaches, any pros and cons ?</p>
<p>Thanks.</p>
| [
{
"answer_id": 359215,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 5,
"selected": true,
"text": "Math.Pi Int32.MinValue"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/41968/"
] |
359,213 | <p>On a Unix systems it's very easy to compile the CLASSPATH by using find:</p>
<pre><code>LIBDIR=`find lib/ -name \*.jar`
for DIR in $LIBDIR:
do
CLASSPATH="$CLASSPATH:$DIR"
done
java -classpath $CLASSPATH com.example.MyClass
</code></pre>
<p>What would be the aquivalent in a Windows batchfile?</p>
| [
{
"answer_id": 359242,
"author": "MrG",
"author_id": 33429,
"author_profile": "https://Stackoverflow.com/users/33429",
"pm_score": 3,
"selected": true,
"text": "setlocal ENABLEDELAYEDEXPANSION\nFOR /R .\\lib %%G IN (*.jar) DO set CLASSPATH=!CLASSPATH!;%%G\n\njava -classpath %CLASSPATH% com.example.MyClass\n"
},
{
"answer_id": 359254,
"author": "kgiannakakis",
"author_id": 24054,
"author_profile": "https://Stackoverflow.com/users/24054",
"pm_score": 1,
"selected": false,
"text": "cmd /v\n set var=.\nFOR /r %%d IN (*.jar) DO SET var=!var!;%%d\nset CLASSPATH=%var%\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33429/"
] |
359,217 | <p>I have a WPF ListView which repeats the data vertically. I cannot figure out how to make it repeat horizontally, like the slideshow view in Windows Explorer. My current ListView definition is:</p>
<pre><code><ListView ItemsSource="{StaticResource MyDataList}" ItemTemplate="{StaticResource ListViewTemplate}">
</ListView>
</code></pre>
<p>The DataTemplate is (although I believe this should not matter);
</p>
<pre><code> <Rectangle HorizontalAlignment="Stretch" Margin="0,1,0,0" x:Name="rectReflection" Width="Auto" Grid.Row="1" Height="30">
<Rectangle.Fill>
<VisualBrush Stretch="None" AlignmentX="Center" AlignmentY="Top" Visual="{Binding ElementName=imgPhoto}">
<VisualBrush.RelativeTransform>
<TransformGroup>
<MatrixTransform Matrix="1,0,0,-1,0,0" />
<TranslateTransform Y="1" />
</TransformGroup>
</VisualBrush.RelativeTransform>
</VisualBrush>
</Rectangle.Fill>
<Rectangle.OpacityMask>
<RadialGradientBrush GradientOrigin="0.5,1.041">
<RadialGradientBrush.RelativeTransform>
<TransformGroup>
<ScaleTransform CenterX="0.5" CenterY="0.5" ScaleX="1.202" ScaleY="2.865"/>
<SkewTransform AngleX="0" AngleY="0" CenterX="0.5" CenterY="0.5"/>
<RotateTransform Angle="0" CenterX="0.5" CenterY="0.5"/>
<TranslateTransform X="-0.002" Y="-0.491"/>
</TransformGroup>
</RadialGradientBrush.RelativeTransform>
<GradientStop Color="#D9000000" Offset="0"/>
<GradientStop Color="#01FFFFFF" Offset="0.8"/>
</RadialGradientBrush>
</Rectangle.OpacityMask>
</Rectangle>
</Grid>
</Border>
</DataTemplate>
</code></pre>
| [
{
"answer_id": 359418,
"author": "Boyan",
"author_id": 38106,
"author_profile": "https://Stackoverflow.com/users/38106",
"pm_score": 9,
"selected": true,
"text": "<ListView.ItemsPanel>\n <ItemsPanelTemplate>\n <StackPanel Orientation=\"Horizontal\"></StackPanel>\n </ItemsPanelTemplate>\n</ListView.ItemsPanel>\n"
},
{
"answer_id": 38215540,
"author": "st35ly",
"author_id": 1137540,
"author_profile": "https://Stackoverflow.com/users/1137540",
"pm_score": 3,
"selected": false,
"text": "<ItemsControl ItemsSource=\"{Binding Path=Steps}\">\n<ItemsControl.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding PageName}\" Padding=\"10\" />\n </DataTemplate>\n</ItemsControl.ItemTemplate> \n<ItemsControl.ItemsPanel>\n <ItemsPanelTemplate>\n <WrapPanel></WrapPanel>\n </ItemsPanelTemplate>\n</ItemsControl.ItemsPanel>\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359217",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26221/"
] |
359,229 | <p>I am working on an application which draws a simple dot grid. I would like the mouse to snap between the points on the grid, eventually to draw lines on the grid.</p>
<p>I have a method which takes in the current mouse location (X,Y) and calculates the nearest grid coordinate.</p>
<p>When I create an event and attempt to move the mouse to the new coordinate the whole system becomes jerky. The mouse doesn't snap smoothly between grid points.</p>
<p>I have copied a code sample below to illustrate what I am attempting to do. Does anyone have any advice they could offer me as to how I can eliminate the jumpiness within the mouse movement?</p>
<hr>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace GridTest
{
public partial class Form1 : Form
{
Graphics g;
const int gridsize = 20;
public Form1()
{
InitializeComponent();
g = splitContainer1.Panel2.CreateGraphics();
splitContainer1.Panel2.Invalidate();
}
private void splitContainer1_Panel2_Paint(object sender, PaintEventArgs e)
{
Drawgrid();
}
private void Drawgrid()
{
for (int x = 0; x < splitContainer1.Panel2.ClientSize.Width; x += gridsize)
{
for (int y = 0; y < splitContainer1.Panel2.ClientSize.Height; y += gridsize)
{ g.DrawLine(Pens.Black, new Point(x, y), new Point(x + 1, y)); }
}
}
private void splitContainer1_Panel2_MouseMove(object sender, MouseEventArgs e)
{
Point newPosition = new Point();
newPosition = RoundToNearest(gridsize, e.Location);
Cursor.Position = splitContainer1.Panel2.PointToScreen(newPosition);
}
private Point RoundToNearest(int nearestRoundValue, Point currentPoint)
{
Point newPoint = new Point();
int lastDigit;
lastDigit = currentPoint.X % nearestRoundValue;
if (lastDigit >= (nearestRoundValue/2))
{ newPoint.X = currentPoint.X - lastDigit + nearestRoundValue; }
else
{ newPoint.X = currentPoint.X - lastDigit; }
lastDigit = currentPoint.Y % nearestRoundValue;
if (lastDigit >= (nearestRoundValue / 2))
{ newPoint.Y = currentPoint.Y - lastDigit + nearestRoundValue; }
else
{ newPoint.Y = currentPoint.Y - lastDigit; }
return newPoint;
}
}
}
</code></pre>
| [
{
"answer_id": 359922,
"author": "user21826",
"author_id": 21826,
"author_profile": "https://Stackoverflow.com/users/21826",
"pm_score": 2,
"selected": true,
"text": "\nImports System\nImports System.Drawing\nImports System.Windows.Forms\n\nModule modSnap\n\n Public Const strApplicationTitle As String = \"Snap Demo\"\n Public frmSnap As SnapForm\n Public ptSnap, ptStart, ptEnd As Point\n\n Public Class SnapForm\n Inherits Form\n Public Sub New()\n Me.Text = \"Snap Demo\"\n Me.ClientSize = New Size(800, 600)\n Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle\n Me.MaximizeBox = False\n Me.StartPosition = FormStartPosition.CenterScreen\n Me.DoubleBuffered = True\n End Sub\n Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)\n MyBase.OnPaint(e)\n e.Graphics.Clear(Color.Black)\n For row As Integer = 20 To 780 Step 20\n For col As Integer = 20 To 580 Step 20\n e.Graphics.DrawEllipse(Pens.Blue, New Rectangle(row - 2, col - 2, 4, 4))\n Next\n Next\n e.Graphics.DrawLine(Pens.Red, ptStart, ptEnd)\n End Sub\n Protected Overrides Sub OnMouseDown(ByVal e As System.Windows.Forms.MouseEventArgs)\n MyBase.OnMouseDown(e)\n Dim x As Integer = CInt(e.X / 20) * 20\n Dim y As Integer = CInt(e.Y / 20) * 20\n ptStart = New Point(x, y)\n ptSnap = New Point(x, y)\n Windows.Forms.Cursor.Position = Me.PointToScreen(ptSnap)\n End Sub\n Protected Overrides Sub OnMouseMove(ByVal e As System.Windows.Forms.MouseEventArgs)\n MyBase.OnMouseMove(e)\n If e.Button = Windows.Forms.MouseButtons.Left Then\n Dim x As Integer = CInt(e.X / 20) * 20\n Dim y As Integer = CInt(e.Y / 20) * 20\n ' must be some delta away from original snap point\n If (x < ptSnap.X - 15 Or x > ptSnap.X + 15) Or (y < ptSnap.Y - 15 Or y > ptSnap.Y + 15) Then\n ptSnap = New Point(x, y)\n ptEnd = New Point(x, y)\n Me.Invalidate(False)\n Windows.Forms.Cursor.Position = Me.PointToScreen(ptSnap)\n End If\n End If\n End Sub\n End Class\n\n Public Sub main()\n Try\n frmSnap = New SnapForm\n Application.Run(frmSnap)\n Catch ex As Exception\n MessageBox.Show(ex.Message, strApplicationTitle, MessageBoxButtons.OK, MessageBoxIcon.Error)\n Finally\n frmSnap.Dispose()\n End Try\n End Sub\n\nEnd Module\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359229",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,232 | <p>I'm using Windows XP Service Pack 3 and have Command Extensions enabled by default in the Windows Registry.
Somehow, the following command does not work on this version of Windows but if I run it in Windows Server 2003 or Windows Vista Business, it works just fine. Any clue?</p>
<p>The problem is that on Windows XP, it seems like the /f option is not working at all and the do part of the command never gets executed.</p>
<p>This is the command:</p>
<pre><code>for /f "tokens=1 delims=: " %A in ('tasklist /FI "IMAGENAME eq python.exe" /NH') do (
If "%A" == "python.exe" (
echo "It's running"
) Else (
echo "It's not running"
)
)
</code></pre>
<p>Thanks in advance.</p>
| [
{
"answer_id": 359274,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "@echo off\nfor /f \"tokens=1 delims=: \" %%A in ('tasklist /FI \"IMAGENAME eq java.exe\" /NH') do (\n If \"%%A\" == \"java.exe\" (\n echo \"It's running\"\n ) Else (\n echo \"It's not running\"\n )\n)\n %%A"
},
{
"answer_id": 359293,
"author": "Tomalak",
"author_id": 18771,
"author_profile": "https://Stackoverflow.com/users/18771",
"pm_score": 3,
"selected": false,
"text": "tasklist.exe STDERR for /f STDOUT python.exe STDERR STDOUT 2>&1 for /F \"tokens=1 delims=: \" %A in ('tasklist /FI \"IMAGENAME eq python.exe\" /NH 2^>^&1') do (\n if \"%A\"==\"python.exe\" (\n echo \"It's running\"\n ) else (\n echo \"It's not running\"\n )\n)\n ^"
},
{
"answer_id": 359314,
"author": "Patrick Cuff",
"author_id": 7903,
"author_profile": "https://Stackoverflow.com/users/7903",
"pm_score": 0,
"selected": false,
"text": "@echo off\nset found=0\n\nfor /f \"tokens=1 delims=: \" %%A in ('tasklist /NH') do (\n If /i \"%%A\" equ \"python.exe\" (\n set found=1\n ) \n)\n\nif %found%==1 (\n @echo It's running\n) else (\n @echo It's not running\n)\n"
},
{
"answer_id": 2267663,
"author": "Daz",
"author_id": 273677,
"author_profile": "https://Stackoverflow.com/users/273677",
"pm_score": 0,
"selected": false,
"text": "Set RUNNING=False\nfor /f \"tokens=1 delims=: \" %%a in ('tasklist /FI \"IMAGENAME eq python.exe\" /NH 2^>NUL') do (Set RUNNING=True)\nIf %RUNNING% == True (\n @Echo It IS running\n) ELSE (\n @Echo It's NOT running\n)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359232",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,237 | <p>This is a somewhat bizarre question. My objectives are to understand the language design decision and to identify the possibilities of reflection in C++.</p>
<ol>
<li><p>Why C++ language committee did not go towards implementing reflection in the language? Is reflection too difficult in a language that does not run on a virtual machine (like java)?</p></li>
<li><p>If one were to implement reflection for C++, what will be the challenges?</p></li>
</ol>
<p>I guess the uses of reflection are well-known: editors can be more easily written, program code will be smaller, mocks can be generated for unit tests and so on. But it would be great if you could comment on uses of reflection too.</p>
| [
{
"answer_id": 359462,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 10,
"selected": true,
"text": "#include operator[] std::vector<int> std::vector<float> std::vector std::vector<int> std::vector<float> std::vector<int>::iterator std::vector<float>::iterator const_iterator std::vector<int> std::vector<int>::iterator std::vector<int> boost::type_traits T type_traits std::vector #include"
},
{
"answer_id": 1411360,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "const const Q_PROPERTY"
},
{
"answer_id": 12121523,
"author": "user1401491",
"author_id": 1401491,
"author_profile": "https://Stackoverflow.com/users/1401491",
"pm_score": -1,
"selected": false,
"text": "#pragma enable reflection"
},
{
"answer_id": 68765709,
"author": "Yakk - Adam Nevraumont",
"author_id": 1774667,
"author_profile": "https://Stackoverflow.com/users/1774667",
"pm_score": 2,
"selected": false,
"text": "struct Member {\n std::string_view name;\n std::any_ref value;\n};\n\nstruct Reflectable {\n virtual std::span<Member> GetMembers() const = 0;\n virtual std::span<Member> GetMembers() = 0;\n};\n\ntemplate<class D>\nstruct ImplReflectable:Reflectable {\n std::span<Member> GetMembers() const final;\n std::span<Member> GetMembers() final;\n};\ntemplate<class D>\nstd::span<Member> ImplReflectable<D>::GetMembers() const {\n // compile time reflection code on D here\n}\ntemplate<class D>\nstd::span<Member> ImplReflectable<D>::GetMembers() {\n // compile time reflection code on D here\n}\n struct Point : ImplReflectable<Point> {\n int x, y;\n};\n Point interface Reflectable {\n std::span<Member> GetMembers() const;\n std::span<Member> GetMembers();\n};\n interface QObject Reflectable PolymorphicValueType NetworkProtocol reflexpr constexpr consteval"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359237",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19501/"
] |
359,257 | <p>In SQL server 2005 this query</p>
<pre><code>select len(cast('the quick brown fox jumped over the lazy dog' as varchar))
</code></pre>
<p>returns 30 as length while the supplied string has more characters. This seems to be the default. Why 30, and not 32 or any other power of 2?</p>
<p><strong>[EDIT]</strong> I am aware that I should always specifiy the length when casting to varchar but this was a quick let's-check-something query. Questions remains, why 30?</p>
| [
{
"answer_id": 359289,
"author": "curtisk",
"author_id": 17651,
"author_profile": "https://Stackoverflow.com/users/17651",
"pm_score": 7,
"selected": true,
"text": "SELECT CAST('the quick brown fox jumped over the lazy dog' AS VARCHAR(45))\n"
},
{
"answer_id": 11529344,
"author": "NG.",
"author_id": 1501472,
"author_profile": "https://Stackoverflow.com/users/1501472",
"pm_score": 0,
"selected": false,
"text": "select len(cast('the quick brown fox jumped over the lazy dog' as varchar(max)))\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359257",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6399/"
] |
359,284 | <p>I have a method which prints out the order of a set of images. I need to submit this to a new php page.</p>
<p>I have a form which currently prints out the order to the same page.</p>
<pre><code><form action="mainpage.php" method="post">
<div style="clear:both;padding-bottom:10px">
<input type="Button" style="width:100px" value="Show order" onclick="saveImageOrder()">
</div>
</code></pre>
<p><code>Saveimageorder()</code> shows the image and it saves the order in a variable called orderString</p>
<pre><code>function saveImageOrder()
{
var orderString = "";
var objects = document.getElementsByTagName('DIV');
for(var no=0;no<objects.length;no++)
{
if(objects[no].className=='imageBox' || objects[no].className=='imageBoxHighlighted')
{
if(orderString.length>0) orderString = orderString + ',';
orderString = orderString + objects[no].id;
}
}
document.getElementById('debug').innerHTML = 'This is the new order of the images(IDs) : <br>' + orderString;
}
</code></pre>
<p>How to do this?</p>
| [
{
"answer_id": 359305,
"author": "jumoel",
"author_id": 1555170,
"author_profile": "https://Stackoverflow.com/users/1555170",
"pm_score": 2,
"selected": false,
"text": "document.formname.submit();\n document.formname.action = 'some_other_url';\n"
},
{
"answer_id": 359338,
"author": "smoothdeveloper",
"author_id": 17049,
"author_profile": "https://Stackoverflow.com/users/17049",
"pm_score": 1,
"selected": false,
"text": "<input type=\"hidden\" name=\"imagesorder\" value=\"\"/>\n document.getElementsByName('imagesorder')[0].value = orderString;\n <input type=\"button\" .../>\n <input type=\"submit\" .../>\n $_POST['imagesorder']\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
359,287 | <p>I am writing an <a href="http://www.eclipse.com" rel="nofollow noreferrer">Eclipse</a> plug-in that loads resources from a central database. I would like to use <a href="http://www.hibernate.org" rel="nofollow noreferrer">Hibernate</a> to access that database. </p>
<p>So how would I add this as a dependency to my plug-in project? I've tried Google but only get hits on about plug-ins for editing Hibernate configuration files.</p>
| [
{
"answer_id": 359676,
"author": "Mario Ortegón",
"author_id": 2309,
"author_profile": "https://Stackoverflow.com/users/2309",
"pm_score": 1,
"selected": false,
"text": "Manifest-Version: 1.0\nBundle-ManifestVersion: 2\nBundle-Name: Solarmetric Kodo\nBundle-SymbolicName: com.solarmetric.kodo\nBundle-Activator: com.solarmetric.kodo.KodoPlugin\nBundle-Localization: plugin\nRequire-Bundle: org.eclipse.core.runtime\nEclipse-AutoStart: true\nEclipse-BuddyPolicy: global\nExport-Package: com.solarmetric.ant,\n com.solarmetric.apache.commons.collections,\n com.solarmetric.apache.commons.collections.buffer,\n com.solarmetric.apache.commons.collections.collection,\n com.solarmetric.apache.commons.collections.functors,\n com.solarmetric.apache.commons.collections.iterators,\n com.solarmetric.apache.commons.collections.keyvalue,\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359287",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1969/"
] |
359,290 | <p>How is it possible to get the FxCop custom dictionary to work correctly?</p>
<p>I have tried adding words to be recognised to the file 'CustomDictionary.xml', which is kept in the same folder as the FxCop project file. This does not seem to work, as I still get the 'Identifiers should be spelled correctly' FxCop message, even after reloading and re-running FxCop. Using version 1.36.</p>
| [
{
"answer_id": 446429,
"author": "spinodal",
"author_id": 11374,
"author_profile": "https://Stackoverflow.com/users/11374",
"pm_score": 5,
"selected": false,
"text": "<Dictionary>\n <Words>\n <Recognized>\n <Word>\"productname\"</Word>\n <Word>\"companyname\"</Word>\n </Recognized>\n </Words>\n</Dictionary>\n"
},
{
"answer_id": 726358,
"author": "David Schmitt",
"author_id": 4918,
"author_profile": "https://Stackoverflow.com/users/4918",
"pm_score": 4,
"selected": false,
"text": "<CustomDictionaries SearchFxCopDir=\"True\"\n SearchUserProfile=\"True\"\n SearchProjectDir=\"True\" />\n /dictionary"
},
{
"answer_id": 1796513,
"author": "Grhm",
"author_id": 204690,
"author_profile": "https://Stackoverflow.com/users/204690",
"pm_score": 2,
"selected": false,
"text": "C:\\Program Files\\Microsoft FxCop 1.36\\CustomDictionary.xml CustomDictionary.xml"
},
{
"answer_id": 2620735,
"author": "Pete",
"author_id": 158483,
"author_profile": "https://Stackoverflow.com/users/158483",
"pm_score": 2,
"selected": false,
"text": "FxCopCmd.exe ... /dictionary:FxCopDictionary.xml\n"
},
{
"answer_id": 10957213,
"author": "Trystan Spangler",
"author_id": 548014,
"author_profile": "https://Stackoverflow.com/users/548014",
"pm_score": 1,
"selected": false,
"text": "*.xml *.xml.txt"
},
{
"answer_id": 24388518,
"author": "Anthony Shaw",
"author_id": 117350,
"author_profile": "https://Stackoverflow.com/users/117350",
"pm_score": 2,
"selected": false,
"text": "<CustomDictionaries SearchFxCopDir=\"True\" SearchUserProfile=\"True\" SearchProjectDir=\"True\" />\n <CustomDictionaries SearchFxCopDir=\"True\" SearchUserProfile=\"True\" SearchProjectDir=\"True\" >\n <CustomDictionary Path=\"$(ProjectDir)/CustomDictionary.xml\"/>\n</CustomDictionaries>\n"
},
{
"answer_id": 73631142,
"author": "dan",
"author_id": 1764696,
"author_profile": "https://Stackoverflow.com/users/1764696",
"pm_score": 0,
"selected": false,
"text": "(?:dictionary|custom).*?\\.(?:xml|dic)$"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359290",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15985/"
] |
359,298 | <p>I have data from a table in a database (string) that contain text and price. I extract the price from the data but my problem is that sometime I can Convert it to float and sometime not.</p>
<p>I have noticed that :</p>
<pre><code>Convert.ToSingle(m.Groups[1].Value);
</code></pre>
<p>It works but not always because sometime the period is the problem (it requires a comma). What can I do? I have try to replace the ".", by "," but sometime on other PC it's a period that it's required!</p>
| [
{
"answer_id": 359311,
"author": "Patrick Desjardins",
"author_id": 13913,
"author_profile": "https://Stackoverflow.com/users/13913",
"pm_score": 6,
"selected": true,
"text": "Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture.NumberFormat);\n"
},
{
"answer_id": 359325,
"author": "Christoffer Lette",
"author_id": 11808,
"author_profile": "https://Stackoverflow.com/users/11808",
"pm_score": 0,
"selected": false,
"text": "Convert.ToSingle(m.Groups[1].Value, CultureInfo.InvariantCulture);\n InvariantCulture"
},
{
"answer_id": 359523,
"author": "ICR",
"author_id": 214,
"author_profile": "https://Stackoverflow.com/users/214",
"pm_score": 2,
"selected": false,
"text": "float f = float.Parse(input);\nstring toDb = f.ToString(CultureInfo.InvariantCulture);\n float f = float.Parse(fromDb, CultureInfo.InvariantCulture);\nstring toOutput = f.ToString();\n float f;\nif (!float.TryParse(input, out f))\n{\n // ERROR\n}\n"
},
{
"answer_id": 360145,
"author": "baretta",
"author_id": 30052,
"author_profile": "https://Stackoverflow.com/users/30052",
"pm_score": 3,
"selected": false,
"text": "System.Globalization.NumberFormatInfo nf\n = new System.Globalization.NumberFormatInfo ( )\n{\n NumberGroupSeparator = \".\"\n};\nfloat f = float.Parse ( \"5.34534\", nf );\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359298",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14441/"
] |
359,303 | <p>I have a IBAction such as:</p>
<pre><code>- (IBAction)showPicker:(id)sender;
</code></pre>
<p>How can I get the name of the control from the sender variable?</p>
<p>I am typically a c# coder so have tried the following to no avail</p>
<pre><code>senderName = ((UIButton *)sender).name;
</code></pre>
<p>I need something more descriptive than the control id (not the button title either). I have 5 buttons all calling the same method. I need to determine which was clicked in order to perform the methods actions on the appropriate control. I.E I have an address picker method but want to populate 5 text fields with different details with each of 5 buttons. Just trying to keep the code tidy</p>
<p>N.B Originally I was planning on using the Interface Builders name field, but I've been advised (below) that this isn't available at runtime.</p>
| [
{
"answer_id": 359358,
"author": "Marc Charbonneau",
"author_id": 35136,
"author_profile": "https://Stackoverflow.com/users/35136",
"pm_score": 2,
"selected": false,
"text": "name tag currentTitle"
},
{
"answer_id": 359369,
"author": "Matthew Schinckel",
"author_id": 188,
"author_profile": "https://Stackoverflow.com/users/188",
"pm_score": 0,
"selected": false,
"text": "NSString *senderName = [sender name];\n NSString *senderName = [sender title];\n"
},
{
"answer_id": 359375,
"author": "Abizern",
"author_id": 41116,
"author_profile": "https://Stackoverflow.com/users/41116",
"pm_score": 0,
"selected": false,
"text": "senderTitle = [sender currentTitle];\n"
},
{
"answer_id": 359378,
"author": "Stephen Darlington",
"author_id": 2998,
"author_profile": "https://Stackoverflow.com/users/2998",
"pm_score": 4,
"selected": true,
"text": "control.tag\n [stringWithFormat:@\"%d\", control.tag]\n"
},
{
"answer_id": 9368375,
"author": "JasonD",
"author_id": 156789,
"author_profile": "https://Stackoverflow.com/users/156789",
"pm_score": 2,
"selected": false,
"text": "@interface CustomSegmentedControl : UISegmentedControl\n@property (nonatomic, retain) NSString* myCustomKey; \n@end\n - (IBAction)myButtonPressed:(id) sender\n{\n if ([sender isKindOfClass:[CustomSegmentedControl class]] == false)\n return;\n\n // get the key-values from the control\n CustomSegmentedControl *control = (CustomSegmentedControl *)sender;\n NSString *key = [control valueForKey:@\"myCustomKey\"];\n NSNumber *value = [NSNumber numberWithInteger:[control selectedSegmentIndex]];\n NSLog(@\"Pressed control %@ with a value of %@\", key, value);\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359303",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/258/"
] |
359,315 | <p>How to configure JAXB unmarshaller so it will trim leading and trailing whitespaces from strings?</p>
<p>For instance let's consider a simple binding between a Java bean and XML using JAXB annotations:</p>
<pre><code>@XmlRootElement(name="bean")
class Bean {
@XmlElement(required=true)
String name;
@XmlElement(required=true)
int number;
}
</code></pre>
<p>I would like to be able to unmarshal XML given bellow so <strong>bean.name</strong> does not include starting and trailing whitespaces - is "<strong>My name</strong>", not "<strong>\n My name\n</strong> ".</p>
<pre><code><bean>
<name>
My name
</name>
<number>1</number>
</bean>
</code></pre>
| [
{
"answer_id": 359363,
"author": "bruno conde",
"author_id": 31136,
"author_profile": "https://Stackoverflow.com/users/31136",
"pm_score": 4,
"selected": true,
"text": "public class MyNormalizedStringAdapter extends XmlAdapter<String, String> {\n\n @Override\n public String marshal(String text) {\n return text.trim();\n }\n\n @Override\n public String unmarshal(String v) throws Exception {\n return v.trim();\n }\n}\n @XmlElement(required=true)\n@XmlJavaTypeAdapter(MyNormalizedStringAdapter.class)\nString name;\n"
},
{
"answer_id": 60336859,
"author": "Sergey Nemchinov",
"author_id": 7666239,
"author_profile": "https://Stackoverflow.com/users/7666239",
"pm_score": 2,
"selected": false,
"text": "@XmlElement(required=true)\n@XmlJavaTypeAdapter(CollapsedStringAdapter.class)\nString name;\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359315",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42201/"
] |
359,320 | <p>I want to create a delegate type in C# inside a method for the purpose of creating Anonymous methods.</p>
<p>For example:</p>
<pre><code>public void MyMethod(){
delegate int Sum(int a, int b);
Sum mySumImplementation=delegate (int a, int b) {return a+b;}
Console.WriteLine(mySumImplementation(1,1).ToString());
}
</code></pre>
<p>Unfortunately, I cannot do it using .NET 2.0 and C# 2.0.</p>
| [
{
"answer_id": 359339,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": true,
"text": "public void MyMethod(){\n Func<int, int, int> mySumImplementation = \n delegate (int a, int b) { return a+b; };\n\n Console.WriteLine(mySumImplementation(1,1).ToString());\n}\n"
},
{
"answer_id": 359345,
"author": "jalf",
"author_id": 33213,
"author_profile": "https://Stackoverflow.com/users/33213",
"pm_score": 4,
"selected": false,
"text": "class MyClass {\n delegate int Sum(int a, int b);\n public void MyMethod(){\n\n Sum mySumImplementation=delegate (int a, int b) {return a+b;}\n\n Console.WriteLine(mySumImplementation(1,1).ToString());\n }\n\n}\n delegate R Func<R>();\ndelegate R Func<T, R>(T t);\ndelegate R Func<T0, T1, R>(T0 t0, T1 t1);\ndelegate R Func<T0, T1, T2, R>(T0 t0, T1 t1, T2 t2);\n Func<int, int, int>"
},
{
"answer_id": 37779197,
"author": "Dim_Ka",
"author_id": 936971,
"author_profile": "https://Stackoverflow.com/users/936971",
"pm_score": 0,
"selected": false,
"text": "static void Main(string[] args)\n{\n Expression<Func<int, int, int>> exFunc = (a, b) => a + b;\n var lambda = exFunc as LambdaExpression;\n Delegate del = exFunc.Compile();\n Console.WriteLine(del.DynamicInvoke(2, 2));\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359320",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/32582/"
] |
359,321 | <p>I have the following SQL query:</p>
<pre><code>select expr1, operator, expr2, count(*) as c
from log_keyword_fulltext
group by expr1, operator, expr2
order by c desc limit 2000;
</code></pre>
<p>Problem: The <code>count(*)</code> as part of my order by is killing my application, probably because it don't use index. I would like to know if there is any way to make it faster, like for example a <code>select</code> inside of another <code>select</code>, or something like that.</p>
<p>My <code>SELECT</code> explained:</p>
<pre><code>+----+-------------+----------------------+-------+---------------+-------+---------+------+--------+----------------------------------------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+----------------------+-------+---------------+-------+---------+------+--------+----------------------------------------------+
| 1 | SIMPLE | log_keyword_fulltext | index | NULL | expr1 | 208 | NULL | 110000 | Using index; Using temporary; Using filesort |
+----+-------------+----------------------+-------+---------------+-------+---------+------+--------+----------------------------------------------+
</code></pre>
<p>UPDATED:</p>
<p>I tried to do a subquery like that</p>
<pre><code>select * from (select b.expr1,b.operator,b.expr2,count(*) as c
from log_keyword_fulltext b group by b.expr1,b.operator,b.expr2) x
order by x.c desc limit 2000;
</code></pre>
<p>its working but not faster, following is the explain:</p>
<pre><code>+----+-------------+------------+-------+---------------+-------+---------+------+--------+----------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+------------+-------+---------------+-------+---------+------+--------+----------------+
| 1 | PRIMARY | <derived2> | ALL | NULL | NULL | NULL | NULL | 38398 | Using filesort |
| 2 | DERIVED | b | index | NULL | expr1 | 208 | NULL | 110000 | Using index |
+----+-------------+------------+-------+---------------+-------+---------+------+--------+----------------+
</code></pre>
<p>You can check that now, its not using temporary anymore, but it still with the same performance. any recommendation ?</p>
| [
{
"answer_id": 359364,
"author": "Paul Tomblin",
"author_id": 3333,
"author_profile": "https://Stackoverflow.com/users/3333",
"pm_score": -1,
"selected": false,
"text": "create foo as \n select expr1, operator, expr2, count(*) as c\n from log_keyword_fulltext \n group by expr1, operator, expr2;\nselect * from foo order by c desc limit 2000;\n"
},
{
"answer_id": 359404,
"author": "Samiksha",
"author_id": 29515,
"author_profile": "https://Stackoverflow.com/users/29515",
"pm_score": 1,
"selected": false,
"text": "Eg:\n\nselect expr1, operator, expr2, count(expr1) as c \nfrom log_keyword_fulltext \ngroup by expr1, operator, expr2 \norder by c desc limit 2000;\n"
},
{
"answer_id": 359471,
"author": "niXar",
"author_id": 19979,
"author_profile": "https://Stackoverflow.com/users/19979",
"pm_score": 0,
"selected": false,
"text": "CREATE TEMP TABLE t (e1 EXP_T, op OP_T, e2 EXP_T, count INTEGER)\nADD AN INDEX ON count\nFOR EACH LINE OF SELECT exp1,operator,exp2 FROM log_blah DO\n UPDATE t SET count=count+1 WHERE exp1=e1 AND operator=op AND exp2=e2\n IF IT DOES NOT WORK INSERT INTO t VALUES (exp1,operator,exp2,1)\nDONE\nSELECT * FROM t ORDER BY count DESC LIMIT 2000\n"
},
{
"answer_id": 360589,
"author": "Chris",
"author_id": 42937,
"author_profile": "https://Stackoverflow.com/users/42937",
"pm_score": 0,
"selected": false,
"text": "ALTER TABLE `log_keyword_fulltext` ADD INDEX `idx_name`(expr1, operator, expr2)\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18642/"
] |
359,328 | <p>I have the following javascript code, which loads without error, however the update function does not actually seem functional, as get_Records.php is never loaded. I can not test if get_auction.php is loaded as it is loaded from within get_records.php</p>
<p><strong>One of my main concerns</strong> is that I am doing the wrong thing by having update() take the paramters pk and query, as only one of them will ever be used. That seems like a bad hack, and poor logic, but I am not aware of a better way.</p>
<p>Here is the code</p>
<pre><code>var xmlHttp
var layername
var url
function update(layer, part, pk, query) {
alert ("update");
if (part=="1") {
alert ("part 1");
url = "get_auction.php?cmd=GetAuctionData&pk="+pk+"&sid="+Math.random()
} else if (part=="2") {
alert ("part 2");
url = "get_records.php?cmd=GetRecordSet&query="+query+"&sid="+Math.random()
}
xmlHttp=GetXmlHttpObject()
if(xmlHttp==null) {
alert("Your browser is not supported?")
}
xmlHttp.onreadystatechange = function() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
document.getElementById(layer).innerHTML=xmlHttp.responseText
} else if (xmlHttp.readyState==1 || xmlHttp.readyState=="loading") {
document.getElementById(layer).innerHTML="loading"
}
};
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function GetXmlHttpObject() {
var xmlHttp=null;
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
try {
xmlHttp =new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {}
}
return xmlHttp;
}
function makewindows() {
child1 = window.open ("about:blank");
child1.document.write(<?php echo htmlspecialchars(json_encode($row2["ARTICLE_DESC"]), ENT_QUOTES); ?>));
child1.document.close();
}
</code></pre>
<p>I placed alert statements into the update function, andnot one is displayed, indicated the update function is never called?</p>
<p>I do not want to, and cannot use a framework, nor do I have access to use firebug, so please do not suggest these things. I am aware of them and use them when I can.</p>
<p>I would also like to know if calling php from within makewindows() is preferred to having makewindows simply take a parameter.., is there any advantage or disadvantage to each approach?</p>
<p>I seem to get an error when trying to call the function, this is how I am doing it in PHP:</p>
<pre><code>echo "<li><a href='#' onclick=update('Layer3','2','0','hello')'>Link 1</a></li>" .
</code></pre>
<p>which makes this html, which should be fine?"\n"; </p>
<pre><code><li><a href='#' onclick='update('Layer3','2','0','hello')'>Link 1</a></li>
</code></pre>
<p>edit: I have taken tester101'S advice and changed it to this:</p>
<pre><code>echo '<li><a href="#" onclick="update(\'Layer3\',\'2\',\'0\',\'hello\')">Link 1</a></li>' . "\n";
</code></pre>
<p>Which still gives an error. I will probably end up using toms answer, but would like to know why this is not working.</p>
| [
{
"answer_id": 359368,
"author": "Jan Aagaard",
"author_id": 37147,
"author_profile": "https://Stackoverflow.com/users/37147",
"pm_score": 0,
"selected": false,
"text": "windows.alert(\"GetXmlHttpObject started.\");"
},
{
"answer_id": 359387,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 1,
"selected": true,
"text": "function update(layer, url) {\n var xmlHttp=GetXmlHttpObject(); //you have this defined elsewhere\n\n if(xmlHttp==null) {\n alert(\"Your browser is not supported?\");\n }\n\n xmlHttp.onreadystatechange = function() {\n if(xmlHttp.readyState==4 || xmlHttp.readyState==\"complete\") {\n document.getElementById(layer).innerHTML=xmlHttp.responseText;\n } else if (xmlHttp.readyState==1 || xmlHttp.readyState==\"loading\") {\n document.getElementById(layer).innerHTML=\"loading\";\n }\n\n //etc\n }\n\n xmlHttp.open(\"GET\",url,true);\n xmlHttp.send(null);\n}\n\n\nfunction updateByPk(layer, pk) {\n url = \"get_auction.php?cmd=GetAuctionData&pk=\"+pk+\"&sid=\"+Math.random();\n update(layer, url);\n}\n\n\nfunction updateByQuery(layer, query) {\n url = \"get_records.php?cmd=GetRecordSet&query=\"+query+\"&sid=\"+Math.random();\n update(layer, url);\n}\n updateByPk('id_of_div', 2);\n updateByQuery('id_of_div2', 'query');\n <a href=\"#\" onclick=\"updateByQuery('Layer3', 'hello');\">Link 1</a>\n <?php echo '<a href=\"#\" onclick=\"updateByQuery(\\'Layer3\\', ' . json_encode($query) . ');\">Link 1</a>';\n"
},
{
"answer_id": 359519,
"author": "Jason S",
"author_id": 44330,
"author_profile": "https://Stackoverflow.com/users/44330",
"pm_score": 2,
"selected": false,
"text": "console.info(\"unexpected value x=%o\", some_object);"
},
{
"answer_id": 359716,
"author": "Jay",
"author_id": 41690,
"author_profile": "https://Stackoverflow.com/users/41690",
"pm_score": 0,
"selected": false,
"text": "function myFunction(var1, var2, var3, var4){\n myFunction('test1','test2');\n if(null != var3){\n"
},
{
"answer_id": 359796,
"author": "Jimmy",
"author_id": 4435,
"author_profile": "https://Stackoverflow.com/users/4435",
"pm_score": 0,
"selected": false,
"text": "child1.document.write(<?php echo htmlspecialchars(json_encode($row2[\"ARTICLE_DESC\"]), ENT_QUOTES); ?>));\n"
},
{
"answer_id": 359813,
"author": "Tester101",
"author_id": 38695,
"author_profile": "https://Stackoverflow.com/users/38695",
"pm_score": 0,
"selected": false,
"text": "\nonclick=update('Layer3','2','0','hello')'>Link 1\n \nonclick=\"update('Layer3','2','0','hello')\">Link 1\n \nonclick='update('Layer3','2','0','hello')'>Link 1\n"
},
{
"answer_id": 360009,
"author": "Piskvor left the building",
"author_id": 19746,
"author_profile": "https://Stackoverflow.com/users/19746",
"pm_score": 0,
"selected": false,
"text": "function update(layer, part, pk, query) {\n alert (\"update\");\n if (part==\"1\") {\n alert (\"part 1\");\n url = \"get_auction.php?cmd=GetAuctionData&pk=\"+pk+\"&sid=\"+Math.random()\n } else if (part==\"2\") {\n alert (\"part 2\");\n url = \"get_records.php?cmd=GetRecordSet&query=\"+query+\"&sid=\"+Math.random()\n }\n // and so on...\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1246613/"
] |
359,332 | <p>I refactor my code and I am looking for a solution to grep my source files for something like</p>
<pre><code>if ( user && user.name && user.name.length() < 128 ) ...
</code></pre>
<p>in order to replace it later with ruby's andand or groovy's ?. operator (safe navigation operator).</p>
| [
{
"answer_id": 362870,
"author": "krusty.ar",
"author_id": 43981,
"author_profile": "https://Stackoverflow.com/users/43981",
"pm_score": 2,
"selected": false,
"text": "line = \"user && user.name && user.name.length()\"\np line.match(/(?:(\\w*)(?:\\s\\&\\&\\s(\\1\\.(\\w*)))(?:\\s\\&\\&\\s(\\2\\.(\\w*))))/).to_a.\n reject {|m| m.match(/\\./)}.join('.andand.')\n\n=> \"user.andand.name.andand.length\"\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/45327/"
] |
359,342 | <p>For a web application, I would like to create a simple but effective licensing system. In C#, this is a little difficult, since my decryption method could be viewed by anyone with Reflector installed.</p>
<p>What are some methods for encrypting files in C# that are fairly tamper-proof?</p>
| [
{
"answer_id": 359923,
"author": "Wolfwyrd",
"author_id": 15570,
"author_profile": "https://Stackoverflow.com/users/15570",
"pm_score": 6,
"selected": true,
"text": "sn -k c:\\keypair.snk\n /// <summary>\n /// Retrieves an RSA public key from a signed assembly\n /// </summary>\n /// <param name=\"assembly\">Signed assembly to retrieve the key from</param>\n /// <returns>RSA Crypto Service Provider initialised with the key from the assembly</returns>\n public static RSACryptoServiceProvider GetPublicKeyFromAssembly(Assembly assembly)\n {\n if (assembly == null)\n throw new ArgumentNullException(\"assembly\", \"Assembly may not be null\");\n\n byte[] pubkey = assembly.GetName().GetPublicKey();\n if (pubkey.Length == 0)\n throw new ArgumentException(\"No public key in assembly.\");\n\n RSAParameters rsaParams = EncryptionUtils.GetRSAParameters(pubkey);\n RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();\n rsa.ImportParameters(rsaParams);\n\n return rsa;\n }\n"
},
{
"answer_id": 1316907,
"author": "mark",
"author_id": 161372,
"author_profile": "https://Stackoverflow.com/users/161372",
"pm_score": 1,
"selected": false,
"text": "RSACryptoServiceProvider rsaKey = EncryptionUtils.GetRSAFromSnkFile(keyFilePath);\n RSACryptoServiceProvider rsaKey = EncryptionUtils.GetPublicKeyFromAssembly\n (System.Reflection.Assembly.GetExecutingAssembly());\n"
},
{
"answer_id": 1643056,
"author": "Cocowalla",
"author_id": 25758,
"author_profile": "https://Stackoverflow.com/users/25758",
"pm_score": 3,
"selected": false,
"text": "GetPublicKeyFromAssembly /// <summary>\n/// Extracts an RSA public key from a signed assembly\n/// </summary>\n/// <param name=\"assembly\">Signed assembly to extract the key from</param>\n/// <returns>RSA Crypto Service Provider initialised with the public key from the assembly</returns>\nprivate RSACryptoServiceProvider GetPublicKeyFromAssembly(Assembly assembly)\n{\n // Extract public key - note that public key stored in assembly has an extra 3 headers\n // (12 bytes) at the front that are not part of a CAPI public key blob, so they must be removed\n byte[] rawPublicKeyData = assembly.GetName().GetPublicKey();\n\n int extraHeadersLen = 12;\n int bytesToRead = rawPublicKeyData.Length - extraHeadersLen;\n byte[] publicKeyData = new byte[bytesToRead];\n Buffer.BlockCopy(rawPublicKeyData, extraHeadersLen, publicKeyData, 0, bytesToRead);\n\n RSACryptoServiceProvider publicKey = new RSACryptoServiceProvider();\n publicKey.ImportCspBlob(publicKeyData);\n\n return publicKey;\n}\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31516/"
] |
359,347 | <p>I would like to execute multiple commands in a row:</p>
<p>i.e. (just to illustrate my need):</p>
<p><code>cmd</code> (the shell)</p>
<p>then</p>
<p><code>cd dir</code></p>
<p>and</p>
<p><code>ls</code></p>
<p>and read the result of the <code>ls</code>.</p>
<p>Any idea with <code>subprocess</code> module?</p>
<p><strong>Update:</strong></p>
<p><code>cd dir</code> and <code>ls</code> are just an example. I need to run complex commands (following a particular order, without any pipelining). In fact, I would like one subprocess shell and the ability to launch many commands on it.</p>
| [
{
"answer_id": 359355,
"author": "unwind",
"author_id": 28169,
"author_profile": "https://Stackoverflow.com/users/28169",
"pm_score": 2,
"selected": false,
"text": "subprocess.Popen() cwd ls ls cd"
},
{
"answer_id": 359432,
"author": "Oli",
"author_id": 22035,
"author_profile": "https://Stackoverflow.com/users/22035",
"pm_score": 3,
"selected": false,
"text": "from subprocess import Popen, PIPE\nfind_process = Popen(['find', '-iname', '*foo*'], stdout=PIPE)\ngrep_process = Popen(['xargs', 'grep', 'bar'], stdin=find_process.stdout, stdout=PIPE)\nout, err = grep_process.communicate()\n"
},
{
"answer_id": 359506,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 6,
"selected": true,
"text": "subprocess.Popen \"command1; command2; command3\"\n subprocess.Popen \"\"\"\ncommand1\ncommand2\ncommand3\n\"\"\"\n class Command( object ):\n def __init__( self, text ):\n self.text = text\n def execute( self ):\n self.proc= subprocess.Popen( ... self.text ... )\n self.proc.wait()\n\nclass CommandSequence( Command ):\n def __init__( self, *steps ):\n self.steps = steps\n def execute( self ):\n for s in self.steps:\n s.execute()\n"
},
{
"answer_id": 359737,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 5,
"selected": false,
"text": "shell=True subprocess.Popen ; & cmd.exe"
},
{
"answer_id": 32923576,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "import sys\nimport subprocess\n\ndef cd(self,line):\n proc1 = subprocess.Popen(['cd'],stdin=subprocess.PIPE)\n proc1.communicate()\n\ndef ls(self,line):\n proc2 = subprocess.Popen(['ls','-l'],stdin=subprocess.PIPE)\n proc2.communicate()\n\ndef dir(silf,line):\n proc3 = subprocess.Popen(['cd',args],stdin=subprocess.PIPE)\n proc3.communicate(sys.argv[1])\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359347",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18648/"
] |
359,351 | <p>I have a multi-user eclipse (3.4) installation with a shared master configuration area.
Users need to override <code>user.name</code> with their full name and the usual method (adding -Duser.name=... to eclipse.ini) is not suitable since the override must be per-user.
I've tried setting user.name in config.ini (inside each user's <code>configuration</code> directory):</p>
<pre><code>user.name=Luca Tettamanti
</code></pre>
<p>but it does work, eclipse still retains the login name. The strange thing is that:</p>
<pre><code>user.foobar=Luca Tettamanti
</code></pre>
<p>is correctly picked up.
Is it possible to somehow override user.name in this configuration?</p>
| [
{
"answer_id": 359417,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": ".cmd net user %username% /domain | find /i \"full\"\n eclipse.exe -clean --launcher.ini shared\\eclipse.ini -vmargs -Duser.name=%FULL_NAME%\n user.name USER exec eclipse -clean --launcher.ini shared/eclipse.ini -vmargs -Duser.name=`eval \"echo $USER\"`\n"
},
{
"answer_id": 359443,
"author": "jamesh",
"author_id": 4737,
"author_profile": "https://Stackoverflow.com/users/4737",
"pm_score": 0,
"selected": false,
"text": "user.name"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42448/"
] |
359,354 | <p>I'm trying to use the EntLib 3.1 within .net code for a dll which is registered for COM interop. Where do I put the config file? </p>
<p>Alternatively, is there a way to specify within the dll code where it should get the entlib config from? Since my dll will be called from COM I don't always know what exe will be calling it.</p>
<p>I created a simple app which uses entlib Logging, with two classes: 'CallingApp' and 'MyComThing'. When I call a method of MyComThing from CallingApp it logs using the configuration in CallingApp's config file. When I call the method of MyComThing from a vbs script, ie through COM, I get an error "The configuration section for Logging cannot be found in the configuration source". My COMThing.dll.config file is in the same folder as the registered COMThing.dll, ie in the bin\debug\ folder.</p>
<p>thanks!</p>
| [
{
"answer_id": 360308,
"author": "Rory",
"author_id": 8479,
"author_profile": "https://Stackoverflow.com/users/8479",
"pm_score": 3,
"selected": true,
"text": " string dllConfigFilename = Assembly.GetExecutingAssembly().Location + \".config\";\n FileConfigurationSource exceptionsSource = new FileConfigurationSource(dllConfigFilename);\n LogWriterFactory writerFactory = new LogWriterFactory(exceptionsSource);\n logWriter = writerFactory.Create();\n LogEntry log = new LogEntry();\n log.Message = message;\n log.Categories = new string[] { \"General\" };\n logWriter.Write(log);\n using System;\nusing System.Collections.Generic;\nusing System.Text;\nusing System.Runtime.InteropServices;\nusing System.Windows.Forms;\nusing System.Reflection;\nusing System.IO;\nusing Microsoft.Practices.EnterpriseLibrary.Logging;\nusing Microsoft.Practices.EnterpriseLibrary.Common.Configuration;\n\nnamespace COMThing\n{\n [ComVisible(true)]\n public class MyComThing : MyComInterface\n {\n LogWriter logWriter; \n\n public MyComThing()\n {\n string dllConfigFilename = Assembly.GetExecutingAssembly().Location + \".config\";\n FileConfigurationSource exceptionsSource = new FileConfigurationSource(dllConfigFilename);\n LogWriterFactory writerFactory = new LogWriterFactory(exceptionsSource);\n logWriter = writerFactory.Create();\n }\n\n public bool ProcessMessage(string message)\n {\n LogEntry log = new LogEntry();\n log.Message = message;\n log.Categories = new string[] { \"General\" };\n logWriter.Write(log);\n MessageBox.Show(message);\n return true;\n }\n }\n\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<configuration>\n <configSections>\n <section name=\"loggingConfiguration\" type=\"Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n <section name=\"dataConfiguration\" type=\"Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\" />\n </configSections>\n <loggingConfiguration name=\"Logging Application Block\" tracingEnabled=\"true\"\n defaultCategory=\"General\" logWarningsWhenNoCategoriesMatch=\"true\">\n <listeners>\n <add source=\"COMThing Logger\" formatter=\"Text Formatter\" log=\"Application\"\n machineName=\"\" listenerDataType=\"Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.FormattedEventLogTraceListenerData, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n traceOutputOptions=\"None\" type=\"Microsoft.Practices.EnterpriseLibrary.Logging.TraceListeners.FormattedEventLogTraceListener, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n name=\"Formatted EventLog TraceListener\" />\n </listeners>\n <formatters>\n <add template=\"Timestamp: {timestamp}
Message: {message}
Category: {category}
Priority: {priority}
EventId: {eventid}
Severity: {severity}
Title:{title}
Machine: {machine}
Application Domain: {appDomain}
Process Id: {processId}
Process Name: {processName}
Win32 Thread Id: {win32ThreadId}
Thread Name: {threadName}
Extended Properties: {dictionary({key} - {value}
)}\"\n type=\"Microsoft.Practices.EnterpriseLibrary.Logging.Formatters.TextFormatter, Microsoft.Practices.EnterpriseLibrary.Logging, Version=3.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n name=\"Text Formatter\" />\n </formatters>\n <categorySources>\n <add switchValue=\"All\" name=\"General\">\n <listeners>\n <add name=\"Formatted EventLog TraceListener\" />\n </listeners>\n </add>\n </categorySources>\n <specialSources>\n <allEvents switchValue=\"All\" name=\"All Events\">\n <listeners>\n <add name=\"Formatted EventLog TraceListener\" />\n </listeners>\n </allEvents>\n <notProcessed switchValue=\"All\" name=\"Unprocessed Category\" />\n <errors switchValue=\"All\" name=\"Logging Errors & Warnings\">\n <listeners>\n <add name=\"Formatted EventLog TraceListener\" />\n </listeners>\n </errors>\n </specialSources>\n </loggingConfiguration>\n</configuration>\n Set obj = CreateObject(\"COMThing.MyComThing\")\nobj.ProcessMessage(\"called from com by vbs\")\n"
}
] | 2008/12/11 | [
"https://Stackoverflow.com/questions/359354",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8479/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.