qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
234,268
<p>When overriding the MembershipProvider and calling it directly, is there a way to fill the NameValueCollection config parameter of the Initialize method without manually looking through the config file for the settings? </p> <p>Obviously this Initialize is being called by asp.net and the config is being filled somewhere. I have implemented my own MembershipProvider and it works fine through the build in controls. I would like to create a new instance of my provider and make a call to it directly, but I don't really want to parse the .config for the MembershipProvider, it's connection string name and then the connection string if it's already being done somewhere.</p>
[ { "answer_id": 234327, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 3, "selected": false, "text": "MembershipSection section = WebConfigurationManager.GetSection(\"membership\");\n" }, { "answer_id": 235274, "author": "JHORN", "author_id": 30848, "author_profile": "https://Stackoverflow.com/users/30848", "pm_score": 5, "selected": true, "text": "string configPath = \"~/web.config\";\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(configPath);\nMembershipSection section = (MembershipSection)config.GetSection(\"system.web/membership\");\nProviderSettingsCollection settings = section.Providers;\nNameValueCollection membershipParams = settings[section.DefaultProvider].Parameters;\nInitialize(section.DefaultProvider, membershipParams);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30848/" ]
234,289
<p>From everything I've read, it seemed that adding paging to a ListView control should be dead simple, but it's not working for me. After adding the ListView and DataPager controls to the form and wiring them together, I'm getting very odd behavior. The DataPager correctly limits the ListView's page size, but clicking the paging buttons doesn't affect the ListView at all. The paging buttons seem to think they are doing they're job, as the last button is disabled when you go to the last page, etc., but the ListView never changes. Also, it takes two clicks on the DataPager to get it to do anything, i.e., clicking on Last once does nothing, but clicking it a second time causes the DataPager to react as if the last page is now selected.</p> <p>The only thing I can think of is that I'm binding the DataSource at runtime (to a LINQ object), not using a LinqDataSource control or anything. Has anyone seen this behavior? Am I doing something wrong? Here's the code I'm using:</p> <pre><code>&lt;asp:DataPager ID="HistoryDataPager" runat="server" PagedControlID="HistoryListView" PageSize="10"&gt; &lt;Fields&gt; &lt;asp:NextPreviousPagerField ButtonType="Button" ShowFirstPageButton="true" ShowLastPageButton="true" /&gt; &lt;/Fields&gt; &lt;/asp:DataPager&gt; &lt;asp:ListView ID="HistoryListView" runat="server"&gt; ... &lt;/asp:ListView&gt; </code></pre> <p>In the code-behind:</p> <pre><code>Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then HistoryListView.DataSource = From x in myContext.myTables ... DataBind() End If End Sub </code></pre>
[ { "answer_id": 237036, "author": "MartinHN", "author_id": 2972, "author_profile": "https://Stackoverflow.com/users/2972", "pm_score": 2, "selected": true, "text": "private ListViewPagedDataSource GetProductsAsPagedDataSource(DataView dv)\n{\n// Limit the results through a PagedDataSource\nListViewPagedDataSource pagedData = new ListViewPagedDataSource();\npagedData.DataSource = dv;\npagedData.MaximumRows = dv.Table.Rows.Count;\npagedData.TotalRowCount = dpTop.PageSize;\n\nif (Request.QueryString[dpTop.QueryStringField] != null)\n pagedData.StartRowIndex = (Convert.ToInt32(Request.QueryString[dpTop.QueryStringField]) - 1) * dpTop.PageSize;\nelse\n pagedData.StartRowIndex = 0;\n\nreturn pagedData;\n}\n" }, { "answer_id": 399104, "author": "Syam", "author_id": 50016, "author_profile": "https://Stackoverflow.com/users/50016", "pm_score": 5, "selected": false, "text": "protected override void OnPreRender(EventArgs e)\n {\n ListView1.DataBind();\n base.OnPreRender(e);\n }\n ListView_PagePropertiesChanged(object sender, EventArgs e)\n{\nListView.DataSource=someDatasource;\nListView.DataBind()\n}\n" }, { "answer_id": 2041929, "author": "Kaz Fernandes", "author_id": 289399, "author_profile": "https://Stackoverflow.com/users/289399", "pm_score": 1, "selected": false, "text": "private void ResetListViewPager()\n{\n DataPager pager = (DataPager)ListViewMembers.FindControl(\"DataPager1\");\n if (pager != null)\n {\n CommandEventArgs commandEventArgs = new CommandEventArgs(DataControlCommands.FirstPageCommandArgument, \"\");\n // MAKE SURE THE INDEX IN THE NEXT LINE CORRESPONDS TO THE CORRECT FIELD IN YOUR PAGER\n NextPreviousPagerField nextPreviousPagerField = pager.Fields[0] as NextPreviousPagerField;\n if (nextPreviousPagerField != null)\n {\n nextPreviousPagerField.HandleEvent(commandEventArgs);\n }\n\n // THIS COMMENTED-OUT SECTION IS HOW IT WOULD BE DONE IF USING A NUMERIC PAGER RATHER THAN A NEXT/PREVIOUS PAGER\n //commandEventArgs = new CommandEventArgs(\"0\", \"\");\n //NumericPagerField numericPagerField = pager.Fields[0] as NumericPagerField;\n //if (numericPagerField != null)\n //{\n // numericPagerField.HandleEvent(commandEventArgs);\n //}\n }\n}\n" }, { "answer_id": 13338848, "author": "Mustafa Iqbal", "author_id": 1814109, "author_profile": "https://Stackoverflow.com/users/1814109", "pm_score": 2, "selected": false, "text": "<asp:DataPager ID=\"DataPagerProducts\" runat=\"server\" QueryStringField=\"ID\" PageSize=\"3\">\n <Fields>\n <asp:NextPreviousPagerField ShowFirstPageButton=\"True\" ShowNextPageButton=\"False\" />\n <asp:NumericPagerField />\n <asp:NextPreviousPagerField ShowLastPageButton=\"True\" ShowPreviousPageButton=\"False\" />\n </Fields>\n </asp:DataPager>\n [ PagedControlID=\"ListView_Name\" ]" }, { "answer_id": 15440735, "author": "y.lahrbi", "author_id": 2175357, "author_profile": "https://Stackoverflow.com/users/2175357", "pm_score": 0, "selected": false, "text": "<asp:ListView ID=\"ListView1\" runat=\"server\" DataSourceID=\"sdsImages\">\n <ItemTemplate>\n <div class=\"photo sample12\">\n <asp:Image ID=\"img_Galerie\" runat=\"server\" ImageUrl='<%# \"~/imageHandler.ashx?ID=\" + Eval(\"ImageID\") %>' />\n </div>\n </ItemTemplate>\n</asp:ListView>\n<asp:DataPager ID=\"DataPager1\" runat=\"server\" PagedControlID=\"ListView1\" PageSize=\"3\" QueryStringField=\"ImageID\">\n <Fields>\n <asp:NextPreviousPagerField ShowFirstPageButton=\"True\" ShowNextPageButton=\"False\" />\n <asp:NumericPagerField />\n <asp:NextPreviousPagerField ShowLastPageButton=\"True\" ShowPreviousPageButton=\"False\" />\n </Fields>\n</asp:DataPager>\n<asp:SqlDataSource ID=\"sdsImages\" runat=\"server\"\n ConnectionString=\"<%$ ConnectionStrings:DBCS %>\"\n SelectCommand=\"SELECT ImageID FROM Images \">\n" }, { "answer_id": 19823036, "author": "Masoumeh Karvar", "author_id": 1937517, "author_profile": "https://Stackoverflow.com/users/1937517", "pm_score": 0, "selected": false, "text": "protected void ListView1_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)\n{\n DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);\n ListView1.DataSource = productList;\n ListView1.DataBind();\n DataPager1.DataBind();\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23935/" ]
234,291
<p>I don´t know why, but my form isn´t calling Form_Load event when it loads.</p> <p>Any ideas why this might be happening?</p>
[ { "answer_id": 234342, "author": "itsmatt", "author_id": 7862, "author_profile": "https://Stackoverflow.com/users/7862", "pm_score": 3, "selected": false, "text": "this.Load += new System.EventHandler(this.Form1_Load);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22869/" ]
234,302
<p>I have to create a site definition for a client that must contain pre-defined web part pages. I can create the web part pages but am at a loss when it comes to attaching them to the site on creation.</p> <p>I know web part pages created through SharePoint are stored in a Document Library. Do I need to pre-populate a "Web Part Pages" document library and add the needed navigation to these files? If so, how do I go about adding the needed aspx files?</p> <p>Finally, are there any caveats that I should be aware of for configuring the custom web part page in onet?</p>
[ { "answer_id": 236238, "author": "Rob Windsor", "author_id": 28785, "author_profile": "https://Stackoverflow.com/users/28785", "pm_score": 2, "selected": false, "text": "<%@ Assembly Name=\"Microsoft.SharePoint,Version=12.0.0.0,Culture=neutral,PublicKeyToken=71e9bce111e9429c\" %> <%@ Register Tagprefix=\"SharePoint\" Namespace=\"Microsoft.SharePoint.WebControls\" Assembly=\"Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %> <%@ Register Tagprefix=\"Utilities\" Namespace=\"Microsoft.SharePoint.Utilities\" Assembly=\"Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %> <%@ Import Namespace=\"Microsoft.SharePoint\" %> <%@ Register Tagprefix=\"WebPartPages\" Namespace=\"Microsoft.SharePoint.WebPartPages\" Assembly=\"Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c\" %>\n\n<%@ Page language=\"C#\" MasterPageFile=\"~masterurl/default.master\" \n Inherits=\"Microsoft.SharePoint.WebPartPages.WebPartPage\" %>\n\n<asp:Content ContentPlaceHolderId=\"PlaceHolderMain\" runat=\"server\">\n <table cellspacing=\"0\" border=\"0\" width=\"100%\">\n <tr>\n <td class=\"ms-pagebreadcrumb\">\n <asp:SiteMapPath SiteMapProvider=\"SPContentMapProvider\" id=\"ContentMap\" SkipLinkText=\"\" NodeStyle-CssClass=\"ms-sitemapdirectional\" runat=\"server\"/>\n </td>\n </tr>\n <tr>\n <td>\n <table width=\"100%\" cellpadding=0 cellspacing=0 style=\"padding: 5px 10px 10px 10px;\">\n <tr>\n <td valign=\"top\" width=\"70%\">\n <WebPartPages:WebPartZone runat=\"server\" FrameType=\"TitleBarOnly\" ID=\"Left\" Title=\"loc:Left\" />\n &nbsp;\n </td>\n <td>&nbsp;</td>\n <td valign=\"top\" width=\"30%\">\n <WebPartPages:WebPartZone runat=\"server\" FrameType=\"TitleBarOnly\" ID=\"Right\" Title=\"loc:Right\" />\n &nbsp;\n </td>\n <td>&nbsp;</td>\n </tr>\n </table>\n </td>\n </tr>\n </table>\n</asp:Content>\n\n<asp:Content ID=\"Content1\" ContentPlaceHolderId=\"PlaceHolderPageTitle\" runat=\"server\">\n <SharePoint:ProjectProperty ID=\"ProjectProperty1\" Property=\"Title\" runat=\"server\"/>\n</asp:Content>\n\n<asp:Content ID=\"Content2\" ContentPlaceHolderId=\"PlaceHolderPageTitleInTitleArea\" runat=\"server\">\n <label class=\"ms-hidden\"><SharePoint:ProjectProperty ID=\"ProjectProperty2\" Property=\"Title\" runat=\"server\"/></label>\n</asp:Content>\n <Module Name=\"Default\" Url=\"\" >\n <File Url=\"default.aspx\" Type=\"Ghostable\">\n <!-- Add a Web Part to left zone -->\n <AllUsersWebPart WebPartZoneID=\"Left\" WebPartOrder=\"0\">\n <![CDATA[ \n <WebPart \n xmlns=\"http://schemas.microsoft.com/WebPart/v2\"\n xmlns:cewp=\"http://schemas.microsoft.com/WebPart/v2/ContentEditor\">\n <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>\n <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>\n <Title>Working with Site Definitions</Title>\n <FrameType>TitleBarOnly</FrameType>\n <cewp:Content>\n This Web Part was added through declarative logic in ONET.XML\n </cewp:Content>\n </WebPart>\n ]]>\n </AllUsersWebPart>\n </File>\n</Module>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14281/" ]
234,312
<p>What tweaks / addins / themes do you have rigged up to make your IDE awesome? For example, in Visual Studio I <a href="http://www.hanselman.com/blog/VisualStudioProgrammerThemesGallery.aspx" rel="nofollow noreferrer">color themes</a>, <a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/" rel="nofollow noreferrer">CodeRush</a> draws lines between braces, I always install and use the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=22e69ae4-7e40-4807-8a86-b3d36fab68d3&amp;displaylang=en" rel="nofollow noreferrer">Consolas</a> font and I have it setup to <a href="http://blogs.msdn.com/saraford/archive/2008/06/30/did-you-know-you-can-use-team-settings-to-keep-visual-studio-settings-on-different-machines-in-sync-248.aspx" rel="nofollow noreferrer">sync my settings across computers</a> for when I change hotkeys and whatnot with the help of <a href="https://www.foldershare.com/welcome.aspx" rel="nofollow noreferrer">FolderShare</a>.</p> <p>Also, this isn't Visual Studio specific, please feel free to mention what you do with Emacs or Eclipse or whatnot as many of us use a few.</p>
[ { "answer_id": 238193, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "#pragma warning #if #include" }, { "answer_id": 238232, "author": "Adam Liss", "author_id": 29157, "author_profile": "https://Stackoverflow.com/users/29157", "pm_score": 1, "selected": false, "text": "vim makeprg errorformat scanf :make :cl errorformat :cc :cn :cp vim makeprg errorformat make gcc vim" }, { "answer_id": 241763, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 1, "selected": false, "text": "HKEY_CURRENT_USER\\Software\\Microsoft\\VisualStudio\\8.0\\Text Editor\\Guides = \"RGB(196,196,196) 80\"" }, { "answer_id": 468414, "author": "John", "author_id": 33, "author_profile": "https://Stackoverflow.com/users/33", "pm_score": 0, "selected": false, "text": " Public Sub WriteBugFix()\n Dim TS As TextSelection = DTE.ActiveDocument.Selection\n TS.Text = \"'Edited for Bug Fixed By JK - \" & Date.Now.ToShortDateString\nEnd Sub\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12862/" ]
234,333
<p>I am displaying a texture that I want to manipulate without out affecting the image data. I want to be able to clamp the texel values so that anything below the lower value becomes 0, anything above the upper value becomes 0, and anything between is linearly mapped from 0 to 1. </p> <p>Originally, to display my image I was using glDrawPixels. And to solve the problem above I would create a color map using glPixelMap. This worked beautifully. However, for performance reasons I have begun using textures to display my image. The glPixelMap approach no longer seems to work. Well that approach may work but I was unable to get it working. </p> <p>I then tried using glPixelTransfer to set scales and bias'. This seemed to have some sort of effect (not necessarily the desired) on first pass, but when the upper and lower constraints were changed no effect was visible. </p> <p>I was then told that fragment shaders would work. But after a call to glGetString(GL_EXTENSIONS), I found that GL_ARB_fragment_shader was not supported. Plus, a call to glCreateShaderObjectARB cause a nullreferenceexception.</p> <p>So now I am at a loss. What should I do? Please Help.</p> <hr> <p>What ever might work I am willing to try. The vendor is Intel and the renderer is Intel 945G. I am unfortunately confined to a graphics card that is integrated on the motherboard, and only has gl 1.4.</p> <p>Thanks for your response thus far.</p>
[ { "answer_id": 235529, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 3, "selected": true, "text": "GL_VENDOR GL_RENDERER ARB_fragment_shader ARB_fragment_program !!ARBfp1.0\nATTRIB tex = fragment.texcoord[0]\nPARAM cbias = program.local[0]\nPARAM cscale = program.local[1]\nOUTPUT cout = result.color\n\nTEMP tmp\nTXP tmp, tex, texture[0], 2D\nSUB tmp, tmp, cbias\nMUL cout, tmp, cscale\n\nEND \n GLuint prog;\nglEnable(GL_FRAGMENT_PROGRAM_ARB);\nglGenProgramsARB(1, &prog);\nglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);\nglProgramStringARB(GL_FRAGMENT_PROGRAM_ARB, GL_PROGRAM_FORMAT_ASCII_ARB, strlen(src), src);\nglDisable(GL_FRAGMENT_PROGRAM_ARB);\n glEnable(GL_FRAGMENT_PROGRAM_ARB);\nglBindProgramARB(GL_FRAGMENT_PROGRAM_ARB, prog);\ncolour4f cbias = cmin;\ncolour4f cscale = 1.0f / (cmax-cmin);\nglProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 0, cbias.r, cbias.g, cbias.b, cbias.a);\nglProgramLocalParameter4fARB(GL_FRAGMENT_PROGRAM_ARB, 1, cscale.r, cscale.g, cscale.b, cscale.a);\n\n//Draw your textured geometry\n\nglDisable(GL_FRAGMENT_PROGRAM_ARB);\n" }, { "answer_id": 235615, "author": "Corey Ross", "author_id": 5927, "author_profile": "https://Stackoverflow.com/users/5927", "pm_score": 0, "selected": false, "text": "GL_ARB_fragment_program" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55638/" ]
234,365
<p>I'm new to Windows programming and after reading the Petzold book I wonder: </p> <p>is it still good practice to use the <code>TCHAR</code> type and the <code>_T()</code> function to declare strings or if I should just use the <code>wchar_t</code> and <code>L""</code> strings in new code?</p> <p>I will target only Windows 2000 and up and my code will be <a href="http://en.wikipedia.org/wiki/Internationalization_and_localization" rel="noreferrer">i18n</a> from the start up.</p>
[ { "answer_id": 3002494, "author": "dan04", "author_id": 287586, "author_profile": "https://Stackoverflow.com/users/287586", "pm_score": 6, "selected": false, "text": "TCHAR _T() char* char* wchar_t* TCHAR TCHAR std::string TCHAR TCHAR std::tcout TCHAR #define _UNICODE char wchar_t typedef UTF16 UTF32" }, { "answer_id": 3118069, "author": "kizzx2", "author_id": 111021, "author_profile": "https://Stackoverflow.com/users/111021", "pm_score": -1, "selected": false, "text": "L\"Hello World\"" }, { "answer_id": 3484237, "author": "Steven", "author_id": 83280, "author_profile": "https://Stackoverflow.com/users/83280", "pm_score": 4, "selected": false, "text": "wchar_t L\"\"" }, { "answer_id": 29056684, "author": "LeOpArD", "author_id": 1796959, "author_profile": "https://Stackoverflow.com/users/1796959", "pm_score": 3, "selected": false, "text": "TCHAR WCHAR TCHAR WCHAR TCHAR WCHAR CHAR WCHAR TCHAR CHAR WCHAR TCHAR WCHAR" }, { "answer_id": 61667913, "author": "OwnageIsMagic", "author_id": 5647513, "author_profile": "https://Stackoverflow.com/users/5647513", "pm_score": -1, "selected": false, "text": "TCHAR WCHAR CHAR" }, { "answer_id": 74112673, "author": "thebluetropics", "author_id": 17754106, "author_profile": "https://Stackoverflow.com/users/17754106", "pm_score": 0, "selected": false, "text": "TCHAR wchar_t* wchar_t*" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9458/" ]
234,388
<p>I'm trying to make a simple blackjack program. Sadly, I'm having problems right off the bat with generating a deck of cards.</p> <pre><code>#include &lt;iostream&gt; #include &lt;vector&gt; using namespace std; int main() { vector&lt;char&gt; deck; char suit[] = {'h','d','c','s'}; char card[] = {'2','3','4','5','6','7','8','9','10','J','Q','K','A'}; for (int j=0; j&lt;13; j++) { for (int i=0; i&lt;4; i++) { deck.push_back(card[j] suit[i]); } } return 0; } </code></pre> <p>I know my problem begins with me trying to assign the value '10' to a char. Obviously I couldn't get this to compile but I'm sure when I try to assign the card values to the vector deck I'll also get an error since I used variable type 'char'. Knowing what kind of variable type to use seems to be killing me. Also, would 'deck.push_back(card[j] suit[i]);' be the correct code to combine the card and suit, or do you have to put something between card[j] and suit[i]? I'd appreciate it if any of you could lead me in the right direction. Also as a little side note, this is part of a homework assignment so please don't just give me entire blocks of code. Thanks for your help.</p>
[ { "answer_id": 234394, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "int char" }, { "answer_id": 234407, "author": "JtR", "author_id": 30958, "author_profile": "https://Stackoverflow.com/users/30958", "pm_score": 5, "selected": true, "text": "public class Card {\n public:\n Card(char suit, char card);\n char suit, card;\n};\n\nint main() {\n vector<Card> deck;\n char suit[] = {'h','d','c','s'};\n char card[] = {'2','3','4','5','6','7','8','9','T','J','Q','K','A'};\n for (int j=0; j<13; j++) {\n for (int i=0; i<4; i++) {\n deck.push_back(new Card(card[j],suit[i]));\n } \n }\n return 0;\n}\n" }, { "answer_id": 234416, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 2, "selected": false, "text": "vector<std::string> deck.push_back(std::string(card[j]) + suit[i]);\n" }, { "answer_id": 234422, "author": "Kevin", "author_id": 4599, "author_profile": "https://Stackoverflow.com/users/4599", "pm_score": 5, "selected": false, "text": "enum SUIT { HEART, CLUB, DIAMOND, SPADE }; \nenum VALUE { ONE, TWO, THREE, ..., TEN, JACK, QUEEN, KING};\n" }, { "answer_id": 234517, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 3, "selected": false, "text": "0000000000001001 <---- Two of hearts\n0100000000000011 <---- King of spades\n1000000000000110 <---- Ace of diamonds\n\n^^^^^^^^^^^^^ (\"face-value\" bits)\n ^ (\"low-ace\" flag)\n ^^ (\"suit\" bits)\n" }, { "answer_id": 234805, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 0, "selected": false, "text": "typedef struct struct_card {\n unsigned short int suit:2;\n unsigned short int card:4;\n// unsigned short int valu:4;\n} card;\n\nint main() {\n card a_card;\n card std_deck[52];\n const unsigned short int rummy_value[13] = {1,2,3,4,5,6,7,8,9,10,10,10,10};\n const char *std_card_name[13] = {\"Ace\",\"Two\",\"Three\",\"Four\",\"Five\",\"Six\",\n \"Seven\",\"Eight\",\"Nine\",\"Ten\",\"Jack\",\"Queen\",\"King\"};\n const char *std_suit_name[4] = {\"Spades\",\"Clubs\",\"Hearts\",\"Diamonds\"};\n\n int j, k, i=0;\n for(j=0; j<4; j++){\n for(k=0; k<13; k++){\n a_card.suit=j; a_card.card=k;\n std_deck[i++] = a_card;\n }\n }\n\n //check our work\n printf(\"In a game of rummy:\\n\");\n for(i=0;i<52;i++){\n printf(\" %-5s of %-8s is worth %2d points.\\n\",\n std_card_name[std_deck[i].card],\n std_suit_name[std_deck[i].suit],\n rummy_value[std_deck[i].card]);\n }\n\n //a different kind of game.\n enum round_mode {SHEILD_TRUMP, FLOWER_TRUMP, BELL_TRUMP, ACORN_TRUMP, BOCK, GEISS} mode;\n const card jass_deck[36]={\n {0,0},{0,1},{0,2},{0,3},{0,4},{0,5},{0,6},{0,7},{0,8},\n {1,1},{1,1},{1,2},{1,3},{1,4},{1,5},{1,6},{1,7},{1,8},\n {2,2},{2,1},{2,2},{2,3},{2,4},{2,5},{2,6},{2,7},{2,8},\n {3,3},{3,1},{3,2},{3,3},{3,4},{3,5},{3,6},{3,7},{3,8},\n };\n#define JASS_V {11,0,0,0,0,10,2,3,4}\n const unsigned short int jass_value[9] = JASS_V;\n#define JASS_TRUMP_V {11,0,0,0,14,10,20,3,4}\n const unsigned short int jass_trump_value[9] = JASS_TRUMP_V;\n#define JASS_BOCK_V {11,0,0,8,0,10,2,3,4}\n const unsigned short int jass_bock_value[9] = JASS_BOCK_V;\n#define JASS_GEISS_V {0,11,0,8,0,10,2,3,4}\n const unsigned short int jass_geiss_value[9] = JASS_GEISS_V;\n const char *jass_card_name[9] = {\"Ace\",\"Six\",\"Seven\",\"Eight\",\"Nine\",\"Banner\",\n \"Under\",\"Ober\",\"King\"};\n const char *jass_suit_name[4] = {\"Sheilds\",\"Flowers\",\"Bells\",\"Acorns\"};\n const unsigned short int jass_all_value[6][4][9] = {\n { JASS_TRUMP_V, JASS_V, JASS_V, JASS_V },\n { JASS_V, JASS_TRUMP_V, JASS_V, JASS_V },\n { JASS_V, JASS_V, JASS_TRUMP_V, JASS_V },\n { JASS_V, JASS_V, JASS_V, JASS_TRUMP_V },\n { JASS_BOCK_V, JASS_BOCK_V, JASS_BOCK_V, JASS_BOCK_V },\n { JASS_GEISS_V, JASS_GEISS_V, JASS_GEISS_V, JASS_GEISS_V }\n };\n\n //check our work 2: work goes on summer vacation\n printf(\"In a game of jass with trump (Sheilds | Flowers | Bells | Acorns) | Bock | Geiss\\n\");\n for(i=0;i<36;i++){\n printf(\" %-6s of %-7s is worth %8d%10d%8d%9d%8d%8d\\n\",\n jass_card_name[jass_deck[i].card],\n jass_suit_name[jass_deck[i].suit],\n jass_all_value[SHEILD_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[FLOWER_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[BELL_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[ACORN_TRUMP][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[BOCK][jass_deck[i].suit][jass_deck[i].card],\n jass_all_value[GEISS][jass_deck[i].suit][jass_deck[i].card]);\n }\n return 0;\n}\n In a game of rummy:\n Ace of Spades is worth 1 points.\n Two of Spades is worth 2 points.\n Three of Spades is worth 3 points.\n Four of Spades is worth 4 points.\n Five of Spades is worth 5 points.\n...\n Nine of Diamonds is worth 9 points.\n Ten of Diamonds is worth 10 points.\n Jack of Diamonds is worth 10 points.\n Queen of Diamonds is worth 10 points.\n King of Diamonds is worth 10 points.\nIn a game of jass with trump (Sheilds | Flowers | Bells | Acorns) | Bock | Geiss\n Ace of Sheilds is worth 11 11 11 11 11 0\n Six of Sheilds is worth 0 0 0 0 0 11\n Seven of Sheilds is worth 0 0 0 0 0 0\n Eight of Sheilds is worth 0 0 0 0 8 8\n Nine of Sheilds is worth 14 0 0 0 0 0\n Banner of Sheilds is worth 10 10 10 10 10 10\n...\n Under of Acorns is worth 2 2 2 20 2 2\n Ober of Acorns is worth 3 3 3 3 3 3\n King of Acorns is worth 4 4 4 4 4 4\n" }, { "answer_id": 235769, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "class Card\n{\npublic:\n enum ESuit\n {\n kSuit_Heart,\n kSuit_Club,\n kSuit_Diamond,\n kSuit_Spade,\n kSuit_Count\n };\n\n enum ERank\n {\n kRank_Ace,\n kRank_Two,\n kRank_Three,\n kRank_Four,\n kRank_Five,\n kRank_Six,\n kRank_Seven,\n kRank_Eight,\n kRank_Nine,\n kRank_Ten,\n kRank_Jack,\n kRank_Queen,\n kRank_King,\n kRank_Count\n };\n\n static int const skNumCards = kSuit_Count * kRank_Count;\n\n Card( int cardIndex )\n : mSuit( static_cast<ESuit>( cardIndex / kRank_Count ) )\n , mRank( static_cast<ERank>( cardIndex % kRank_Count ) )\n {}\n\n ESuit GetSuit() const { return mSuit );\n ERank GetRank() const { return mRank );\n\nprivate:\n ESuit mSuit;\n ERank mRank;\n}\n rstl::vector<Card> mCards;\nmCards.reserve( Card::skNumCards );\n\nfor ( int cardValue = 0; cardValue < Card::skNumCards; ++cardValue )\n{\n mCards.push_back( Card( cardValue ) );\n}\n #include <algorithm>\nstd::random_shuffle( mCards.begin(), mCards.end() );\n if ( mCards[0].GetSuit() == Card::kRank_Club && mCards[0].GetRank() == Card::kRank_Ace )\n{\n std::cout << \"ACE OF CLUBS!\" << std::endl;\n}\n" }, { "answer_id": 10475743, "author": "Travis Weston", "author_id": 833696, "author_profile": "https://Stackoverflow.com/users/833696", "pm_score": 1, "selected": false, "text": "#include \"AnubisCards.cpp\"\n\nint main() {\n\n Deck *shoe = new Deck(10);\n\n}\n for(int suit = 1; suit <= 4; suit++){\n for(int card = 1; card <= 13; card++){\n // Add card to array\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234388", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38/" ]
234,439
<p>Disclaimer: I've solved the problem using Expressions from System.Linq.Expressions, but I'm still looking for a better/easier way.</p> <p>Consider the following situation :</p> <pre><code>var query = from c in db.Customers where (c.ContactFirstName.Contains("BlackListed") || c.ContactLastName.Contains("BlackListed") || c.Address.Contains("BlackListed")) select c; </code></pre> <p>The columns/attributes that need to be checked against the blacklisted term are only available to me at runtime. How do I generate this dynamic where clause?</p> <p>An additional complication is that the Queryable collection (db.Customers above) is typed to a Queryable of the base class of 'Customer' (say 'Person'), and therefore writing c.Address as above is not an option.</p>
[ { "answer_id": 234523, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 3, "selected": false, "text": "var query = from C in db.Customers select c;\n\nif (seachFirstName)\n query = query.Where(c=>c.ContactFirstname.Contains(\"Blacklisted\"));\n\nif (seachLastName)\n query = query.Where(c=>c.ContactLastname.Contains(\"Blacklisted\"));\n\nif (seachAddress)\n query = query.Where(c=>c.Address.Contains(\"Blacklisted\"));\n" }, { "answer_id": 237120, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 4, "selected": false, "text": "Expression<Fun<T,bool>> pred = null; //delcare the predicate to start with. Note - I don't know your type so I just used T \nif(blacklistFirstName){\n pred = p => p.ContactFirstName.Contains(\"Blacklisted\");\n}\nif(blacklistLastName){\n if(pred == null){\n pred = p => p.ContactLastName.Contains(\"Blacklisted\"); //if it doesn't exist just assign it\n }else{\n pred = pred.And(p => p.ContactLastName.Contains(\"Blacklisted\"); //otherwise we add it as an And clause\n }\n}\n var results = db.Customers.Where(pred).Select(c => c);\n" }, { "answer_id": 9516029, "author": "timothy", "author_id": 1210530, "author_profile": "https://Stackoverflow.com/users/1210530", "pm_score": 2, "selected": false, "text": "//Turn on all where clauses\nbool ignoreFirstName = false;\nbool ignoreLastName = false;;\nbool ignoreAddress = false;\n\n//Decide which WHERE clauses we are going to turn off because of something.\nif(something)\n ignoreFirstName = true; \n\n//Create the query\nvar queryCustomers = from c in db.Customers \n where (ignoreFirstName || (c.ContactFirstName.Contains(\"BlackListed\")))\n where (ignoreLastName || (c.ContactLastName.Contains(\"BlackListed\")))\n where (ignoreAddress || (c.Address.Contains(\"BlackListed\"))\n select j; \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9178/" ]
234,458
<p>I recently stumbled across <a href="http://googletesting.blogspot.com/2008/08/by-miko-hevery-so-you-decided-to.html" rel="noreferrer">this entry in the google testing blog</a> about guidelines for writing more testable code. I was in agreement with the author until this point:</p> <blockquote> <p>Favor polymorphism over conditionals: If you see a switch statement you should think polymorphisms. If you see the same if condition repeated in many places in your class you should again think polymorphism. Polymorphism will break your complex class into several smaller simpler classes which clearly define which pieces of the code are related and execute together. This helps testing since simpler/smaller class is easier to test.</p> </blockquote> <p>I simply cannot wrap my head around that. I can understand using polymorphism instead of RTTI (or DIY-RTTI, as the case may be), but that seems like such a broad statement that I can't imagine it actually being used effectively in production code. It seems to me, rather, that it would be easier to add additional test cases for methods which have switch statements, rather than breaking down the code into dozens of separate classes.</p> <p>Also, I was under the impression that polymorphism can lead to all sorts of other subtle bugs and design issues, so I'm curious to know if the tradeoff here would be worth it. Can someone explain to me exactly what is meant by this testing guideline?</p>
[ { "answer_id": 234491, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 7, "selected": true, "text": "class Animal\n{\n public:\n Noise warningNoise();\n Noise pleasureNoise();\n private:\n AnimalType type;\n};\n\nNoise Animal::warningNoise()\n{\n switch(type)\n {\n case Cat: return Hiss;\n case Dog: return Bark;\n }\n}\nNoise Animal::pleasureNoise()\n{\n switch(type)\n {\n case Cat: return Purr;\n case Dog: return Bark;\n }\n}\n class Animal\n{\n public:\n virtual Noise warningNoise() = 0;\n virtual Noise pleasureNoise() = 0;\n};\n\nclass Cat: public Animal\n{\n // Compiler forces you to define both method.\n // Otherwise you can't have a Cat object\n\n // All code local to the cat belongs to the cat.\n\n};\n" }, { "answer_id": 234510, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 3, "selected": false, "text": "If (weapon is a rifle) then //Code to attack with rifle else\nIf (weapon is a plasma gun) //Then code to attack with plasma gun\n weapon.attack()\n" }, { "answer_id": 234549, "author": "Nick Fortescue", "author_id": 5346, "author_profile": "https://Stackoverflow.com/users/5346", "pm_score": 1, "selected": false, "text": "switch(obj.type): {\ncase 1: cout << \"Type 1\" << obj.foo <<...; break; \ncase 2: cout << \"Type 2\" << ...\n cout << object.toString();\n" }, { "answer_id": 234737, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "interface A{\n\n int foo();\n\n}\n\nfinal class B implements A{\n\n int foo(){ print(\"B\"); }\n\n}\n\nfinal class C implements A{\n\n int foo(){ print(\"C\"); }\n\n}\n class A{\n\n int foo(){print(\"A\");}\n\n}\n\nclass B extends A{\n\n int foo(){print(\"B\");}\n\n}\n\nclass C extends B{\n\n int foo(){print(\"C\");}\n\n}\n\n...\n\nclass Z extends Y{\n\n int foo(){print(\"Z\");\n\n}\n\nmain(){\n\n F* f = new Z();\n A* a = f;\n a->foo();\n f->foo();\n\n}\n A* a = new Z;\nA a2 = *a;\na->foo();\na2.foo();\n" }, { "answer_id": 235028, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": false, "text": "void MyProcedure(int p_iCommand, void *p_vParam)\n{\n // A LOT OF CODE ???\n // each case has a lot of code, with both similarities\n // and differences, and of course, casting p_vParam\n // into something, depending on hoping no one\n // did a mistake, associating the wrong command with\n // the wrong data type in p_vParam\n\n switch(p_iCommand)\n {\n case COMMAND_AAA: { /* A LOT OF CODE (see above) */ } break ;\n case COMMAND_BBB: { /* A LOT OF CODE (see above) */ } break ;\n // etc.\n case COMMAND_XXX: { /* A LOT OF CODE (see above) */ } break ;\n case COMMAND_ZZZ: { /* A LOT OF CODE (see above) */ } break ;\n default: { /* call default procedure */} break ;\n }\n}\n void MyProcedure(int p_iCommand, void *p_vParam)\n{\n switch(p_iCommand)\n {\n // Only one case. Isn't it cool?\n case COMMAND:\n {\n Command * c = static_cast<Command *>(p_vParam) ;\n c->process() ;\n }\n break ;\n default: { /* call default procedure */} break ;\n }\n}\n [+] Command\n |\n +--[+] CommandServer\n | |\n | +--[+] CommandServerInitialize\n | |\n | +--[+] CommandServerInsert\n | |\n | +--[+] CommandServerUpdate\n | |\n | +--[+] CommandServerDelete\n |\n +--[+] CommandAction\n | |\n | +--[+] CommandActionStart\n | |\n | +--[+] CommandActionPause\n | |\n | +--[+] CommandActionEnd\n |\n +--[+] CommandMessage\n class CommandAction : public Command\n{\n // etc.\n virtual void process() // overriding Command::process pure virtual method\n {\n this->processBefore() ;\n this->processWhile() ;\n this->processAfter() ;\n }\n\n virtual void processBefore() = 0 ; // To be overriden\n \n virtual void processWhile()\n {\n // Do something common for all CommandAction objects\n }\n \n virtual void processAfter() = 0 ; // To be overriden\n\n} ;\n class CommandActionStart : public CommandAction\n{\n // etc.\n virtual void processBefore()\n {\n // Do something common for all CommandActionStart objects\n }\n\n virtual void processAfter()\n {\n // Do something common for all CommandActionStart objects\n }\n} ;\n" }, { "answer_id": 15389260, "author": "Calmarius", "author_id": 58805, "author_profile": "https://Stackoverflow.com/users/58805", "pm_score": 2, "selected": false, "text": "switch (type)\n{\n case T_FOO: doFoo(); break;\n case T_BAR: doBar(); break;\n default:\n fprintf(stderr, \"You, who are reading this, add a new case for %d to the FooBar function ASAP!\\n\", type);\n assert(0);\n}\n grep 'case[ ]*T_BAR' rn ." } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14302/" ]
234,479
<p>I'm writing a config file and I need to define if the process expects a windows format file or a unix format file. I've got a copy of the expected file - is there a way I can check if it uses \n or \r\n without exiting emacs?</p>
[ { "answer_id": 234557, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 4, "selected": true, "text": "(defun describe-eol ()\n (interactive)\n (let ((eol-type (coding-system-eol-type buffer-file-coding-system)))\n (when (vectorp eol-type)\n (setq eol-type (coding-system-eol-type (aref eol-type 0))))\n (message \"Line endings are of type: %s\"\n (case eol-type\n (0 \"Unix\") (1 \"DOS\") (2 \"Mac\") (t \"Unknown\")))))\n" }, { "answer_id": 234692, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "nil \"\\r\\n\" .emacs M-x check-eol (defun check-eol (FILE)\n (interactive \"fFile: \")\n (set-buffer (generate-new-buffer \"*check-eol*\"))\n (insert-file-contents-literally FILE)\n (let ((point (search-forward \"\\r\\n\")))\n (kill-buffer nil)\n point))\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26880/" ]
234,482
<p>I have a collection of elements that I need to operate over, calling member functions on the collection:</p> <pre><code>std::vector&lt;MyType&gt; v; ... // vector is populated </code></pre> <p>For calling functions with no arguments it's pretty straight-forward:</p> <pre><code>std::for_each(v.begin(), v.end(), std::mem_fun(&amp;MyType::myfunc)); </code></pre> <p>A similar thing can be done if there's one argument to the function I wish to call.</p> <p>My problem is that I want to call a function on elements in the vector if it meets some condition. <code>std::find_if</code> returns an iterator to the first element meeting the conditions of the predicate. </p> <pre><code>std::vector&lt;MyType&gt;::iterator it = std::find_if(v.begin(), v.end(), MyPred()); </code></pre> <p>I wish to find <strong>all</strong> elements meeting the predicate and operate over them.</p> <p>I've been looking at the STL algorithms for a "<code>find_all</code>" or "<code>do_if</code>" equivalent, or a way I can do this with the existing STL (such that I only need to iterate once), rather than rolling my own or simply do a standard iteration using a for loop and comparisons.</p>
[ { "answer_id": 234525, "author": "Marcin", "author_id": 22724, "author_profile": "https://Stackoverflow.com/users/22724", "pm_score": 3, "selected": false, "text": "MyType::myfunc" }, { "answer_id": 234556, "author": "John Dibling", "author_id": 241536, "author_profile": "https://Stackoverflow.com/users/241536", "pm_score": 4, "selected": false, "text": "for_each_if() for_each_equal() for_each_if() for_each_equal() operator == /* ---\n\n For each\n 25.1.1\n\n template< class InputIterator, class Function, class T>\n Function for_each_equal(InputIterator first, InputIterator last, const T& value, Function f)\n\n template< class InputIterator, class Function, class Predicate >\n Function for_each_if(InputIterator first, InputIterator last, Predicate pred, Function f)\n\n Requires: \n\n T is of type EqualityComparable (20.1.1) \n\n Effects: \n\n Applies f to each dereferenced iterator i in the range [first, last) where one of the following conditions hold:\n\n 1: *i == value\n 2: pred(*i) != false\n\n Returns: \n\n f\n\n Complexity: \n\n At most last - first applications of f\n\n --- */\n\n template< class InputIterator, class Function, class Predicate >\n Function for_each_if(InputIterator first, \n InputIterator last, \n Predicate pred, \n Function f)\n {\n for( ; first != last; ++first)\n {\n if( pred(*first) )\n f(*first);\n }\n return f;\n };\n\n template< class InputIterator, class Function, class T>\n Function for_each_equal(InputIterator first, \n InputIterator last, \n const T& value, \n Function f)\n {\n for( ; first != last; ++first)\n {\n if( *first == value )\n f(*first);\n }\n return f;\n };\n" }, { "answer_id": 234593, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 5, "selected": true, "text": "#include <boost/lambda/lambda.hpp>\n#include <boost/lambda/bind.hpp>\n#include <boost/lambda/if.hpp>\n\nstd::for_each( v.begin(), v.end(), \n if_( MyPred() )[ std::mem_fun(&MyType::myfunc) ] \n );\n std::for_each( v.begin(), v.end(), \n if_( _1 % 2 == 0 )[ std::mem_fun( &MyType::myfunc ) ]\n );\n std::for_each( v.begin(), v.end(),\n [](MyType& mt ) mutable\n {\n if( mt % 2 == 0)\n { \n mt.myfunc(); \n }\n } );\n" }, { "answer_id": 234618, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 0, "selected": false, "text": "for_each(v.begin(), v.end(), [](MyType& x){ if (Check(x) DoSuff(x); }) \n" }, { "answer_id": 235036, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 0, "selected": false, "text": "BOOST_FOREACH (vector<...>& x, v)\n{\n if (Check(x)\n DoStuff(x);\n}\n" }, { "answer_id": 235491, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 1, "selected": false, "text": "std::vector<int> v, matches;\nstd::vector<int>::iterator i = v.begin();\nMyPred my_pred;\nwhile(true) {\n i = std::find_if(i, v.end(), my_pred);\n if (i == v.end())\n break;\n matches.push_back(*i);\n}\n end() list end() vector vector end() std::vector<int> v, matches;\nstd::vector<int>::iterator i = v.begin(), end = v.end();\nMyPred my_pred;\nwhile(true) {\n i = std::find_if(i, v.end(), my_pred);\n if (i == end)\n break;\n matches.push_back(*i);\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24263/" ]
234,503
<p>I'm looking into some possible options for unit testing C++ classes. </p> <p>So, short and to the point, what are you using?</p>
[ { "answer_id": 234551, "author": "Ben Straub", "author_id": 1319, "author_profile": "https://Stackoverflow.com/users/1319", "pm_score": 2, "selected": false, "text": "test*" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1473493/" ]
234,507
<p>This was something originally discussed during a presentation given by Charles Brian Quinn of the <a href="http://www.bignerdranch.com/" rel="noreferrer">Big Nerd Ranch</a> at <a href="http://www.actsasconference.com" rel="noreferrer">acts_as_conference</a>. He was discussing what he had learned from instructing a Ruby on Rails Bootcamp to many people both new to programming and new to Rails.</p> <p>One particular slide that stood out was along the lines of <strong>never using foo and bar as examples when trying to teach someone to program</strong>. His reasoning was very simple.</p> <p>Which is easier to understand?</p> <pre><code>baz = foo + bar </code></pre> <p>or</p> <pre><code>answer = first_number + second_number </code></pre> <p>It's happened many times myself when explaining something and I immediately jump to the go to foo bar placeholders but then realize my mistake and make the example make a lot more sense by using a real world scenario. </p> <p>This is especially applicable when trying to teach someone who has had no programming exposure and you end up needing explain foo and bar before explaining what you're actually trying to teach.</p> <p>However, using foo and bar for experienced programmers seems OK, though I personally think, along with Charles, that it's something that needs to change.</p> <p>A quick SO search for "foo" returns over 20 pages of results with foo being used in more ways that I can comprehend. And in some cases where I'm reading a question on a particular language and I'm doing so to help understand that language better. If applicable variable names are used instead of foo and bar, it makes it much easier to understand and interpret the problem. So for seasoned developers, the construct seems a bit flawed as well.</p> <p>Is this a habit that will ever be able to be kicked? Why do you choose to foo bar or to not foo bar?</p>
[ { "answer_id": 234538, "author": "Santiago Palladino", "author_id": 12791, "author_profile": "https://Stackoverflow.com/users/12791", "pm_score": 6, "selected": true, "text": "public void foo() { \n\n // Do some things\n\n if (errorCondition) {\n throw new Exception(\"Error message\");\n }\n\n}\n public void foo() { \n\n // Do some things\n\n if (bar) {\n throw new Exception(baz);\n }\n\n}\n" }, { "answer_id": 11070739, "author": "Matt Montag", "author_id": 264970, "author_profile": "https://Stackoverflow.com/users/264970", "pm_score": 1, "selected": false, "text": "foo bar myNumber myFunction" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234507", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23909/" ]
234,512
<p>I have a string which is like this:</p> <p>this is [bracket test] "and quotes test "</p> <p>I'm trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I'm looking for is:</p> <p>['this','is','bracket test','and quotes test '] </p>
[ { "answer_id": 234645, "author": "Bryan Oakley", "author_id": 7432, "author_profile": "https://Stackoverflow.com/users/7432", "pm_score": 3, "selected": false, "text": "import re\nre.findall('\\[[^\\]]*\\]|\\\"[^\\\"]*\\\"|\\S+',s)\n" }, { "answer_id": 234674, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 1, "selected": false, "text": "class SimpleParser(object):\n\n def __init__(self):\n self.mode = None\n self.result = None\n\n def parse(self, text):\n self.initial_mode()\n self.result = []\n for word in text.split(' '):\n self.mode.handle_word(word)\n return self.result\n\n def initial_mode(self):\n self.mode = InitialMode(self)\n\n def bracket_mode(self):\n self.mode = BracketMode(self)\n\n def quote_mode(self):\n self.mode = QuoteMode(self)\n\n\nclass InitialMode(object):\n\n def __init__(self, parser):\n self.parser = parser\n\n def handle_word(self, word):\n if word.startswith('['):\n self.parser.bracket_mode()\n self.parser.mode.handle_word(word[1:])\n elif word.startswith('\"'):\n self.parser.quote_mode()\n self.parser.mode.handle_word(word[1:])\n else:\n self.parser.result.append(word)\n\n\nclass BlockMode(object):\n\n end_marker = None\n\n def __init__(self, parser):\n self.parser = parser\n self.result = []\n\n def handle_word(self, word):\n if word.endswith(self.end_marker):\n self.result.append(word[:-1])\n self.parser.result.append(' '.join(self.result))\n self.parser.initial_mode()\n else:\n self.result.append(word)\n\nclass BracketMode(BlockMode):\n end_marker = ']'\n\nclass QuoteMode(BlockMode):\n end_marker = '\"'\n" }, { "answer_id": 234855, "author": "Sanjaya R", "author_id": 9353, "author_profile": "https://Stackoverflow.com/users/9353", "pm_score": -1, "selected": false, "text": "rrr = []\nqqq = s.split('\\\"')\n[ rrr.extend( qqq[x].split(), [ qqq[x] ] )[ x%2]) for x in range( len( qqq ) )]\nprint rrr\n" }, { "answer_id": 234957, "author": "Kirk Strauser", "author_id": 32538, "author_profile": "https://Stackoverflow.com/users/32538", "pm_score": 0, "selected": false, "text": "#!/usr/bin/env python\n\na = 'this is [bracket test] \"and quotes test \"'\n\nwords = a.split()\nwordlist = []\n\nwhile True:\n try:\n word = words.pop(0)\n except IndexError:\n break\n if word[0] in '\"[':\n buildlist = [word[1:]]\n while True:\n try:\n word = words.pop(0)\n except IndexError:\n break\n if word[-1] in '\"]':\n buildlist.append(word[:-1])\n break\n buildlist.append(word)\n wordlist.append(' '.join(buildlist))\n else:\n wordlist.append(word)\n\nprint wordlist\n" }, { "answer_id": 235412, "author": "PhE", "author_id": 31335, "author_profile": "https://Stackoverflow.com/users/31335", "pm_score": 3, "selected": false, "text": ">>> import re\n>>> txt = 'this is [bracket test] \"and quotes test \"'\n>>> [x[1:-1] if x[0] in '[\"' else x for x in re.findall('\\[[^\\]]*\\]|\\\"[^\\\"]*\\\"|\\S+', txt)]\n['this', 'is', 'bracket test', 'and quotes test ']\n" }, { "answer_id": 238476, "author": "zvoase", "author_id": 31600, "author_profile": "https://Stackoverflow.com/users/31600", "pm_score": 0, "selected": false, "text": "(defun hello_world (&optional (text \"Hello, World!\"))\n (format t text))\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31256/" ]
234,526
<p>Can I setup a custom MIME type through ASP.NET or some .NET code? I need to register the Silverlight XAML and XAP MIME types in IIS 6.</p>
[ { "answer_id": 234613, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 4, "selected": true, "text": "using (DirectoryEntry mimeMap = new DirectoryEntry(\"IIS://Localhost/MimeMap\"))\n{\n PropertyValueCollection propValues = mimeMap.Properties[\"MimeMap\"];\n\n IISOle.MimeMapClass newMimeType = new IISOle.MimeMapClass();\n newMimeType.Extension = extension; // string - .xap\n newMimeType.MimeType = mimeType; // string - application/x-silverlight-app\n\n propValues.Add(newMimeType);\n mimeMap.CommitChanges();\n}\n 'IIS://Localhost/MimeMap' 'IIS://Localhost/W3SVC/[iisnumber]/root' '[iisnumber]'" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234526", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
234,532
<p>I have data that looks like</p> <blockquote> <pre><code>CUSTOMER, CUSTOMER_ID, PRODUCT ABC INC 1 XYX ABC INC 1 ZZZ DEF CO 2 XYX DEF CO 2 ZZZ DEF CO 2 WWW GHI LLC 3 ZYX </code></pre> </blockquote> <p>I'd like to write a query that'd make the data look like this:</p> <blockquote> <pre><code>CUSTOMER, CUSTOMER_ID, PRODUCTS ABC INC 1 XYX, ZZZ DEF CO 2 XYX, ZZZ, WWW GHI LLC 3 ZYX </code></pre> </blockquote> <p>Using Oracle 10g if helps. I saw something that would work using MYSQL, but I need a plain SQL or ORACLE equivalent. I've also seen examples of stored procs that could be made, however, I cannot use a stored proc with the product i'm using.</p> <p>Here's how'd it work in MySQL if I were using it</p> <pre><code>SELECT CUSTOMER, CUSTOMER_ID, GROUP_CONCAT( PRODUCT ) FROM MAGIC_TABLE GROUP BY CUSTOMER, CUSTOMER_ID </code></pre> <p>Thank you.</p>
[ { "answer_id": 234843, "author": "Roy Rico", "author_id": 1580, "author_profile": "https://Stackoverflow.com/users/1580", "pm_score": 0, "selected": false, "text": "SELECT CUSTOMER, CUSTOMER_ID, COUNT(PRODUCT) PROD_COUNT, \n RTRIM( \n XMLAGG( XMLELEMENT (C, PRODUCT || ',') ORDER BY PRODUCT\n).EXTRACT ('//text()'), ',' \n ) AS PRODUCTS FROM (\n SELECT DISTINCT CUSTOMER, CUSTOMER_ID, PRODUCT\n FROM MAGIC_TABLE\n ) GROUP BY CUSTOMER, CUSTOMER_ID ORDER BY 1 , 2\n" }, { "answer_id": 10252843, "author": "ScrappyDev", "author_id": 620192, "author_profile": "https://Stackoverflow.com/users/620192", "pm_score": 4, "selected": false, "text": " SELECT CUSTOMER, CUSTOMER_ID,\n LISTAGG(PRODUCT, ', ') WITHIN GROUP (ORDER BY PRODUCT)\n FROM SOME_TABLE\nGROUP BY CUSTOMER, CUSTOMER_ID\nORDER BY 1, 2\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1580/" ]
234,558
<p>I can't seem to be able to disable ViewState for controls that I add to a page dynamically.</p> <p><strong>ASPX</strong></p> <pre><code>&lt;%@ Page Language="C#" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" EnableViewState="false" %&gt; ... &lt;asp:PlaceHolder ID="DropDownPlaceHolder" runat="server" EnableViewState="false" /&gt; &lt;asp:Button ID="Submit" runat="server" OnClick="Submit_OnClick" Text="Click Me!" EnableViewState="false"/&gt; ... </code></pre> <p><strong>ASPX.CS</strong></p> <pre><code>protected override void OnInit(EventArgs e) { DropDownList dropDown = new DropDownList(); TextBox textBox = new TextBox(); textBox.EnableViewState = false; dropDown.Items.Add("Apple"); dropDown.Items.Add("Dell"); dropDown.Items.Add("HP"); dropDown.AutoPostBack = true; dropDown.EnableViewState = false; DropDownPlaceHolder.Controls.Add(dropDown); DropDownPlaceHolder.Controls.Add(textBox); base.OnInit(e); } </code></pre> <p>If I can't disable ViewState on these controls, then I can never programmatically override what a user has entered/selected.</p> <p>I've tried placing this code in OnInit and Page_Load, but the effect is the same in either location -- ViewState is enabled (the DropDownList maintains selected value and TextBox retains text that was entered).</p> <p>So, how can I disable ViewState and keep it from populating these controls?</p> <p>Thanks!</p> <hr> <p>Thanks for your response. Unfortunately, this isn't a workable solution in my situation.</p> <p>I will be dynamically loading controls based upon a configuration file, and some of those controls will load child controls.</p> <p>I need to be able to turn the ViewState of controls off individually, without the need to code logic for loading controls in different places (in OnInit vs. LoadComplete method).</p>
[ { "answer_id": 234763, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 0, "selected": false, "text": " Public Sub Page_In(ByVal sender As Object, ByVal e As EventArgs) _ \n Handles Me.LoadComplete\n\n Dim ddl As New DropDownList()\n ddl.EnableViewState = False\n ddl.Items.Add(\"Hello\")\n ddl.Items.Add(\"Stackoverflow\")\n\n phTest.Controls.Add(ddl)\n\nEnd Sub\n" }, { "answer_id": 243052, "author": "Adrian Clark", "author_id": 148, "author_profile": "https://Stackoverflow.com/users/148", "pm_score": 2, "selected": false, "text": "ControlState DropDownList TextBox BackColor ViewState ViewState ViewState" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234558", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8797/" ]
234,560
<p>I'm wondering whether anyone here has ever used a <a href="http://en.wikipedia.org/wiki/Skip_list" rel="nofollow noreferrer">skip list</a>. It looks to have roughly the same advantages as a balanced binary tree but is simpler to implement. If you have, did you write your own, or use a pre-written library (and if so, what was its name)?</p>
[ { "answer_id": 234967, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 3, "selected": false, "text": "std::map std::map" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12193/" ]
234,564
<p>How do I make <a href="http://en.wikipedia.org/wiki/Vi" rel="noreferrer">vi</a>-<a href="http://en.wikipedia.org/wiki/Vim_%28text_editor%29" rel="noreferrer">Vim</a> never use tabs (converting spaces to tabs, bad!), makes the tab key == 4 spaces, and automatically indent code after curly brace blocks like <a href="http://en.wikipedia.org/wiki/Emacs" rel="noreferrer">Emacs</a> does?</p> <p>Also, how do I save these settings so I never have to input them again?</p> <p>I've seen other questions related to this, but it always seems to be a little off from what I want.</p>
[ { "answer_id": 234578, "author": "Ken", "author_id": 20074, "author_profile": "https://Stackoverflow.com/users/20074", "pm_score": 12, "selected": true, "text": ".vimrc filetype plugin indent on\n\" show existing tab with 4 spaces width\nset tabstop=4\n\" when indenting with '>', use 4 spaces width\nset shiftwidth=4\n\" On pressing tab, insert 4 spaces\nset expandtab\n set smartindent\nset tabstop=4\nset shiftwidth=4\nset expandtab\n :help smartindent\n :help auto-setting\n :set all\n :help C-indenting\n" }, { "answer_id": 234597, "author": "Joey Gibson", "author_id": 6645, "author_profile": "https://Stackoverflow.com/users/6645", "pm_score": 4, "selected": false, "text": "{" }, { "answer_id": 323014, "author": "netjeff", "author_id": 41191, "author_profile": "https://Stackoverflow.com/users/41191", "pm_score": 8, "selected": false, "text": "set expandtab ts=4 sw=4 ai\n :%retab\n" }, { "answer_id": 411670, "author": "graywh", "author_id": 18038, "author_profile": "https://Stackoverflow.com/users/18038", "pm_score": 7, "selected": false, "text": "filetype plugin indent on set sw=4 sts=4 et" }, { "answer_id": 21323445, "author": "Shervin Emami", "author_id": 199142, "author_profile": "https://Stackoverflow.com/users/199142", "pm_score": 6, "selected": false, "text": "~/.vimrc \" Only do this part when compiled with support for autocommands.\nif has(\"autocmd\")\n \" Use filetype detection and file-based automatic indenting.\n filetype plugin indent on\n\n \" Use actual tab chars in Makefiles.\n autocmd FileType make set tabstop=8 shiftwidth=8 softtabstop=0 noexpandtab\nendif\n\n\" For everything else, use a tab width of 4 space chars.\nset tabstop=4 \" The width of a TAB is set to 4.\n \" Still it is a \\t. It is just that\n \" Vim will interpret it to be having\n \" a width of 4.\nset shiftwidth=4 \" Indents will have a width of 4.\nset softtabstop=4 \" Sets the number of columns for a TAB.\nset expandtab \" Expand TABs to spaces.\n" }, { "answer_id": 23426067, "author": "Chaudhry Junaid", "author_id": 2082308, "author_profile": "https://Stackoverflow.com/users/2082308", "pm_score": 5, "selected": false, "text": "set expandtab\nset shiftwidth=2\nset softtabstop=2\nfiletype plugin indent on\n" }, { "answer_id": 25119808, "author": "Erick", "author_id": 1125122, "author_profile": "https://Stackoverflow.com/users/1125122", "pm_score": 6, "selected": false, "text": ".vimrc .viminfo cd ~ vim .vimrc filetype plugin indent on\nset tabstop=4\nset shiftwidth=4\nset expandtab\n" }, { "answer_id": 33005115, "author": "Yusuf Ibrahim", "author_id": 2674072, "author_profile": "https://Stackoverflow.com/users/2674072", "pm_score": 4, "selected": false, "text": "$ vim ~/.vimrc\n set tabstop=4\nset shiftwidth=4\nset softtabstop=4\nset expandtab\n" }, { "answer_id": 33788330, "author": "User", "author_id": 2199852, "author_profile": "https://Stackoverflow.com/users/2199852", "pm_score": 4, "selected": false, "text": ":set tabstop=4\n:set shiftwidth=4\n:set expandtab\n" }, { "answer_id": 60103290, "author": "Kaz", "author_id": 1250772, "author_profile": "https://Stackoverflow.com/users/1250772", "pm_score": 2, "selected": false, "text": "tabstop shiftwidth expandtab :imap <Tab> ^T\n :imap <S-Tab> ^D\n :set expandtab <Tab> :set smarttab smarttab :map <Tab> >\n:map <S-Tab> <\n shiftwidth tabstop expandtab shiftwidth :set shiftwidth=4 :set sw=4 noexpandtab :set expandtab expandtab tabstop set tabstop=8 expandtab" }, { "answer_id": 63152909, "author": "Cheung Johnson", "author_id": 11235024, "author_profile": "https://Stackoverflow.com/users/11235024", "pm_score": 2, "selected": false, "text": "set tabstop=4\n" }, { "answer_id": 71031011, "author": "ashish", "author_id": 1542701, "author_profile": "https://Stackoverflow.com/users/1542701", "pm_score": 2, "selected": false, "text": "set tabstop=4\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234564", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
234,589
<p>One problem that I come across regularly and yet don't have a solution to is to restrict or permit access to specific entities in a system. Some companies (banks, for example) have very strict policies regarding which employees may access certain information. For example, an employee at a specific branch may access account information for customers of that specific branch but not from other branches. Also, banks that have branches in many countries may be subject to legal restrictions that restricts employees in other countries from accessing information about domestic customers.</p> <p>Another example I've come across is a public website where users belong to a specific entity (such as a company) and may access information regarding that entity only and not other entities.</p> <p>If the number of entities is small and fixed, this is not a problem. Simply specify domain groups in the active directory (if you're working in Microsoft environments, which is the case for me), add users to the groups and restrict access using IsInRole() for each entity. So if there is a company called ABC in the system I'd create a domain group called "Admins_ABC" or something like that and when a user tries to administer information about ABC, I'd make sure the user is a member of that group. This is not really the way the AD is intended to be used, but for a small number of entities I've found it reasonable.</p> <p>The complexity increases when the number of entities change often and when the requirements become more detailed. I've seen security requirements that are similar to security in NTFS - some users (or groups of users) should be able to access some entities (files in NTFS) or groups of entities (the permissions that are set on directories in NTFS are propagated to it's children). </p> <p>I try to avoid situations like these because they tend to be a nightmare to model and code and they usually become complex to administer, but the customers I work with often need solutions to this problem.</p> <p>Like I said, I have never actually solved this problem in a <em>good</em> way. How would you go about modeling and developing a solution for this problem in a way that can be reused? Do you know of any general, proprietary solutions that can be used?</p>
[ { "answer_id": 234735, "author": "cfeduke", "author_id": 5645, "author_profile": "https://Stackoverflow.com/users/5645", "pm_score": 3, "selected": true, "text": "<domain> Project\n|- <class> Person\n| |- <instance> John\n| |- <instance> Mary\n|- <class> FormX\n| |- <instance> John's Leave Form\n...\n <group> Administrators\n|- <class> Person: actions (Read, Create, Update, Suspend)\n <group> Office Administrator\n|- <class> Person: actions (Create)\n|- <class> FormX: actions (Approve, Deny)\n <user> John\n|- <class> Person\n| |- <instance> John: actions (Edit)\n <group> { Allow, None, Deny } SecurityManager.Test SecurityManager.Test" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15157/" ]
234,591
<p>When doing case-insensitive comparisons, is it more efficient to convert the string to upper case or lower case? Does it even matter?</p> <p>It is suggested <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c#12137">in this SO post</a> that C# is more efficient with ToUpper because "Microsoft optimized it that way." But I've also read <a href="http://www.petefreitag.com/item/175.cfm" rel="noreferrer">this argument</a> that converting ToLower vs. ToUpper depends on what your strings contain more of, and that typically strings contain more lower case characters which makes ToLower more efficient.</p> <p>In particular, I would like to know:</p> <ul> <li>Is there a way to optimize ToUpper or ToLower such that one is faster than the other?</li> <li>Is it faster to do a case-insensitive comparison between upper or lower case strings, and why?</li> <li>Are there any programming environments (eg. C, C#, Python, whatever) where one case is clearly better than the other, and why?</li> </ul>
[ { "answer_id": 234615, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 4, "selected": false, "text": "UPPER lower long" }, { "answer_id": 234639, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 3, "selected": false, "text": "ToUpperInvariant() ToUpper()" }, { "answer_id": 14128850, "author": "Ian Boyd", "author_id": 12597, "author_profile": "https://Stackoverflow.com/users/12597", "pm_score": 5, "selected": false, "text": "Original: ϱ\nToUpper: Ρ\nToLower: ρ\n" }, { "answer_id": 65451148, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 2, "selected": false, "text": "ToLower ToUpper using System;\n\nclass Program {\n static void Main() {\n char[][] pairs = {\nnew[]{'\\u00E5','\\u212B'},new[]{'\\u00C5','\\u212B'},new[]{'\\u0399','\\u1FBE'},\nnew[]{'\\u03B9','\\u1FBE'},new[]{'\\u03B2','\\u03D0'},new[]{'\\u03B5','\\u03F5'},\nnew[]{'\\u03B8','\\u03D1'},new[]{'\\u03B8','\\u03F4'},new[]{'\\u03D1','\\u03F4'},\nnew[]{'\\u03B9','\\u1FBE'},new[]{'\\u0345','\\u03B9'},new[]{'\\u0345','\\u1FBE'},\nnew[]{'\\u03BA','\\u03F0'},new[]{'\\u00B5','\\u03BC'},new[]{'\\u03C0','\\u03D6'},\nnew[]{'\\u03C1','\\u03F1'},new[]{'\\u03C2','\\u03C3'},new[]{'\\u03C6','\\u03D5'},\nnew[]{'\\u03C9','\\u2126'},new[]{'\\u0392','\\u03D0'},new[]{'\\u0395','\\u03F5'},\nnew[]{'\\u03D1','\\u03F4'},new[]{'\\u0398','\\u03D1'},new[]{'\\u0398','\\u03F4'},\nnew[]{'\\u0345','\\u1FBE'},new[]{'\\u0345','\\u0399'},new[]{'\\u0399','\\u1FBE'},\nnew[]{'\\u039A','\\u03F0'},new[]{'\\u00B5','\\u039C'},new[]{'\\u03A0','\\u03D6'},\nnew[]{'\\u03A1','\\u03F1'},new[]{'\\u03A3','\\u03C2'},new[]{'\\u03A6','\\u03D5'},\nnew[]{'\\u03A9','\\u2126'},new[]{'\\u0398','\\u03F4'},new[]{'\\u03B8','\\u03F4'},\nnew[]{'\\u03B8','\\u03D1'},new[]{'\\u0398','\\u03D1'},new[]{'\\u0432','\\u1C80'},\nnew[]{'\\u0434','\\u1C81'},new[]{'\\u043E','\\u1C82'},new[]{'\\u0441','\\u1C83'},\nnew[]{'\\u0442','\\u1C84'},new[]{'\\u0442','\\u1C85'},new[]{'\\u1C84','\\u1C85'},\nnew[]{'\\u044A','\\u1C86'},new[]{'\\u0412','\\u1C80'},new[]{'\\u0414','\\u1C81'},\nnew[]{'\\u041E','\\u1C82'},new[]{'\\u0421','\\u1C83'},new[]{'\\u1C84','\\u1C85'},\nnew[]{'\\u0422','\\u1C84'},new[]{'\\u0422','\\u1C85'},new[]{'\\u042A','\\u1C86'},\nnew[]{'\\u0463','\\u1C87'},new[]{'\\u0462','\\u1C87'}\n };\n int upper = 0, lower = 0;\n foreach (char[] pair in pairs) {\n Console.Write(\n \"U+{0:X4} U+{1:X4} pass: \",\n Convert.ToInt32(pair[0]),\n Convert.ToInt32(pair[1])\n );\n if (Char.ToUpper(pair[0]) == Char.ToUpper(pair[1])) {\n Console.Write(\"ToUpper \");\n upper++;\n } else {\n Console.Write(\" \");\n }\n if (Char.ToLower(pair[0]) == Char.ToLower(pair[1])) {\n Console.Write(\"ToLower\");\n lower++;\n }\n Console.WriteLine();\n }\n Console.WriteLine(\"upper pass: {0}, lower pass: {1}\", upper, lower);\n }\n}\n Invariant U+00E5 U+212B pass: ToLower\nU+00C5 U+212B pass: ToLower\nU+0399 U+1FBE pass: ToUpper\nU+03B9 U+1FBE pass: ToUpper\nU+03B2 U+03D0 pass: ToUpper\nU+03B5 U+03F5 pass: ToUpper\nU+03B8 U+03D1 pass: ToUpper\nU+03B8 U+03F4 pass: ToLower\nU+03D1 U+03F4 pass:\nU+03B9 U+1FBE pass: ToUpper\nU+0345 U+03B9 pass: ToUpper\nU+0345 U+1FBE pass: ToUpper\nU+03BA U+03F0 pass: ToUpper\nU+00B5 U+03BC pass: ToUpper\nU+03C0 U+03D6 pass: ToUpper\nU+03C1 U+03F1 pass: ToUpper\nU+03C2 U+03C3 pass: ToUpper\nU+03C6 U+03D5 pass: ToUpper\nU+03C9 U+2126 pass: ToLower\nU+0392 U+03D0 pass: ToUpper\nU+0395 U+03F5 pass: ToUpper\nU+03D1 U+03F4 pass:\nU+0398 U+03D1 pass: ToUpper\nU+0398 U+03F4 pass: ToLower\nU+0345 U+1FBE pass: ToUpper\nU+0345 U+0399 pass: ToUpper\nU+0399 U+1FBE pass: ToUpper\nU+039A U+03F0 pass: ToUpper\nU+00B5 U+039C pass: ToUpper\nU+03A0 U+03D6 pass: ToUpper\nU+03A1 U+03F1 pass: ToUpper\nU+03A3 U+03C2 pass: ToUpper\nU+03A6 U+03D5 pass: ToUpper\nU+03A9 U+2126 pass: ToLower\nU+0398 U+03F4 pass: ToLower\nU+03B8 U+03F4 pass: ToLower\nU+03B8 U+03D1 pass: ToUpper\nU+0398 U+03D1 pass: ToUpper\nU+0432 U+1C80 pass: ToUpper\nU+0434 U+1C81 pass: ToUpper\nU+043E U+1C82 pass: ToUpper\nU+0441 U+1C83 pass: ToUpper\nU+0442 U+1C84 pass: ToUpper\nU+0442 U+1C85 pass: ToUpper\nU+1C84 U+1C85 pass: ToUpper\nU+044A U+1C86 pass: ToUpper\nU+0412 U+1C80 pass: ToUpper\nU+0414 U+1C81 pass: ToUpper\nU+041E U+1C82 pass: ToUpper\nU+0421 U+1C83 pass: ToUpper\nU+1C84 U+1C85 pass: ToUpper\nU+0422 U+1C84 pass: ToUpper\nU+0422 U+1C85 pass: ToUpper\nU+042A U+1C86 pass: ToUpper\nU+0463 U+1C87 pass: ToUpper\nU+0462 U+1C87 pass: ToUpper\nupper pass: 46, lower pass: 8\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234591", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9974/" ]
234,594
<p>In Eclipse, under <kbd>Windows</kbd> -> <kbd>Preference</kbd> -> <kbd>Java</kbd> -> <kbd>Code Style</kbd>, you can define code templates for comments and code, and you can setup a code formatter. </p> <p>I'm wondering if it is possible in Eclipse to have these setting take affect every time I save a source file. Basically, instead of me highlighting everything and pressing <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>F</kbd>, I want Eclipse to be responsible for making sure my code is formatted properly.</p> <p>Is this possible and how do you set it up?</p> <p><strong>Note On Using the Auto-Format:</strong> It's probably best to choose "Format Edited Lines" as merging changes becomes very difficult when you reformat a whole file that is in source control already that was not formatted properly. Already did this to a co-worker.</p>
[ { "answer_id": 234625, "author": "Neal Swearer", "author_id": 29962, "author_profile": "https://Stackoverflow.com/users/29962", "pm_score": 9, "selected": true, "text": "Version: 3.3.3.r33x_r20080129-_19UEl7Ezk_gXF1kouft<br>\nBuild id: M20080221-1800\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16524/" ]
234,600
<p>I would like to use <code>Class.newInstance()</code> but the class I am instantiating does not have a nullary constructor. Therefore I need to be able to pass in constructor arguments. Is there a way to do this?</p>
[ { "answer_id": 234614, "author": "Marko", "author_id": 31141, "author_profile": "https://Stackoverflow.com/users/31141", "pm_score": 7, "selected": false, "text": "myObject.getClass().getDeclaredConstructors(types list).newInstance(args list);\n" }, { "answer_id": 234617, "author": "jsight", "author_id": 1432, "author_profile": "https://Stackoverflow.com/users/1432", "pm_score": 8, "selected": false, "text": "MyClass.class.getDeclaredConstructor(String.class).newInstance(\"HERESMYARG\");\n obj.getClass().getDeclaredConstructor(String.class).newInstance(\"HERESMYARG\");\n" }, { "answer_id": 235196, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": false, "text": "Class.newInstance() Constructor.newInstance()" }, { "answer_id": 17428883, "author": "Lajos Arpad", "author_id": 436560, "author_profile": "https://Stackoverflow.com/users/436560", "pm_score": 1, "selected": false, "text": "getDeclaredConstructor public static JFrame createJFrame(Class c, String name, Component parentComponent)\n{\n try\n {\n JFrame frame = (JFrame)c.getDeclaredConstructor(new Class[] {String.class}).newInstance(\"name\");\n if (parentComponent != null)\n {\n frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n }\n else\n {\n frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);\n }\n frame.setLocationRelativeTo(parentComponent);\n frame.pack();\n frame.setVisible(true);\n }\n catch (InstantiationException instantiationException)\n {\n ExceptionHandler.handleException(instantiationException, parentComponent, Language.messages.get(Language.InstantiationExceptionKey), c.getName());\n }\n catch(NoSuchMethodException noSuchMethodException)\n {\n //ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.NoSuchMethodExceptionKey, \"NamedConstructor\");\n ExceptionHandler.handleException(noSuchMethodException, parentComponent, Language.messages.get(Language.NoSuchMethodExceptionKey), \"(Constructor or a JFrame method)\");\n }\n catch (IllegalAccessException illegalAccessException)\n {\n ExceptionHandler.handleException(illegalAccessException, parentComponent, Language.messages.get(Language.IllegalAccessExceptionKey));\n }\n catch (InvocationTargetException invocationTargetException)\n {\n ExceptionHandler.handleException(invocationTargetException, parentComponent, Language.messages.get(Language.InvocationTargetExceptionKey));\n }\n finally\n {\n return null;\n }\n}\n" }, { "answer_id": 24109870, "author": "Martin Konecny", "author_id": 276949, "author_profile": "https://Stackoverflow.com/users/276949", "pm_score": 6, "selected": false, "text": "class MyClass {\n public MyClass(Long l, String s, int i) {\n\n }\n}\n Class classToLoad = MyClass.class;\n\nClass[] cArg = new Class[3]; //Our constructor has 3 arguments\ncArg[0] = Long.class; //First argument is of *object* type Long\ncArg[1] = String.class; //Second argument is of *object* type String\ncArg[2] = int.class; //Third argument is of *primitive* type int\n\nLong l = new Long(88);\nString s = \"text\";\nint i = 5;\n\nclassToLoad.getDeclaredConstructor(cArg).newInstance(l, s, i);\n" }, { "answer_id": 40318262, "author": "Ravindra babu", "author_id": 4999394, "author_profile": "https://Stackoverflow.com/users/4999394", "pm_score": 3, "selected": false, "text": "Constructor Class[] getDeclaredConstructor Class Object[] newInstance Constructor import java.lang.reflect.*;\n\nclass NewInstanceWithReflection{\n public NewInstanceWithReflection(){\n System.out.println(\"Default constructor\");\n }\n public NewInstanceWithReflection( String a){\n System.out.println(\"Constructor :String => \"+a);\n }\n public static void main(String args[]) throws Exception {\n\n NewInstanceWithReflection object = (NewInstanceWithReflection)Class.forName(\"NewInstanceWithReflection\").newInstance();\n Constructor constructor = NewInstanceWithReflection.class.getDeclaredConstructor( new Class[] {String.class});\n NewInstanceWithReflection object1 = (NewInstanceWithReflection)constructor.newInstance(new Object[]{\"StackOverFlow\"});\n\n }\n}\n java NewInstanceWithReflection\nDefault constructor\nConstructor :String => StackOverFlow\n" }, { "answer_id": 74557289, "author": "Optimus Prime", "author_id": 1723626, "author_profile": "https://Stackoverflow.com/users/1723626", "pm_score": 0, "selected": false, "text": "Class clazz final Constructor constructor = clazz.getConstructors()[0];\nfinal int constructorArgsCount = constructor.getParameterCount();\nif (constructorArgsCount > 0) {\n final Object[] constructorArgs = new Object[constructorArgsCount];\n int i = 0;\n for (Class parameterClass : constructor.getParameterTypes()) {\n Object dummyParameterValue = getDummyValue(Class.forName(parameterClass.getTypeName()), null);\n constructorArgs[i++] = dummyParameterValue;\n }\n instance = constructor.newInstance(constructorArgs);\n} else {\n instance = clazz.newInstance();\n}\n getDummyValue() private static Object getDummyValue(final Class clazz, final Field field) throws Exception {\n if (int.class.equals(clazz) || Integer.class.equals(clazz)) {\n return DUMMY_INT;\n } else if (String.class.equals(clazz)) {\n return DUMMY_STRING;\n } else if (boolean.class.equals(clazz) || Boolean.class.equals(clazz)) {\n return DUMMY_BOOL;\n } else if (List.class.equals(clazz)) {\n Class fieldClassGeneric = Class.forName(((ParameterizedType) field.getGenericType()).getActualTypeArguments()[0].getTypeName());\n return List.of(getDummyValue(fieldClassGeneric, null));\n } else if (USER_DEFINED_CLASSES.contains(clazz.getSimpleName())) {\n return createClassInstance(clazz);\n } else {\n throw new Exception(\"Dummy value for class type not defined - \" + clazz.getName();\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
234,622
<p>I have been tasked to optimize some sql queries at work. Everything I have found points to using Explain Plan to identify problem areas. The problem I can not find out exactly what explain plan is telling me. You get Cost, Cardinality, and bytes. </p> <p>What do this indicate, and how should I be using this as a guide. Are low numbers better? High better? Any input would be greatly appreciated. </p> <p>Or if you have a better way to go about optimizing a query, I would be interested.</p>
[ { "answer_id": 236391, "author": "Walter Mitty", "author_id": 19937, "author_profile": "https://Stackoverflow.com/users/19937", "pm_score": 4, "selected": false, "text": "select * from customers \nwhere\n State = @State\n and ZipCode = @ZipCode\n select * from customers\n where Country = @Country\n and State = @State\n and ZipCode = @ZipCode\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3340/" ]
234,657
<p>We have a Procedure in Oracle with a SYS_REFCURSOR output parameter that returns the data we want to bind to an ASP.NET GridView control. I've seen this done before but I can't find the original reference I used to solve the problem.</p> <p>Here is what the procedure looks like:</p> <pre><code>create or replace PROCEDURE GETSOMEDATA ( P_Data OUT SYS_REFCURSOR ) AS BEGIN OPEN P_Data FOR SELECT * FROM SOMETABLE; END GETSOMEDATA; </code></pre> <p>And for now the GridView is just bare-bones:</p> <pre><code>&lt;asp:GridView ID="grdData" runat="server" AutoGenerateColumns="true"&gt;&lt;/asp:GridView&gt; </code></pre>
[ { "answer_id": 243611, "author": "Brian Schmitt", "author_id": 30492, "author_profile": "https://Stackoverflow.com/users/30492", "pm_score": 2, "selected": true, "text": " Public Function GetSomeData() as DataTable\n Dim OrclConn as New OracleConnection(\"Connectionstring\")\n Dim OrclCmd as New Oraclecommand(\"GETSOMEDATA\", OrclConn)\n OrclCmd.CommandType = CommandType.StoredProcedure\n OrclCmd.Parameters.Add(\"P_Data\", OracleType.Cursor).Direction = ParameterDirection.Output 'Or ParameterDirection.ReturnValue\n\n Dim OrclDA as New OracleDataAdapter(OrclCmd)\n Dim RtnTable as DataTable\n OrclConn.Open\n OrclDA.Fill(RtnTable)\n OrclConn.Close\n\n Return RtnTable\n End Function\n" }, { "answer_id": 359073, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "Dim oracon As New OracleConnection(\"User Id=developer;Password=developer;Data Source=orcl;\")\n Dim ds As New Data.DataSet\n Dim qry As String\n oracon.Open()\n qry = \"select * from Employee\"\n Dim adp As New OracleDataAdapter(qry, oracon)\n adp.Fill(ds)\n GridView1.DataSource = ds\n GridView1.DataBind()\n oracon.Close()\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31267/" ]
234,683
<p>Which algorithm does the JavaScript <code>Array#sort()</code> function use? I understand that it can take all manner of arguments and functions to perform different kinds of sorts, I'm simply interested in which algorithm the vanilla sort uses.</p>
[ { "answer_id": 236534, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 9, "selected": true, "text": "std::qsort qsort // FIXME: Since we sort by string value, a fast algorithm might be to use a\n// radix sort. That would be O(N) rather than O(N log N).\n" }, { "answer_id": 37245185, "author": "Joe Thomas", "author_id": 3072896, "author_profile": "https://Stackoverflow.com/users/3072896", "pm_score": 6, "selected": false, "text": " var QuickSort = function QuickSort(a, from, to) {\n var third_index = 0;\n while (true) {\n // Insertion sort is faster for short arrays.\n if (to - from <= 10) {\n InsertionSort(a, from, to);\n return;\n }\n if (to - from > 1000) {\n third_index = GetThirdIndex(a, from, to);\n } else {\n third_index = from + ((to - from) >> 1);\n }\n // Find a pivot as the median of first, last and middle element.\n var v0 = a[from];\n var v1 = a[to - 1];\n var v2 = a[third_index];\n var c01 = comparefn(v0, v1);\n if (c01 > 0) {\n // v1 < v0, so swap them.\n var tmp = v0;\n v0 = v1;\n v1 = tmp;\n } // v0 <= v1.\n var c02 = comparefn(v0, v2);\n if (c02 >= 0) {\n // v2 <= v0 <= v1.\n var tmp = v0;\n v0 = v2;\n v2 = v1;\n v1 = tmp;\n } else {\n // v0 <= v1 && v0 < v2\n var c12 = comparefn(v1, v2);\n if (c12 > 0) {\n // v0 <= v2 < v1\n var tmp = v1;\n v1 = v2;\n v2 = tmp;\n }\n }\n // v0 <= v1 <= v2\n a[from] = v0;\n a[to - 1] = v2;\n var pivot = v1;\n var low_end = from + 1; // Upper bound of elements lower than pivot.\n var high_start = to - 1; // Lower bound of elements greater than pivot.\n a[third_index] = a[low_end];\n a[low_end] = pivot;\n\n // From low_end to i are elements equal to pivot.\n // From i to high_start are elements that haven't been compared yet.\n partition: for (var i = low_end + 1; i < high_start; i++) {\n var element = a[i];\n var order = comparefn(element, pivot);\n if (order < 0) {\n a[i] = a[low_end];\n a[low_end] = element;\n low_end++;\n } else if (order > 0) {\n do {\n high_start--;\n if (high_start == i) break partition;\n var top_elem = a[high_start];\n order = comparefn(top_elem, pivot);\n } while (order > 0);\n a[i] = a[high_start];\n a[high_start] = element;\n if (order < 0) {\n element = a[i];\n a[i] = a[low_end];\n a[low_end] = element;\n low_end++;\n }\n }\n }\n if (to - high_start < low_end - from) {\n QuickSort(a, high_start, to);\n to = low_end;\n } else {\n QuickSort(a, from, low_end);\n from = high_start;\n }\n }\n };\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11042/" ]
234,695
<p>Is there a way to have a default parameter passed to a action in the case where the regex didnt match anything using django?</p> <pre><code> urlpatterns = patterns('',(r'^test/(?P&lt;name&gt;.*)?$','myview.displayName')) #myview.py def displayName(request,name): # write name to response or something </code></pre> <p>I have tried setting the third parameter in the urlpatterns to a dictionary containing ' and giving the name parameter a default value on the method, none of which worked. the name parameter always seems to be None. I really dont want to code a check for None if i could set a default value.</p> <p>Clarification: here is an example of what i was changing it to.</p> <pre><code> def displayName(request,name='Steve'): return HttpResponse(name) #i also tried urlpatterns = patterns('', (r'^test/(?P&lt;name&gt;.*)?$', 'myview.displayName', dict(name='Test') ) ) </code></pre> <p>when i point my browser at the view it displays the text 'None'</p> <p>Any ideas?</p>
[ { "answer_id": 234741, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 0, "selected": false, "text": "def displayName(request, name=defaultObj)" }, { "answer_id": 234995, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 4, "selected": true, "text": ">>> url.match(\"test/\").groupdict()\n{'name': None}\n view(request, *groups, **groupdict)\n view(request, name = None)\n urlpatterns = patterns('',\n (r'^test/(?P<name>.+)$','myview.displayName'), # note the '+' instead of the '*'\n (r'^test/$','myview.displayName'),\n)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24730/" ]
234,696
<p>I have lots of mp3s on my site that I want my friends to be able to play only- but I don't want them all downloading as soon as the page opens and would prefer them to only start downloading into the buffer if someone wants to play it- is this possible with the embed tag? I can't seem to find anything on Google so I am wondering if it's something I'll have to do in JavaScript or think of an HTML work around.</p> <p>cheers</p>
[ { "answer_id": 236703, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 0, "selected": false, "text": "blog.stackoverflow.com" }, { "answer_id": 1294499, "author": "BigBlondeViking", "author_id": 119910, "author_profile": "https://Stackoverflow.com/users/119910", "pm_score": 0, "selected": false, "text": "<a href=\"http://mediaplayer.yahoo.com/example1.mp3\">First link</a>\n<a href=\"http://mediaplayer.yahoo.com/example2.mp3\">Second link</a>\n<a href=\"http://mediaplayer.yahoo.com/example3.mp3\">Third link</a>\n\n\n<script type=\"text/javascript\" src=\"http://mediaplayer.yahoo.com/js\"></script>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
234,697
<p>I was recently approached by a network-engineer, co-worker who would like to offload his minor network admin duties to a junior-level helpdesk tech. The specific location in need of management acts as an ISP for tenants on its single-site property, so there's a lot of small adjustments being made on a daily basis.</p> <p>I am thinking it would be helpful to write him a winform app to manage the 32 Cisco devices, on-site. I'd like to initially provide functionality which could modify access control lists, port VLAN assignments, and bandwidth limitations per VLAN... adding more to the list as its deemed valuable.</p> <p><strong>My initial thought was to emulate a telnet session</strong> with the network device; utilizing my network-engineer's familiarity with the command-line / IOS interaction. Minimal time would be required to learn Cisco IOS conventions, myself.</p> <p><strong>Though while searching for solutions, it appears that most people favor SNMP.</strong> That, or, their specific circumstances pushed them in the direction of SNMP.</p> <p>I wanted to know if I've overlooked an obvious benefit of SNMP. <strong>Should I be using SNMP? Why or why not?</strong></p>
[ { "answer_id": 2582997, "author": "Noah Gift", "author_id": 309746, "author_profile": "https://Stackoverflow.com/users/309746", "pm_score": 2, "selected": false, "text": "expect" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18213/" ]
234,723
<p>I would like to redirect <code>www.example.com</code> to <code>example.com</code>. The following htaccess code makes this happen:</p> <pre><code>RewriteCond %{HTTP_HOST} ^www\.example\.com [NC] RewriteRule ^(.*)$ http://example.com/$1 [L,R=301] </code></pre> <p>But, is there a way to do this in a generic fashion without hardcoding the domain name?</p>
[ { "answer_id": 234745, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 3, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteRule ^(.*)$ %{HTTP_HOST}$1 [C]\nRewriteRule ^www\\.(.*)$ http://$1 [L,R=301]\n" }, { "answer_id": 235064, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 4, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^/(.*)$ https://%1/$1 [R]\n RewriteCond HTTP_HOST www. %1 RewriteRule / $1" }, { "answer_id": 1270281, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 11, "selected": true, "text": "RewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://%1/$1 [R=301,L]\n" }, { "answer_id": 2475982, "author": "Andron", "author_id": 284602, "author_profile": "https://Stackoverflow.com/users/284602", "pm_score": 7, "selected": false, "text": "RewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://%1/$1 [R=301,L]\n" }, { "answer_id": 4715215, "author": "Htaccess Redirect", "author_id": 578750, "author_profile": "https://Stackoverflow.com/users/578750", "pm_score": 3, "selected": false, "text": "RewriteEngine On\n\nRewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\n\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L] \n" }, { "answer_id": 5145927, "author": "sulfy", "author_id": 638181, "author_profile": "https://Stackoverflow.com/users/638181", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^site\\.ro\nRewriteRule (.*) http://www.site.ro/$1 [R=301,L]\n" }, { "answer_id": 5254797, "author": "William Denniss", "author_id": 72176, "author_profile": "https://Stackoverflow.com/users/72176", "pm_score": 6, "selected": false, "text": "<VirtualHost *>\n ServerName www.example.com\n Redirect 301 / http://example.com/\n</VirtualHost>\n" }, { "answer_id": 5262044, "author": "Dmytro", "author_id": 541961, "author_profile": "https://Stackoverflow.com/users/541961", "pm_score": 6, "selected": false, "text": "RewriteCond %{HTTPS} off\nRewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://www.%{HTTP_HOST}/$1 [R=301,L]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{HTTP_HOST} !^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ https://www.%{HTTP_HOST}/$1 [R=301,L]\n" }, { "answer_id": 7822978, "author": "pelajar", "author_id": 908647, "author_profile": "https://Stackoverflow.com/users/908647", "pm_score": 2, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/subfolder/$1 [R=301,L]\n" }, { "answer_id": 8538284, "author": "local", "author_id": 1028069, "author_profile": "https://Stackoverflow.com/users/1028069", "pm_score": 0, "selected": false, "text": "# non-www.* -> www.*, if subdomain exist, wont work\nRewriteCond %{HTTP_HOST} ^whattimein\\.com\nRewriteRule ^(.*)$ http://www.whattimein.com/$1 [R=permanent,L]\n" }, { "answer_id": 10362615, "author": "Salman A", "author_id": 87015, "author_profile": "https://Stackoverflow.com/users/87015", "pm_score": 5, "selected": false, "text": "#########################\n# redirect www to no-www\n#########################\n\nRewriteCond %{HTTP_HOST} ^www\\.(.+) [NC]\nRewriteRule ^(.*) http://%1/$1 [R=301,NE,L]\n #########################\n# redirect no-www to www\n#########################\n\nRewriteCond %{HTTP_HOST} ^(?!www\\.)(.+) [NC]\nRewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]\n NE http://www.example.com/?foo%20bar http://www.example.com/?foo%2250bar" }, { "answer_id": 10698176, "author": "Luke", "author_id": 1409662, "author_profile": "https://Stackoverflow.com/users/1409662", "pm_score": 2, "selected": false, "text": "############################################\n## always send 404 on missing files in these folders\n\n RewriteCond %{REQUEST_URI} !^/(media|skin|js)/\n\n############################################\n## never rewrite for existing files, directories and links\n\n RewriteCond %{REQUEST_FILENAME} !-f\n RewriteCond %{REQUEST_FILENAME} !-d\n RewriteCond %{REQUEST_FILENAME} !-l\n\n############################################\n## rewrite everything else to index.php\n\n RewriteRule .* index.php [L]\n" }, { "answer_id": 25672535, "author": "Rick", "author_id": 1827424, "author_profile": "https://Stackoverflow.com/users/1827424", "pm_score": 2, "selected": false, "text": "RewriteCond %{HTTP_HOST} ^www\\.(.+)$ [NC]\nRewriteRule ^ http%{ENV:protossl}://%1%{REQUEST_URI} [L,R=301]\n /site/location/.htaccess \n" }, { "answer_id": 28831108, "author": "Rajith Ramachandran", "author_id": 2881568, "author_profile": "https://Stackoverflow.com/users/2881568", "pm_score": 2, "selected": false, "text": "RewriteEngine on\n\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n\nRewriteCond %{HTTPS} !on\nRewriteRule (.*) https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n" }, { "answer_id": 30052977, "author": "Chirag Parekh", "author_id": 2389637, "author_profile": "https://Stackoverflow.com/users/2389637", "pm_score": -1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^example.com\nRewriteRule (.*) http://www.example.com/$1 [R=301,L]\n" }, { "answer_id": 35297464, "author": "Gregor Macgregor", "author_id": 5711788, "author_profile": "https://Stackoverflow.com/users/5711788", "pm_score": 3, "selected": false, "text": "RewriteEngine On\nRewriteBase /\n\n# Force WWW. when no subdomain in host\nRewriteCond %{HTTP_HOST} ^[^.]+\\.[^.]+$ [NC]\nRewriteCond %{HTTPS}s ^on(s)|off [NC]\nRewriteRule ^ http%1://www.%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n\n# Remove WWW. when subdomain(s) in host \nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteCond %{HTTPS}s ^on(s)|off [NC]\nRewriteCond http%1://%{HTTP_HOST} ^(https?://)(www\\.)(.+\\.)(.+\\.)(.+)$ [NC]\nRewriteRule ^ %1%3%4%5%{REQUEST_URI} [R=301,L]\n" }, { "answer_id": 37055252, "author": "William Entriken", "author_id": 300224, "author_profile": "https://Stackoverflow.com/users/300224", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteBase /\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$\nRewriteRule ^(.*)$ http://%1/$1 [R=301,L]\n [NC]" }, { "answer_id": 38289947, "author": "Amit Verma", "author_id": 3160747, "author_profile": "https://Stackoverflow.com/users/3160747", "pm_score": 2, "selected": false, "text": "RewriteEngine on\n# if host value starts with \"www.\"\nRewriteCond %{HTTP_HOST} ^www\\.\n# redirect the request to \"non-www\"\nRewriteRule ^ http://example.com%{REQUEST_URI} [NE,L,R]\n www http https RewriteEngine on\nRewriteCond %{HTTP_HOST} ^www\\.\nRewriteCond %{HTTPS}s ^on(s)|offs\nRewriteRule ^ http%1://example.com%{REQUEST_URI} [NE,L,R]\n 2.4.* Redirect if <if \"%{HTTP_HOST} =='www.example.com'\">\nRedirect / http://example.com/\n</if>\n" }, { "answer_id": 41662722, "author": "luky", "author_id": 4870273, "author_profile": "https://Stackoverflow.com/users/4870273", "pm_score": 1, "selected": false, "text": "RewriteEngine On\nRewriteCond %{HTTP_HOST} ^www\\.(.*)$ [NC]\nRewriteRule ^(.*)$ http://%1%{REQUEST_URI} [L,R=301]\n" }, { "answer_id": 45453201, "author": "Universal Omega", "author_id": 7039493, "author_profile": "https://Stackoverflow.com/users/7039493", "pm_score": 2, "selected": false, "text": "// similar behavior as an HTTP redirect\nwindow.location.replace(\"http://www.stackoverflow.com\");\n// similar behavior as clicking on a link\nwindow.location.href = \"http://stackoverflow.com\";\n RewriteEngine On\nRewriteBase /\nRewritecond %{HTTP_HOST} ^www\\.yoursite\\.com$ [NC]\nRewriteRule ^(.*)$ https://yoursite.com/$1 [R=301,L]\n $protocol = (@$_SERVER[\"HTTPS\"] == \"on\") ? \"https://\" : \"http://\";\n\nif (substr($_SERVER['HTTP_HOST'], 0, 4) !== 'www.') {\n header('Location: '.$protocol.'www.'.$_SERVER ['HTTP_HOST'].'/'.$_SERVER['REQUEST_URI']);\n exit;\n}\n $.ajax({\n type: \"POST\",\n url: reqUrl,\n data: reqBody,\n dataType: \"json\",\n success: function(data, textStatus) {\n if (data.redirect) {\n // data.redirect contains the string URL to redirect to\n window.location.href = data.redirect;\n }\n else {\n // data.form contains the HTML for the replacement form\n $(\"#myform\").replaceWith(data.form);\n }\n }\n});\n" }, { "answer_id": 55741915, "author": "Rohallah Hatami", "author_id": 6901246, "author_profile": "https://Stackoverflow.com/users/6901246", "pm_score": 2, "selected": false, "text": "<IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{HTTP_HOST} ^domain\\.tld [NC]\n RewriteRule ^(.*)$ http://www.domain.tld/$1 [L,R=301]\n</IfModule>\n <IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteCond %{HTTP_HOST} ^www\\.domain\\.tld [NC]\n RewriteRule ^(.*)$ http://domain.tld/$1 [L,R=301]\n</IfModule>\n" }, { "answer_id": 58458780, "author": "Bobík", "author_id": 1594000, "author_profile": "https://Stackoverflow.com/users/1594000", "pm_score": 1, "selected": false, "text": "CNAME r.simpleredirect.net\nA 89.221.218.22\n" }, { "answer_id": 59319072, "author": "Jeaf Gilbert", "author_id": 351564, "author_profile": "https://Stackoverflow.com/users/351564", "pm_score": 0, "selected": false, "text": "RewriteEngine On\n\nRewriteBase /\nRewriteCond %{HTTP_HOST} !localhost [NC]\nRewriteCond %{HTTPS} off [OR]\nRewriteCond %{HTTP_HOST} ^www\\. [NC]\nRewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21473/" ]
234,724
<p>Is it possible to serialize and deserialize a class in C++?</p> <p>I've been using Java for 3 years now, and serialization / deserialization is fairly trivial in that language. Does C++ have similar features? Are there native libraries that handle serialization?</p> <p>An example would be helpful.</p>
[ { "answer_id": 234740, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 8, "selected": true, "text": "Boost::serialization Boost::serialization operator<< operator>>" }, { "answer_id": 234846, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 4, "selected": false, "text": "<< >> << iostream >>" }, { "answer_id": 6235167, "author": "Dave", "author_id": 783683, "author_profile": "https://Stackoverflow.com/users/783683", "pm_score": 2, "selected": false, "text": " //Create a new AMEF object\n AMEFObject *object = new AMEFObject();\n\n //Add a child string object\n object->addPacket(\"This is the Automated Message Exchange Format Object property!!\",\"adasd\"); \n\n //Add a child integer object\n object->addPacket(21213);\n\n //Add a child boolean object\n object->addPacket(true);\n\n AMEFObject *object2 = new AMEFObject();\n string j = \"This is the property of a nested Automated Message Exchange Format Object\";\n object2->addPacket(j);\n object2->addPacket(134123);\n object2->addPacket(false);\n\n //Add a child character object\n object2->addPacket('d');\n\n //Add a child AMEF Object\n object->addPacket(object2);\n\n //Encode the AMEF obejct\n string str = new AMEFEncoder()->encode(object,false);\n string arr = amef encoded byte array value;\n AMEFDecoder decoder = new AMEFDecoder()\n AMEFObject object1 = AMEFDecoder.decode(arr,true);\n" }, { "answer_id": 22122547, "author": "Azoth", "author_id": 710791, "author_profile": "https://Stackoverflow.com/users/710791", "pm_score": 6, "selected": false, "text": "c++ serialization" }, { "answer_id": 48024116, "author": "streaver91", "author_id": 2189264, "author_profile": "https://Stackoverflow.com/users/2189264", "pm_score": 1, "selected": false, "text": "std::vector<int> data({22, 333, -4444});\nstd::string serialized = hps::serialize_to_string(data);\nauto parsed = hps::parse_from_string<std::vector<int>>(serialized);\n" }, { "answer_id": 57830053, "author": "Goblinhack", "author_id": 3437661, "author_profile": "https://Stackoverflow.com/users/3437661", "pm_score": 0, "selected": false, "text": "#include \"c_plus_plus_serializer.h\"\n\nclass Custom {\npublic:\n int a;\n std::string b;\n std::vector c;\n\n friend std::ostream& operator<<(std::ostream &out, \n Bits my)\n {\n out << bits(my.t.a) << bits(my.t.b) << bits(my.t.c);\n return (out);\n }\n\n friend std::istream& operator>>(std::istream &in, \n Bits my)\n {\n in >> bits(my.t.a) >> bits(my.t.b) >> bits(my.t.c);\n return (in);\n }\n\n friend std::ostream& operator<<(std::ostream &out, \n class Custom &my)\n {\n out << \"a:\" << my.a << \" b:\" << my.b;\n\n out << \" c:[\" << my.c.size() << \" elems]:\";\n for (auto v : my.c) {\n out << v << \" \";\n }\n out << std::endl;\n\n return (out);\n }\n};\n\nstatic void save_map_key_string_value_custom (const std::string filename)\n{\n std::cout << \"save to \" << filename << std::endl;\n std::ofstream out(filename, std::ios::binary );\n\n std::map< std::string, class Custom > m;\n\n auto c1 = Custom();\n c1.a = 1;\n c1.b = \"hello\";\n std::initializer_list L1 = {\"vec-elem1\", \"vec-elem2\"};\n std::vector l1(L1);\n c1.c = l1;\n\n auto c2 = Custom();\n c2.a = 2;\n c2.b = \"there\";\n std::initializer_list L2 = {\"vec-elem3\", \"vec-elem4\"};\n std::vector l2(L2);\n c2.c = l2;\n\n m.insert(std::make_pair(std::string(\"key1\"), c1));\n m.insert(std::make_pair(std::string(\"key2\"), c2));\n\n out << bits(m);\n}\n\nstatic void load_map_key_string_value_custom (const std::string filename)\n{\n std::cout << \"read from \" << filename << std::endl;\n std::ifstream in(filename);\n\n std::map< std::string, class Custom > m;\n\n in >> bits(m);\n std::cout << std::endl;\n\n std::cout << \"m = \" << m.size() << \" list-elems { \" << std::endl;\n for (auto i : m) {\n std::cout << \" [\" << i.first << \"] = \" << i.second;\n }\n std::cout << \"}\" << std::endl;\n}\n\nvoid map_custom_class_example (void)\n{\n std::cout << \"map key string, value class\" << std::endl;\n std::cout << \"============================\" << std::endl;\n save_map_key_string_value_custom(std::string(\"map_of_custom_class.bin\"));\n load_map_key_string_value_custom(std::string(\"map_of_custom_class.bin\"));\n std::cout << std::endl;\n}\n map key string, value class\n============================\nsave to map_of_custom_class.bin\nread from map_of_custom_class.bin\n\nm = 2 list-elems {\n [key1] = a:1 b:hello c:[2 elems]:vec-elem1 vec-elem2\n [key2] = a:2 b:there c:[2 elems]:vec-elem3 vec-elem4\n}\n" }, { "answer_id": 58301738, "author": "Calmarius", "author_id": 58805, "author_profile": "https://Stackoverflow.com/users/58805", "pm_score": 1, "selected": false, "text": "template <class T, class Mode = void> struct Serializer\n{\n template <class OutputCharIterator>\n static void serializeImpl(const T &object, OutputCharIterator &&it)\n {\n object.template serializeThis<Mode>(it);\n }\n\n template <class InputCharIterator>\n static T deserializeImpl(InputCharIterator &&it, InputCharIterator &&end)\n {\n return T::template deserializeFrom<Mode>(it, end);\n }\n};\n\ntemplate <class Mode = void, class T, class OutputCharIterator>\nvoid serialize(const T &object, OutputCharIterator &&it)\n{\n Serializer<T, Mode>::serializeImpl(object, it);\n}\n\ntemplate <class T, class Mode = void, class InputCharIterator>\nT deserialize(InputCharIterator &&it, InputCharIterator &&end)\n{\n return Serializer<T, Mode>::deserializeImpl(it, end);\n}\n\ntemplate <class Mode = void, class T, class InputCharIterator>\nvoid deserialize(T &result, InputCharIterator &&it, InputCharIterator &&end)\n{\n result = Serializer<T, Mode>::deserializeImpl(it, end);\n}\n T Mode Serializer Serializer struct LittleEndianMode\n{\n};\n\ntemplate <class T>\nstruct Serializer<\n T, std::enable_if_t<std::is_unsigned<T>::value, LittleEndianMode>>\n{\n template <class InputCharIterator>\n static T deserializeImpl(InputCharIterator &&it, InputCharIterator &&end)\n {\n T res = 0;\n\n for (size_t i = 0; i < sizeof(T); i++)\n {\n if (it == end) break;\n res |= static_cast<T>(*it) << (CHAR_BIT * i);\n it++;\n }\n\n return res;\n }\n\n template <class OutputCharIterator>\n static void serializeImpl(T number, OutputCharIterator &&it)\n {\n for (size_t i = 0; i < sizeof(T); i++)\n {\n *it = (number >> (CHAR_BIT * i)) & 0xFF;\n it++;\n }\n }\n};\n std::vector<char> serialized;\nuint32_t val = 42;\nserialize<LittleEndianMode>(val, std::back_inserter(serialized));\n uint32_t val;\ndeserialize(val, serialized.begin(), serialized.end());\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234724", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24639/" ]
234,742
<p>In <code>tcsh</code>, I have the following script working:</p> <pre><code>#!/bin/tcsh setenv X_ROOT /some/specified/path setenv XDB ${X_ROOT}/db setenv PATH ${X_ROOT}/bin:${PATH} xrun -d xdb1 -i $1 &gt; $2 </code></pre> <p>What is the equivalent to the <code>tcsh setenv</code> function in Bash? </p> <p>Is there a direct analog? The environment variables are for locating the executable.</p>
[ { "answer_id": 234753, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 3, "selected": false, "text": "export export VARIABLE=value\n" }, { "answer_id": 234756, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 8, "selected": true, "text": "export VAR=value export VAR='my val' export VAR=\"$MY_OTHER_VAR\"" }, { "answer_id": 234828, "author": "iny", "author_id": 27067, "author_profile": "https://Stackoverflow.com/users/27067", "pm_score": 4, "selected": false, "text": "VAR=value export VAR export VAR=value" }, { "answer_id": 235368, "author": "zaphod", "author_id": 13871, "author_profile": "https://Stackoverflow.com/users/13871", "pm_score": 5, "selected": false, "text": "VAR=value\nexport VAR\n export VAR=value\n bash" }, { "answer_id": 25408907, "author": "Eric Leschinski", "author_id": 445131, "author_profile": "https://Stackoverflow.com/users/445131", "pm_score": 5, "selected": false, "text": "el@server /home/el $ set | grep LOL\nel@server /home/el $\nel@server /home/el $ env | grep LOL\nel@server /home/el $\n el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ env | grep LOL\nel@server /home/el $\n exec bash el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ exec bash\nel@server /home/el $ set | grep LOL\nel@server /home/el $\n el@server /home/el $ LOL=\"so wow much code\"\nel@server /home/el $ set | grep LOL\nLOL='so wow much code'\nel@server /home/el $ unset LOL\nel@server /home/el $ set | grep LOL\nel@server /home/el $\n el@server /home/el $ DOGE=\"such variable\"\nel@server /home/el $ export DOGE\nel@server /home/el $ set | grep DOGE\nDOGE='such variable'\nel@server /home/el $ env | grep DOGE\nDOGE=such variable\n el@server /home/el $ exec bash\nel@server /home/el $ env | grep DOGE\nDOGE=such variable\nel@server /home/el $ set | grep DOGE\nDOGE='such variable'\n el@server /home/el $ export CAN=\"chuck norris\"\nel@server /home/el $ env | grep CAN\nCAN=chuck norris\nel@server /home/el $ set | grep CAN\nCAN='chuck norris'\nel@server /home/el $ env -i bash\nel@server /home/el $ set | grep CAN\nel@server /home/el $ env | grep CAN\n el@server /home/el $ export FOO=\"bar\"\nel@server /home/el $ env | grep FOO\nFOO=bar\nel@server /home/el $ unset FOO\nel@server /home/el $ env | grep FOO\nel@server /home/el $\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
234,774
<p>Is there an easy way to display a messagebox in VB.NET with custom button captions? I came across <em><a href="https://stackoverflow.com/questions/77293/what-is-an-easy-way-to-create-a-messagebox-with-custom-button-text-in-managed-c">What is an easy way to create a MessageBox with custom button text in Managed C++?</a></em>, in the Stack Overflow archives, but it's for <a href="http://en.wikipedia.org/wiki/Managed_Extensions_for_C%2B%2B" rel="noreferrer">Managed C++</a>.</p>
[ { "answer_id": 234835, "author": "BradC", "author_id": 21398, "author_profile": "https://Stackoverflow.com/users/21398", "pm_score": 4, "selected": false, "text": "FormBorderType = FixedDialog Me.AcceptButton = OKButton\n Me.CancelButton = CancelButton\n Me.FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog\n Me.HelpButton = True\n Me.MaximizeBox = False\n Me.MinimizeBox = False\n Me.ShowInTaskbar = False\n Me.ShowIcon = False\n Me.StartPosition = FormStartPosition.CenterParent\n" }, { "answer_id": 235497, "author": "Hans Passant", "author_id": 17034, "author_profile": "https://Stackoverflow.com/users/17034", "pm_score": 5, "selected": false, "text": "Nobugz.PatchMsgBox(New String() {\"Da\", \"Njet\"})\nMsgBox(\"gack\", MsgBoxStyle.YesNo)\n Imports System.Text\nImports System.Runtime.InteropServices\n\nPublic Class Nobugz\n Private Shared mLabels() As String '' Desired new labels\n Private Shared mLabelIndex As Integer '' Next caption to update\n\n Public Shared Sub PatchMsgBox(ByVal labels() As String)\n ''--- Updates message box buttons\n mLabels = labels\n Application.OpenForms(0).BeginInvoke(New FindWindowDelegate(AddressOf FindMsgBox), GetCurrentThreadId())\n End Sub\n\n Private Shared Sub FindMsgBox(ByVal tid As Integer)\n ''--- Enumerate the windows owned by the UI thread\n EnumThreadWindows(tid, AddressOf EnumWindow, IntPtr.Zero)\n End Sub\n\n Private Shared Function EnumWindow(ByVal hWnd As IntPtr, ByVal lp As IntPtr) As Boolean\n ''--- Is this the message box?\n Dim sb As New StringBuilder(256)\n GetClassName(hWnd, sb, sb.Capacity)\n If sb.ToString() <> \"#32770\" Then Return True\n ''--- Got it, now find the buttons\n mLabelIndex = 0\n EnumChildWindows(hWnd, AddressOf FindButtons, IntPtr.Zero)\n Return False\n End Function\n\n Private Shared Function FindButtons(ByVal hWnd As IntPtr, ByVal lp As IntPtr) As Boolean\n Dim sb As New StringBuilder(256)\n GetClassName(hWnd, sb, sb.Capacity)\n If sb.ToString() = \"Button\" And mLabelIndex <= UBound(mLabels) Then\n ''--- Got one, update text\n SetWindowText(hWnd, mLabels(mLabelIndex))\n mLabelIndex += 1\n End If\n Return True\n End Function\n\n ''--- P/Invoke declarations\n Private Delegate Sub FindWindowDelegate(ByVal tid As Integer)\n Private Delegate Function EnumWindowDelegate(ByVal hWnd As IntPtr, ByVal lp As IntPtr) As Boolean\n Private Declare Auto Function EnumThreadWindows Lib \"user32.dll\" (ByVal tid As Integer, ByVal callback As EnumWindowDelegate, ByVal lp As IntPtr) As Boolean\n Private Declare Auto Function EnumChildWindows Lib \"user32.dll\" (ByVal hWnd As IntPtr, ByVal callback As EnumWindowDelegate, ByVal lp As IntPtr) As Boolean\n Private Declare Auto Function GetClassName Lib \"user32.dll\" (ByVal hWnd As IntPtr, ByVal name As StringBuilder, ByVal maxlen As Integer) As Integer\n Private Declare Auto Function GetCurrentThreadId Lib \"kernel32.dll\" () As Integer\n Private Declare Auto Function SetWindowText Lib \"user32.dll\" (ByVal hWnd As IntPtr, ByVal text As String) As Boolean\nEnd Class\n" }, { "answer_id": 4507391, "author": "Tassaduq", "author_id": 550959, "author_profile": "https://Stackoverflow.com/users/550959", "pm_score": 1, "selected": false, "text": " private void DGroup_Click(object sender, EventArgs e)\n {\n messageBox m = new messageBox();\n m.ShowDialog();\n if (m.DialogResult == DialogResult.Yes)\n {\n //del(groups.php?opt=del&amp;id=613','asdasd');\n String[] asd = new String[2];\n asd[0] = \"groups.php?opt=del&amp;id=613\";\n asd[1] = \"asdasd\";\n addgroup.Document.InvokeScript(\"del\",asd);\n }\n else\n if (m.DialogResult == DialogResult.No)\n {\n MessageBox.Show(\"App won´t close\");\n }\n }\n private void deleteGroupOnly_Click(object sender, EventArgs e)\n {\n this.DialogResult = DialogResult.Yes;\n this.Close();\n }\n\n private void deleteAll_Click(object sender, EventArgs e)\n {\n this.DialogResult = DialogResult.No;\n this.Close();\n }\n\n private void cancel_Click(object sender, EventArgs e)\n {\n this.DialogResult = DialogResult.Cancel;\n this.Close();\n }\n" }, { "answer_id": 7430160, "author": "Dan Nolan", "author_id": 266882, "author_profile": "https://Stackoverflow.com/users/266882", "pm_score": 0, "selected": false, "text": " [DllImport(\"kernel32.dll\")]\n static extern uint GetCurrentThreadId();\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern int CallNextHookEx(int idHook, int nCode, IntPtr wParam, IntPtr lParam);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern bool UnhookWindowsHookEx(int idHook);\n\n [DllImport(\"user32.dll\", CharSet = CharSet.Auto)]\n private static extern int SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hInstance, int threadId);\n\n [DllImport(\"user32.dll\")]\n private static extern bool SetDlgItemText(IntPtr hWnd, int nIDDlgItem, string lpString);\n\n delegate int HookProc(int nCode, IntPtr wParam, IntPtr lParam);\n\n static HookProc dlgHookProc;\n\n private const long WH_CBT = 5;\n private const long HCBT_ACTIVATE = 5;\n\n private const int ID_BUT_OK = 1;\n private const int ID_BUT_CANCEL = 2;\n private const int ID_BUT_ABORT = 3;\n private const int ID_BUT_RETRY = 4;\n private const int ID_BUT_IGNORE = 5;\n private const int ID_BUT_YES = 6;\n private const int ID_BUT_NO = 7;\n\n private const string BUT_OK = \"Save\";\n private const string BUT_CANCEL = \"Cancel\";\n private const string BUT_ABORT = \"Stop\";\n private const string BUT_RETRY = \"Continue\";\n private const string BUT_IGNORE = \"Ignore\";\n private const string BUT_YES = \"Yeeh\";\n private const string BUT_NO = \"Never\";\n\n private static int _hook = 0;\n\n private static int DialogHookProc(int nCode, IntPtr wParam, IntPtr lParam)\n {\n if (nCode < 0)\n {\n return CallNextHookEx(_hook, nCode, wParam, lParam);\n }\n\n if (nCode == HCBT_ACTIVATE)\n {\n SetDlgItemText(wParam, ID_BUT_OK, BUT_OK);\n SetDlgItemText(wParam, ID_BUT_CANCEL, BUT_CANCEL);\n SetDlgItemText(wParam, ID_BUT_ABORT, BUT_ABORT);\n SetDlgItemText(wParam, ID_BUT_RETRY, BUT_RETRY);\n SetDlgItemText(wParam, ID_BUT_IGNORE, BUT_IGNORE);\n SetDlgItemText(wParam, ID_BUT_YES, BUT_YES);\n SetDlgItemText(wParam, ID_BUT_NO, BUT_NO);\n }\n\n return CallNextHookEx(_hook, nCode, wParam, lParam);\n }\n\n private void Button_Click(object sender, EventArgs e)\n {\n dlgHookProc = new HookProc(DialogHookProc);\n\n _hook = SetWindowsHookEx((int)WH_CBT, dlgHookProc, (IntPtr)0, (int)GetCurrentThreadId());\n\n DialogResult dlgEmptyCheck = MessageBox.Show(\"Text\", \"Caption\", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button3);\n\n if (dlgEmptyCheck == DialogResult.Abort)\n {\n\n }\n\n UnhookWindowsHookEx(_hook);\n }\n" }, { "answer_id": 35298370, "author": "Miguel Yskatll", "author_id": 5494500, "author_profile": "https://Stackoverflow.com/users/5494500", "pm_score": 2, "selected": false, "text": "<DllImport(\"kernel32.dll\")> _\nPrivate Shared Function GetCurrentThreadId() As UInteger\nEnd Function\n\n<DllImport(\"user32.dll\", CharSet:=CharSet.Auto)> _\nPrivate Shared Function CallNextHookEx(ByVal idHook As Integer, ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer\nEnd Function\n\n<DllImport(\"user32.dll\", CharSet:=CharSet.Auto)> _\nPrivate Shared Function UnhookWindowsHookEx(ByVal idHook As Integer) As Boolean\nEnd Function\n\n<DllImport(\"user32.dll\", CharSet:=CharSet.Auto)> _\nPrivate Shared Function SetWindowsHookEx(ByVal idHook As Integer, ByVal lpfn As HookProc, ByVal hInstance As IntPtr, ByVal threadId As Integer) As Integer\nEnd Function\n\n<DllImport(\"user32.dll\")> _\nPrivate Shared Function SetDlgItemText(ByVal hWnd As IntPtr, ByVal nIDDlgItem As Integer, ByVal lpString As String) As Boolean\nEnd Function\n\nPrivate Delegate Function HookProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer\n\nShared dlgHookProc As HookProc\n\nPrivate Const WH_CBT As Long = 5\nPrivate Const HCBT_ACTIVATE As Long = 5\n\nPrivate Const ID_BUT_OK As Integer = 1\nPrivate Const ID_BUT_CANCEL As Integer = 2\nPrivate Const ID_BUT_ABORT As Integer = 3\nPrivate Const ID_BUT_RETRY As Integer = 4\nPrivate Const ID_BUT_IGNORE As Integer = 5\nPrivate Const ID_BUT_YES As Integer = 6\nPrivate Const ID_BUT_NO As Integer = 7\n\nPrivate Const BUT_OK As String = \"Save\"\nPrivate Const BUT_CANCEL As String = \"Cancelar\"\nPrivate Const BUT_ABORT As String = \"Stop\"\nPrivate Const BUT_RETRY As String = \"Continue\"\nPrivate Const BUT_IGNORE As String = \"Ignore\"\nPrivate Const BUT_YES As String = \"Si\"\nPrivate Const BUT_NO As String = \"No\"\n\nPrivate Shared _hook As Integer = 0\n\nPrivate Shared Function DialogHookProc(ByVal nCode As Integer, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As Integer\n If nCode < 0 Then\n Return CallNextHookEx(_hook, nCode, wParam, lParam)\n End If\n\n If nCode = HCBT_ACTIVATE Then\n SetDlgItemText(wParam, ID_BUT_OK, BUT_OK)\n SetDlgItemText(wParam, ID_BUT_CANCEL, BUT_CANCEL)\n SetDlgItemText(wParam, ID_BUT_ABORT, BUT_ABORT)\n SetDlgItemText(wParam, ID_BUT_RETRY, BUT_RETRY)\n SetDlgItemText(wParam, ID_BUT_IGNORE, BUT_IGNORE)\n SetDlgItemText(wParam, ID_BUT_YES, BUT_YES)\n SetDlgItemText(wParam, ID_BUT_NO, BUT_NO)\n End If\n\n Return CallNextHookEx(_hook, nCode, wParam, lParam)\nEnd Function\n\nPrivate Sub btn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn.Click\n dlgHookProc = New HookProc(AddressOf DialogHookProc)\n\n _hook = SetWindowsHookEx(CInt(WH_CBT), dlgHookProc, IntPtr.op_Explicit(0), CInt(GetCurrentThreadId()))\n\n Dim dlgEmptyCheck As DialogResult = MessageBox.Show(\"Text\", \"Caption\", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button3)\n\n\n If dlgEmptyCheck = DialogResult.Abort Then\n End If\n\n UnhookWindowsHookEx(_hook)\nEnd Sub\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30415/" ]
234,785
<p>The situation is as follows: I've got 2 models: 'Action' and 'User'. These models refer to the tables 'actions' and 'users', respectively.</p> <p>My action table contains a column <code>user_id</code>. At this moment, I need an overview of all actions, and the users to which they are assigned to. When i use <code>$action-&gt;fetchAll()</code>, I only have the user ID, so I want to be able to join the data from the user model, preferably without making a call to <code>findDependentRowset()</code>.</p> <p>I thought about creating custom <code>fetchAll()</code>, <code>fetchRow()</code> and <code>find()</code> methods in my model, but this would break default behaviour.</p> <p>What is the best way to solve this issue? Any help would be greatly appreciated.</p>
[ { "answer_id": 235267, "author": "Peter Bailey", "author_id": 8815, "author_profile": "https://Stackoverflow.com/users/8815", "pm_score": 2, "selected": false, "text": "CREATE OR REPLACE VIEW VwAction AS\nSELECT [columns]\n FROM action\n LEFT JOIN user\n ON user.id = action.user_id\n $vwAction->fetchAll();\n" }, { "answer_id": 237323, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 5, "selected": true, "text": "findDependentRowset() findParentRow() $actionTable = new Action();\n$actionRowset = $actionTable->fetchAll();\nforeach ($actionRowset as $actionRow) {\n $userRow = $actionRow->findParentRow('User');\n}\n save() $actionTable = new Action();\n$actionQuery = $actionTable->select()\n ->setIntegrityCheck(false) // allows joins\n ->from($actionTable)\n ->join('user', 'user.id = action.user_id');\n$joinedRowset = $actionTable->fetchAll($actionQuery);\nforeach ($joinedRowset as $joinedRow) {\n print_r($joinedRow->toArray());\n}\n save() action_id action_type user_id user_name\n 1 Buy 1 Bill\n 2 Sell 1 Bill\n 3 Buy 2 Aron\n 4 Sell 2 Aron\n $joinedRow->user_name = 'William';\n$joinedRow->save();\n save() save()" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11568/" ]
234,797
<p>I need to use sed to convert all occurences of <code>##XXX##</code> to <code>${XXX}</code>. X could be any alphabetic character or '_'. I know that I need to use something like:</p> <pre><code>'s/##/\${/g' </code></pre> <p>But of course that won't work properly, as it will convert <code>##FOO##</code> to <code>${FOO${</code></p>
[ { "answer_id": 234806, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 1, "selected": false, "text": "s/##\\([^#]*\\)##/${\\1}/\n" }, { "answer_id": 234818, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 1, "selected": false, "text": "sed 's/##\\([a-zA-Z_][a-zA-Z_][a-zA-Z_]\\)##/${\\1}/'\n \\(...\\) \\1 sed 's/##\\([a-zA-Z_]\\{3\\}\\)##/${\\1}/'\n" }, { "answer_id": 234823, "author": "postfuturist", "author_id": 1892, "author_profile": "https://Stackoverflow.com/users/1892", "pm_score": 5, "selected": true, "text": "'s/##\\([a-zA-Z_]\\+\\)##/${\\1}/g'\n 's/##\\([a-zA-Z_]\\{3\\}\\)##/${\\1}/g'\n" }, { "answer_id": 655312, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "echo '##XXX##' | sed \"s/^##\\([^#]*\\)/##$\\{\\1\\}/g\"\n" }, { "answer_id": 12617668, "author": "Sabarish", "author_id": 1700108, "author_profile": "https://Stackoverflow.com/users/1700108", "pm_score": -1, "selected": false, "text": "sed 's/\\([^a-z]*[^A-Z]*[^0-9]*\\)/(&)/pg\n" }, { "answer_id": 26356786, "author": "NeronLeVelu", "author_id": 2885763, "author_profile": "https://Stackoverflow.com/users/2885763", "pm_score": 1, "selected": false, "text": "echo \"##foo##\" | sed 's/##/${/;s//}/'\n s s// ##" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
234,845
<p>I am looking for a way to change the password of a local user account (local Administrator) on a Windows (XP in this case) machine. I have read the <a href="http://www.codeproject.com/KB/threads/Reset-Administrator-Pass.aspx" rel="noreferrer">CodeProject article</a> about one way to do this, but this just doesn't seem 'clean'. </p> <p>I can see that this is <a href="http://www.microsoft.com/technet/scriptcenter/resources/qanda/oct04/hey1015.mspx" rel="noreferrer">possible to do with WMI</a>, so that might be the answer, but I can't figure out how to use the WinNT WMI namespace with ManagementObject. When I try the following code it throws an "Invalid Parameter" exception.</p> <pre><code>public static void ResetPassword(string computerName, string username, string newPassword){ ManagementObject managementObject = new ManagementObject("WinNT://" + computerName + "/" + username); // Throws Exception object[] newpasswordObj = {newPassword}; managementObject.InvokeMethod("SetPassword", newpasswordObj); } </code></pre> <p>Is there a better way to do this? (I'm using .NET 3.5)</p> <p><strong>Edit:</strong> Thanks Ely for pointing me in the right direction. Here is the code I ended up using:</p> <pre><code>public static void ResetPassword(string computerName, string username, string newPassword) { DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username)); directoryEntry.Invoke("SetPassword", newPassword); } </code></pre>
[ { "answer_id": 235085, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 3, "selected": true, "text": "DirectoryEntry ManagementObject" }, { "answer_id": 238975, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "String myADSPath = \"LDAP://onecity/CN=Users,\n DC=onecity,DC=corp,DC=fabrikam,DC=com\";\n\n// Create an Instance of DirectoryEntry.\nDirectoryEntry myDirectoryEntry = new DirectoryEntry(myADSPath);\nmyDirectoryEntry.Username = UserName;\nmyDirectoryEntry.Password = SecurelyStoredPassword;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234845", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12367/" ]
234,848
<p>I found in MYSQL and apparently other database engines that there is a "greatest" function that can be used like: greatest(1, 2, 3, 4), and it would return 4. I need this, but I am using IBM's DB2. Does anybody know of such an equivalent function, even if it only accepts 2 parameters?</p> <p>I found somewhere that MAX should do it, but it doesn't work... it only works on selecting the MAX of a column.</p> <p>If there is no such function, does anybody have an idea what a stored procedure to do this might look like? (I have no stored procedure experience, so I have no clue what DB2 would be capable of).</p>
[ { "answer_id": 234898, "author": "Dave", "author_id": 21294, "author_profile": "https://Stackoverflow.com/users/21294", "pm_score": 3, "selected": false, "text": " 1\n ---------------\n 8\n\n 1 record(s) selected.\n" }, { "answer_id": 632369, "author": "weiyin", "author_id": 14870, "author_profile": "https://Stackoverflow.com/users/14870", "pm_score": 1, "selected": false, "text": "create function importgenius.max2(x double, y double)\nreturns double\nlanguage sql\ncontains sql\ndeterministic\nno external action\nbegin atomic\n if y is null or x >= y then return x;\n else return y;\n end if;\nend\n" }, { "answer_id": 48660590, "author": "srinath", "author_id": 9326702, "author_profile": "https://Stackoverflow.com/users/9326702", "pm_score": 0, "selected": false, "text": "select * from table1 a,\n(select appno as sub_appno,max(sno) as sub_maxsno from table1 group by appno) as tab2\nwhere a.appno =tab2.sub_appno and a.sno=tab2.sub_maxsno\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
234,849
<p>I am using activemq to pass requests between different processes. In some cases, I have multiple, duplicate message (which are requests) in the queue. I would like to have only one. Is there a way to send a message in a way that it will replace an older message with similar attributes? If there isn't, is there a way to inspect the queue and check for a message with specific attributes (in this case I will not send the new message if an older one exists).</p> <p>Clarrification (based on Dave's answer): I am actually trying to make sure that there aren't any duplicate messages on the queue to reduce the amount of processing that is happening whenever the consumer gets the message. Hence I would like either to replace a message or not even put it on the queue.</p> <p>Thanks.</p>
[ { "answer_id": 239318, "author": "James Strachan", "author_id": 2068211, "author_profile": "https://Stackoverflow.com/users/2068211", "pm_score": 2, "selected": false, "text": "from(\"activemq:queueA\").\n idempotentConsumer(memoryMessageIdRepository(200)).\n header(\"myHeader\").\n to(\"activemq:queueB\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31289/" ]
234,866
<p>I come from a .NET world and I'm new to writting C++. I'm just wondering what are the preferred naming conventions when it comes to naming local variables and struct members.</p> <p>For example, the legacy code that I've inheritted has alot of these:</p> <pre><code>struct MyStruct { TCHAR szMyChar[STRING_SIZE]; bool bMyBool; unsigned long ulMyLong; void* pMyPointer; MyObject** ppMyObjects; } </code></pre> <p>Coming from a C# background I was shocked to see the variables with hungarian notation (I couldn't stop laughing at the pp prefix the first time I saw it).</p> <p>I would much rather name my variables this way instead (although I'm not sure if capitalizing the first letter is a good convention. I've seen other ways (see links below)):</p> <pre><code>struct MyStruct { TCHAR MyChar[STRING_SIZE]; bool MyBool; unsigned long MyLong; void* MyPointer; MyObject** MyObjects; } </code></pre> <p>My question: Is this (the former way) still a preferred way to name variables in C++?</p> <p>References:</p> <p><a href="http://geosoft.no/development/cppstyle.html" rel="noreferrer">http://geosoft.no/development/cppstyle.html</a></p> <p><a href="http://www.syntext.com/books/syntext-cpp-conventions.htm" rel="noreferrer">http://www.syntext.com/books/syntext-cpp-conventions.htm</a></p> <p><a href="http://ootips.org/hungarian-notation.html" rel="noreferrer">http://ootips.org/hungarian-notation.html</a></p> <p>Thanks!</p>
[ { "answer_id": 235397, "author": "peterchen", "author_id": 31317, "author_profile": "https://Stackoverflow.com/users/31317", "pm_score": 4, "selected": false, "text": "int * i = 17;\nint j = ***i;\n float fXmin, fXmax, fXpeak; // x values of range and where y=max\nint iXmin, iXMax, iXpeak; // respective indices in x axis vector\n" }, { "answer_id": 10601138, "author": "bkausbk", "author_id": 575491, "author_profile": "https://Stackoverflow.com/users/575491", "pm_score": 1, "selected": false, "text": "class MyClass : public IMyInterface {\npublic:\n unsigned int PublicMember;\n MyClass() : PublicMember(1), _PrivateMember(0), _ProtectedMember(2) {}\n unsigned int PrivateMember() {\n return _PrivateMember * 1234; // some senseless calculation here\n }\nprotected:\n unsigned int _ProtectedMember;\nprivate:\n unsigned int _PrivateMember;\n};\n// ...\nMyClass My;\nMy.PublicMember = 12345678;\n struct IMyInterface {\n virtual void MyVirtualMethod() = 0;\n};\n struct IMyInterfaceAsAbstract abstract {\n virtual void MyVirtualMethod() = 0;\n virtual void MyImplementedMethod() {}\n unsigned int EvenAnPublicMember;\n};\n" }, { "answer_id": 21226726, "author": "Tho", "author_id": 875775, "author_profile": "https://Stackoverflow.com/users/875775", "pm_score": 2, "selected": false, "text": "string table_name; // OK - uses underscore.\nstring tablename; // OK - all lowercase.\n\nstring tableName; // Bad - mixed case.\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18170/" ]
234,869
<p>I have a winforms application, that why someone clicks on a button I need to open up IE to a specific URL.</p> <p>When someone closes the winforms app, I then need to close IE.</p> <p>Is this possible? If yes, how?</p>
[ { "answer_id": 234904, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "Utilities.Utilities.SendMessage(mTestPanelHandle, WM_COMMAND, WM_CLOSE, 0);\n public const int WM_COMMAND = 0x0112;\npublic const int WM_CLOSE = 0xF060;\n[DllImport(\"user32.dll\", EntryPoint = \"SendMessage\", SetLastError = true,\n CallingConvention = CallingConvention.StdCall)]\npublic static extern int SendMessage(IntPtr hwnd, uint Msg, int wParam, int lParam)\n" }, { "answer_id": 234983, "author": "Inisheer", "author_id": 2982, "author_profile": "https://Stackoverflow.com/users/2982", "pm_score": 0, "selected": false, "text": "Process ieProcess = Process.Start(\"iexplore\", @\"http://www.website.com\");\n\n// Do work, etc\n\nieProcess.Kill();\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
234,871
<p>This is a follow on to this <a href="https://stackoverflow.com/questions/232500/how-to-configure-security-when-calling-wcf-service-from-net-20-client">question</a>. I am trying to avoid using the x509 certificate method as that makes my client installs more complex. If basicHttpBinding is not the only option, where are some samples of other binding methods. </p> <p>My clients are on .Net 2.0, I don't have access to System.ServiceModel namespace as that didn't come out until 3.0.</p> <p>Update: To be clear, clients: .Net 2.0, web service: .net3.5/WCF</p>
[ { "answer_id": 234896, "author": "Toran Billups", "author_id": 2701, "author_profile": "https://Stackoverflow.com/users/2701", "pm_score": 1, "selected": false, "text": "Dim client As WebServiceClient = New WebServiceClient(\"basicHttpWebService\")\nclient.ClientCredentials.UserName.UserName = \"username\"\nclient.ClientCredentials.UserName.Password = \"password\"\n <bindings>\n <basicHttpBinding>\n <binding name=\"basicHttp\">\n <security mode=\"TransportWithMessageCredential\">\n <transport/>\n <message clientCredentialType=\"UserName\"/>\n </security>\n </binding>\n </basicHttpBinding>\n </bindings>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"NorthwindBehavior\">\n <serviceMetadata httpGetEnabled=\"true\"/>\n <serviceAuthorization principalPermissionMode=\"UseAspNetRoles\"/>\n <serviceCredentials>\n <userNameAuthentication userNamePasswordValidationMode=\"MembershipProvider\"/>\n </serviceCredentials>\n </behavior>\n </serviceBehaviors>\n </behaviors>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1865/" ]
234,906
<p>I'm going through MSIL and noticing there are a lot of <a href="http://msdn.microsoft.com/en-us/library/system.reflection.emit.opcodes.nop.aspx" rel="nofollow noreferrer">nop</a> instructions in the MSIL.</p> <p>The MSDN article says they take no action and are used to fill space if the opcode is patched. They're used a lot more in debug builds than release builds.</p> <p>I know that these kinds of statements are used in assembly languages to align later instructions, but why are MSIL nops needed in MSIL?</p> <p>(Editor's note: the accepted answer is about machine-code NOPs, not MSIL/CIL NOPs which the question originally asked about.)</p>
[ { "answer_id": 235825, "author": "Steve Steiner", "author_id": 3892, "author_profile": "https://Stackoverflow.com/users/3892", "pm_score": 4, "selected": false, "text": "nop" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23427/" ]
234,929
<p>I am trying to create a databound WPF GridView whose rows can either be read-only or editable (by double-clicking or through a context menu). I would like for the row to return to a read-only state if any of its editable controls loses focus. The functionality I am looking for is very similar to <a href="http://blogs.msdn.com/atc_avalon_team/archive/2006/03/14/550934.aspx" rel="nofollow noreferrer">this example</a> but with an entire row being editted simultaneously (rather than a single cell). Does anyone know how to implement this?</p>
[ { "answer_id": 72894728, "author": "Hadi", "author_id": 2286867, "author_profile": "https://Stackoverflow.com/users/2286867", "pm_score": 0, "selected": false, "text": "<DataGrid x:Name=\"dataGrid\" Margin=\"0,50,0,0\" CurrentCellChanged=\"dataGrid_CurrentCellChanged\"/>\n public MainWindow()\n{\n InitializeComponent();\n\n List<myDataType>? tmp;\n //Add data\n dataGrid.ItemsSource = tmp;\n}\n\nprivate void dataGrid_CurrentCellChanged(object sender, EventArgs e)\n{\n myDataType tmp = (sender as DataGrid).SelectedItem as myDataType ;\n if (tmp != null)\n {\n //Do your job here\n //tmp has edited data\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/317/" ]
234,930
<p>Here's a quicky question. Which method name makes the most sense for an Objective-C Cocoa application?</p> <pre><code>-(void) doSomethingWithAnimation:(BOOL)animated </code></pre> <p>or:</p> <pre><code>-(void) doSomething:(BOOL)animated </code></pre> <p>or even:</p> <pre><code>-(void) doSomethingAnimated:(BOOL)animated </code></pre>
[ { "answer_id": 235039, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 4, "selected": true, "text": "-(void) doSomethingWithAnimation:(BOOL)animated\n -(void) doSomething:(BOOL)animated\n -(void) doSomethingAnimated:(BOOL)animated\n" }, { "answer_id": 235467, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 0, "selected": false, "text": "-doSomething -doSomethingWithAnimation" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17188/" ]
234,935
<p>I'm having a problem dynamically adding columns to a GridView. I need to change the layout -- i.e. the included columns -- based on the value in a DropDownList. When the user changes the selection in this list, I need to remove all but the first column and dynamically add additional columns based on the selection.</p> <p>I have only one column defined in my markup -- column 0, a template column, in which I declare a Select link and another application specific LinkButton. That column needs to always be there. When the ListBoxSelection is made, I remove all but the first column and then re-add the desired columns (in this sample, I've simplified it to always add a "Title" column). Here is a portion of the code:</p> <pre><code>RemoveVariableColumnsFromGrid(); BoundField b = new BoundField(); b.DataField = "Title"; this.gvPrimaryListView.Columns.Add(b); this.gvPrimaryListView.DataBind(); private void RemoveVariableColumnsFromGrid() { int ColCount = this.gvPrimaryListView.Columns.Count; //Leave column 0 -- our select and view template column while (ColCount &gt; 1) { this.gvPrimaryListView.Columns.RemoveAt(ColCount - 1); --ColCount; } } </code></pre> <p>The first time this code runs through, I see both the static column and the dynamically added "Title" column. However, the next time a selection is made, the first column is generated empty (nothing in it). I see the title column, and I see the first column to its left -- but there's nothing generated within it. In the debugger, I can see that gvPrimaryListView does indeed still have two columns and the first one (index 0) is indeed a template column. In fact, the column even retains it's width which is set as 165px in the markup below (for debugging purposes).</p> <p>Any ideas?</p> <pre><code>&lt;asp:GridView ID="gvPrimaryListView" runat="server" Width="100%" AutoGenerateColumns="false" DataKeyNames="Document_ID" EnableViewState="true" DataSourceID="odsPrimaryDataSource" AllowPaging="true" AllowSorting="true" PageSize="10" OnPageIndexChanging="activeListView_PageIndexChanging" AutoGenerateSelectButton="False" OnSelectedIndexChanged="activeListView_SelectedIndexChanged" Visible="true" OnRowDataBound="CtlDocList_RowDataBound" Font-Size="8pt" Font-Names="Helvetica"&gt; &lt;Columns&gt; &lt;asp:TemplateField ShowHeader="false"&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton EnableTheming="false" ID="CtlSelectDocRowBtn" runat="server" Text="Select" CommandName="Select" CssClass="gridbutton" OnClick="RowSelectBtn_Click" /&gt; &lt;asp:ImageButton EnableTheming="false" ID="DocViewBtn" runat="server" ImageUrl="../../images/ViewDoc3.png" CssClass="gridbutton" CommandName="Select" OnClick="DocViewBtn_Click" /&gt; &lt;/ItemTemplate&gt; &lt;ItemStyle Width="165px" /&gt; &lt;/asp:TemplateField&gt; &lt;/Columns&gt; &lt;EmptyDataTemplate&gt; &lt;asp:Label ID="Label6" runat="server" Text="No rows found." SkinID="LabelHeader"&gt;&lt;/asp:Label&gt; &lt;/EmptyDataTemplate&gt; &lt;/asp:GridView&gt; </code></pre> <hr> <p>Just some additional information.</p> <p>It has nothing to do with the fact that it is the first column but everything to do with the fact that it is a TemplateField. If I put a normal column to the left (in the markup) and shift the TemplateField column to the right, the first column renders fine, and the (now second) TemplateField column disappears.</p> <p>Another strange thing -- the problem doesn't happen the first postback -- OR THE SECOND -- but it starts on the third postback and then continues for subsequent postbacks. I'm stumped.</p>
[ { "answer_id": 250791, "author": "DiningPhilanderer", "author_id": 30934, "author_profile": "https://Stackoverflow.com/users/30934", "pm_score": 3, "selected": false, "text": " private void GridViewProject_AddColumns()\n {\n DataSet dsDataSet = new DataSet();\n TemplateField templateField = null;\n\n try\n {\n StoredProcedure sp = new StoredProcedure(\"ExpenseReportItemType_GetList\", \"INTRANETWEBDB\", Context.User.Identity.Name);\n dsDataSet = sp.GetDataSet();\n\n if (sp.RC != 0 && sp.RC != 3000)\n {\n labelMessage.Text = sp.ErrorMessage;\n }\n\n int iIndex = 0;\n int iCount = dsDataSet.Tables[0].Rows.Count;\n string strCategoryID = \"\";\n string strCategoryName = \"\";\n iStaticColumnCount = GridViewProject.Columns.Count;\n\n // Insert all columns immediatly to the left of the LAST column\n while (iIndex < iCount)\n {\n strCategoryName = dsDataSet.Tables[0].Rows[iIndex][\"CategoryName\"].ToString();\n strCategoryID = dsDataSet.Tables[0].Rows[iIndex][\"CategoryID\"].ToString();\n\n templateField = new TemplateField();\n templateField.HeaderTemplate = new GridViewTemplateExternal(DataControlRowType.Header, strCategoryName, strCategoryID);\n templateField.ItemTemplate = new GridViewTemplateExternal(DataControlRowType.DataRow, strCategoryName, strCategoryID);\n templateField.FooterTemplate = new GridViewTemplateExternal(DataControlRowType.Footer, strCategoryName, strCategoryID);\n\n // Have to decriment iStaticColumnCount to insert dynamic columns BEFORE the edit row\n GridViewProject.Columns.Insert((iIndex + (iStaticColumnCount-1)), templateField);\n iIndex++;\n }\n iFinalColumnCount = GridViewProject.Columns.Count;\n iERPEditColumnIndex = (iFinalColumnCount - 1); // iIndex is zero based, Count is not\n }\n catch (Exception exception)\n {\n labelMessage.Text = exception.Message;\n }\n }\n public class GridViewTemplateExternal : System.Web.UI.ITemplate\n{\n #region Fields\n public DataControlRowType DataRowType;\n private string strCategoryID;\n private string strColumnName;\n #endregion\n\n #region Constructor\n public GridViewTemplateExternal(DataControlRowType type, string ColumnName, string CategoryID)\n {\n DataRowType = type; // Header, DataRow,\n strColumnName = ColumnName; // Header name\n strCategoryID = CategoryID;\n }\n #endregion\n\n #region Methods\n public void InstantiateIn(System.Web.UI.Control container)\n {\n switch (DataRowType)\n {\n case DataControlRowType.Header:\n // build the header for this column\n Label labelHeader = new Label();\n labelHeader.Text = \"<b>\" + strColumnName + \"</b>\";\n // All CheckBoxes \"Look Up\" to the header row for this information\n labelHeader.Attributes[\"ERICategoryID\"] = strCategoryID;\n labelHeader.Style[\"writing-mode\"] = \"tb-rl\";\n labelHeader.Style[\"filter\"] = \"flipv fliph\";\n container.Controls.Add(labelHeader);\n break;\n case DataControlRowType.DataRow:\n CheckBox checkboxAllowedRow = new CheckBox();\n checkboxAllowedRow.Enabled = false;\n checkboxAllowedRow.DataBinding += new EventHandler(this.CheckBox_DataBinding);\n container.Controls.Add(checkboxAllowedRow);\n break;\n case DataControlRowType.Footer:\n // No data handling for the footer addition row\n CheckBox checkboxAllowedFooter = new CheckBox();\n container.Controls.Add(checkboxAllowedFooter);\n break;\n default:\n break;\n }\n }\n public void CheckBox_DataBinding(Object sender, EventArgs e)\n {\n CheckBox checkboxAllowed = (CheckBox)sender;// get the control that raised this event\n GridViewRow row = (GridViewRow)checkboxAllowed.NamingContainer;// get the containing row\n string RawValue = DataBinder.Eval(row.DataItem, strColumnName).ToString();\n if (RawValue.ToUpper() == \"TRUE\")\n {\n checkboxAllowed.Checked = true;\n }\n else\n {\n checkboxAllowed.Checked = false;\n }\n }\n #endregion\n}\n" }, { "answer_id": 9005642, "author": "helper", "author_id": 1169568, "author_profile": "https://Stackoverflow.com/users/1169568", "pm_score": 1, "selected": false, "text": " void Page_PreRenderComplete(object sender, EventArgs e)\n {\n // TemplateField reorder bug: if there is a TemplateField based column (or derived therefrom), GridView may blank out\n // the column (plus possibly others) during any postback, if the user has moved it from its original markup position.\n // This is probably a viewstate bug, as it happens only if a TemplateField based column has been moved. The workaround is\n // to force a databind before each response. See https://connect.microsoft.com/VisualStudio/feedback/details/104994/templatefield-in-a-gridview-doesnt-have-its-viewstate-restored-when-boundfields-are-inserted\n //\n // This problem is also happening for grid views inside a TabPanel, even if the TemplateField based columns have not\n // been moved. Also do a databind in that case.\n //\n // We also force a databind right after the user has submitted the column chooser dialog.\n // (This is because the user could have moved TemplateField based column(s) but ColChooserHasMovedTemplateFields()\n // returns false -- ie when the user has moved all TemplateField based columns back to their original positions.\n if ((!_DataBindingDone && (ColChooserHasMovedTemplateFields() || _InTabPanel)) || _ColChooserPanelSubmitted || _ColChooserPanelCancelled)\n DataBind();\n\n // There is a problem with the GridView in case of custom paging (which is true here) that if we are on the last page,\n // and we delete all row(s) of that page, GridView is not aware of the deletion during the subsequent data binding,\n // will ask the ODS for the last page of data, and will display a blank. By PreRenderComplete, it will somehow have\n // realized that its PageIndex, PageCount, etc. are too big and updated them properly, but this is too late\n // as the data binding has already occurred with oudated page variables. So, if we were on the last page just before\n // the last data binding (_LastPageIndex == _LastPageCount - 1) and PageIndex was decremented after the data binding,\n // we know this scenario has happened and we redo the data binding. See http://scottonwriting.net/sowblog/archive/2006/05/30/163173.aspx\n // for a discussion of the problem when the GridView uses the ODS to delete data. The discussion also applies when we\n // delete data directly through ClassBuilder objects.\n if (_LastPageIndex == _LastPageCount - 1 && PageIndex < _LastPageIndex)\n DataBind();\n\n if (EnableColChooser)\n {\n if (!_IsColChooserApplied)\n ApplyColChooser(null, false, false);\n else\n {\n // The purpose of calling ApplyColChooser() here is to order the column headers properly. The GridView\n // at this point will have reverted the column headers to their original order regardless of ViewState,\n // so we need to apply our own ordering. (This is not true of data cells, so we don't have to apply\n // ordering to them, as reflected by the parameters of the call.)\n\n // If we have already processed column reordering upon the column chooser panel being submitted,\n // don't repeat the operation.\n if (!_ColChooserPanelSubmitted)\n ApplyColChooser(null, false, true);\n }\n }\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234935", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7961/" ]
234,945
<p>I've inherited a WSDL file for a web service on a system that I don't have access to for development and testing.</p> <p>I need to generate a web service that adheres to that WSDL. The wrapper is .NET, but if there's an easy way to do this with another platform, we might be able to look at that. The production web service is Java-based.</p> <p>What's the best way to go about doing this?</p> <p>Note: The inherited wsdl doesn't appear to be compatible with <b>wsdl.exe</b> because it doesn't conform to WS-I Basic Profile v1.1. In particular, the group that passed it on mentioned it uses another standard that the Microsoft tool doesn't support, but they didn't clarify. The error is related to a required 'name' field:</p> <pre>Error: Element Reference '{namespace}/:viewDocumentResponse' declared in schema type '' from namespace '' - the required attribute 'name' is missing</pre> <p>For clarity's sake, I understand that I can easily create a .NET wrapper class from the WSDL file, but that's not what I need. It's like this:</p> <p>Update: The original web service was created using Axis.</p> <p><a href="http://paulw.us/blog/uploads/SO-WSDL-Question2.gif" rel="nofollow noreferrer">Diagram of system showing unavailable web service and mock web service http://paulw.us/blog/uploads/SO-WSDL-Question2.gif</a></p>
[ { "answer_id": 235005, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "wsdl.exe /serverInterface" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234945", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7301/" ]
234,949
<p>I'm new to CakePHP but I've been though their FAQs and guides to no avail. This is so simple that I just must not be thinking straight:</p> <p>How can I access a parameter sent through the URL within my view files? </p> <p>Example: <a href="http://example.com/view/6" rel="nofollow noreferrer">http://example.com/view/6</a></p> <p>How would I take that parameter ("6") and cycle it through the controller to another view page?</p> <p>If that's too complex for a quick answer, how can I reference the 6 within the view page itself? The 6 in this situation is the "Id" value in my database, and I need to set it as the "parent" -</p> <p>Thanks</p>
[ { "answer_id": 235017, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": true, "text": "http://example.com/thinger/view/6\n thingerControllerObject->view(\"6\")" }, { "answer_id": 235054, "author": "neilcrookes", "author_id": 9968, "author_profile": "https://Stackoverflow.com/users/9968", "pm_score": 3, "selected": false, "text": "$this->params" }, { "answer_id": 2349166, "author": "Nikolay Ruban", "author_id": 1821012, "author_profile": "https://Stackoverflow.com/users/1821012", "pm_score": 4, "selected": false, "text": "$this->params['pass']\n // URL: /posts/view/12/print/narrow\nArray\n(\n [0] => 12\n [1] => print\n [2] => narrow\n)\n" }, { "answer_id": 29944097, "author": "sabin", "author_id": 3427661, "author_profile": "https://Stackoverflow.com/users/3427661", "pm_score": 0, "selected": false, "text": "$url=Router::url($this->here, true);\n$url_arr=explode(\"/\",$url);\n $url pr($url_arr);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24565/" ]
234,963
<p>If I accidentally closed the <em>scratch</em> buffer in Emacs, how do I create a new <em>scratch</em> buffer?</p>
[ { "answer_id": 234982, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 3, "selected": false, "text": "*scratch* *scratch*" }, { "answer_id": 234988, "author": "stephanea", "author_id": 8776, "author_profile": "https://Stackoverflow.com/users/8776", "pm_score": -1, "selected": false, "text": "*scratch*" }, { "answer_id": 235069, "author": "Trey Jackson", "author_id": 6148, "author_profile": "https://Stackoverflow.com/users/6148", "pm_score": 9, "selected": true, "text": "*scratch* switch-to-buffer *scratch* *scratch* *scratch* initial-major-mode NAME NAME write-file text-mode apropos-command -mode$" }, { "answer_id": 235186, "author": "dwj", "author_id": 346, "author_profile": "https://Stackoverflow.com/users/346", "pm_score": 2, "selected": false, "text": ";;; Prevent killing the *scratch* buffer -- source forgotten\n;;;----------------------------------------------------------------------\n;;; Make the *scratch* buffer behave like \"The thing your aunt gave you,\n;;; which you don't know what is.\"\n(save-excursion\n (set-buffer (get-buffer-create \"*scratch*\"))\n (make-local-variable 'kill-buffer-query-functions)\n (add-hook 'kill-buffer-query-functions 'kill-scratch-buffer))\n\n(defun kill-scratch-buffer ()\n ;; The next line is just in case someone calls this manually\n (set-buffer (get-buffer-create \"*scratch*\"))\n\n ;; Kill the current (*scratch*) buffer\n (remove-hook 'kill-buffer-query-functions 'kill-scratch-buffer)\n (kill-buffer (current-buffer))\n\n ;; Make a brand new *scratch* buffer\n (set-buffer (get-buffer-create \"*scratch*\"))\n (lisp-interaction-mode)\n (make-local-variable 'kill-buffer-query-functions)\n (add-hook 'kill-buffer-query-functions 'kill-scratch-buffer)\n\n ;; Since we killed it, don't let caller do that.\n nil)\n;;;----------------------------------------------------------------------\n" }, { "answer_id": 358740, "author": "user45273", "author_id": 45273, "author_profile": "https://Stackoverflow.com/users/45273", "pm_score": 5, "selected": false, "text": ";; bury *scratch* buffer instead of kill it\n(defadvice kill-buffer (around kill-buffer-around-advice activate)\n (let ((buffer-to-kill (ad-get-arg 0)))\n (if (equal buffer-to-kill \"*scratch*\")\n (bury-buffer)\n ad-do-it)))\n" }, { "answer_id": 776052, "author": "Edric", "author_id": 88076, "author_profile": "https://Stackoverflow.com/users/88076", "pm_score": 2, "selected": false, "text": "*scratch* lisp-interaction-mode (defun eme-goto-scratch () \n \"this sends you to the scratch buffer\"\n (interactive)\n (let ((eme-scratch-buffer (get-buffer-create \"*scratch*\")))\n (switch-to-buffer eme-scratch-buffer)\n (lisp-interaction-mode)))\n" }, { "answer_id": 1042839, "author": "Gyom", "author_id": 117814, "author_profile": "https://Stackoverflow.com/users/117814", "pm_score": 2, "selected": false, "text": " (run-with-idle-timer 1 t\n '(lambda () (get-buffer-create \"*scratch*\")))\n" }, { "answer_id": 4658587, "author": "kjfletch", "author_id": 134107, "author_profile": "https://Stackoverflow.com/users/134107", "pm_score": 2, "selected": false, "text": "(defun switch-buffer-scratch ()\n \"Switch to the scratch buffer. If the buffer doesn't exist,\ncreate it and write the initial message into it.\"\n (interactive)\n (let* ((scratch-buffer-name \"*scratch*\")\n (scratch-buffer (get-buffer scratch-buffer-name)))\n (unless scratch-buffer\n (setq scratch-buffer (get-buffer-create scratch-buffer-name))\n (with-current-buffer scratch-buffer\n (lisp-interaction-mode)\n (insert initial-scratch-message)))\n (switch-to-buffer scratch-buffer)))\n\n(global-set-key \"\\C-cbs\" 'switch-buffer-scratch)\n" }, { "answer_id": 11719472, "author": "idbrii", "author_id": 79125, "author_profile": "https://Stackoverflow.com/users/79125", "pm_score": 4, "selected": false, "text": "(defun create-scratch-buffer nil\n \"create a scratch buffer\"\n (interactive)\n (switch-to-buffer (get-buffer-create \"*scratch*\"))\n (lisp-interaction-mode)) \n" }, { "answer_id": 13343320, "author": "Andreas Spindler", "author_id": 887771, "author_profile": "https://Stackoverflow.com/users/887771", "pm_score": 1, "selected": false, "text": "(defun --scratch-buffer(&optional reset)\n \"Get the *scratch* buffer object.\nMake new scratch buffer unless it exists. \nIf RESET is non-nil arrange it that it can't be killed.\"\n (let ((R (get-buffer \"*scratch*\")))\n (unless R\n (message \"Creating new *scratch* buffer\")\n (setq R (get-buffer-create \"*scratch*\") reset t))\n (when reset\n (save-excursion\n (set-buffer R)\n (lisp-interaction-mode)\n (make-local-variable 'kill-buffer-query-functions)\n (add-hook 'kill-buffer-query-functions '(lambda()(bury-buffer) nil)\n )))\n R))\n (--scratch-buffer t)\n(run-with-idle-timer 3 t '--scratch-buffer)\n scratch (defun scratch()\n \"Switch to *scratch*. With prefix-arg delete its contents.\"\n (interactive)\n (switch-to-buffer (--scratch-buffer))\n (if current-prefix-arg\n (delete-region (point-min) (point-max))\n (goto-char (point-max))))\n desktop-dirname default-directory (defvar --scratch-directory\n (save-excursion (set-buffer \"*scratch*\") default-directory)\n \"The `default-directory' local variable of the *scratch* buffer.\")\n\n(defconst --no-desktop (member \"--no-desktop\" command-line-args)\n \"True when no desktop file is loaded (--no-desktop command-line switch set).\")\n\n(defun --startup-directory ()\n \"Return directory from which Emacs was started: `desktop-dirname' or the `--scratch-directory'.\nNote also `default-minibuffer-frame'.\"\n (if (and (not --no-desktop) desktop-dirname) \n desktop-dirname\n --scratch-directory))\n --scratch-directory" }, { "answer_id": 21058075, "author": "paprika", "author_id": 61815, "author_profile": "https://Stackoverflow.com/users/61815", "pm_score": 2, "selected": false, "text": "scratch (defun scratch ()\n \"create a new scratch buffer to work in. (could be *scratch* - *scratchX*)\"\n (interactive)\n (let ((n 0)\n bufname)\n (while (progn\n (setq bufname (concat \"*scratch\"\n (if (= n 0) \"\" (int-to-string n))\n \"*\"))\n (setq n (1+ n))\n (get-buffer bufname)))\n (switch-to-buffer (get-buffer-create bufname))\n (if (= n 1) initial-major-mode))) ; 1, because n was incremented\n" }, { "answer_id": 21071757, "author": "lawlist", "author_id": 2112489, "author_profile": "https://Stackoverflow.com/users/2112489", "pm_score": 2, "selected": false, "text": "(add-hook 'emacs-startup-hook\n (lambda ()\n (kill-buffer \"*scratch*\")\n (find-file \"/Users/HOME/Desktop/.scratch\")))\n desktop.el (kill-buffer \"*scratch*\") (find-file \"/Users/HOME/Desktop/.scratch\") auto-save-buffers-enhanced (require 'auto-save-buffers-enhanced)\n(auto-save-buffers-enhanced t)\n(setq auto-save-buffers-enhanced-save-scratch-buffer-to-file-p 1)\n(setq auto-save-buffers-enhanced-exclude-regexps '(\"\\\\.txt\" \"\\\\.el\" \"\\\\.tex\"))\n (defun lawlist-new-buffer ()\n \"Create a new buffer -- \\*lawlist\\*\"\n(interactive)\n (let* (\n (n 0)\n bufname)\n (catch 'done\n (while t\n (setq bufname (concat \"*lawlist\"\n (if (= n 0) \"\" (int-to-string n))\n \"*\"))\n (setq n (1+ n))\n (if (not (get-buffer bufname))\n (throw 'done nil)) ))\n (switch-to-buffer (get-buffer-create bufname))\n (text-mode) ))\n" }, { "answer_id": 26248579, "author": "Qian", "author_id": 1236121, "author_profile": "https://Stackoverflow.com/users/1236121", "pm_score": 1, "selected": false, "text": "(defun create-scratch-buffer nil\n \"create a scratch buffer\"\n (interactive)\n (switch-to-buffer (get-buffer-create \"*scratch*\"))\n (lisp-interaction-mode))\n" }, { "answer_id": 27981369, "author": "CodyChan", "author_id": 1528712, "author_profile": "https://Stackoverflow.com/users/1528712", "pm_score": 2, "selected": false, "text": "(global-set-key (kbd \"C-x M-z\")\n '(lambda ()\n (interactive)\n (switch-to-buffer \"*scratch*\")))\n *scratch* *scratch* lisp-interaction-mode" }, { "answer_id": 36779992, "author": "nj35", "author_id": 6237671, "author_profile": "https://Stackoverflow.com/users/6237671", "pm_score": 2, "selected": false, "text": "unkillable-scratch scratch-persist" }, { "answer_id": 54292160, "author": "petre", "author_id": 3540204, "author_profile": "https://Stackoverflow.com/users/3540204", "pm_score": 0, "selected": false, "text": "*scratch* *scratch* C-x b C-b *scratch* RET" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5694/" ]
234,973
<p>What is the best way to check for the existence of a session variable in ASP.NET C#? </p> <p>I like to use <code>String.IsNullOrEmpty()</code> works for strings and wondered if there was a similar method for <code>Session</code>. Currently the only way I know of is:</p> <pre><code> var session; if (Session["variable"] != null) { session = Session["variable"].ToString(); } else { session = "set this"; Session["variable"] = session; } </code></pre>
[ { "answer_id": 234991, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 4, "selected": false, "text": "sSession = (string)Session[\"variable\"] ?? \"set this\";\n" }, { "answer_id": 234997, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": " private const string SESSION_VAR = \"myString\";\n string sSession;\n if (Session[SESSION_VAR] != null)\n {\n sSession = (string)Session[SESSION_VAR];\n }\n else\n {\n sSession = \"set this\";\n Session[SESSION_VAR] = sSession;\n }\n" }, { "answer_id": 235024, "author": "Michael Kniskern", "author_id": 26327, "author_profile": "https://Stackoverflow.com/users/26327", "pm_score": 0, "selected": false, "text": "public static bool IsNull(this object input)\n{\n input == null ? return true : return false;\n}\n\npublic void Main()\n{\n object x = new object();\n if(x.IsNull)\n {\n //do your thing\n }\n}\n" }, { "answer_id": 235062, "author": "oglester", "author_id": 2017, "author_profile": "https://Stackoverflow.com/users/2017", "pm_score": 4, "selected": false, "text": "string MySessionVar\n{\n get{\n return Session[\"MySessionVar\"] ?? String.Empty;\n }\n set{\n Session[\"MySessionVar\"] = value;\n }\n}\n if( String.IsNullOrEmpty( MySessionVar ) )\n{\n // do something\n}\n" }, { "answer_id": 235131, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 1, "selected": false, "text": "public class SessionProxy\n{\n private HttpSessionState session; // use dependency injection for testability\n public SessionProxy( HttpSessionState session )\n {\n this.session = session; //might need to throw an exception here if session is null\n }\n\n public DateTime LastUpdate\n {\n get { return this.session[\"LastUpdate\"] != null\n ? (DateTime)this.session[\"LastUpdate\"] \n : DateTime.MinValue; }\n set { this.session[\"LastUpdate\"] = value; }\n }\n\n public string UserLastName\n {\n get { return (string)this.session[\"UserLastName\"]; }\n set { this.session[\"UserLastName\"] = value; }\n }\n}\n" }, { "answer_id": 235142, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 8, "selected": true, "text": "public class SessionVar\n{\n static HttpSessionState Session\n {\n get\n {\n if (HttpContext.Current == null)\n throw new ApplicationException(\"No Http Context, No Session to Get!\");\n\n return HttpContext.Current.Session;\n }\n }\n\n public static T Get<T>(string key)\n {\n if (Session[key] == null)\n return default(T);\n else\n return (T)Session[key];\n }\n\n public static void Set<T>(string key, T value)\n {\n Session[key] = value;\n }\n}\n public static string GetString(string key)\n{\n string s = Get<string>(key);\n return s == null ? string.Empty : s;\n}\n\npublic static void SetString(string key, string value)\n{\n Set<string>(key, value);\n}\n public class CustomerInfo\n{\n public string Name\n {\n get\n {\n return SessionVar.GetString(\"CustomerInfo_Name\");\n }\n set\n {\n SessionVar.SetString(\"CustomerInfo_Name\", value);\n }\n }\n}\n" }, { "answer_id": 235245, "author": "Aaron Palmer", "author_id": 24908, "author_profile": "https://Stackoverflow.com/users/24908", "pm_score": 3, "selected": false, "text": "string mySessionVar = Session[\"mySessionVar\"] as string;\n int mySessionInt;\nif (!int.TryParse(mySessionVar, out mySessionInt)){\n // handle the case where your session variable did not parse into the expected type \n // e.g. mySessionInt = 0;\n}\n" }, { "answer_id": 236050, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 1, "selected": false, "text": "string Name\n{\n get \n {\n if(Session[\"Name\"] == Null)\n Session[\"Name\"] = \"Default value\";\n return (string)Session[\"Name\"];\n }\n set { Session[\"Name\"] = value; }\n}\n" }, { "answer_id": 7155396, "author": "Jon Falkner", "author_id": 906879, "author_profile": "https://Stackoverflow.com/users/906879", "pm_score": 2, "selected": false, "text": " String sVar = (string)(Session[\"SessionVariable\"] ?? \"Default Value\");\n DateTime sDateVar = (datetime)(Session[\"DateValue\"] ?? \"2010-01-01\");\n Int NextYear = sDateVar.Year + 1;\n String Message = \"The Procrastinators Club will open it's doors Jan. 1st, \" +\n (string)(Session[\"OpeningDate\"] ?? NextYear);\n" }, { "answer_id": 37277749, "author": "Sarfaraaz", "author_id": 4801298, "author_profile": "https://Stackoverflow.com/users/4801298", "pm_score": 2, "selected": false, "text": "if((Session[\"MySessionVariable\"] ?? \"\").ToString() != \"\")\n //More code for the Code God\n ToString Object" }, { "answer_id": 52702507, "author": "Yakup Ad", "author_id": 7699822, "author_profile": "https://Stackoverflow.com/users/7699822", "pm_score": 1, "selected": false, "text": "if (Session.Dictionary.ContainsKey(\"Sessionkey\")) --> return Bool\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12252/" ]
234,976
<p>Scenario - I need to access an HTML template to generate a e-mail from my Business Logic Layer. It is a class library contains a sub folder that contains the file. When I tried the following code in a unit test:</p> <pre><code>string FilePath = string.Format(@"{0}\templates\MyFile.htm", Environment.CurrentDirectory); string FilePath1 = string.Format(@"{0}\templates\MyFile.htm", System.AppDomain.CurrentDomain.BaseDirectory); </code></pre> <p>It was using the C:\WINNT\system32\ or the ASP.NET Temporary Folder directory.</p> <p>What is the best to access this file without having to use an app.config or web.config file?</p> <p>[This is using a WCF Service]</p>
[ { "answer_id": 234984, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "Server.MapPath() System.IO.Path.Combine() System.Web System.Reflection.Assembly.GetExecutingAssembly().Location\n GetEntryAssembly()" }, { "answer_id": 234987, "author": "harpo", "author_id": 4525, "author_profile": "https://Stackoverflow.com/users/4525", "pm_score": 0, "selected": false, "text": "System.Web.HttpServerUtility.MapPath( \"~/templates/myfile.htm\" )\n" }, { "answer_id": 235122, "author": "Krzysztof Kozmic", "author_id": 13163, "author_profile": "https://Stackoverflow.com/users/13163", "pm_score": 1, "selected": false, "text": "System.IO.Path.GetDirectoryName(Application.ExecutablePath);\n" }, { "answer_id": 4121313, "author": "woaksie", "author_id": 39567, "author_profile": "https://Stackoverflow.com/users/39567", "pm_score": 1, "selected": false, "text": " <system.serviceModel>\n<serviceHostingEnvironment aspNetCompatibilityEnabled=\"true\">\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26327/" ]
234,994
<p>Two questions:</p> <ol> <li>Can someone point me to unbiased data that compares .NET performance to VB 6 performance? I have searched but it is surprisingly difficult to find.</li> <li>What is the best way to compare .NET performance to VB 6 performance as an app behaves at a customer's site?</li> </ol> <p>We have a WindowsForms, client-server app (written for 2.0, upgrading to 3.5 SP 1 soon) about which certain customers complain of "slow performance" as compared to the previous VB 6 version. I know, "slow performance" is very vague and general, but is it true to assume .NET code might be slower than VB 6 code because .NET runs in a VM? I wrote 100% of the code in C#, so it was not ported by some third person or wizard.</p> <p>Not all customers make this complaint, so we suspect something environmental. Is our only option to measure performance at a customer site? Some of our customers use SQL Server 2005 on Windows Server 2003 on a Novell network. Would they see dramatically different data access performance than a similar machine on a Windows network?</p>
[ { "answer_id": 235080, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 3, "selected": true, "text": "mult Option Strict Option Strict" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/234994", "https://Stackoverflow.com", "https://Stackoverflow.com/users/470/" ]
235,003
<p>I'm practicing for the upcoming ACM programming competition in a week and I've gotten stumped on this programming problem.</p> <p><strong>The problem is as follows:</strong></p> <hr> <p>You have a puzzle consisting of a square grid of size 4. Each grid square holds a single coin; each coin is showing either heads (H) and tails (T). One such puzzle is shown here:</p> <blockquote> <p>H H H H<br> T T T T<br> H T H T<br> T T H T </p> </blockquote> <p>Any coin that is current showing Tails (T) can be flipped to Heads (H). However, any time we flip a coin, we must also flip the adjacent coins direct above, below and to the left and right in the same row. Thus if we flip the second coin in the second row we must also flip 4 other coins, giving us this arrangment (coins that changed are shown in bold).</p> <blockquote> <p>H <strong>T</strong> H H<br> <strong>H</strong> <strong>H</strong> <strong>H</strong> T<br> H <strong>H</strong> H T<br> T T H T </p> </blockquote> <p>If a coin is at the edge of the puzzle, so there is no coin on one side or the other, then we flip fewer coins. We do not "wrap around" to the other side. For example, if we flipped the bottom right coin of the arragnement above we would get:</p> <blockquote> <p>H T H H<br> H H H T<br> H H H <strong>H</strong><br> T T <strong>T</strong> <strong>H</strong> </p> </blockquote> <p>Note: Only coins showing (T) tails can be selected for flipping. However, anytime we flip such a coin, adjacent coins are also flipped, regardless of their state.</p> <p>The goal of the puzzle is to have all coins show heads. While it is possible for some arragnements to not have solutions, all the problems given will have solutions. The answer we are looking for is, for any given 4x4 grid of coins what is the least number of flips in order to make the grid entirely heads.</p> <p>For Example the grid:<br> H T H H<br> T T T H<br> H T H T<br> H H T T </p> <p>The answer to this grid is: 2 flips.</p> <hr> <p>What I have done so far:</p> <p>I'm storing our grids as two-dimensional array of booleans. Heads = true, tails = false. I have a <strong>flip(int row, int col)</strong> method that will flip the adjacent coins according the rules above and I have a <strong>isSolved()</strong> method that will determine if the puzzle is in a solved state (all heads). So we have our "mechanics" in place.</p> <p>The part we are having problems with is how should we loop through, going an the least amount of times deep?</p>
[ { "answer_id": 235022, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "ABCD\nEFGH\nIJKL\nMNOP\n using System;\n\npublic class CoinFlip\n{\n // All ints could really be ushorts, but ints are easier \n // to work with\n static readonly int[] MoveTransitions = CalculateMoveTransitions();\n\n static int[] CalculateMoveTransitions()\n {\n int[] ret = new int[16];\n for (int i=0; i < 16; i++)\n {\n int row = i / 4;\n int col = i % 4;\n ret[i] = PositionToBit(row, col) +\n PositionToBit(row-1, col) +\n PositionToBit(row+1, col) +\n PositionToBit(row, col-1) +\n PositionToBit(row, col+1);\n }\n return ret;\n }\n\n static int PositionToBit(int row, int col)\n {\n if (row < 0 || row > 3 || col < 0 || col > 3)\n {\n // Makes edge detection easier\n return 0;\n }\n return 1 << (row * 4 + col);\n }\n\n static void Main(string[] args)\n {\n int initial = 0;\n foreach (char c in args[0])\n {\n initial += 1 << (c-'A');\n }\n Console.WriteLine(\"Initial = {0}\", initial);\n ChangeState(initial, 0, 0);\n }\n\n static void ChangeState(int current, int nextCoin, int currentFlips)\n {\n // Reached the end. Success?\n if (nextCoin == 16)\n {\n if (current == 0)\n {\n // More work required if we want to display the solution :)\n Console.WriteLine(\"Found solution with {0} flips\", currentFlips);\n }\n }\n else\n {\n // Don't flip this coin\n ChangeState(current, nextCoin+1, currentFlips);\n // Or do...\n ChangeState(current ^ MoveTransitions[nextCoin], nextCoin+1, currentFlips+1);\n }\n }\n}\n" }, { "answer_id": 235123, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "// Tries all the n bit patterns with k bits set to 1\ntryAllPatterns(unsigned short n, unsigned short k, unsigned short commonAddend=0)\n{\n if(n == 0)\n tryPattern(commonAddend);\n else\n {\n // All the patterns that have the n-th bit set to 1 and k-1 bits\n // set to 1 in the remaining\n tryAllPatterns(n-1, k-1, (2^(n-1) xor commonAddend) );\n\n // All the patterns that have the n-th bit set to 0 and k bits\n // set to 1 in the remaining\n tryAllPatterns(n-1, k, commonAddend );\n }\n}\n" }, { "answer_id": 235182, "author": "CAdaker", "author_id": 30579, "author_profile": "https://Stackoverflow.com/users/30579", "pm_score": 2, "selected": false, "text": "G s x Gx=s x y Gy = 0 x^y y G" }, { "answer_id": 235683, "author": "Andru Luvisi", "author_id": 5922, "author_profile": "https://Stackoverflow.com/users/5922", "pm_score": 2, "selected": false, "text": "Create a queue.\nCreate a state that contains the start position and an empty list of moves.\nPut this state into the queue.\nLoop forever:\n Pull first state off of queue.\n For each coin showing tails on the board:\n Create a new state by flipping that coin and the appropriate others around it.\n Add the coordinates of that coin to the list of moves in the new state.\n If the new state shows all heads:\n Rejoice, you are done.\n Push the new state into the end of the queue.\n" }, { "answer_id": 236141, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Collections.Generic;\n\npublic class CoinFlip\n{\n struct Position\n {\n readonly string moves;\n readonly int state;\n\n public Position(string moves, int state)\n {\n this.moves = moves;\n this.state = state;\n }\n\n public string Moves { get { return moves; } } \n public int State { get { return state; } }\n\n public IEnumerable<Position> GetNextPositions()\n {\n for (int move = 0; move < 16; move++)\n {\n if ((state & (1 << move)) == 0)\n { \n continue; // Not allowed - it's already heads\n }\n int newState = state ^ MoveTransitions[move];\n yield return new Position(moves + (char)(move+'A'), newState);\n }\n }\n }\n\n // All ints could really be ushorts, but ints are easier \n // to work with\n static readonly int[] MoveTransitions = CalculateMoveTransitions();\n\n static int[] CalculateMoveTransitions()\n {\n int[] ret = new int[16];\n for (int i=0; i < 16; i++)\n {\n int row = i / 4;\n int col = i % 4;\n ret[i] = PositionToBit(row, col) +\n PositionToBit(row-1, col) +\n PositionToBit(row+1, col) +\n PositionToBit(row, col-1) +\n PositionToBit(row, col+1);\n }\n return ret;\n }\n\n static int PositionToBit(int row, int col)\n {\n if (row < 0 || row > 3 || col < 0 || col > 3)\n {\n return 0;\n }\n return 1 << (row * 4 + col);\n }\n\n static void Main(string[] args)\n {\n int initial = 0;\n foreach (char c in args[0])\n {\n initial += 1 << (c-'A');\n }\n\n int maxDepth = int.Parse(args[1]);\n\n Queue<Position> queue = new Queue<Position>();\n queue.Enqueue(new Position(\"\", initial));\n\n while (queue.Count != 0)\n {\n Position current = queue.Dequeue();\n if (current.State == 0)\n {\n Console.WriteLine(\"Found solution in {0} moves: {1}\",\n current.Moves.Length, current.Moves);\n return;\n }\n if (current.Moves.Length == maxDepth)\n {\n continue;\n }\n // Shame Queue<T> doesn't have EnqueueRange :(\n foreach (Position nextPosition in current.GetNextPositions())\n {\n queue.Enqueue(nextPosition);\n }\n }\n Console.WriteLine(\"No solutions\");\n }\n}\n" }, { "answer_id": 1566323, "author": "mmcdole", "author_id": 2635, "author_profile": "https://Stackoverflow.com/users/2635", "pm_score": 0, "selected": false, "text": "import java.util.*;\n\nclass Node\n{\n public boolean[][] Value;\n public Node Parent;\n\n public Node (boolean[][] value, Node parent)\n {\n this.Value = value;\n this.Parent = parent;\n }\n}\n\n\npublic class CoinFlip\n{\n public static void main(String[] args)\n {\n boolean[][] startState = {{true, false, true, true},\n {false, false, false, true},\n {true, false, true, false},\n {true, true, false, false}};\n\n\n List<boolean[][]> solutionPath = search(startState);\n\n System.out.println(\"Solution Depth: \" + solutionPath.size());\n for(int i = 0; i < solutionPath.size(); i++)\n {\n System.out.println(\"Transition \" + (i+1) + \":\");\n print2DArray(solutionPath.get(i));\n }\n\n }\n\n public static List<boolean[][]> search(boolean[][] startState)\n {\n Queue<Node> Open = new LinkedList<Node>();\n Queue<Node> Closed = new LinkedList<Node>();\n\n Node StartNode = new Node(startState, null);\n Open.add(StartNode);\n\n while(!Open.isEmpty())\n {\n Node nextState = Open.remove();\n\n System.out.println(\"Considering: \");\n print2DArray(nextState.Value);\n\n if (isComplete(nextState.Value))\n {\n System.out.println(\"Solution Found!\");\n return constructPath(nextState);\n }\n else\n {\n List<Node> children = generateChildren(nextState);\n Closed.add(nextState);\n\n for(Node child : children)\n {\n if (!Open.contains(child))\n Open.add(child);\n }\n }\n\n }\n\n return new ArrayList<boolean[][]>();\n\n }\n\n public static List<boolean[][]> constructPath(Node node)\n {\n List<boolean[][]> solutionPath = new ArrayList<boolean[][]>();\n\n while(node.Parent != null)\n {\n solutionPath.add(node.Value);\n node = node.Parent;\n }\n Collections.reverse(solutionPath);\n\n return solutionPath;\n }\n\n public static List<Node> generateChildren(Node parent)\n {\n System.out.println(\"Generating Children...\");\n List<Node> children = new ArrayList<Node>();\n\n boolean[][] coinState = parent.Value;\n\n for(int i = 0; i < coinState.length; i++)\n {\n for(int j = 0; j < coinState[i].length; j++)\n {\n if (!coinState[i][j])\n {\n boolean[][] child = arrayDeepCopy(coinState);\n flip(child, i, j);\n children.add(new Node(child, parent));\n\n }\n }\n }\n\n return children;\n }\n\n public static boolean[][] arrayDeepCopy(boolean[][] original)\n {\n boolean[][] r = new boolean[original.length][original[0].length];\n for(int i=0; i < original.length; i++)\n for (int j=0; j < original[0].length; j++)\n r[i][j] = original[i][j];\n\n return r;\n }\n\n public static void flip(boolean[][] grid, int i, int j)\n {\n //System.out.println(\"Flip(\"+i+\",\"+j+\")\");\n // if (i,j) is on the grid, and it is tails\n if ((i >= 0 && i < grid.length) && (j >= 0 && j <= grid[i].length))\n {\n // flip (i,j)\n grid[i][j] = !grid[i][j];\n // flip 1 to the right\n if (i+1 >= 0 && i+1 < grid.length) grid[i+1][j] = !grid[i+1][j];\n // flip 1 down\n if (j+1 >= 0 && j+1 < grid[i].length) grid[i][j+1] = !grid[i][j+1];\n // flip 1 to the left\n if (i-1 >= 0 && i-1 < grid.length) grid[i-1][j] = !grid[i-1][j];\n // flip 1 up\n if (j-1 >= 0 && j-1 < grid[i].length) grid[i][j-1] = !grid[i][j-1];\n }\n }\n\n public static boolean isComplete(boolean[][] coins)\n {\n boolean complete = true;\n\n for(int i = 0; i < coins.length; i++)\n {\n for(int j = 0; j < coins[i].length; j++)\n {\n if (coins[i][j] == false) complete = false; \n }\n\n }\n return complete;\n }\n\n public static void print2DArray(boolean[][] array) \n {\n for (int row=0; row < array.length; row++) \n {\n for (int col=0; col < array[row].length; col++)\n {\n System.out.print((array[row][col] ? \"H\" : \"T\") + \" \");\n }\n System.out.println();\n }\n }\n\n}\n" }, { "answer_id": 2327607, "author": "Larry", "author_id": 277763, "author_profile": "https://Stackoverflow.com/users/277763", "pm_score": 1, "selected": false, "text": "O(2^N) N (x,y) (x,y-1) (x,y)" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
235,018
<p>Scaffolding, what is it? Is it a Rails-only thing?</p>
[ { "answer_id": 40007535, "author": "Zanon", "author_id": 1476885, "author_profile": "https://Stackoverflow.com/users/1476885", "pm_score": 4, "selected": false, "text": "yo" }, { "answer_id": 41658322, "author": "Obmerk Kronen", "author_id": 1244126, "author_profile": "https://Stackoverflow.com/users/1244126", "pm_score": 6, "selected": false, "text": "scaffolding skeleton boilerplate" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,025
<p><a href="/questions/61400/what-makes-a-good-unit-test">What Makes a Good Unit Test?</a> says that a test should test only one thing. What is the benefit from that?</p> <p>Wouldn't it be better to write a bit bigger tests that test bigger block of code? Investigating a test failure is anyway hard and I don't see help to it from smaller tests. </p> <p>Edit: The word unit is not that important. Let's say I consider the unit a bit bigger. That is not the issue here. The real question is why make a test or more for all methods as few tests that cover many methods is simpler.</p> <p>An example: A list class. Why should I make separate tests for addition and removal? A one test that first adds then removes sounds simpler.</p>
[ { "answer_id": 235034, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 4, "selected": false, "text": "[TestMethod]\npublic void TestSomething() {\n // Test condition A\n // Test condition B\n // Test condition C\n // Test condition D\n}\n" }, { "answer_id": 235066, "author": "Newtopian", "author_id": 25812, "author_profile": "https://Stackoverflow.com/users/25812", "pm_score": 4, "selected": false, "text": "@Test\npublic void checkNullInputFirstArgument(){...}\n@Test\npublic void checkNullInputSecondArgument(){...}\n@Test\npublic void checkOverInputFirstArgument(){...}\n...\n @Test\npublic void testLimitConditions(){...}\n @Test\npublic void doesWork(){...}\n" }, { "answer_id": 235654, "author": "Ryan", "author_id": 8819, "author_profile": "https://Stackoverflow.com/users/8819", "pm_score": 2, "selected": false, "text": "class TestCase():\n def setup():\n self.stack = new Stack()\n def test():\n stack.push(1)\n stack.push(2)\n stack.pop()\n assert stack.top() == 1, \"top() isn't showing correct object\"\n assert stack.getSize() == 1, \"getSize() call failed\"\n push() pop() top() getSize() def test_size():\n assert stack.getSize() == 0\n assert stack.isEmpty()\n\ndef test_push():\n self.stack.push(1)\n assert stack.top() == 1, \"top returns wrong object after push\"\n assert stack.getSize() == 1, \"getSize wrong after push\"\n\ndef test_pop():\n stack.push(1)\n stack.pop()\n assert stack.getSize() == 0, \"getSize wrong after push\"\n test_push top() getSize()" }, { "answer_id": 511271, "author": "Dave Cameron", "author_id": 49775, "author_profile": "https://Stackoverflow.com/users/49775", "pm_score": 2, "selected": false, "text": "namespace Tests.Integration\n{\n [TestFixture]\n public class FeeMessageTest\n {\n [Test]\n public void ShouldHaveCorrectValues\n {\n var fees = CallSlowRunningFeeService();\n Assert.AreEqual(6.50m, fees.ConvenienceFee);\n Assert.AreEqual(2.95m, fees.CreditCardFee);\n Assert.AreEqual(59.95m, fees.ChangeFee);\n }\n }\n}\n namespace Tests.Integration\n{\n [TestFixture]\n public class FeeMessageTest\n {\n Fees fees;\n [TestFixtureSetUp]\n public void FetchFeesMessageFromService()\n {\n fees = CallSlowRunningFeeService();\n }\n\n [Test]\n public void ShouldHaveCorrectConvenienceFee()\n {\n Assert.AreEqual(6.50m, fees.ConvenienceFee);\n }\n\n [Test]\n public void ShouldHaveCorrectCreditCardFee()\n {\n Assert.AreEqual(2.95m, fees.CreditCardFee);\n }\n\n [Test]\n public void ShouldHaveCorrectChangeFee()\n {\n Assert.AreEqual(59.95m, fees.ChangeFee);\n }\n }\n}\n" }, { "answer_id": 2349349, "author": "Esko Luontola", "author_id": 62130, "author_profile": "https://Stackoverflow.com/users/62130", "pm_score": 1, "selected": false, "text": "func StackSpec(c gospec.Context) {\n stack := NewStack()\n\n c.Specify(\"An empty stack\", func() {\n\n c.Specify(\"is empty\", func() {\n c.Then(stack).Should.Be(stack.Empty())\n })\n c.Specify(\"After a push, the stack is no longer empty\", func() {\n stack.Push(\"foo\")\n c.Then(stack).ShouldNot.Be(stack.Empty())\n })\n })\n\n c.Specify(\"When objects have been pushed onto a stack\", func() {\n stack.Push(\"one\")\n stack.Push(\"two\")\n\n c.Specify(\"the object pushed last is popped first\", func() {\n x := stack.Pop()\n c.Then(x).Should.Equal(\"two\")\n })\n c.Specify(\"the object pushed first is popped last\", func() {\n stack.Pop()\n x := stack.Pop()\n c.Then(x).Should.Equal(\"one\")\n })\n c.Specify(\"After popping all objects, the stack is empty\", func() {\n stack.Pop()\n stack.Pop()\n c.Then(stack).Should.Be(stack.Empty())\n })\n })\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27067/" ]
235,033
<p>In Delphi, why does the Assigned() function still return True after I call the destructor?</p> <p>The below example code will write "sl is still assigned" to the console.</p> <p>However, I can call FreeAndNil(sl); and it won't be assigned.</p> <p>I've been programming in Delphi for a while, but this never made sense to me.</p> <p>Can someone explain?</p> <pre><code>program Project1; {$APPTYPE CONSOLE} uses SysUtils, Classes; var sl : TStringList; begin sl := TStringList.Create; sl.Free; if Assigned(sl) then WriteLn('sl is still assigned') else WriteLn('sl is not assigned'); end. </code></pre> <p>I tried comparing the VCL operations... FreeAndNil is short and sweet and makes sense:</p> <pre><code>procedure FreeAndNil(var Obj); var P: TObject; begin P := TObject(Obj); TObject(Obj) := nil; // clear the reference before destroying the object P.Free; end; </code></pre> <p>But TObject.Free is in mysterious assembler, which I don't understand:</p> <pre><code>procedure TObject.Free; asm TEST EAX,EAX JE @@exit MOV ECX,[EAX] MOV DL,1 CALL dword ptr [ECX].vmtDestroy @@exit: end; </code></pre>
[ { "answer_id": 235041, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 6, "selected": true, "text": "var\n sl1, sl2: TStringList;\nbegin\n sl1 := TStringList.Create;\n sl2 := sl1;\n FreeAndNil(sl1);\n // sl2 is still assigned and must be cleared separately (not with FreeAndNil because it points to the already freed object.)\nend;\n\n\n\n\nprocedure TObject.Free;\nasm\n TEST EAX,EAX\n JE @@exit // Jump to exit if pointer is nil.\n MOV ECX,[EAX] \n MOV DL,1\n CALL dword ptr [ECX].vmtDestroy // Call cleanup code (and destructor).\n@@exit:\nend;\n" }, { "answer_id": 235063, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "if Obj != NIL then\n vmtDestroy(obj); // which is basically the destructor/deallocator.\n" }, { "answer_id": 26045416, "author": "user1897277", "author_id": 1897277, "author_profile": "https://Stackoverflow.com/users/1897277", "pm_score": 1, "selected": false, "text": "Assigned() Obj FreeAndNil(Obj) Assigned() {Opened a new VCL application, placed a Button1, Memo1 on the form\nNext added a public reference GlobalButton of type TButton\nNext in OnClick handler of Button1 added a variable LocalButton \nNext in body, check if GlobalButton and LocalButton are assigned}\n\n TForm2 = class(TForm)\n Button1: TButton;\n Memo1: TMemo;\n procedure Button1Click(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n GlobalButton: TButton;\n end;\n\nprocedure TForm2.Button1Click(Sender: TObject);\nvar\n LocalButton: TButton;\nbegin\n if Assigned(GlobalButton) then \n Memo1.Lines.Add('GlobalButton assigned');\n if Assigned(LocalButton) then \n Memo1.Lines.Add('LocalButton assigned');\nend;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
235,047
<p>I am trying to insert about 50,000 objects (and therefore 50,000 keys) into a <code>java.util.HashMap&lt;java.awt.Point, Segment&gt;</code>. However, I keep getting an OutOfMemory exception. (<code>Segment</code> is my own class - very light weight - one <code>String</code> field, and 3 <code>int</code> fields).</p> <pre>Exception in thread "main" java.lang.OutOfMemoryError: Java heap space at java.util.HashMap.resize(HashMap.java:508) at java.util.HashMap.addEntry(HashMap.java:799) at java.util.HashMap.put(HashMap.java:431) at bus.tools.UpdateMap.putSegment(UpdateMap.java:168)</pre> <p>This seems quite ridiculous since I see that there is plenty of memory available on the machine - both in free RAM and HD space for virtual memory.</p> <p>Is it possible Java is running with some stringent memory requirements? Can I increase these?</p> <p>Is there some weird limitation with <code>HashMap</code>? Am I going to have to implement my own? Are there any other classes worth looking at?</p> <p>(I am running Java 5 under OS X 10.5 on an Intel machine with 2GB RAM.)</p>
[ { "answer_id": 235053, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 6, "selected": true, "text": "// Get current size of heap in bytes\nlong heapSize = Runtime.getRuntime().totalMemory();\n\n// Get maximum size of heap in bytes. The heap cannot grow beyond this size.\n// Any attempt will result in an OutOfMemoryException.\nlong heapMaxSize = Runtime.getRuntime().maxMemory();\n\n// Get amount of free memory within the heap in bytes. This size will increase\n// after garbage collection and decrease as new objects are created.\nlong heapFreeSize = Runtime.getRuntime().freeMemory();\n" }, { "answer_id": 235108, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 1, "selected": false, "text": "-Xmx<NN>m java <NN> Comparable TreeMap" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235047", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
235,072
<p>Does the C++ compiler optimize the multiply by two operation <code>x*2</code> to a bitshift operation <code>x&lt;&lt;1</code>?</p> <p>I would love to believe that yes.</p>
[ { "answer_id": 235103, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 6, "selected": true, "text": "01391000 push ecx \n int x = 0;\n\n scanf(\"%d\", &x);\n01391001 lea eax,[esp] \n01391004 push eax \n01391005 push offset string \"%d\" (13920F4h) \n0139100A mov dword ptr [esp+8],0 \n01391012 call dword ptr [__imp__scanf (13920A4h)] \n\n int y = x * 2;\n01391018 mov ecx,dword ptr [esp+8] \n0139101C lea edx,[ecx+ecx] \n int y = x * 2;\n000000013FB9101E mov edx,dword ptr [x] \n\n printf(\"%d\", y);\n000000013FB91022 lea rcx,[string \"%d\" (13FB921B0h)] \n000000013FB91029 add edx,edx \n" }, { "answer_id": 235110, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 4, "selected": false, "text": " x = x * 2;\n004013E7 mov eax,dword ptr [x] \n004013EA shl eax,1 \n004013EC mov dword ptr [x],eax \n x = x << 1 x = x * 2 * 2 << 1" }, { "answer_id": 52289986, "author": "tobi_s", "author_id": 8680401, "author_profile": "https://Stackoverflow.com/users/8680401", "pm_score": 0, "selected": false, "text": "2*x x+x 2 x x*2 74 2*x x for(int x = 0; x < count; ++x) ...2*x...\n int count2 = count * 2\n for(int x = 0; x < count2; x += 2) ...x...\n count lea x*2 x<<1" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24975/" ]
235,081
<p>We primarily use an ASP.NET environment at work. Right now I'm building an application which uses "Modules", which is just a UserControl, with its' Javascript right in the control, and a link element to the stylesheet for that control. I want to keep it modular, and would like the style of this control to be independent from the markup/javascript.</p> <p>So I'm wondering what the preferred method of doing this is? Obviously if I didn't want the "theme" functionality I'm after, I could just use style tags at the top of the control. Right now I have a link element, as I said, and this isn't proper I don't think. </p> <p>Does anyone have any preferred methods, and if so, what and why?</p> <hr> <p>I considered ASP.NET themes briefly, but the idea of these controls are a little different, I think.</p> <p>It's basically a shopping cart system. I don't want to get into it all, but we are using a really neat security system, and we don't want to use a premade shopping cart. I'm developing a set of controls that can be dropped on a page, for instance in SiteFinity (which is the CMS system we use) or for any other project we might have. Normally I would compile these into a DLL so we get ACTUAL controls we can drag &amp; drop from the toolbox, then I could use internal "generic" styling and allow for any additive styling someone might want, as well as supplying a few fancier styles as well.</p> <p>This is the first time I've ever done this, or really the first time anyone in our shop has done this either so I'm kind of figuring it out as I go. I might be pretty far off-base, but hopefully I'm not.</p> <hr> <p>Right, the idea for this is to have a "theme", which is really just a CSS file and a jQuery template. I have them named the same, and have a Theme property on the usercontrol to set it. </p> <p>When these controls are finalized, I might refactor the javascript to a RegisterScriptBlock on the code-behind, but for now they just in script tags on the control itself.</p> <p>What prompted this question was DebugBar for IE, giving me warnings that link elements are not allowed inside a div. I don't much care, but after thinking about it, I had no idea how to link to the css file without doing that. I considered very briefly having an 'empty' link tag on the master and then setting THAT in the code behind on Page_Load of the UserControl, but that just seems like ass.</p> <p>I could use @import I guess but I think link tags are preferred, correct?</p>
[ { "answer_id": 237526, "author": "sliderhouserules", "author_id": 31385, "author_profile": "https://Stackoverflow.com/users/31385", "pm_score": 3, "selected": true, "text": "string filePath = page.ClientScript.GetWebResourceUrl(type, css);\n\n// if filePath is not empty, embedded CSS exists -- register it\nif (!String.IsNullOrEmpty(filePath))\n{\n if (!Helpers.HeadContainsLinkHref(page, filePath))\n {\n HtmlLink link = new HtmlLink();\n link.Href = page.ResolveUrl(filePath);\n link.Attributes[\"type\"] = \"text/css\";\n link.Attributes[\"rel\"] = \"stylesheet\";\n page.Header.Controls.Add(link);\n }\n}\n" }, { "answer_id": 240450, "author": "thismat", "author_id": 14045, "author_profile": "https://Stackoverflow.com/users/14045", "pm_score": 1, "selected": false, "text": ".30daypricingcalc_main_content\n{\n ...\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31307/" ]
235,090
<p>How do you configure cruiseControl to send out emails that contains the error log whenever a build fails? I've gotten it to send out emails to users when the build fails, but it does not include the actual error that caused the build to fail. I know that if I only configure it to send out emails to the users that have made modifications, the error log is included in those emails. This is a sample of what I have:</p> <p>&lt; publishers><br/> &nbsp; &nbsp;&nbsp;&lt; rss/><br/> &nbsp; &nbsp;&nbsp;&lt; xmllogger/> <br/> &nbsp; &nbsp;&nbsp;&lt; email from="abc@abc.com" mailhost="abc.abc.com" includeDetails="TRUE"><br/>&nbsp; &nbsp;&nbsp; &lt; users><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; user name="Joe" group="devs" address="joe@abc.com"/><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; user name="Jim" group="devs" address="jim@abc.com"/><br/>&nbsp; &nbsp;&nbsp; &lt; /users><br/>&nbsp; &nbsp;&nbsp; &lt; groups><br/>&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt; group name="devs" notification="Failed"/><br/>&nbsp; &nbsp;&nbsp; &lt; /groups><br/>&nbsp; &nbsp;&nbsp; &lt; /email><br/> &lt; /publishers></p>
[ { "answer_id": 235210, "author": "stung", "author_id": 18170, "author_profile": "https://Stackoverflow.com/users/18170", "pm_score": 2, "selected": false, "text": "<!-- Specifies the stylesheets that are used to transform the build results when using the EmailPublisher -->\n<xslFiles>\n <file name=\"xsl\\header.xsl\" />\n <file name=\"xsl\\compile.xsl\" />\n <file name=\"xsl\\unittests.xsl\" />\n <file name=\"xsl\\fit.xsl\" />\n <file name=\"xsl\\modifications.xsl\" />\n <file name=\"xsl\\fxcop-summary.xsl\" />\n</xslFiles>\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,118
<p>I am trying to create a route with a Username...</p> <p>So the URL would be mydomain.com/abrudtkhul (abrudtkhul being the username)</p> <p>My application will have public profiles based on usernames (Ex: <a href="http://delicious.com/abrudtkuhl" rel="noreferrer">http://delicious.com/abrudtkuhl</a>). I want to replicate this URL scheme.</p> <p>How can I structure this in ASP.Net MVC? I am using Membership/Roles Providers too.</p>
[ { "answer_id": 235128, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": false, "text": "{username}\n Controller = \"Users\"\n routes.MapRoute(\n \"Users\",\n \"{username}\",\n new { controller = \"Users\" }\n" }, { "answer_id": 235276, "author": "danswain", "author_id": 30861, "author_profile": "https://Stackoverflow.com/users/30861", "pm_score": 1, "selected": false, "text": "routes.MapRoute(\n \"Users\",\n \"{username}\", \n new { controller = \"Users\", action=\"ShowUser\", username=\"\"});\n" }, { "answer_id": 235347, "author": "Javier Lozano", "author_id": 16016, "author_profile": "https://Stackoverflow.com/users/16016", "pm_score": 6, "selected": true, "text": "routes.MapRoute(\n \"Users\",\n \"{username}\", \n new { controller = \"User\", action=\"index\", username=\"\"});\n public ActionResult Index(MembershipUser usr)\n {\n ViewData[\"Welcome\"] = \"Viewing \" + usr.UserName;\n\n return View();\n }\n public class UserBinder : IModelBinder\n{\n public ModelBinderResult BindModel(ModelBindingContext bindingContext)\n {\n var request = bindingContext.HttpContext.Request;\n var username = request[\"username\"];\n MembershipUser user = Membership.GetUser(username);\n\n return new ModelBinderResult(user);\n }\n}\n public ActionResult Index([ModelBinder(typeof(UserBinder))] \n MembershipUser usr)\n{\n ViewData[\"Welcome\"] = \"Viewing \" + usr.Username;\n return View();\n}\n" }, { "answer_id": 575692, "author": "Steve T", "author_id": 415, "author_profile": "https://Stackoverflow.com/users/415", "pm_score": 4, "selected": false, "text": "// do not route the following\nroutes.IgnoreRoute(\"{resource}.axd/{*pathInfo}\");\nroutes.IgnoreRoute(\"content/{*pathInfo}\"); \nroutes.IgnoreRoute(\"images/{*pathInfo}\");\n\n// route the following based on the controller constraints\nroutes.MapRoute(\n \"Default\", // Route name\n \"{controller}/{action}/{id}\", // URL with parameters\n new { controller = \"Home\", action = \"Index\", id = \"\" } // Parameter defaults\n , new { controller = @\"(admin|help|profile|settings)\" } // Constraints\n);\n\n// this will catch the remaining allowed usernames\nroutes.MapRoute(\n \"Users\",\n \"{username}\",\n new { controller = \"Users\", action = \"View\", username = \"\" }\n);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12442/" ]
235,120
<p>In Apple's iPhone apps (like Contacts), they have a nice magnifying glass icon at the top of the table view index. Since the table view index API is character-based, I assume that this magnifying glass is a Unicode character. So far I've resorted to placing a question mark character there, but that looks lame.</p> <p>Can anyone tell me what character the magnifying glass is?</p>
[ { "answer_id": 236233, "author": "rpetrich", "author_id": 4007, "author_profile": "https://Stackoverflow.com/users/4007", "pm_score": 0, "selected": false, "text": "UIImageView" }, { "answer_id": 282849, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "@\"{search}\"" }, { "answer_id": 998819, "author": "user123417", "author_id": 123417, "author_profile": "https://Stackoverflow.com/users/123417", "pm_score": 8, "selected": true, "text": "UITableViewIndexSearch UITableView.indexSearch" }, { "answer_id": 2487909, "author": "Marcello Bastea-Forte", "author_id": 100374, "author_profile": "https://Stackoverflow.com/users/100374", "pm_score": 5, "selected": false, "text": "- (NSInteger) tableView:(UITableView *)tableView\nsectionForSectionIndexTitle:(NSString *)title\n atIndex:(NSInteger)index {\n if (index == 0) {\n [tableView setContentOffset:CGPointZero animated:NO];\n return NSNotFound;\n }\n return index;\n}\n" }, { "answer_id": 7498433, "author": "weibel", "author_id": 705741, "author_profile": "https://Stackoverflow.com/users/705741", "pm_score": 3, "selected": false, "text": "[NSString stringWithFormat:@\"%C%C\", 0xD83D, 0xDD0D];\n" }, { "answer_id": 18963037, "author": "ghiscoding", "author_id": 1212166, "author_profile": "https://Stackoverflow.com/users/1212166", "pm_score": 1, "selected": false, "text": "<input type=\"text\" style=\"font-family: Segoe UI Symbol;\" placeholder=\"&#128269;\">\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26829/" ]
235,127
<p>Can you do ajax on ASP.net webform without using ajax toolkit? (Please post a example link)</p>
[ { "answer_id": 235144, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 0, "selected": false, "text": "HttpHandler ajax.aspx // client-side js:\nvar foo = new Ajax.Request('ajax.aspx',\n{\n method:'get',\n parameters: { method: 'GetFive' },\n onSuccess: function(transport){\n var response = transport.responseText || \"no response text\";\n alert(\"Success! \\n\\n\" + response);\n},\nonFailure: function(){ alert('Something went wrong...') }\n});\n\n// web.config:\n<httpHandlers>\n <!-- pre existing handlers go here -->\n <add verb=\"GET\" path=\"ajax.aspx\" type=\"Fully.Qualified.Name.AjaxHandler, AssemblyName\" validate=\"false\" />\n</httpHandlers>\n\n// AjaxHandler.cs\npublic class AjaxHandler : IHttpHandler {\n internal delegate object AjaxFunction();\n\n private Dictionary<string, AjaxFunction> functions;\n\n public bool IsReusable {\n get { return true; }\n }\n\n public void ProcessRequest(HttpContext context) {\n this.functions = new Dicionary<string, AjaxFunction>();\n this.functions.Add(\"GetFive\", delegate() {\n return 5;\n });\n\n string functionName = context.Request[\"method\"];\n AjaxFunction func = this.functions[functionName];\n if (func != null) {\n object val = func();\n context.Response.Write(val);\n }\n }\n}\n" }, { "answer_id": 235190, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "$(\"#<%=telephoneNumber.ClientID %>\").attr(\"disabled\", \"disabled\");\n" }, { "answer_id": 235318, "author": "Corey Trager", "author_id": 9328, "author_profile": "https://Stackoverflow.com/users/9328", "pm_score": 0, "selected": false, "text": "function GetXmlHttpObject()\n{\n var objXMLHttp=null\n if (window.XMLHttpRequest)\n {\n objXMLHttp=new XMLHttpRequest()\n }\n else if (window.ActiveXObject)\n {\n objXMLHttp=new ActiveXObject(\"Microsoft.XMLHTTP\")\n }\n return objXMLHttp\n}\n\n\nfunction stateChanged()\n{\n if (xmlHttp.readyState==4 || xmlHttp.readyState==\"complete\")\n {\n // do something with xmlHttp.responseText\n }\n}\n\n\nfunction SendAsyncHttpRequest()\n{\n xmlHttp=GetXmlHttpObject()\n\n if (xmlHttp==null)\n {\n return\n }\n\n var url = \"http://YOUR_URL\"\n xmlHttp.onreadystatechange=stateChanged\n xmlHttp.open(\"GET\",url,true)\n xmlHttp.send(null)\n} \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
235,145
<p>I am building a Flex Application that calls a .aspx page on the same webserver which builds a PDF report using SQL Reporting Services. When the report is built it prompts the user to open or save the PDF.</p> <p>We are trying to find a way to display a Progress Bar to let the user know that the report they requested is being built, and then destroy the Progress Bar once the report is finished being built.</p> <p>I've tried opening a new window using JavaScript and trying to catch when the window closes, as well as trying XMLHTTPRequest, but nothing to seems to work.</p> <p>Does anyone have any suggestions?</p>
[ { "answer_id": 235271, "author": "Chetan S", "author_id": 31284, "author_profile": "https://Stackoverflow.com/users/31284", "pm_score": 1, "selected": false, "text": "FileReference" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235145", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31298/" ]
235,146
<p>I need to replace the standard Overflow function in a ToolStrip to a "More..." button which would then pop up a menu with the overflowed items. Does anyone have any ideas about how to accomplish this?</p>
[ { "answer_id": 235277, "author": "Nick", "author_id": 1490, "author_profile": "https://Stackoverflow.com/users/1490", "pm_score": 0, "selected": false, "text": "toolStrip1.OverflowButton.Paint += new PaintEventHandler(OverflowButton_Paint);\n VisibleChanged" }, { "answer_id": 254364, "author": "sbeskur", "author_id": 10446, "author_profile": "https://Stackoverflow.com/users/10446", "pm_score": 3, "selected": true, "text": " public class ToolStripCustomiseMenuItem : ToolStripDropDownButton {\n public ToolStripCustomiseMenuItem()\n : base(\"Add Remove Buttons\") {\n this.Overflow = ToolStripItemOverflow.Always;\n DropDown = CreateCheckImageContextMenuStrip();\n }\n\n ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();\n internal ContextMenuStrip CreateCheckImageContextMenuStrip() {\n ContextMenuStrip checkImageContextMenuStrip = new ContextMenuStrip();\n checkImageContextMenuStrip.ShowCheckMargin = true;\n checkImageContextMenuStrip.ShowImageMargin = true;\n checkImageContextMenuStrip.Closing += new ToolStripDropDownClosingEventHandler(checkImageContextMenuStrip_Closing);\n checkImageContextMenuStrip.Opening += new CancelEventHandler(checkImageContextMenuStrip_Opening);\n DropDownOpening += new EventHandler(ToolStripAddRemoveMenuItem_DropDownOpening);\n return checkImageContextMenuStrip;\n }\n\n void checkImageContextMenuStrip_Opening(object sender, CancelEventArgs e) {\n\n }\n\n void ToolStripAddRemoveMenuItem_DropDownOpening(object sender, EventArgs e) {\n DropDownItems.Clear();\n if (this.Owner == null) return;\n foreach (ToolStripItem ti in Owner.Items) {\n if (ti is ToolStripSeparator) continue;\n if (ti == this) continue;\n MyToolStripCheckedMenuItem itm = new MyToolStripCheckedMenuItem(ti);\n itm.Checked = ti.Visible;\n DropDownItems.Add(itm);\n }\n }\n\n void checkImageContextMenuStrip_Closing(object sender, ToolStripDropDownClosingEventArgs e) {\n if (e.CloseReason == ToolStripDropDownCloseReason.ItemClicked) {\n e.Cancel = true;\n }\n }\n}\n\ninternal class MyToolStripCheckedMenuItem : ToolStripMenuItem {\n ToolStripItem tsi;\n public MyToolStripCheckedMenuItem(ToolStripItem tsi)\n : base(tsi.Text) {\n this.tsi = tsi;\n this.Image = tsi.Image;\n this.CheckOnClick = true;\n this.CheckState = CheckState.Checked;\n CheckedChanged += new EventHandler(MyToolStripCheckedMenuItem_CheckedChanged);\n }\n\n void MyToolStripCheckedMenuItem_CheckedChanged(object sender, EventArgs e) {\n tsi.Visible = this.Checked;\n }\n\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4770/" ]
235,147
<p>I'm needing to cache some data using <strong>System.Web.Caching.Cache</strong>. Not sure if it matters, but the data does not come from a database, but a plethora of custom objects.</p> <p>The ASP.NET MVC is fairly new to me and I'm wondering where it makes sense for this caching to occur?</p> <h3>Model or Controller?</h3> <p>At some level this makes sense to cache at the <strong>Model</strong> level but I don't necessarily know the implications of doing this (if any). If caching were to be done at the <strong>Controller</strong> level, will that affect all requests, or just for the current <strong>HttpContext</strong>?</p> <p><strong>So... where should application data caching be done, and what's a good way of actually doing it?</strong></p> <h3>Update</h3> <p>Thanks for the great answers! I'm still trying to gather where it makes most sense to cache given different scenarios. If one is caching the entire page, then keeping it in the view makes sense but where to draw the line when it's not the entire page?</p>
[ { "answer_id": 327883, "author": "Ole Lynge", "author_id": 41094, "author_profile": "https://Stackoverflow.com/users/41094", "pm_score": 2, "selected": false, "text": "Entry IEntryHandler IEntryHandler" }, { "answer_id": 342761, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 2, "selected": false, "text": "[OutputCache(Duration=60, VaryByParam=\"None\")]\npublic ActionResult CacheDemo() {\n return View();\n}\n OutputCach" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4916/" ]
235,148
<p>I'm currently on chapter 4 of Real World Haskell, and I'm trying to wrap my head around <a href="http://book.realworldhaskell.org/read/functional-programming.html#x_E9" rel="noreferrer">implementing foldl in terms of foldr</a>.</p> <p>(Here's their code:)</p> <pre><code>myFoldl :: (a -&gt; b -&gt; a) -&gt; a -&gt; [b] -&gt; a myFoldl f z xs = foldr step id xs z where step x g a = g (f a x) </code></pre> <p>I thought I'd try to implement <code>zip</code> using the same technique, but I don't seem to be making any progress. Is it even possible?</p>
[ { "answer_id": 235207, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 3, "selected": false, "text": "myzip = foldr step (const []) :: [a] -> [b] -> [(a,b)]\n where step a f (b:bs) = (a,b):(f bs)\n step a f [] = []\n" }, { "answer_id": 235208, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 5, "selected": true, "text": "zip2 xs ys = foldr step done xs ys\n where done ys = []\n step x zipsfn [] = []\n step x zipsfn (y:ys) = (x, y) : (zipsfn ys)\n zip2 xs ys = foldr step done xs ys\n zip2 = foldr step done\n" }, { "answer_id": 235242, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 3, "selected": false, "text": "> (define (zip lista listb)\n ((foldr (lambda (el func)\n (lambda (a)\n (if (empty? a)\n empty\n (cons (cons el (first a)) (func (rest a))))))\n (lambda (a) empty)\n lista) listb))\n> (zip '(1 2 3 4) '(5 6 7 8))\n(list (cons 1 5) (cons 2 6) (cons 3 7) (cons 4 8))\n foldr lambda el->3, func->(lambda (a) empty)\n (lambda (a) (cons (cons el (first a)) (func (rest a))))\n(lambda (a) (cons (cons 3 (first a)) ((lambda (a) empty) (rest a))))\n > (define f (lambda (a) (cons (cons 3 (first a)) ((lambda (a) empty) (rest a)))))\n> (f (list 9))\n(list (cons 3 9))\n el->3, func->f ;using f for shorthand\n(lambda (a) (cons (cons el (first a)) (func (rest a))))\n(lambda (a) (cons (cons 2 (first a)) (f (rest a))))\n (list 2 3) > (define g (lambda (a) (cons (cons 2 (first a)) (f (rest a)))))\n> (g (list 9 1))\n(list (cons 2 9) (cons 3 1))\n (lambda (a) (cons (cons 2 (first a)) (f (rest a))))\n a (list 9 1) (cons (cons 2 (first (list 9 1))) (f (rest (list 9 1))))\n(cons (cons 2 9) (f (list 1)))\n f 3" }, { "answer_id": 26285107, "author": "Will Ness", "author_id": 849891, "author_profile": "https://Stackoverflow.com/users/849891", "pm_score": 4, "selected": false, "text": "f x1 ys f x1 r1 ys r1 = (f x2 (f x3 (... (f xn z) ...))) = foldr f z [x2,x3,...,xn] r1 ys1 foldr f z [x2,x3,...,xn] ys1 = f x2 r2 ys1 ys xs [] f ys xs f [] f xn z (yn:ysn) xs zip z = const [] zip xs ys = foldr f (const []) xs ys\n where\n f x r [] = []\n f x r (y:ys) = (x,y) : r ys\n f r f (x,y) r ys x z = const [] nil foldr ys x f [] ys ys xs f z = id x foldl f a xs =~ foldr (\\x r a-> r (f a x)) id xs a\n foldr f a xs =~ foldl (\\r x a-> r (f x a)) id xs a\n foldlWhile t f a xs = foldr cons id xs a\n where \n cons x r a = if t x then r (f a x) else a\n foldlWhen t ... cons x r a = if t x then r (f a x) else r a\n" }, { "answer_id": 34744061, "author": "Mirzhan Irkegulov", "author_id": 596361, "author_profile": "https://Stackoverflow.com/users/596361", "pm_score": 2, "selected": false, "text": "zip xs ys = foldr step done xs ys\n step done foldr foldr :: (a -> state -> state) -> state -> [a] -> state\n foldr foldr :: (a -> ? -> ?) -> ? -> [a] -> [b] -> [(a,b)]\n -> foldr :: (a -> ? -> ?) -> ? -> [a] -> ([b] -> [(a,b)])\n ([b] -> [(a,b)]) state foldr state foldr :: (a -> ([b] -> [(a,b)]) -> ([b] -> [(a,b)]))\n -> ([b] -> [(a,b)])\n -> [a]\n -> ([b] -> [(a,b)])\n foldr step :: a -> ([b] -> [(a,b)]) -> [b] -> [(a,b)]\ndone :: [b] -> [(a,b)]\nxs :: [a]\nys :: [b]\n foldr (+) 0 [1,2,3] 1 + (2 + (3 + 0))\n xs = [1,2,3] ys = [4,5,6,7] foldr 1 `step` (2 `step` (3 `step` done)) $ [4,5,6,7]\n 1 `step` (2 `step` (3 `step` done)) [4,5,6,7] [b] -> [(a,b)] 3 `step` done done 0 foldr (+) 0 [1..3] xs [] done done :: [b] -> [(a,b)]\n [] const done = const [] -- this is equivalent to done = \\_ -> []\n step a [b] -> [(a,b)] [b] -> [(a,b)] 3 `step` done (3,6) xs ys 3 `step` done \\(y:ys) -> (3,y) : done ys\n step foldr 3 `step` done -- becomes\n(\\(y:ys) -> (3,y) : done ys)\n2 `step` (\\(y:ys) -> (3,y) : done ys) -- becomes\n(\\(y:ys) -> (2,y) : (\\(y:ys) -> (3,y) : done ys) ys)\n1 `step` (\\(y:ys) -> (2,y) : (\\(y:ys) -> (3,y) : done ys) ys) -- becomes\n(\\(y:ys) -> (1,y) : (\\(y:ys) -> (2,y) : (\\(y:ys) -> (3,y) : done ys) ys) ys)\n ys step x f = \\[] -> []\nstep x f = \\(y:ys) -> (x,y) : f ys\n zip zip :: [a] -> [b] -> [(a,b)]\nzip xs ys = foldr step done xs ys\n where done = const []\n step x f [] = []\n step x f (y:ys) = (x,y) : f ys\n" }, { "answer_id": 42542733, "author": "Zemyla", "author_id": 4416280, "author_profile": "https://Stackoverflow.com/users/4416280", "pm_score": 3, "selected": false, "text": "zip newtype H a b = H { invoke :: H b a -> b }\n push :: (a -> b) -> H a b -> H a b\npush f q = H $ \\k -> f $ invoke k q\n (.#.) :: H b c -> H a b -> H a c\nf .#. g = H $ \\k -> invoke f $ g .#. k\n push (push f x) .#. (push g y) = push (f . g) (x .#. y)\n self :: H a a\nself = H $ \\k -> invoke k self\n base :: b -> H a b\nbase b = H $ const b\n run :: H a a -> a\nrun q = invoke q self\n run push base zip xs ys = run $ foldr (\\x h -> push (first x) h) (base []) xs .#. foldr (\\y h -> push (second y) h) (base Nothing) ys where\n first _ Nothing = []\n first x (Just (y, xys)) = (x, y):xys\n\n second y xys = Just (y, xys)\n build foldr" }, { "answer_id": 47565981, "author": "guthrie", "author_id": 593975, "author_profile": "https://Stackoverflow.com/users/593975", "pm_score": 0, "selected": false, "text": "lZip, rZip :: Foldable t => [b] -> t a -> [(a, b)]\n\n-- implement zip using fold?\nlZip xs ys = reverse.fst $ foldl f ([],xs) ys\n where f (zs, (y:ys)) x = ((x,y):zs, ys)\n\n-- Or;\nrZip xs ys = fst $ foldr f ([],reverse xs) ys\n where f x (zs, (y:ys)) = ((x,y):zs, ys)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7581/" ]
235,156
<p>I'd like to know if it is possible to redirect StreamWriter output to a variable</p> <p>Something like</p> <pre><code>String^ myString; StreamWriter sw = gcnew StreamWriter([somehow specify myString]) sw-&gt;WriteLine("Foo"); </code></pre> <p>then myString will contain Foo. The reason I would like to do this is to reuse a complex function. I should probably refactor it into a String returning function but it still would be a nice hack to know</p>
[ { "answer_id": 235194, "author": "Ely", "author_id": 30488, "author_profile": "https://Stackoverflow.com/users/30488", "pm_score": 6, "selected": false, "text": "StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\n// now, the StringWriter instance 'sw' will write to 'sb'\n" }, { "answer_id": 16556418, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "StringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\nstring s = sb.ToString(); <-- Now it will be a string.\n" }, { "answer_id": 29679597, "author": "Pascal Ganaye", "author_id": 964743, "author_profile": "https://Stackoverflow.com/users/964743", "pm_score": 4, "selected": false, "text": "MemoryStream mem = new MemoryStream(); \nStreamWriter sw = new StreamWriter(mem);\nsw.WriteLine(\"Foo\"); \n// then later you should be able to get your string.\n// this is in c# but I am certain you can do something of the sort in C++\nString result = System.Text.Encoding.UTF8.GetString(mem.ToArray(), 0, (int) mem.Length);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
235,166
<p>I'm trying to add parameters to an objectDataSource at runtime like this:</p> <pre><code> Parameter objCustomerParameter = new Parameter("CustomerID", DbType.String, customerID); Parameter objGPDatabaseParameter = new Parameter("Database", DbType.String, gpDatabase); //set up object data source parameters objCustomer.SelectParameters["CustomerID"] = objCustomerParameter; objCustomer.SelectParameters["Database"] = objGPDatabaseParameter; </code></pre> <p>At what point in the objectDataSource lifecycle should these parameters be added (what event)? Also, some values are coming from a master page property (which loads <em>after</em> the page_load of the page containing the objectDataSource).</p>
[ { "answer_id": 235217, "author": "wprl", "author_id": 17847, "author_profile": "https://Stackoverflow.com/users/17847", "pm_score": 2, "selected": false, "text": "PreInit" }, { "answer_id": 236420, "author": "Andy C.", "author_id": 28541, "author_profile": "https://Stackoverflow.com/users/28541", "pm_score": 6, "selected": true, "text": "e.InputParameters[\"CustomerID\"] = customerId;\ne.InputParameters[\"database\"] = dbName;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1874/" ]
235,188
<p>I want to implement user stories in a new project where can i find a good template or other ones used in agile development?</p>
[ { "answer_id": 235290, "author": "Hates_", "author_id": 3410, "author_profile": "https://Stackoverflow.com/users/3410", "pm_score": 5, "selected": false, "text": "As a <user> I want to <do something> so that <I can accomplish goal>.\n" }, { "answer_id": 8700486, "author": "mantrid", "author_id": 404357, "author_profile": "https://Stackoverflow.com/users/404357", "pm_score": 3, "selected": false, "text": "In order to <accomplish a goal>, as a <user> I want to <do something> \n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235188", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14440/" ]
235,191
<p>What is the best way to make trailing slashes not matter in the latest version of Routes (1.10)? I currently am using the clearly non-DRY:</p> <pre><code>map.connect('/logs/', controller='logs', action='logs') map.connect('/logs', controller='logs', action='logs') </code></pre> <p>I think that turning minimization on would do the trick, but am under the impression that it was disabled in the newer versions of Routes for a reason. Unfortunately documentation doesn't seem to have caught up with Routes development, so I can't find any good resources to go to. Any ideas?</p>
[ { "answer_id": 1441104, "author": "Marius Gedminas", "author_id": 110151, "author_profile": "https://Stackoverflow.com/users/110151", "pm_score": 4, "selected": false, "text": "map.redirect('/*(url)/', '/{url}',\n _redirect_code='301 Moved Permanently')\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235191", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12981/" ]
235,224
<p>I am curious to do what happens when you edit a post on this site.</p> <p>I am using wmd for my markdown editor, of course when I goto edit, I get the HTML it generated not the markdown like on stackoverflow. Now, is there a way I can store both? or is it reliable enough to simply convert the HTML back to markdown to show in the wmd editor?</p> <p>Thanks!</p>
[ { "answer_id": 235235, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "optionsExample.html" }, { "answer_id": 3850158, "author": "kvz", "author_id": 151666, "author_profile": "https://Stackoverflow.com/users/151666", "pm_score": 4, "selected": false, "text": "cat my.html | python html2text.py # outputs markdown\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29466/" ]
235,226
<p>I am having the worst luck with this. We bought a template to update our own website (don't have enough time to start our own from scratch!) but when I make simple changes in the Flash CS4 native file and re-export the swf, it doesn't work correctly!</p> <p>I am wondering if anyone has run across the same problems with a Template Monster Flash website template.</p> <p>Thanks.</p>
[ { "answer_id": 235235, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": true, "text": "optionsExample.html" }, { "answer_id": 3850158, "author": "kvz", "author_id": 151666, "author_profile": "https://Stackoverflow.com/users/151666", "pm_score": 4, "selected": false, "text": "cat my.html | python html2text.py # outputs markdown\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30043/" ]
235,231
<p>I have a requirement of reading subject, sender address and message body of new message in my Outlook inbox from a C# program. But I am getting security alert 'A Program is trying to access e-mail addresses you have stored in Outlook. Do you want to allow this'.</p> <p>By some googling I found few third party COM libraries to avoid this. But I am looking for a solution which don't require any third party COM library.</p>
[ { "answer_id": 1197190, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "string GetSenderEmail(Outlook.MailItem item)\n {\n string emailAddress = \"\";\n if (item.SenderEmailType == \"EX\")\n {\n Outlook.MailItem tempItem = (Outlook.MailItem)Globals.ThisAddIn.Application.CreateItem(Outlook.OlItemType.olMailItem);\n tempItem.To = item.SenderEmailAddress;\n emailAddress = tempItem.Recipients[1].AddressEntry.GetExchangeUser().PrimarySmtpAddress.Trim();\n\n }\n else\n {\n emailAddress = item.SenderEmailAddress.Trim();\n\n }\n\n return emailAddress;\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31001/" ]
235,233
<p>Derik Whitaker posted an <a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/10/22/how-is-interacting-with-your-data-repository-in-your-controller-different-or-better-than-doing-it-in-your-code-behind.aspx" rel="noreferrer">article</a> a couple of days ago that hit a point that I've been curious about for some time: <strong>should business logic exist in controllers?</strong></p> <p>So far all the ASP.NET MVC demos I've seen put repository access and business logic in the controller. Some even throw validation in there as well. This results in fairly large, bloated controllers. Is this really the way to use the MVC framework? It seems that this is just going to end up with a lot of duplicated code and logic spread out across different controllers.</p>
[ { "answer_id": 235243, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 7, "selected": true, "text": "public interface IOrderService{\n int CalculateTotal(Order order);\n}\n public class Order{\n int CalculateTotal(ITaxService service){...} \n}\n public class OrdersController{\n public OrdersController(ITaxService taxService, IOrdersRepository ordersRepository){...}\n\n public void Show(int id){\n ViewData[\"OrderTotal\"] = ordersRepository.LoadOrder(id).CalculateTotal(taxService);\n }\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
235,236
<p>Can JQuery and YUI live together w/o any conflicts?</p>
[ { "answer_id": 4330185, "author": "sebarmeli", "author_id": 506570, "author_profile": "https://Stackoverflow.com/users/506570", "pm_score": 3, "selected": false, "text": "YUI().use(\"test\", function(){\n test : function() {\n $('div li').addClass(\"example\");\n Y.Assert.areEqual(\"example\", $('div li').attr(\"class\"));\n }\n});\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,240
<p>Recently, <a href="https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception">I made a post about the developers I'm working with not using try catch blocks properly</a>, and unfortuantely using try... catch blocks in critical situations and ignoring the exception error all together. causing me major heart ache. Here is an example of one of the several thousand sections of code that they did this (some code left out that doesn't particuarly matter:</p> <pre><code>public void AddLocations(BOLocation objBllLocations) { try { dbManager.Open(); if (objBllLocations.StateID != 0) { // about 20 Paramters added to dbManager here } else { // about 19 Paramters added here } dbManager.ExecuteNonQuery(CommandType.StoredProcedure, "ULOCATIONS.AddLocations"); } catch (Exception ex) { } finally { dbManager.Dispose(); } } </code></pre> <p>This is absolutely discusting, in my eyes, and does not notify the user in case some potential problem occurred. I know many people say that OOP is evil, and that adding multiple layers adds to the number of lines of code and to the complexity of the program, leading to possible issues with code maintainence. Much of my programming background, I personally, have taken almost the same approach in this area. Below I have listed out a basic structure of the way I normally code in such a situation, and I've been doing this accross many languages in my career, but this particular code is in C#. But the code below is a good basic idea of how I use the Objects, it seems to work for me, but since this is a good source of some fairly inteligent programming mines, I'd like to know If I should re-evaluate this technique that I've used for so many years. Mainly, because, in the next few weeks, i'm going to be plunging into the not so good code from the outsourced developers and modifying huge sections of code. i'd like to do it as well as possible. sorry for the long code reference. </p> <pre><code>// ******************************************************************************************* /// &lt;summary&gt; /// Summary description for BaseBusinessObject /// &lt;/summary&gt; /// &lt;remarks&gt; /// Base Class allowing me to do basic function on a Busines Object /// &lt;/remarks&gt; public class BaseBusinessObject : Object, System.Runtime.Serialization.ISerializable { public enum DBCode { DBUnknownError, DBNotSaved, DBOK } // private fields, public properties public int m_id = -1; public int ID { get { return m_id; } set { m_id = value; } } private int m_errorCode = 0; public int ErrorCode { get { return m_errorCode; } set { m_errorCode = value; } } private string m_errorMsg = ""; public string ErrorMessage { get { return m_errorMsg; } set { m_errorMsg = value; } } private Exception m_LastException = null; public Exception LastException { get { return m_LastException; } set { m_LastException = value;} } //Constructors public BaseBusinessObject() { Initialize(); } public BaseBusinessObject(int iID) { Initialize(); FillByID(iID); } // methods protected void Initialize() { Clear(); Object_OnInit(); // Other Initializable code here } public void ClearErrors() { m_errorCode = 0; m_errorMsg = ""; m_LastException = null; } void System.Runtime.Serialization.ISerializable.GetObjectData( System.Runtime.Serialization.SerializationInfo info, System.Runtime.Serialization.StreamingContext context) { //Serialization code for Object must be implemented here } // overrideable methods protected virtual void Object_OnInit() { // User can override to add additional initialization stuff. } public virtual BaseBusinessObject FillByID(int iID) { throw new NotImplementedException("method FillByID Must be implemented"); } public virtual void Clear() { throw new NotImplementedException("method Clear Must be implemented"); } public virtual DBCode Save() { throw new NotImplementedException("method Save Must be implemented"); } } // ******************************************************************************************* /// &lt;summary&gt; /// Example Class that might be based off of a Base Business Object /// &lt;/summary&gt; /// &lt;remarks&gt; /// Class for holding all the information about a Customer /// &lt;/remarks&gt; public class BLLCustomer : BaseBusinessObject { // *************************************** // put field members here other than the ID private string m_name = ""; public string Name { get { return m_name; } set { m_name = value; } } public override void Clear() { m_id = -1; m_name = ""; } public override BaseBusinessObject FillByID(int iID) { Clear(); try { // usually accessing a DataLayerObject, //to select a database record } catch (Exception Ex) { Clear(); LastException = Ex; // I can have many different exception, this is usually an enum ErrorCode = 3; ErrorMessage = "Customer couldn't be loaded"; } return this; } public override DBCode Save() { DBCode ret = DBCode.DBUnknownError; try { // usually accessing a DataLayerObject, //to save a database record ret = DBCode.DBOK; } catch (Exception Ex) { LastException = Ex; // I can have many different exception, this is usually an enum // i do not usually use just a General Exeption ErrorCode = 3; ErrorMessage = "some really weird error happened, customer not saved"; ret = DBCode.DBNotSaved; } return ret; } } // ******************************************************************************************* // Example of how it's used on an asp page.. protected void Page_Load(object sender, EventArgs e) { // Simplifying this a bit, normally, I'd use something like, // using some sort of static "factory" method // BaseObject.NewBusinessObject(typeof(BLLCustomer)).FillByID(34); BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34); if (cust.ErrorCode != 0) { // There was an error.. Error message is in //cust.ErrorMessage // some sort of internal error code is in //cust.ErrorCode // Give the users some sort of message through and asp:Label.. // probably based off of cust.ErrorMessage //log can be handled in the data, business layer... or whatever lab.ErrorText = cust.ErrorMessage; } else { // continue using the object, to fill in text boxes, // literals or whatever. this.labID = cust.ID.toString(); this.labCompName = cust.Name; } } </code></pre> <p>Bottom line, my question is, Am I over complicating things with the muliple layers, and the inherited classes or is my old concept illustrated still working good and stable? Is there a better way now a days to accomplish these things? Should I go to just making straight SQL calls from the asp.net page code behind pages as fellow work associate developer suggested (though that last solution makes me feel icky), instead of going through a business object, and data layer (data layer not shown, but basically holds all the stored proc calls). Yeah, another developer did ask me why i go through the effort of layering things, when you can just type what you need straight in a *.aspx.cs code behind page, and then I can have the joys of over 1k lines of code behind. What is some advice here?</p>
[ { "answer_id": 235301, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 2, "selected": true, "text": "BLLCustomer cust = ((BLLCustomer)new BLLCustomer()).FillByID(34);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18893/" ]
235,248
<p>In Silverlight how can I launch / navigate to another page?</p>
[ { "answer_id": 235253, "author": "Eric", "author_id": 4540, "author_profile": "https://Stackoverflow.com/users/4540", "pm_score": 4, "selected": true, "text": "System.Windows.Browser.HtmlPage.Window.Navigate(\n new Uri( \"http://www.google.com\" ),\n \"_blank\"\n );\n" }, { "answer_id": 6353036, "author": "Philip K. Adetiloye", "author_id": 706454, "author_profile": "https://Stackoverflow.com/users/706454", "pm_score": 2, "selected": false, "text": "Frame frame =this.parent as Frame;\nframe.navigate(new Uri(\"/Views/Details.xaml\"),Uri.Relative);\n" }, { "answer_id": 6806639, "author": "Ernest Poletaev", "author_id": 771098, "author_profile": "https://Stackoverflow.com/users/771098", "pm_score": 1, "selected": false, "text": "this.NavigationService.Navigate(new Uri(\"/OtherPage.xaml\", UriKind.Relative));\n" }, { "answer_id": 15001687, "author": "user2045883", "author_id": 2045883, "author_profile": "https://Stackoverflow.com/users/2045883", "pm_score": 0, "selected": false, "text": "this.content=new (place the page name which You want to navigate);\n\n but this code only works while navigate page having in same folder else You have to write like in given below manner\n here in place of Views write the folder name where the page having...\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4540/" ]
235,254
<p>I am running GNU Emacs on Windows so entering:</p> <pre><code>M-x shell </code></pre> <p>launches the Windows command-line DOS shell. However, I would like to instead be able to run the Cygwin Bash Shell (or any other non-Windows shell) from within Emacs. How can this be easily done?</p>
[ { "answer_id": 235344, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 3, "selected": false, "text": "init.el ;; Let's use CYGWIN bash...\n;;\n(setq binary-process-input t) \n(setq w32-quote-process-args ?\\\") \n(setq shell-file-name \"bash\") ;; or sh if you rename your bash executable to sh. \n(setenv \"SHELL\" shell-file-name) \n(setq explicit-shell-file-name shell-file-name) \n(setq explicit-sh-args '(\"-login\" \"-i\"))\n" }, { "answer_id": 235356, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 6, "selected": true, "text": "shell-file-name explicit-shell-file-name M-x shell explicit-shell-file-name (defun cygwin-shell ()\n \"Run cygwin bash in shell mode.\"\n (interactive)\n (let ((explicit-shell-file-name \"C:/cygwin/bin/bash\"))\n (call-interactively 'shell)))\n --login explicit-bash-args M-x shell explicit- -args .exe" }, { "answer_id": 339026, "author": "Ray", "author_id": 4872, "author_profile": "https://Stackoverflow.com/users/4872", "pm_score": 2, "selected": false, "text": "Microsoft Windows XP [Version 5.1.2600]\n(C) Copyright 1985-2001 Microsoft Corp.\n\nC:\\temp>bash\nbash \n ls\nbash: line 1: $'ls\\r': command not found\n ls #\nmyfile,txt\nfoo.bar\nanotherfile.txt\n" }, { "answer_id": 2164491, "author": "Yoo", "author_id": 37664, "author_profile": "https://Stackoverflow.com/users/37664", "pm_score": 2, "selected": false, "text": "C-h a shell$" }, { "answer_id": 8748674, "author": "Chris Jones", "author_id": 107357, "author_profile": "https://Stackoverflow.com/users/107357", "pm_score": 3, "selected": false, "text": ";; When running in Windows, we want to use an alternate shell so we\n;; can be more unixy.\n(setq shell-file-name \"C:/MinGW/msys/1.0/bin/bash\")\n(setq explicit-shell-file-name shell-file-name)\n(setenv \"PATH\"\n (concat \".:/usr/local/bin:/mingw/bin:/bin:\"\n (replace-regexp-in-string \" \" \"\\\\\\\\ \"\n (replace-regexp-in-string \"\\\\\\\\\" \"/\"\n (replace-regexp-in-string \"\\\\([A-Za-z]\\\\):\" \"/\\\\1\"\n (getenv \"PATH\"))))))\n" }, { "answer_id": 13453672, "author": "mcheema", "author_id": 519057, "author_profile": "https://Stackoverflow.com/users/519057", "pm_score": 0, "selected": false, "text": " (setq explicit-bash-args '(\"--noediting\" \"-i\"))\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4872/" ]
235,258
<p>Can a <code>JApplet</code> use a <code>JFileChooser</code> so that the user can select a file on his hard-drive? Or would this violate Java applet security? (I'm assuming that the default security settings are being used. I don't want to ask my users to grant me extra permissions.)</p>
[ { "answer_id": 235321, "author": "Michael Myers", "author_id": 13531, "author_profile": "https://Stackoverflow.com/users/13531", "pm_score": 3, "selected": true, "text": "JFileChooser" }, { "answer_id": 237840, "author": "hishadow", "author_id": 7188, "author_profile": "https://Stackoverflow.com/users/7188", "pm_score": 2, "selected": false, "text": "URL appletUrl = MyApplet.class.getProtectionDomain().getCodeSource().getLocation();\nif(appletUrl.toString().equalsIgnoreCase(safeAppletUrl) == false)\n return false;\n URL documentUrl = this.getDocumentBase(); \nif(documentUrl.toString().equalsIgnoreCase(safeDocumentUrl) == false)\n return false;\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7648/" ]
235,264
<p>I am trying to connect to 2 databases on the same instance of MySQL from 1 PHP script.</p> <p>At the moment the only way I've figured out is to connect to both databases with a different user for each.</p> <p>I am using this in a migration script where I am grabbing data from the original database and inserting it into the new one, so I am looping through large lists of results.</p> <p>Connecting to 1 database and then trying to initiate a second connection with the same user just changes the current database to the new one.</p> <p>Any other ideas?</p>
[ { "answer_id": 235294, "author": "The.Anti.9", "author_id": 2128, "author_profile": "https://Stackoverflow.com/users/2128", "pm_score": 2, "selected": false, "text": " $old = mysql_connect('old.database.com', 'user', 'pass);\n mysql_select_db('old_db', $old);\n\n\n $new = mysql_connect('new.database.com','user','pass);\n mysql_select_db('new_db', $new)\n\n // run select query on $old\n // run matching insert query on $new\n" }, { "answer_id": 235334, "author": "Gaurav", "author_id": 13492, "author_profile": "https://Stackoverflow.com/users/13492", "pm_score": 3, "selected": false, "text": "$db_conn = connect_db(host, user, pwd);\nmysql_select_db('existing_db', $db_conn);\n -- do selects and scrub data --\nmysql_select_db('new_db', $db_conn);\n-- insert the required data --\n" }, { "answer_id": 235353, "author": "Joe Lencioni", "author_id": 18986, "author_profile": "https://Stackoverflow.com/users/18986", "pm_score": 4, "selected": false, "text": "SELECT column\nFROM database.table\n INSERT INTO INSERT INTO database1.table (column)\nSELECT database2.table.column\nFROM database2.table\n" }, { "answer_id": 38803098, "author": "Rajpal Singh", "author_id": 4179025, "author_profile": "https://Stackoverflow.com/users/4179025", "pm_score": 0, "selected": false, "text": "<?php\n define('HOST', \"YOURHOSTNAME\");\n define('USER', \"YOURHOSTNAME\");\n define('PASS', \"YOURHOSTNAME\");\n define('DATABASE1', \"NAMEOFDATABASE1\");\n define('DATABASE2', \"NAMEOFDATABASE2\");\n\n $DATABASE1 = mysqli_connect(HOST, USER, PASS, DATABASE1);\n $DATABASE2 = mysqli_connect(HOST, USER, PASS, DATABASE2);\n if(!$DATABASE1){\n die(\"DATABASE1 CONNECTION ERROR: \".mysqli_connect_error());\n }\n if(!$DATABASE2){\n die(\"DATABASE2 CONNECTION ERROR: \".mysqli_connect_error());\n }\n\n\n $sql = \"SELECT * FROM TABLE\"; /* You can use your own query */\n\n $DATABASE1_QUERY = mysqli_query($DATABASE1, $sql);\n $DATABASE2_QUERY = mysqli_query($DATABASE2, $sql);\n\n $DATABASE1_RESULT = mysqli_fetch_assoc($DATABASE1_QUERY);\n $DATABASE2_RESULT = mysqli_fetch_assoc($DATABASE2_QUERY);\n\n /* SHOW YOUR RESULT HERE WHICH DATABASE YOU WANT FROM */\n echo $DATABASE1_RESULT['id'];\n echo $DATABASE2_RESULT['id'];\n\n\n /*After complete your all work don't forgot about close database connections*/\n mysqli_close($DATABASE1);\n mysqli_close($DATABASE2);\n ?>\n" }, { "answer_id": 38803253, "author": "Sachin Sanchaniya", "author_id": 6082661, "author_profile": "https://Stackoverflow.com/users/6082661", "pm_score": -1, "selected": false, "text": "$database1 = mysql_connect(\"localhost\",\"root\",\"password\");\n$database2 = mysql_connect(\"localhost\",\"root\",\"password\");\n $database1_select = mysql_select_db(\"db_name_1\") or die(\"Can't Connect To Database\",$database1);\n$database_select = mysql_select_db(\"db_name_2\") or die(\"Can't Connect To Database\",$database2);\n $select = mysql_query(\"SELECT * FROM table_name\",$database1);\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
235,272
<p>I'm probably doing this all wrong. I have a text file full of data and I want to match and replace patterns of "item" and "catalog number" that are in the file. But the order of each element in the file is very important, so I want to match/replace starting from the top of the file and then work my way down.</p> <p>The code snippet below actually works, but when I execute it, it replaces the third instance of the "SeaMonkey" &amp; "SMKY-1978" pattern and then it replaces the second instance of that pattern. What I'd like it to do is replace the first instance of the pattern and then the second.</p> <p>So I'd like the output to say "Found <strong>Kurt's</strong> SMKY-1978 SeaMonkeys" and then "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and then leave Mick's SMKY-1978 SeaMonkeys alone since I only want to find and replace the first 2 instances of the pattern. Right now it says "Found <strong>Shane's</strong> SMKY-1978 SeaMonkeys" and "Found <strong>Mick's</strong> SMKY-1978 SeaMonkeys" because it is matching the last pattern each time the for loop is executed.</p> <p>So am I missing a subtle little known regex character or am I just doing what I want to do completely and utterly wrong?</p> <p>Here is the working code:</p> <pre><code># my regexp matches from the bottom to the top but I'd like it to replace from the top down local $/=undef; my $DataToParse = &lt;DATA&gt;; my $item = "SeaMonkeys"; my $catNum = "SMKY-1978"; my $maxInstancesToReplace = 2; parseData(); exit(); sub parseData { for (my $counter = 0; $counter &lt; $maxInstancesToReplace; $counter++) { # Stick in a temporary text placeholder that I will replace later after more processing $DataToParse =~ s/(.+)\sELEMENT\s(.+?)\s\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/$1 ***** Found $2\'s $catNum $item. (counter: $counter) *****$3/s; } print("Here's the result:\n$DataToParse\n"); } __DATA__ ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ELEMENT Shane (Item := "SeaMonkeys", ItemID := 1032, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ELEMENT Mick (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1978/F", Vendor := 77, END_ELEMENT ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT </code></pre> <p>And here is what it currently outputs:</p> <pre>Here's the result: ELEMENT Kurt (Item := "BrightLite", ItemID := 29, CatalogNumber := "BTLT-9274", Vendor := 100, END_ELEMENT ELEMENT Mick (Item := "PetRock", ItemID := 36, CatalogNumber := "PTRK-3475/A", Vendor := 82, END_ELEMENT ELEMENT Kurt (Item := "SeaMonkeys", ItemID := 12, CatalogNumber := "SMKY-1978/E", Vendor := 77, END_ELEMENT ELEMENT Joe (Item := "Pong", ItemID := 24, CatalogNumber := "PONG-1482", Vendor := 5, END_ELEMENT ***** Found Shane's SMKY-1978 SeaMonkeys. (counter: 1) ***** ELEMENT Kurt (Item := "Battleship", ItemID := 99, CatalogNumber := "BTLS-5234", Vendor := 529, END_ELEMENT ***** Found Mick's SMKY-1978 SeaMonkeys. (counter: 0) ***** ELEMENT Frank (Item := "PetRock", ItemID := 42, CatalogNumber := "PTRK-3475/B", Vendor := 82, END_ELEMENT ELEMENT Joe (Item := "SeaMonkeys", ItemID := 8, CatalogNumber := "SMKY-1979/A", Vendor := 77, END_ELEMENT</pre>
[ { "answer_id": 235300, "author": "Alexandr Ciornii", "author_id": 13467, "author_profile": "https://Stackoverflow.com/users/13467", "pm_score": 4, "selected": false, "text": "my $re=qr/\\sELEMENT\\s(.+?)\\s\\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT/;\n sub parseData {\n my $re=qr/\\sELEMENT\\s(.+?)\\s\\(Item := \"$item\".+?CatalogNumber := \"$catNum.+?END_ELEMENT(.+)/;\n foreach my $counter (0..$maxInstancesToReplace) {\n # Stick in a temporary text placeholder that I will replace later after more processing\n $DataToParse =~ s/$re/ ***** Found $1\\'s $catNum $item. (counter: $counter) *****$2/s;\n } \n print(\"Here's the result:\\n$DataToParse\\n\");\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27687/" ]
235,326
<p>I want to hold a bunch of const char pointers into an std::set container [1]. std::set template requires a comparator functor, and the standard C++ library offers std::less, but its implementation is based on comparing the two keys directly, which is not standard for pointers.</p> <p>I know I can define my own functor and implement the operator() by casting the pointers to integers and comparing them, but is there a cleaner, 'standard' way of doing it?</p> <p>Please do not suggest creating std::strings - it is a waste of time and space. The strings are static, so they can be compared for (in)equality based on their address.</p> <p>1: The pointers are to static strings, so there is no problem with their lifetimes - they won't go away.</p>
[ { "answer_id": 235330, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "std::string" }, { "answer_id": 235336, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 2, "selected": false, "text": "struct MyCharComparator\n{\n bool operator()(const char * A, const char * B) const\n {\n return (strcmp(A, B) < 0) ;\n }\n} ;\n std::set<const char *, MyCharComparator>\n std::set<std::string>\n { \"AAA\", \"AAA\", \"AAA\" }\n std::set<const char *>\n" }, { "answer_id": 235337, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 0, "selected": false, "text": "const char* std::string std::set const char* const char* data = theString.c_str();\n" }, { "answer_id": 235339, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "std::string struct ConstCharStarComparator\n{\n bool operator()(const char *s1, const char *s2) const\n {\n return strcmp(s1, s2) < 0;\n }\n};\n\ntypedef std::set<const char *, ConstCharStarComparator> stringset_t;\nstringset_t myStringSet;" }, { "answer_id": 235354, "author": "Andrew Top", "author_id": 30036, "author_profile": "https://Stackoverflow.com/users/30036", "pm_score": -1, "selected": false, "text": "bool foo = \"blah\" < \"grar\";\n std::set<const char*> int std::string std::string const char* std::string strcmp" }, { "answer_id": 235370, "author": "xtofl", "author_id": 6610, "author_profile": "https://Stackoverflow.com/users/6610", "pm_score": 0, "selected": false, "text": "std::string const char* a(\"a\");\nconst char* b(\"b\");\n\nstruct CWrap {\n const char* p;\n bool operator<(const CWrap& other) const{\n return strcmp( p, other.p ) < 0;\n }\n CWrap( const char* p ): p(p){}\n};\n\nstd::set<CWrap> myset;\nmyset.insert(a);\nmyset.insert(b);\n" }, { "answer_id": 236057, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 0, "selected": false, "text": "const char* std::string std::set std::set std::set std::vector operator< static const char keys[] = \"apple\\0banana\\0cantaloupe\";\n std::set<const char*> uintptr_t" }, { "answer_id": 236364, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 3, "selected": true, "text": "set<const char*>" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235326", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18308/" ]
235,345
<p>I'm working on a consumer web app that needs to do a long running background process that is tied to each customer request. By long running, I mean anywhere between 1 and 3 minutes.</p> <p>Here is an example flow. The object/widget doesn't really matter.</p> <ol> <li>Customer comes to the site and specifies object/widget they are looking for.</li> <li>We search/clean/filter for widgets matching some initial criteria. &lt;-- long running process</li> <li>Customer further configures more detail about the widget they are looking for.</li> <li>When the long running process is complete the customer is able to complete the last few steps before conversion. </li> </ol> <p>Steps 3 and 4 aren't really important. I just mention them because we can buy some time while we are doing the long running process.</p> <p>The environment we are working in is a LAMP stack-- currently using PHP. It doesn't seem like a good design to have the long running process take up an apache thread in mod_php (or fastcgi process). The apache layer of our app <em>should</em> be focused on serving up content and not data processing IMO. </p> <p>A few questions:</p> <ol> <li>Is our thinking right in that we should separate this "long running" part out of the apache/web app layer?</li> <li>Is there a <em>standard/typical</em> way to break this out under Linux/Apache/MySQL/PHP (we're open to using a different language for the processing if appropriate)?</li> <li>Any suggestions on how to go about breaking it out? E.g. do we create a deamon that churns through a FIFO queue?</li> </ol> <p>Edit: Just to clarify, only about 1/4 of the long running process is database centric. We're working on optimizing that part. There is some work that we could potentially do, but we are limited in the amount we can do right now.</p> <p>Thanks!</p>
[ { "answer_id": 235357, "author": "jonnii", "author_id": 4590, "author_profile": "https://Stackoverflow.com/users/4590", "pm_score": 0, "selected": false, "text": "exec (\"/usr/bin/php long_running_process.php > /dev/null &\");\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8243/" ]
235,360
<p>Today I had a discussion with a colleague about nested functions in Javascript:</p> <pre><code>function a() { function b() { alert('boo') } var c = 'Bound to local call object.' d = 'Bound to global object.' } </code></pre> <p>In this example, trials point out that b is not reachable outside the body of a, much like c is. However, d is - after executing a(). Looking for the exact definition of this behaviour in the <a href="http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf" rel="noreferrer">ECMAScript v.3 standard </a>, I didn't find the exact wording I was looking for; what Sec.13 p.71 does not say, is which object the function object created by the function declaration statement is to be bound to. Am I missing something?</p>
[ { "answer_id": 235377, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "function a() { ... }\n var a = function() { ... }\n" }, { "answer_id": 235388, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n d = 'Bound to global object.'\n}\n function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n var d = 'Bound to local object.'\n}\n" }, { "answer_id": 235550, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "function a() {\n d = 'Hello World';\n}\nalert(window.d); // shows 'Hello World'\n function a() {\n document = 'something';\n}\n with(window)" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31330/" ]
235,369
<p>I've searched around a bit in the small amount of iPhone/iPod Touch development information available and couldn't find anything for or against. Can an application find out information about currently playing song on iPhone/iPod Touch? Since the music can continue to play while you are in 3rd party applications, is there a function or library that will give you information about what is playing? (Track, Artist, Album, etc.) I know generally that applications are sand-boxed but thought maybe there was a way.</p>
[ { "answer_id": 235377, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "function a() { ... }\n var a = function() { ... }\n" }, { "answer_id": 235388, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 0, "selected": false, "text": "function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n d = 'Bound to global object.'\n}\n function a() {\n function b() {\n alert('boo')\n }\n var c = 'Bound to local call object.'\n var d = 'Bound to local object.'\n}\n" }, { "answer_id": 235550, "author": "Prestaul", "author_id": 5628, "author_profile": "https://Stackoverflow.com/users/5628", "pm_score": 2, "selected": false, "text": "function a() {\n d = 'Hello World';\n}\nalert(window.d); // shows 'Hello World'\n function a() {\n document = 'something';\n}\n with(window)" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2133351/" ]
235,373
<p>I've been trying to modify the following menu to make it look indentical in IE, Firefox, and Safari/Chrome but I can't seem to get it to look right in Safari/Chrome.</p> <p>Could anyone tell me how to fix it? When viewed in Safari or Chrome, notice that the menu is ignoring the padding.</p> <p><a href="http://www.candesprojects.com/downloads/flickr-horizontal-menu/" rel="nofollow noreferrer">View flickr-like menu</a></p> <p>Thanks in advance!</p>
[ { "answer_id": 473162, "author": "Bo Jeanes", "author_id": 56690, "author_profile": "https://Stackoverflow.com/users/56690", "pm_score": 0, "selected": false, "text": "inline inline-block" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,376
<p>Is there any way to add a field to a class at runtime ( a field that didn't exist before ) ? Something like this snippet :</p> <pre><code>Myobject *ob; // create an object ob-&gt;addField("newField",44); // we add the field to the class and we assign an initial value to it printf("%d",ob-&gt;newField); // now we can access that field </code></pre> <p>I don't really care how it would be done , I don't care if it's an ugly hack or not , I would like to know if it could be done , and a small example , if possible .</p> <p><strong>Another Example:</strong> say I have an XML file describing this class :</p> <pre><code>&lt;class name="MyClass"&gt; &lt;member name="field1" /&gt; &lt;member name="field2" /&gt; &lt;/class&gt; </code></pre> <p>and I want to "add" the fields "field1" and "field2" to the class (assuming the class already exists) . Let's say this is the code for the class :</p> <pre><code>class MyClass { }; </code></pre> <p>I don't want to create a class at runtime , I just want to add members/fields to an existing one .</p> <p>Thank you !</p>
[ { "answer_id": 235417, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 2, "selected": false, "text": "std::vector<void*> extra_data;\n size_t add_data_link(void *p); // points to existing data, returns index\nsize_t add_data_copy(void *p, size_t s) // copies data (dispose at\n // destruction time!), returns \n // index \nvoid* get_data(size_t i); //...\n" }, { "answer_id": 235482, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 2, "selected": false, "text": "template< typename T > T get_member( string name );\ntemplate< typename T > void set_member( string name, T value );\n" }, { "answer_id": 235503, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 5, "selected": true, "text": "#include <map>\n#include <boost/variant.hpp>\n\ntypedef boost::variant< int, std::string > MyValue ;\ntypedef std::map<std::string, MyValue> MyValueMap ;\n oMyValueMap.insert(std::make_pair(\"newField\", 44)) ;\noMyValueMap.insert(std::make_pair(\"newField2\", \"Hello World\")) ;\nstd::cout << oMyValueMap[\"newField\"] ;\nstd::cout << oMyValueMap[\"newField2\"] ;\n oMyObject.addField(\"newField\", 44) ;\noMyObject.addField(\"newField2\", \"Hello World\") ;\nstd::cout << oMyObject[\"newField\"] ;\nstd::cout << oMyObject[\"newField2\"] ;\n" }, { "answer_id": 8537463, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "struct AnyMap {\n void addAnyPair( const std::string& key , boost::any& value );\n\n template<typename T>\n T& get( const std::string key ) {\n return( boost::any_cast<T&>(map_[key]) );\n }\n\n std::map<const std::string, boost::any> map_;\n};\n\nvoid AnyMap::addAnyPair( const std::string& key , boost::any& value ) {\n map_.insert( std::make_pair( key, value ) );\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11234/" ]
235,383
<p>In traditional Waterfall, requirements were gathered - typically in a MS-Word document - following an esoteric template. In a "strict" waterfall model, this document is frozen after the requirement phase and a Change Control / Change Management process is responsible for introducing controlled changes. (**) [Typically, the document is turned into a "living document" and eventually a "living nightmare"]</p> <p>Currently, I've to lead a project that is a rewrite of an existing desktop application to web (from VB 6.0 to ASP.Net). The client has a baselined version of the application that he wants rewritten. [So requirments are frozen... No scope creep]. The data model to be reused as is. Only the front end/Business rules to be migrated. Looking at the application, I feel it's a at most 3/4 major screens and that's it.</p> <p>Some of the team members want to document (old school of thought, in my opinion) the entire thing before they start on the new development. I &amp; and some others feel, it shoud be relatively easy translate the UI to Web, to look up old code, write the business logic, do automated unit tests, proceed to integration tests and deliver screen by screen (or business function by function)</p> <p>My question is: In an Agile development how I do I remain "agile" if I were not to optimize this. My opinion is writing detailed documentation is anti-agile. What do you think? How would an agile guru approach the above problem (of rewriting an existing VB 6.0 app to ASP.Net)?</p> <hr> <p>Disclaimer: <em>Creation of a 1000 page Functional Spec could possibly be to meet contractual obligations, a political necessity, the system could be genuinely complex (now, definition of "complexity" is a journey unto murky-land).</em></p>
[ { "answer_id": 15463234, "author": "Josh Bruce", "author_id": 1304423, "author_profile": "https://Stackoverflow.com/users/1304423", "pm_score": 2, "selected": false, "text": "Given I am working on a document\nWhen I select \"Save As...\"\nThen a menu should appear allowing me to choose a name, \nand a file type, \nand a location in the file system,\nand a file should be created in the file system\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235383", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28413/" ]
235,386
<p>What's the best way to use NaNs in C++?</p> <p>I found <code>std::numeric_limits&lt;double&gt;::quiet_NaN()</code> and <code>std::numeric_limits&lt;double&gt;::signaling_NaN()</code>. I'd like to use <code>signaling_NaN</code> to represent an uninitialized variable as follows:</p> <pre><code>double diameter = std::numeric_limits&lt;double&gt;::signaling_NaN(); </code></pre> <p>This, however, signals (raises an exception) on assignment. I want it to raise an exception on use, not on assignment.</p> <p>Is there any way to use <code>signaling_NaN</code> without raising an exception on assignment? Is there a good, portable alternative to <code>signaling_NaN</code> that will raise a floating point exception when used?</p>
[ { "answer_id": 235490, "author": "Menkboy", "author_id": 29539, "author_profile": "https://Stackoverflow.com/users/29539", "pm_score": 2, "selected": false, "text": "void set_snan( double &d )\n{\n long long *bits = (long long *)&d;\n *bits = 0x7ff0000080000001LL;\n}\n" }, { "answer_id": 236942, "author": "HS.", "author_id": 1398, "author_profile": "https://Stackoverflow.com/users/1398", "pm_score": 2, "selected": false, "text": "double value = _Nan._Double;\n" }, { "answer_id": 236952, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "template <class T>\nclass initialized {\n T t;\n bool is_initialized;\npublic:\n initialized() : t(T()), is_initialized(false) { }\n initialized(const T& tt) : t(tt), is_initialized(true) { }\n T& operator=(const T& tt) { t = tt; is_initialized = true; return t; }\n operator T&() {\n if (!is_initialized)\n throw std::exception(\"uninitialized\");\n return t; \n }\n};\n" }, { "answer_id": 281771, "author": "Josh Kelley", "author_id": 25507, "author_profile": "https://Stackoverflow.com/users/25507", "pm_score": 5, "selected": true, "text": "signaling_NaN signaling_NaN" }, { "answer_id": 13235569, "author": "Rahul", "author_id": 1264515, "author_profile": "https://Stackoverflow.com/users/1264515", "pm_score": 2, "selected": false, "text": "#define NegativeNaN log(-1)\n exp() extended_exp()" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25507/" ]
235,394
<p>In class, we learned about the halting problem, Turing machines, reductions, etc. A lot of classmates are saying these are all abstract and useless concepts, and there's no real point in knowing them (i.e., you can forget them once the course is over and not lose anything).</p> <p>Why is theory useful? Do you ever use it in your day-to-day coding? </p>
[ { "answer_id": 235465, "author": "benjismith", "author_id": 22979, "author_profile": "https://Stackoverflow.com/users/22979", "pm_score": 5, "selected": false, "text": "Blah blah blah ${MyTemplateString} blah blah blah.\n" }, { "answer_id": 42369187, "author": "code_dredd", "author_id": 4594973, "author_profile": "https://Stackoverflow.com/users/4594973", "pm_score": 1, "selected": false, "text": "+--------------+-------+-----------------------------------------------------------------+\n| No. Cities | O(N!) | Possibilities |\n+--------------+-------+-----------------------------------------------------------------+\n| 5 | 5! | 120 |\n| 10 | 10! | 3,628,800 |\n| 40 | 40! | 815,915,283,247,897,734,345,611,269,596,115,894,272,000,000,000 | <-- GG\n+--------------+-------+-----------------------------------------------------------------+\n kill -SIGTERM <id> kill" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
235,402
<p>What's the best way to unit test large data sets? Some legacy code that I'm maintaining has structures of a hundred members or more; other parts of the code that we're working on create or analyze data sets of hundreds of samples.</p> <p>The best approach I've found so far is to serialize the structures or data sets from disk, perform the operations under test, serialize the results to disk, then diff the files containing the serialized results against files containing expected results. This isn't terribly fast, and it violates the "don't touch the disk" principle of unit testing. However, the only alternative I can think of (writing code to initialize and test hundreds of members and data points) seems unbearably tedious.</p> <p>Are there any better solutions? </p>
[ { "answer_id": 237110, "author": "Dave Hillier", "author_id": 1575281, "author_profile": "https://Stackoverflow.com/users/1575281", "pm_score": 1, "selected": false, "text": "unsigned char mySerialisedData[] = { 0xFF, 0xFF, 0xFF, 0xFF, ... };\n\ntest()\n{\n MyStruct* s = (MyStruct*) mySerialisedData;\n\n}\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25507/" ]
235,409
<p>I have trouble comparing 2 double in Excel VBA</p> <p>suppose that I have the following code</p> <pre><code>Dim a as double Dim b as double a = 0.15 b = 0.01 </code></pre> <p>After a few manipulations on b, b is now equal to 0.6</p> <p>however the imprecision related to the double data type gives me headache because</p> <pre><code>if a = b then //this will never trigger end if </code></pre> <p>Do you know how I can remove the trailing imprecision on the double type?</p>
[ { "answer_id": 235581, "author": "C. Dragon 76", "author_id": 5682, "author_profile": "https://Stackoverflow.com/users/5682", "pm_score": 2, "selected": false, "text": "Dim a as Decimal\nDim b as Decimal\na = 0.15\nb = 0.01\n" }, { "answer_id": 5576799, "author": "Anonymous Type", "author_id": 141720, "author_profile": "https://Stackoverflow.com/users/141720", "pm_score": 3, "selected": false, "text": "Dim a as double \n Dim b as double \n a = 0.15 \n b = 0.01\n If Round(a,2) = Round(b,2) Then \n //code inside block will now trigger.\n End If \n" }, { "answer_id": 24041248, "author": "user3706920", "author_id": 3706920, "author_profile": "https://Stackoverflow.com/users/3706920", "pm_score": 3, "selected": false, "text": "Function dblCheckTheSame(number1 As Double, number2 As Double, Optional Digits As Integer = 12) As Boolean\n\nIf (number1 - number2) ^ 2 < (10 ^ -Digits) ^ 2 Then\n dblCheckTheSame = True\nElse\n dblCheckTheSame = False\nEnd If\n\nEnd Function\n MsgBox dblCheckTheSame(1.2345, 1.23456789)\nMsgBox dblCheckTheSame(1.2345, 1.23456789, 4)\nMsgBox dblCheckTheSame(1.2345678900001, 1.2345678900002)\nMsgBox dblCheckTheSame(1.2345678900001, 1.2345678900002, 14)\n" }, { "answer_id": 56482767, "author": "Josh Anstead", "author_id": 6322229, "author_profile": "https://Stackoverflow.com/users/6322229", "pm_score": 0, "selected": false, "text": " Sub Test_Rounded_Numbers()\n\n Dim Num1 As Double\n\n Dim Num2 As Double\n\n Let Num1 = 123.123456789\n\n Let Num2 = 123.123467891\n\n Let Num1 = Round(Num1, 4) '123.1235\n\n\n Let Num2 = Round(Num2, 4) '123.1235\n\n If Num1 = Num2 Then\n\n MsgBox \"Correct Match, \" & Num1 & \" does equal \" & Num2\n Else\n MsgBox \"Inccorrect Match, \" & Num1 & \" does not equal \" & Num2\n End If\n\n 'Here it would say that \"Inccorrect Match, 123.1235 does not equal 123.1235.\"\n\n End Sub\n\n Sub Fixed_Double_Value_Type_Compare_Issue()\n\n Dim Num1 As Double\n\n Dim Num2 As Double\n\n Let Num1 = 123.123456789\n\n Let Num2 = 123.123467891\n\n Let Num1 = Round(Num1, 4) '123.1235\n\n\n Let Num2 = Round(Num2, 4) '123.1235\n\n 'Add CDbl(CStr(Double_Value))\n 'By doing this step the numbers\n 'would trigger if they matched\n '100% of the time\n\n If CDbl(CStr(Num1)) = CDbl(CStr(Num2)) Then\n\n MsgBox \"Correct Match\"\n Else\n MsgBox \"Inccorrect Match\"\n\n End If\n\n 'Now it says Here it would say that \"Correct Match, 123.1235 does equal 123.1235.\"\n End Sub\n" }, { "answer_id": 61971839, "author": "Elimar", "author_id": 9681226, "author_profile": "https://Stackoverflow.com/users/9681226", "pm_score": -1, "selected": false, "text": "Public Sub Test()\nDim D01 As Double\nDim D02 As Double\nDim S01 As Single\nDim S02 As Single\nS01 = 45.678 / 12\nS02 = 45.678\nD01 = S01\nD02 = S02\nDebug.Print S01 * 12\nDebug.Print S02\nDebug.Print D01 * 12\nDebug.Print D02\nEnd Sub\n\n 45,678 \n 45,678 \n 45,67799949646 \n 45,6780014038086 \n" }, { "answer_id": 68291403, "author": "Greedo", "author_id": 6609896, "author_profile": "https://Stackoverflow.com/users/6609896", "pm_score": 2, "selected": false, "text": "'@NoIndent: Don't want to lose our description annotations\n'@Folder(\"Tests.Utils\")\n\nOption Explicit\nOption Private Module\n\n'Based on Python's math.isclose https://github.com/python/cpython/blob/17f94e28882e1e2b331ace93f42e8615383dee59/Modules/mathmodule.c#L2962-L3003\n'math.isclose -> boolean\n' a: double\n' b: double\n' relTol: double = 1e-09\n' maximum difference for being considered \"close\", relative to the\n' magnitude of the input values\n' absTol: double = 0.0\n' maximum difference for being considered \"close\", regardless of the\n' magnitude of the input values\n'Determine whether two floating point numbers are close in value.\n'Return True if a is close in value to b, and False otherwise.\n'For the values to be considered close, the difference between them\n'must be smaller than at least one of the tolerances.\n'-inf, inf and NaN behave similarly to the IEEE 754 Standard. That\n'is, NaN is not close to anything, even itself. inf and -inf are\n'only close to themselves.\n'@Description(\"Determine whether two floating point numbers are close in value, accounting for special values in IEEE 754\")\nPublic Function IsClose(ByVal a As Double, ByVal b As Double, _\n Optional ByVal relTol As Double = 0.000000001, _\n Optional ByVal absTol As Double = 0 _\n ) As Boolean\n \n If relTol < 0# Or absTol < 0# Then\n Err.Raise 5, Description:=\"tolerances must be non-negative\"\n ElseIf a = b Then\n 'Short circuit exact equality -- needed to catch two infinities of\n ' the same sign. And perhaps speeds things up a bit sometimes.\n IsClose = True\n ElseIf IsInfinity(a) Or IsInfinity(b) Then\n 'This catches the case of two infinities of opposite sign, or\n ' one infinity and one finite number. Two infinities of opposite\n ' sign would otherwise have an infinite relative tolerance.\n 'Two infinities of the same sign are caught by the equality check\n ' above.\n IsClose = False\n Else\n 'Now do the regular computation on finite arguments. Here an\n ' infinite tolerance will always result in the function returning True,\n ' since an infinite difference will be <= to the infinite tolerance.\n \n 'This is to supress overflow errors as we deal with infinity.\n 'NaN has already been filtered out in the equality checks earlier.\n On Error Resume Next\n Dim diff As Double: diff = Abs(b - a)\n \n If diff <= absTol Then\n IsClose = True\n ElseIf diff <= CDbl(Abs(relTol * b)) Then\n IsClose = True\n ElseIf diff <= CDbl(Abs(relTol * a)) Then\n IsClose = True\n End If\n On Error GoTo 0\n End If\nEnd Function\n\n'@Description \"Checks if Number is IEEE754 +/- inf, won't raise an error\"\nPublic IsInfinity(ByVal Number As Double) As Boolean\n On Error Resume Next 'in case of NaN\n IsInfinity = Abs(Number) = PosInf\n On Error GoTo 0\nEnd Function\n\n'@Description \"IEEE754 -inf\"\nPublic Property Get NegInf() As Double\n On Error Resume Next\n NegInf = -1 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description \"IEEE754 +inf\"\nPublic Property Get PosInf() As Double\n On Error Resume Next\n PosInf = 1 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description \"IEEE754 signaling NaN (sNaN)\"\nPublic Property Get NaN() As Double\n On Error Resume Next\n NaN = 0 / 0\n On Error GoTo 0\nEnd Property\n\n'@Description \"IEEE754 quiet NaN (qNaN)\"\nPublic Property Get QNaN() As Double\n QNaN = -NaN\nEnd Property\n IsClose assert(IsClose(0, 0.0001233, absTol:= 0.001)) 'same to 3 d.p.?\n assert(IsClose(1234.5, 1234.6, relTol:= 0.0001)) '0.01% relative difference?\n" }, { "answer_id": 72864907, "author": "Michael", "author_id": 7444507, "author_profile": "https://Stackoverflow.com/users/7444507", "pm_score": 0, "selected": false, "text": "if cstr(a) = cstr(b)\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6367/" ]
235,411
<p>Finding out what's selected in real browsers is as simple as:</p> <pre><code>var range = { start: textbox.selectionStart, end: textbox.selectionEnd } </code></pre> <p>But IE, as usual, doesn't understand. What's the best cross-browser way to do this?</p>
[ { "answer_id": 235419, "author": "TALlama", "author_id": 5657, "author_profile": "https://Stackoverflow.com/users/5657", "pm_score": 3, "selected": false, "text": "function getSelection(inputBox) {\n if (\"selectionStart\" in inputBox) {\n return {\n start: inputBox.selectionStart,\n end: inputBox.selectionEnd\n }\n }\n\n //and now, the blinkered IE way\n var bookmark = document.selection.createRange().getBookmark()\n var selection = inputBox.createTextRange()\n selection.moveToBookmark(bookmark)\n\n var before = inputBox.createTextRange()\n before.collapse(true)\n before.setEndPoint(\"EndToStart\", selection)\n\n var beforeLength = before.text.length\n var selLength = selection.text.length\n\n return {\n start: beforeLength,\n end: beforeLength + selLength\n }\n}\n" }, { "answer_id": 4207763, "author": "Tim Down", "author_id": 96100, "author_profile": "https://Stackoverflow.com/users/96100", "pm_score": 6, "selected": true, "text": "focus() function getInputSelection(el) {\n var start = 0, end = 0, normalizedValue, range,\n textInputRange, len, endRange;\n\n if (typeof el.selectionStart == \"number\" && typeof el.selectionEnd == \"number\") {\n start = el.selectionStart;\n end = el.selectionEnd;\n } else {\n range = document.selection.createRange();\n\n if (range && range.parentElement() == el) {\n len = el.value.length;\n normalizedValue = el.value.replace(/\\r\\n/g, \"\\n\");\n\n // Create a working TextRange that lives only in the input\n textInputRange = el.createTextRange();\n textInputRange.moveToBookmark(range.getBookmark());\n\n // Check if the start and end of the selection are at the very end\n // of the input, since moveStart/moveEnd doesn't return what we want\n // in those cases\n endRange = el.createTextRange();\n endRange.collapse(false);\n\n if (textInputRange.compareEndPoints(\"StartToEnd\", endRange) > -1) {\n start = end = len;\n } else {\n start = -textInputRange.moveStart(\"character\", -len);\n start += normalizedValue.slice(0, start).split(\"\\n\").length - 1;\n\n if (textInputRange.compareEndPoints(\"EndToEnd\", endRange) > -1) {\n end = len;\n } else {\n end = -textInputRange.moveEnd(\"character\", -len);\n end += normalizedValue.slice(0, end).split(\"\\n\").length - 1;\n }\n }\n }\n }\n\n return {\n start: start,\n end: end\n };\n}\n\nvar el = document.getElementById(\"your_input\");\nel.focus();\nvar sel = getInputSelection(el);\nalert(sel.start + \", \" + sel.end);\n" }, { "answer_id": 27116215, "author": "Atav32", "author_id": 1248811, "author_profile": "https://Stackoverflow.com/users/1248811", "pm_score": 0, "selected": false, "text": " function getCursorPosition($element) {\n var position = 0,\n selection;\n\n if (document.selection) {\n // IE Support\n $element.focus();\n selection = document.selection.createRange();\n selection.moveStart ('character', -$element.value.length);\n position = selection.text.length;\n } else if ($element.selectionStart || $element.selectionStart === 0) {\n position = $element.selectionStart;\n }\n\n return position;\n }\n\n function setCursorPosition($element, position) {\n var selection;\n\n if (document.selection) {\n // IE Support\n $element.focus ();\n selection = document.selection.createRange();\n selection.moveStart ('character', -$element.value.length);\n selection.moveStart ('character', position);\n selection.moveEnd ('character', 0);\n selection.select ();\n } else if ($element.selectionStart || $element.selectionStart === 0) {\n $element.selectionStart = position;\n $element.selectionEnd = position;\n $element.focus ();\n }\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5657/" ]
235,418
<p>I have (simplified for the example) a table with the following data</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-04 01 38 4 2008-10-04 2008-10-05 01 23 5 2008-10-05 2008-10-06 03 14 6 2008-10-06 2008-10-07 02 3 7 2008-10-07 2008-10-08 02 8 8 2008-10-08 2008-11-08 03 19 </code></pre> <p>The dates represent a period in time, the ID is the state a system was in during that period and the amount is a value related to that state.</p> <p>What I want to do is to aggregate the Amounts for <em>adjacent</em> rows with the <em>same</em> ID number, but keep the same overall sequence so that contiguous runs can be combined. Thus I want to end up with data like:</p> <pre><code>Row Start Finish ID Amount --- --------- ---------- -- ------ 1 2008-10-01 2008-10-02 01 10 2 2008-10-02 2008-10-03 02 20 3 2008-10-03 2008-10-05 01 61 4 2008-10-05 2008-10-06 03 14 5 2008-10-06 2008-10-08 02 11 6 2008-10-08 2008-11-08 03 19 </code></pre> <p>I am after a T-SQL solution that can be put into a SP, however I can't see how to do that with simple queries. I suspect that it may require iteration of some sort but I don't want to go down that path.</p> <p>The reason I want to do this aggregation is that the next step in the process is to do a SUM() and Count() grouped by the unique ID's that occur within the sequence, so that my final data will look something like:</p> <pre><code>ID Counts Total -- ------ ----- 01 2 71 02 2 31 03 2 33 </code></pre> <p>However if I do a simple </p> <pre><code>SELECT COUNT(ID), SUM(Amount) FROM data GROUP BY ID </code></pre> <p>On the original table I get something like</p> <pre><code>ID Counts Total -- ------ ----- 01 3 71 02 3 31 03 2 33 </code></pre> <p>Which is not what I want.</p>
[ { "answer_id": 235956, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "-- Derived from Figure 6.25 from Snodgrass \"Developing Time-Oriented\n-- Database Applications in SQL\"\nCREATE TABLE Data\n(\n Start DATE,\n Finish DATE,\n ID CHAR(2),\n Amount INT\n);\n\nINSERT INTO Data VALUES('2008-10-01', '2008-10-02', '01', 10);\nINSERT INTO Data VALUES('2008-10-02', '2008-10-03', '02', 20);\nINSERT INTO Data VALUES('2008-10-03', '2008-10-04', '01', 38);\nINSERT INTO Data VALUES('2008-10-04', '2008-10-05', '01', 23);\nINSERT INTO Data VALUES('2008-10-05', '2008-10-06', '03', 14);\nINSERT INTO Data VALUES('2008-10-06', '2008-10-07', '02', 3);\nINSERT INTO Data VALUES('2008-10-07', '2008-10-08', '02', 8);\nINSERT INTO Data VALUES('2008-10-08', '2008-11-08', '03', 19);\n\nSELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start < L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish < M.Start\n AND M.Start < L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start < M.Start\n AND M.Start <= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start < F.Start AND F.Start <= T2.Finish)\n OR (T2.Start <= L.Finish AND L.Finish < T2.Finish)));\n 01 2008-10-01 2008-10-02\n01 2008-10-03 2008-10-05\n02 2008-10-02 2008-10-03\n02 2008-10-06 2008-10-08\n03 2008-10-05 2008-10-06\n03 2008-10-05 2008-11-08\n03 2008-10-08 2008-11-08\n SELECT M.ID, M.Start, M.Finish, SUM(D.Amount)\n FROM Data AS D,\n (SELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start < L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish < M.Start\n AND M.Start < L.Start\n AND NOT EXISTS (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start < M.Start\n AND M.Start <= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start < F.Start AND F.Start <= T2.Finish)\n OR (T2.Start <= L.Finish AND L.Finish < T2.Finish)))) AS M\n WHERE D.ID = M.ID\n AND M.Start <= D.Start\n AND M.Finish >= D.Finish\n GROUP BY M.ID, M.Start, M.Finish\n ORDER BY M.ID, M.Start;\n ID Start Finish Amount\n01 2008-10-01 2008-10-02 10\n01 2008-10-03 2008-10-05 61\n02 2008-10-02 2008-10-03 20\n02 2008-10-06 2008-10-08 11\n03 2008-10-05 2008-10-06 14\n03 2008-10-05 2008-11-08 33 -- Here be trouble!\n03 2008-10-08 2008-11-08 19\n SELECT I.ID, COUNT(*) AS Number, SUM(I.Amount) AS Amount\n FROM (SELECT M.ID, M.Start, M.Finish, SUM(D.Amount) AS Amount\n FROM Data AS D,\n (SELECT DISTINCT F.ID, F.Start, L.Finish\n FROM Data AS F, Data AS L\n WHERE F.Start < L.Finish\n AND F.ID = L.ID\n -- There are no gaps between F.Finish and L.Start\n AND NOT EXISTS\n (SELECT *\n FROM Data AS M\n WHERE M.ID = F.ID\n AND F.Finish < M.Start\n AND M.Start < L.Start\n AND NOT EXISTS\n (SELECT *\n FROM Data AS T1\n WHERE T1.ID = F.ID\n AND T1.Start < M.Start\n AND M.Start <= T1.Finish))\n -- Cannot be extended further\n AND NOT EXISTS\n (SELECT *\n FROM Data AS T2\n WHERE T2.ID = F.ID\n AND ((T2.Start < F.Start AND F.Start <= T2.Finish) OR\n (T2.Start <= L.Finish AND L.Finish < T2.Finish)))\n ) AS M\n WHERE D.ID = M.ID\n AND M.Start <= D.Start\n AND M.Finish >= D.Finish\n GROUP BY M.ID, M.Start, M.Finish\n ) AS I\n GROUP BY I.ID\n ORDER BY I.ID;\n\nid number amount\n01 2 71\n02 2 31\n03 3 66\n" }, { "answer_id": 240574, "author": "Peter M", "author_id": 31326, "author_profile": "https://Stackoverflow.com/users/31326", "pm_score": 0, "selected": false, "text": "INSERT INTO #CONSEC\n SELECT a.ID, a.Start, b.Finish, b.Amount \n FROM Data a JOIN Data b \n ON (a.Finish = b.Start) AND (a.ID = b.ID)\n DECLARE CCursor CURSOR FOR\n SELECT ID, Start, Finish, Amount FROM #CONSEC ORDER BY Start DESC\n\n@Total = 0\nOPEN CCursor\nFETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT\nWHILE @FETCH_STATUS = 0\nBEGIN\n @Total = @Total + @Amount\n @Start_Last = @Start\n @Finish_Last = @Finish\n @ID_Last = @ID\n\n DELETE FROM Data WHERE Start = @Finish\n FETCH NEXT FROM CCursor INTO @ID, @START, @FINISH, @AMOUNT\n IF (@ID_Last<> @ID) OR (@Finish<>@Start_Last)\n BEGIN\n UPDATE Data\n SET Amount = Amount + @Total\n WHERE Start = @Start_Last\n @Total = 0\n END \nEND\n\nCLOSE CCursor\nDEALLOCATE CCursor\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31326/" ]
235,422
<p>I can't seem to find the _findfirst / findfirst, _findnext / findnext API on gcc for Linux, and would actually rather use the Standard Template Library (STL) for that if it is included there.</p> <p>Does anyone know what API there is available for listing files in a directory under Linux for C++ (gcc)?</p>
[ { "answer_id": 68798714, "author": "Martin Konrad", "author_id": 7583635, "author_profile": "https://Stackoverflow.com/users/7583635", "pm_score": 1, "selected": false, "text": "std::filesystem Boost.Filesystem std::filesystem::directory_iterator _findfirst findnext opendir readdir closedir" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4829/" ]
235,435
<p>Python's access to environment variables does not accurately reflect the operating system's view of the processes environment.</p> <p>os.getenv and os.environ do not function as expected in particular cases.</p> <p>Is there a way to properly get the running process' environment?</p> <hr> <p>To demonstrate what I mean, take the two roughly equivalent programs (the first in C, the other in python):</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;unistd.h&gt; int main(int argc, char *argv[]){ char *env; for(;;){ env = getenv("SOME_VARIABLE"); if(env) puts(env); sleep(5); } } </code></pre> <hr> <pre><code>import os import time while True: env = os.getenv("SOME_VARIABLE") if env is not None: print env time.sleep(5) </code></pre> <hr> <p>Now, if we run the C program and attach to the running process with gdb and forcibly change the environment under the hood by doing something like this:</p> <pre><code>(gdb) print setenv("SOME_VARIABLE", "my value", 1) [Switching to Thread -1208600896 (LWP 16163)] $1 = 0 (gdb) print (char *)getenv("SOME_VARIABLE") $2 = 0x8293126 "my value" </code></pre> <p>then the aforementioned C program will start spewing out "my value" once every 5 seconds. The aforementioned python program, however, will not.</p> <p>Is there a way to get the python program to function like the C program in this case?</p> <p>(Yes, I realize this is a very obscure and potentially damaging action to perform on a running process)</p> <p>Also, I'm currently using python 2.4, this may have been fixed in a later version of python.</p>
[ { "answer_id": 235475, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 5, "selected": true, "text": "os os.environ posix .environ" }, { "answer_id": 237217, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 2, "selected": false, "text": "import os; os.environ['SOME_VARIABLE']='my_value'" }, { "answer_id": 242175, "author": "Glyph", "author_id": 13564, "author_profile": "https://Stackoverflow.com/users/13564", "pm_score": 4, "selected": false, "text": "ctypes >>> from ctypes import CDLL, c_char_p\n>>> getenv = CDLL(\"libc.so.6\").getenv\n>>> getenv.restype = c_char_p\n>>> getenv(\"HOME\")\n'/home/glyph'\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9241/" ]
235,437
<p>Given the following file:</p> <pre><code>department=value1 location=valueA location=valueB department=value2 </code></pre> <p>I use the following to load the file into a Perl hash:</p> <pre><code>use File::Slurp; use Data::Dumper; my %hash = map { s/#.*//; s/^\s+//; s/\s+$//; m/(.*?)\s*=\s*(.*)/; } read_file($file); print Dumper(\%hash); </code></pre> <p>The result, however, is as follows:</p> <pre><code>$VAR1 = { 'location' =&gt; 'valueB', 'department' =&gt; 'value2' }; </code></pre> <p>How can I load the above file into a hash with, say,</p> <pre><code>$VAR1 = { 'location' =&gt; 'valueA,valueB', 'department' =&gt; 'value1,value2' }; </code></pre> <p>Thanks.</p>
[ { "answer_id": 235489, "author": "Nikhil", "author_id": 5734, "author_profile": "https://Stackoverflow.com/users/5734", "pm_score": 6, "selected": true, "text": "my %hash;\nwhile (<FILE>)\n{\n chomp;\n my ($key, $val) = split /=/;\n $hash{$key} .= exists $hash{$key} ? \",$val\" : $val;\n}\n" }, { "answer_id": 237256, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 3, "selected": false, "text": "name: Wally Jones\ndepartment: [foo, bar]\nlocation: [baz, biff]\n use File::Slurp;\nuse YAML::XS;\nuse Data::Dumper;\n\nprint Dumper Load scalar read_file(shift);\n $VAR1 = {\n 'department' => [\n 'foo',\n 'bar'\n ],\n 'location' => [\n 'baz',\n 'biff'\n ],\n 'name' => 'Wally Jones'\n };\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235437", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
235,439
<p>The way I do 80-column indication in Vim seems incorrect:<code>set columns=80</code>. At times I also <code>set textwidth</code>, but I want to be able to see and anticipate line overflow with the <code>set columns</code> alternative.</p> <p>This has some <strong>unfortunate</strong> side effects:</p> <ol> <li>I can't <code>set number</code> for fear of splitting between files that have different orders of line numbers; i.e. &lt; 100 line files and >= 100 line files will require two different <code>set columns</code> values because of the extra column used for the additional digit display. </li> <li>I also start new (g)Vim sessions instead of splitting windows vertically. This is because <code>vsplit</code> forces me to <code>set columns</code> every time I open or close a pane, so starting a new session is less hassle.</li> </ol> <p>How do you handle the 80-character indication when you want to <code>set numbers</code>, vertically split, etc.?</p>
[ { "answer_id": 235501, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 3, "selected": false, "text": ":set textwidth=80 :set ruler :set columns=80" }, { "answer_id": 235599, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": ":set numberwidth=x" }, { "answer_id": 235962, "author": "Aristotle Pagaltzis", "author_id": 9410, "author_profile": "https://Stackoverflow.com/users/9410", "pm_score": 3, "selected": false, "text": "au BufWinEnter * if &textwidth > 8\n\\ | let w:m1=matchadd('MatchParen', printf('\\%%<%dv.\\%%>%dv', &textwidth+1, &textwidth-8), -1)\n\\ | let w:m2=matchadd('ErrorMsg', printf('\\%%>%dv.\\+', &textwidth), -1)\n\\ | endif\n &textwidth" }, { "answer_id": 235970, "author": "Simon Howard", "author_id": 24806, "author_profile": "https://Stackoverflow.com/users/24806", "pm_score": 10, "selected": true, "text": "highlight OverLength ctermbg=red ctermfg=white guibg=#592929\nmatch OverLength /\\%81v.\\+/\n" }, { "answer_id": 1117367, "author": "Maksim Vi.", "author_id": 136666, "author_profile": "https://Stackoverflow.com/users/136666", "pm_score": 6, "selected": false, "text": "match ErrorMsg '\\%>80v.\\+'\n" }, { "answer_id": 3305790, "author": "Z.Zen", "author_id": 345844, "author_profile": "https://Stackoverflow.com/users/345844", "pm_score": 5, "selected": false, "text": "/\\%81v.\\+/ highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9\nmatch OverLength /\\%>80v.\\+/\n" }, { "answer_id": 3765575, "author": "Jeremy W. Sherman", "author_id": 72508, "author_profile": "https://Stackoverflow.com/users/72508", "pm_score": 10, "selected": false, "text": "set colorcolumn=80 set cc=80 .vimrc if exists('+colorcolumn')\n set colorcolumn=80\nelse\n au BufWinEnter * let w:m2=matchadd('ErrorMsg', '\\%>80v.\\+', -1)\nendif\n colorcolumn" }, { "answer_id": 3809577, "author": "Ding-Yi Chen", "author_id": 350580, "author_profile": "https://Stackoverflow.com/users/350580", "pm_score": 2, "selected": false, "text": "set columns set textwidth set wrapmargin set linebreak set showbreak" }, { "answer_id": 4431701, "author": "Mike L", "author_id": 540835, "author_profile": "https://Stackoverflow.com/users/540835", "pm_score": 1, "selected": false, "text": "let &co=80 + &foldcolumn + (&number || &relativenumber ? &numberwidth : 0)" }, { "answer_id": 14082092, "author": "ErichBSchulz", "author_id": 894487, "author_profile": "https://Stackoverflow.com/users/894487", "pm_score": 2, "selected": false, "text": "\" make window 80 + some for numbers wide \nnoremap <Leader>w :let @w=float2nr(log10(line(\"$\")))+82\\|:vertical resize <c-r>w<cr> \n" }, { "answer_id": 21406581, "author": "Dominykas Mostauskis", "author_id": 1714997, "author_profile": "https://Stackoverflow.com/users/1714997", "pm_score": 4, "selected": false, "text": "augroup collumnLimit\n autocmd!\n autocmd BufEnter,WinEnter,FileType scala,java\n \\ highlight CollumnLimit ctermbg=DarkGrey guibg=DarkGrey\n let collumnLimit = 79 \" feel free to customize\n let pattern =\n \\ '\\%<' . (collumnLimit+1) . 'v.\\%>' . collumnLimit . 'v'\n autocmd BufEnter,WinEnter,FileType scala,java\n \\ let w:m1=matchadd('CollumnLimit', pattern, -1)\naugroup END\n FileType scala,java" }, { "answer_id": 26685437, "author": "Shanded", "author_id": 3624253, "author_profile": "https://Stackoverflow.com/users/3624253", "pm_score": 4, "selected": false, "text": "highlight ColorColumn ctermbg=magenta \"set to whatever you like\ncall matchadd('ColorColumn', '\\%81v', 100) \"set column nr\n" }, { "answer_id": 30265194, "author": "0x8BADF00D", "author_id": 2196150, "author_profile": "https://Stackoverflow.com/users/2196150", "pm_score": 4, "selected": false, "text": "let &colorcolumn=join(range(81,999),\",\")\nlet &colorcolumn=\"80,\".join(range(400,999),\",\")\n" }, { "answer_id": 35794968, "author": "wieczorek1990", "author_id": 761200, "author_profile": "https://Stackoverflow.com/users/761200", "pm_score": 6, "selected": false, "text": "highlight ColorColumn ctermbg=gray\nset colorcolumn=80\n" }, { "answer_id": 70432783, "author": "Techie", "author_id": 6764110, "author_profile": "https://Stackoverflow.com/users/6764110", "pm_score": 0, "selected": false, "text": "set autoindent \nset smartindent \nset nowrap \nset hlsearch \nset tabstop=4 \nset shiftwidth=4 \nsyntax on \nset colorcolumn=80\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235439", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3594/" ]
235,446
<p>Anybody have a slicker way to do this? Seems like it should be easier than this, but I'm having a mental block. Basically I need to remove items from an dictionary and recurse into the values of the items that are also dictionaries.</p> <pre><code>private void RemoveNotPermittedItems(ActionDictionary menu) { var keysToRemove = new List&lt;string&gt;(); foreach (var item in menu) { if (!GetIsPermitted(item.Value.Call)) { keysToRemove.Add(item.Key); } else if (item.Value is ActionDictionary) { RemoveNotPermittedItems((ActionDictionary)item.Value); if (((ActionDictionary)item.Value).Count == 0) { keysToRemove.Add(item.Key); } } } foreach (var key in (from item in menu where keysToRemove.Contains(item.Key) select item.Key).ToArray()) { menu.Remove(key); } } </code></pre> <p>Action dictionary is like this:</p> <pre><code>public class ActionDictionary : Dictionary&lt;string, IActionItem&gt;, IActionItem </code></pre>
[ { "answer_id": 235469, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 2, "selected": false, "text": "foreach foreach (var key in keysToRemove)\n{\n menu.Remove(key);\n}\n Dictionary RemoveAll" }, { "answer_id": 235916, "author": "Lex Li", "author_id": 11182, "author_profile": "https://Stackoverflow.com/users/11182", "pm_score": 2, "selected": false, "text": " \n\nvar table = new Dictionary<string, int>() {{\"first\", 1}, {\"second\", 2}};\nfor (int i = 0; i < table.Keys.Count; i++)//string key in table.Keys)\n{\n string key = table.Keys.ElementAt(i);\n if (key.StartsWith(\"f\"))\n {\n table.Remove(key);\n }\n}\n\n\n var table = new Dictionary<string, int>() {{\"first\", 1}, {\"second\", 2}};\nfor (int i = 0; i < table.Keys.Count; i++)//string key in table.Keys)\n{\n string key = table.Keys.ElementAt(i);\n if (key.StartsWith(\"f\"))\n {\n table.Remove(key);\n }\n}\n " }, { "answer_id": 235994, "author": "Jared", "author_id": 7388, "author_profile": "https://Stackoverflow.com/users/7388", "pm_score": 3, "selected": true, "text": "Dictionary<string,object> static int counter = 0;\n private static void RemoveNotPermittedItems(Dictionary<string, object> menu)\n {\n for (int c = menu.Count - 1; c >= 0; c--)\n {\n var key = menu.Keys.ElementAt(c);\n var value = menu[key];\n if (value is Dictionary<string, object>)\n {\n RemoveNotPermittedItems((Dictionary<string, object>)value);\n if (((Dictionary<string, object>)value).Count == 0)\n {\n menu.Remove(key);\n }\n }\n else if (!GetIsPermitted(value))\n {\n menu.Remove(key);\n }\n }\n }\n\n // This just added to actually cause some elements to be removed...\n private static bool GetIsPermitted(object value)\n {\n if (counter++ % 2 == 0)\n return false;\n return true;\n }\n" }, { "answer_id": 10566049, "author": "Writwick", "author_id": 1118933, "author_profile": "https://Stackoverflow.com/users/1118933", "pm_score": 1, "selected": false, "text": "KeyValuePair<...> List<T> RemoveAll RemoveRange List<T> RemoveRange() RemoveAll()" }, { "answer_id": 10623148, "author": "Val Bakhtin", "author_id": 798261, "author_profile": "https://Stackoverflow.com/users/798261", "pm_score": 1, "selected": false, "text": "private ActionDictionary RemoveNotPermittedItems(ActionDictionary menu)\n{\n return new ActionDictionary(from item in menu where GetIsPermitted(item.Value.Call) select item)\n.ToDictionary(d=>d.Key, d=>d.Value is ActionDictionary?RemoveNotPermittedItems(d.Value as ActionDictionary) : d.Value));\n}\n" }, { "answer_id": 10638955, "author": "Jesse C. Slicer", "author_id": 3312, "author_profile": "https://Stackoverflow.com/users/3312", "pm_score": 1, "selected": false, "text": " private static void RemoveNotPermittedItems(IDictionary<string, IActionItem> menu)\n {\n var keysToRemove = new List<string>();\n\n foreach (var item in menu)\n {\n if (GetIsPermitted(item.Value.Call))\n {\n var value = item.Value as ActionDictionary;\n\n if (value != null)\n {\n RemoveNotPermittedItems(value);\n if (!value.Any())\n {\n keysToRemove.Add(item.Key);\n }\n }\n }\n else\n {\n keysToRemove.Add(item.Key);\n }\n }\n\n foreach (var key in keysToRemove)\n {\n menu.Remove(key);\n }\n }\n\n private static bool GetIsPermitted(object call)\n {\n return ...;\n }\n" }, { "answer_id": 10640444, "author": "Gebb", "author_id": 129073, "author_profile": "https://Stackoverflow.com/users/129073", "pm_score": 1, "selected": false, "text": "keysToRemove HashSet<string> Contains List<string>" }, { "answer_id": 10646195, "author": "ZagNut", "author_id": 401659, "author_profile": "https://Stackoverflow.com/users/401659", "pm_score": 1, "selected": false, "text": "private void RemoveNotPermittedItems(ActionDictionary menu)\n{\n foreach(var _checked in (from m in menu\n select new\n {\n gip = !GetIsPermitted(m.Value.Call),\n recur = m.Value is ActionDictionary,\n item = m\n }).ToArray())\n {\n ActionDictionary tmp = _checked.item.Value as ActionDictionary;\n if (_checked.recur)\n {\n RemoveNotPermittedItems(tmp);\n }\n if (_checked.gip || (tmp != null && tmp.Count == 0) {\n menu.Remove(_checked.item.Key);\n }\n }\n}\n" }, { "answer_id": 10650748, "author": "misha", "author_id": 1403091, "author_profile": "https://Stackoverflow.com/users/1403091", "pm_score": 1, "selected": false, "text": "public class ActionSet : HashSet<IActionItem>, IActionItem\n bool Clean(ActionSet nodes)\n {\n if (nodes != null)\n {\n var removed = nodes.Where(n => this.IsNullOrNotPermitted(n) || !this.IsNotSetOrNotEmpty(n) || !this.Clean(n as ActionSet));\n\n removed.ToList().ForEach(n => nodes.Remove(n));\n\n return nodes.Any();\n }\n\n return true;\n }\n\n bool IsNullOrNotPermitted(IActionItem node)\n {\n return node == null || *YourTest*(node.Call);\n }\n\n bool IsNotSetOrNotEmpty(IActionItem node)\n {\n var hset = node as ActionSet;\n return hset == null || hset.Any();\n }\n" } ]
2008/10/24
[ "https://Stackoverflow.com/questions/235446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29493/" ]