qid
int64 4
19.1M
| question
stringlengths 18
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence |
---|---|---|---|---|
7,694 | <p>Is this even a valid question? I have a .NET Windows app that is using MSTDC and it is throwing an exception:</p>
<blockquote>
<p>System.Transactions.TransactionManagerCommunicationException: Network access for Distributed Transaction Manager (MSDTC) has been disabled. Please enable DTC for
network access in the security configuration for MSDTC using the Component Services Administrative tool ---> System.Runtime.InteropServices.COMException (0x8004D024): The transaction manager has disabled its support for remote/network
transactions. (Exception from HRESULT: 0x8004D024) at System.Transactions.Oletx.IDtcProxyShimFactory.ReceiveTransaction(UInt32
propgationTokenSize, Byte[] propgationToken, IntPtr managedIdentifier,
Guid& transactionIdentifier, OletxTransactionIsolationLevel&
isolationLevel, ITransactionShim& transactionShim)....</p>
</blockquote>
<p>I followed <a href="https://support.microsoft.com/en-us/kb/883960" rel="noreferrer">the Kbalertz guide to enable MSDTC</a> on the PC on which the app is installed, but the error still occurs. </p>
<p>I was wondering if this was a database issue? If so, how can I resolve it?</p>
| [
{
"answer_id": 27263904,
"author": "Shiv Singh",
"author_id": 2384642,
"author_profile": "https://Stackoverflow.com/users/2384642",
"pm_score": 8,
"selected": true,
"text": "C:\\Windows\\System32\\msdtc.exe"
},
{
"answer_id": 67428837,
"author": "nmbell",
"author_id": 5034468,
"author_profile": "https://Stackoverflow.com/users/5034468",
"pm_score": 1,
"selected": false,
"text": "# Import the module\nImport-Module -Name MsDtc\n\n# Set the DTC config\n$dtcNetworkSetting = @{\n DtcName = 'Local'\n AuthenticationLevel = 'NoAuth'\n InboundTransactionsEnabled = $true\n OutboundTransactionsEnabled = $true\n RemoteClientAccessEnabled = $true\n RemoteAdministrationAccessEnabled = $true\n XATransactionsEnabled = $false\n LUTransactionsEnabled = $true\n}\nSet-DtcNetworkSetting @dtcNetworkSetting\n\n# Restart the MsDtc service\nGet-Service -Name MsDtc | Restart-Service\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7694",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230/"
] |
7,707 | <p>I have an element which may contain very big amounts of data, but I don't want it to ruin the page layout, so I set <code>max-height: 100px</code> and <code>overflow:auto</code>, hoping for scrollbars to appear when the content does not fit. </p>
<p>It all works fine in Firefox and IE7, but IE8 behaves as if <code>overflow:hidden</code> was present instead of <code>overflow:auto</code>. </p>
<p>I tried <code>overflow:scroll</code>, still does not help, IE8 simply truncates the content without showing scrollbars. Changing <code>max-height</code> declaration to <code>height</code> makes overflow work OK, it's the combination of <code>max-height</code> and <code>overflow:auto</code> that breaks things.</p>
<p>This is also logged as an <a href="http://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=408759" rel="noreferrer">official bug in the final, release version of IE8</a></p>
<p>Is there a workaround? For now I resorted to using <code>height</code> instead of <code>max-height</code>, but it leaves plenty of empty space in case there isn't much data.</p>
| [
{
"answer_id": 668205,
"author": "James Koch",
"author_id": 79509,
"author_profile": "https://Stackoverflow.com/users/79509",
"pm_score": 2,
"selected": false,
"text": "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">\n<head>\n <title>Test</title>\n <style type=\"text/css\">\n .calendarBody\n {\n overflow: scroll;\n max-height: 500px;\n }\n </style>\n</head>\n<body>\n <table>\n <tbody>\n <tr>\n <td>\n This is a cell in the outer table.\n <div class=\"calendarBody\">\n <table>\n <tbody>\n <tr>\n <td>\n This is a cell in the inner table.\n </td>\n </tr>\n </tbody>\n </table>\n </div>\n </td>\n </tr>\n </tbody>\n</table>\n</body>\n</html>\n"
},
{
"answer_id": 881597,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 7,
"selected": true,
"text": "<pre> max-height:600 width:auto /*\nSUPER nasty IE8 hack to deal with this bug\n*/\npre \n{\n max-height: none\\9 \n}\n"
},
{
"answer_id": 3862770,
"author": "ANeves",
"author_id": 148412,
"author_profile": "https://Stackoverflow.com/users/148412",
"pm_score": 1,
"selected": false,
"text": "<HTML>\n<HEAD>\n <META content=\"IE=8\" http-equiv=\"X-UA-Compatible\"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width=\"100%\">\n <TR>\n <TD>\n <TABLE width=\"100%\">\n <TR>\n <TD>\n <DIV style=\"overflow-y: scroll; max-height: 100px;\">\n X\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n <HTML>\n<HEAD>\n <META content=\"IE=8\" http-equiv=\"X-UA-Compatible\"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width=\"100%\">\n <TR>\n <TD>\n <TABLE width=\"100%\">\n <TR>\n <TD>\n <DIV style=\"overflow-y: scroll; max-height: 100px;\">\n The quick brown fox\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n <HTML>\n<HEAD>\n <META content=\"IE=8\" http-equiv=\"X-UA-Compatible\"/>\n</HEAD>\n\n<BODY>\n look:\n \n <TABLE width=\"100%\">\n <TR>\n <TD>\n <TABLE width=\"100%\">\n <TR>\n <TD>\n <DIV style=\"overflow-y: scroll; max-height: 100px;\">\n </DIV>\n </TD>\n </TR>\n </TABLE>\n </TD>\n </TR>\n </TABLE>\n</BODY>\n</HTML>\n"
},
{
"answer_id": 4969503,
"author": "Egglabs",
"author_id": 171842,
"author_profile": "https://Stackoverflow.com/users/171842",
"pm_score": 2,
"selected": false,
"text": "{\noverflow:auto\n}\n"
},
{
"answer_id": 5867887,
"author": "Ashish Joseph",
"author_id": 735892,
"author_profile": "https://Stackoverflow.com/users/735892",
"pm_score": 2,
"selected": false,
"text": "{max-height:200px, Overflow:auto}\n"
},
{
"answer_id": 33763541,
"author": "Vadim Svv",
"author_id": 3909772,
"author_profile": "https://Stackoverflow.com/users/3909772",
"pm_score": 0,
"selected": false,
"text": "* html div#division { \n height: expression( this.scrollHeight > 332 ? \"333px\" : \"auto\" ); /* sets max-height for IE */\n }"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7707",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/979/"
] |
7,719 | <p>Is there any way to capture the MouseDown even from the .NET 2.0 TextBox control?
I know the inherited Control class has the event, but it's not exposed in TextBox.
Is there a way to override the event handler?</p>
<p>I also tried the OpenNETCF TextBox2 control which does have the MouseDown event exposed, but no matter what I do, it doesn't fire the handler.</p>
<p>Any suggestions?</p>
<hr>
<blockquote>
<p>What kind of crazy mobile device do
you have that has a mouse? :)</p>
</blockquote>
<p>Yes, windows mobile does not have an actual mouse, but you are mistaken that Windows Mobile .NET do not support the Mouse events. A click or move on the screen is still considered a "Mouse" event. It was done this way so that code could port over from full Windows easily. And this is not a Windows Mobile specific issue. The TextBox control on Windows does not have native mouse events either. I just happened to be using Windows Mobile in this case.</p>
<p>Edit: And on a side note...as Windows Mobile is built of the WindowsCE core which is often used for embedded desktop systems and Slim Terminal Services clients or "WinTerms" it has support for a hardware mouse and has for a long time. Most devices just don't have the ports to plug one in.</p>
<hr>
<blockquote>
<p>According to the .Net Framework, the
MouseDown Event Handler on a TextBox
is supported. What happens when you
try to run the code?</p>
</blockquote>
<p>Actually, that's only there because it inherits it from "Control", as does <em>every</em> other Form control. It is, however, overridden (and changed to private I believe) in the TextBox class. So it will not show up in IntelliSense in Visual Studio.</p>
<p>However, you actually can write the code:</p>
<pre><code>textBox1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.textBox1_MouseDown);
</code></pre>
<p>and it will compile and run just fine, the only problem is that textBox1_MouseDown() will not be fired when you tap the TextBox control. I assume this is because of the Event being overridden internally. I don't even want to change what's happening on the event internally, I just want to add my own event handler to that event so I can fire some custom code as you could with any other event.</p>
| [
{
"answer_id": 7805,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 0,
"selected": false,
"text": "public class MyTextBox : TextBox\n{\n public MyTextBox()\n {\n }\n\n protected override void OnMouseDown(MouseEventArgs e)\n {\n //do something specific here\n base.OnMouseDown(e);\n }\n}\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
7,720 | <p>I am writing an application in Java for the desktop using the Eclipse SWT library for GUI rendering. I think SWT helps Java get over the biggest hurdle for acceptance on the desktop: namely providing a Java application with a consistent, responsive interface that looks like that belonging to any other app on your desktop. However, I feel that packaging an application is still an issue. </p>
<p>OS X natively provides an easy mechanism for wrapping Java apps in native application bundles, but producing an app for Windows/Linux that doesn't require the user to run an ugly batch file or click on a .jar is still a hassle. Possibly that's not such an issue on Linux, where the user is likely to be a little more tech-savvy, but on Windows I'd like to have a regular .exe for him/her to run.</p>
<p>Has anyone had any experience with any of the .exe generation tools for Java that are out there? I've tried JSmooth but had various issues with it. Is there a better solution before I crack out Visual Studio and roll my own?</p>
<p><strong>Edit:</strong> I should perhaps mention that I am unable to spend a lot of money on a commercial solution.</p>
| [
{
"answer_id": 8602,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 2,
"selected": false,
"text": "CreateProcess"
},
{
"answer_id": 149971,
"author": "Brian Kelly",
"author_id": 8252,
"author_profile": "https://Stackoverflow.com/users/8252",
"pm_score": 6,
"selected": true,
"text": "<launch4jConfig>\n <dontWrapJar>true</dontWrapJar>\n <headerType>gui</headerType>\n <jar>rpgam.jar</jar>\n <outfile>rpgam.exe</outfile>\n <errTitle></errTitle>\n <cmdLine></cmdLine>\n <chdir>.</chdir>\n <priority>normal</priority>\n <downloadUrl>http://www.rpgaudiomixer.com/</downloadUrl>\n <supportUrl></supportUrl>\n <customProcName>false</customProcName>\n <stayAlive>false</stayAlive>\n <manifest></manifest>\n <icon></icon>\n <jre>\n <path></path>\n <minVersion>1.5.0</minVersion>\n <maxVersion></maxVersion>\n <jdkPreference>preferJre</jdkPreference>\n </jre>\n <splash>\n <file>..\\images\\splash.bmp</file>\n <waitForWindow>true</waitForWindow>\n <timeout>60</timeout>\n <timeoutErr>true</timeoutErr>\n </splash>\n</launch4jConfig>\n ; The name of the installer\nName \"RPG Audio Mixer\"\n\n!ifndef VERSION\n !define VERSION A.B.C\n!endif\n\n; The file to write\noutfile \"..\\dist\\installers\\windows\\rpgam-${VERSION}.exe\"\n\n; The default installation directory\nInstallDir \"$PROGRAMFILES\\RPG Audio Mixer\"\n\n; Registry key to check for directory (so if you install again, it will \n; overwrite the old one automatically)\nInstallDirRegKey HKLM \"Software\\RPG_Audio_Mixer\" \"Install_Dir\"\n\n# create a default section.\nsection \"RPG Audio Mixer\"\n\n SectionIn RO\n\n ; Set output path to the installation directory.\n SetOutPath $INSTDIR\n File /r \"..\\dist\\layout\\windows\\\"\n\n ; Write the installation path into the registry\n WriteRegStr HKLM SOFTWARE\\RPG_Audio_Mixer \"Install_Dir\" \"$INSTDIR\"\n\n ; Write the uninstall keys for Windows\n WriteRegStr HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"DisplayName\" \"RPG Audio Mixer\"\n WriteRegStr HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"UninstallString\" '\"$INSTDIR\\uninstall.exe\"'\n WriteRegDWORD HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"NoModify\" 1\n WriteRegDWORD HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\" \"NoRepair\" 1\n WriteUninstaller \"uninstall.exe\"\n\n ; read the value from the registry into the $0 register\n ;readRegStr $0 HKLM \"SOFTWARE\\JavaSoft\\Java Runtime Environment\" CurrentVersion\n\n ; print the results in a popup message box\n ;messageBox MB_OK \"version: $0\"\n\nsectionEnd\n\nSection \"Start Menu Shortcuts\"\n CreateDirectory \"$SMPROGRAMS\\RPG Audio Mixer\"\n CreateShortCut \"$SMPROGRAMS\\RPG Audio Mixer\\Uninstall.lnk\" \"$INSTDIR\\uninstall.exe\" \"\" \"$INSTDIR\\uninstall.exe\" 0\n CreateShortCut \"$SMPROGRAMS\\RPG AUdio Mixer\\RPG Audio Mixer.lnk\" \"$INSTDIR\\rpgam.exe\" \"\" \"$INSTDIR\\rpgam.exe\" 0\nSectionEnd\n\nSection \"Uninstall\"\n\n ; Remove registry keys\n DeleteRegKey HKLM \"Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\RPGAudioMixer\"\n DeleteRegKey HKLM SOFTWARE\\RPG_Audio_Mixer\n\n ; Remove files and uninstaller\n Delete $INSTDIR\\rpgam.exe\n Delete $INSTDIR\\uninstall.exe\n\n ; Remove shortcuts, if any\n Delete \"$SMPROGRAMS\\RPG Audio Mixer\\*.*\"\n\n ; Remove directories used\n RMDir \"$SMPROGRAMS\\RPG Audio Mixer\"\n RMDir \"$INSTDIR\"\n\nSectionEnd\n <property name=\"launch4j.dir\" location=\"vendor/launch4j\" />\n<taskdef name=\"launch4j\" \n classname=\"net.sf.launch4j.ant.Launch4jTask\"\n classpath=\"${launch4j.dir}/launch4j.jar:${launch4j.dir}/lib/xstream.jar\" />\n <target name=\"executable-windows\" depends=\"jar\" description=\"Create Windows executable (EXE)\">\n <launch4j configFile=\"scripts/launch4j.xml\" outfile=\"${exeFile}\" />\n</target>\n <target name=\"installer-windows\" depends=\"executable-windows\" description=\"Create the installer for Windows (EXE)\">\n <!-- Lay out files needed for building the installer -->\n <mkdir dir=\"${windowsLayoutDirectory}\" />\n <copy file=\"${jarFile}\" todir=\"${windowsLayoutDirectory}\" />\n <copy todir=\"${windowsLayoutDirectory}/lib\">\n <fileset dir=\"${libraryDirectory}\" />\n <fileset dir=\"${windowsLibraryDirectory}\" />\n </copy>\n <copy todir=\"${windowsLayoutDirectory}/icons\">\n <fileset dir=\"${iconsDirectory}\" />\n </copy>\n <copy todir=\"${windowsLayoutDirectory}\" file=\"${exeFile}\" />\n\n <mkdir dir=\"${windowsInstallerDirectory}\" />\n\n <!-- Build the installer using NSIS -->\n <exec executable=\"vendor/nsis/makensis.exe\">\n <arg value=\"/DVERSION=${version}\" />\n <arg value=\"scripts/rpgam-setup.nsi\" />\n </exec>\n</target>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7720",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/998/"
] |
7,737 | <p>Is there a good way for displaying unicode text in opengl under Windows? For example, when you have to deal with different languages. The most common approach like</p>
<pre><code>#define FONTLISTRANGE 128
GLuint list;
list = glGenLists(FONTLISTRANGE);
wglUseFontBitmapsW(hDC, 0, FONTLISTRANGE, list);
</code></pre>
<p>just won't do because you can't create enough lists for all unicode characters.</p>
| [
{
"answer_id": 480067,
"author": "jheriko",
"author_id": 17604,
"author_profile": "https://Stackoverflow.com/users/17604",
"pm_score": 2,
"selected": false,
"text": "* glTextRender class by Semi Essessi\n *\n * FreeType2 empowered text renderer\n *\n */\n\n#include \"glTextRender.h\"\n#include \"jEngine.h\"\n\n#include \"glSystem.h\"\n\n#include \"jMath.h\"\n#include \"jProfiler.h\"\n#include \"log.h\"\n\n#include <windows.h>\n\nFT_Library glTextRender::ftLib = 0;\n\n//TODO::maybe fix this so it use wchar_t for the filename\nglTextRender::glTextRender(jEngine* j, const char* fontName, int size = 12)\n{\n#ifdef _DEBUG\n jProfiler profiler = jProfiler(L\"glTextRender::glTextRender\");\n#endif\n char fontName2[1024];\n memset(fontName2,0,sizeof(char)*1024);\n sprintf(fontName2,\"fonts\\\\%s\",fontName);\n\n if(!ftLib)\n {\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Font: %s was requested before FreeType was initialised\", fn);\n#endif\n return;\n }\n\n // constructor code for glTextRender\n e=j;\n\n gl = j->gl;\n\n red=green=blue=alpha=1.0f;\n\n face = 0;\n\n // remember that for some weird reason below font size 7 everything gets scrambled up\n height = max(6,(int)floorf((float)size*((float)gl->getHeight())*0.001666667f));\n aHeight = ((float)height)/((float)gl->getHeight());\n\n setPosition(0.0f,0.0f);\n\n // look in base fonts dir\n if(FT_New_Face(ftLib, fontName2, 0, &face ))\n {\n // if we dont have it look in windows fonts dir\n char buf[1024];\n GetWindowsDirectoryA(buf,1024);\n strcat(buf, \"\\\\fonts\\\\\");\n strcat(buf, fontName);\n\n if(FT_New_Face(ftLib, buf, 0, &face ))\n {\n //TODO::check in mod fonts directory\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Request for font: %s has failed\", fn);\n#endif\n face = 0;\n return;\n }\n }\n\n // FreeType uses 64x size and 72dpi for default\n // doubling size for ms \n FT_Set_Char_Size(face, mulPow2(height,7), mulPow2(height,7), 96, 96);\n\n // set up cache table and then generate the first 256 chars and the console prompt character\n for(int i=0;i<65536;i++) \n {\n cached[i]=false;\n width[i]=0.0f;\n }\n\n for(unsigned short i = 0; i < 256; i++) getChar((wchar_t)i);\n getChar(CHAR_PROMPT);\n\n#ifdef _DEBUG\n wchar_t fn[128];\n mbstowcs(fn,fontName,strlen(fontName)+1);\n LogWriteLine(L\"\\x25CB\\x25CB\\x25CF Font: %s loaded OK\", fn);\n#endif\n}\n\nglTextRender::~glTextRender()\n{\n // destructor code for glTextRender\n for(int i=0;i<65536;i++)\n {\n if(cached[i])\n {\n glDeleteLists(listID[i],1);\n glDeleteTextures(1,&(texID[i]));\n }\n }\n\n // TODO:: work out stupid freetype crashz0rs\n try\n {\n static int foo = 0;\n if(face && foo < 1)\n {\n foo++;\n FT_Done_Face(face);\n face = 0;\n }\n }\n catch(...)\n {\n face = 0;\n }\n}\n\n\n// return true if init works, or if already initialised\nbool glTextRender::initFreeType()\n{\n if(!ftLib)\n {\n if(!FT_Init_FreeType(&ftLib)) return true;\n else return false;\n } else return true;\n}\n\nvoid glTextRender::shutdownFreeType()\n{\n if(ftLib)\n {\n FT_Done_FreeType(ftLib);\n ftLib = 0;\n }\n}\n\nvoid glTextRender::print(const wchar_t* str)\n{\n // store old stuff to set start position\n glPushAttrib(GL_TRANSFORM_BIT);\n // get viewport size\n GLint viewport[4];\n glGetIntegerv(GL_VIEWPORT, viewport);\n\n glMatrixMode(GL_PROJECTION);\n glPushMatrix();\n glLoadIdentity();\n\n gluOrtho2D(viewport[0],viewport[2],viewport[1],viewport[3]);\n glPopAttrib();\n\n float color[4];\n glGetFloatv(GL_CURRENT_COLOR, color);\n\n glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT); \n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n glLoadIdentity();\n\n glEnable(GL_TEXTURE_2D);\n //glDisable(GL_DEPTH_TEST);\n\n // set blending for AA\n glEnable(GL_BLEND);\n glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);\n\n glTranslatef(xPos,yPos,0.0f);\n\n glColor4f(red,green,blue,alpha);\n\n // call display lists to render text\n glListBase(0u);\n for(unsigned int i=0;i<wcslen(str);i++) glCallList(getChar(str[i]));\n\n // restore old states\n glMatrixMode(GL_MODELVIEW);\n glPopMatrix();\n glPopAttrib();\n\n glColor4fv(color);\n\n glPushAttrib(GL_TRANSFORM_BIT);\n glMatrixMode(GL_PROJECTION);\n glPopMatrix();\n glPopAttrib();\n}\n\nvoid glTextRender::printf(const wchar_t* str, ...)\n{\n if(!str) return;\n\n wchar_t* buf = 0;\n va_list parg;\n va_start(parg, str);\n\n // allocate buffer\n int len = (_vscwprintf(str, parg)+1);\n buf = new wchar_t[len];\n if(!buf) return;\n vswprintf(buf, str, parg);\n va_end(parg);\n\n print(buf);\n\n delete[] buf;\n}\n\nGLuint glTextRender::getChar(const wchar_t c)\n{\n int i = (int)c;\n\n if(cached[i]) return listID[i];\n\n // load glyph and get bitmap\n if(FT_Load_Glyph(face, FT_Get_Char_Index(face, i), FT_LOAD_DEFAULT )) return 0;\n\n FT_Glyph glyph;\n if(FT_Get_Glyph(face->glyph, &glyph)) return 0;\n\n FT_Glyph_To_Bitmap(&glyph, FT_RENDER_MODE_NORMAL, 0, 1);\n\n FT_BitmapGlyph bitmapGlyph = (FT_BitmapGlyph)glyph;\n FT_Bitmap& bitmap = bitmapGlyph->bitmap;\n\n int w = roundPow2(bitmap.width);\n int h = roundPow2(bitmap.rows);\n\n // convert to texture in memory\n GLubyte* texture = new GLubyte[2*w*h];\n\n for(int j=0;j<h;j++)\n {\n bool cond = j>=bitmap.rows;\n\n for(int k=0;k<w;k++)\n {\n texture[2*(k+j*w)] = 0xFFu;\n texture[2*(k+j*w)+1] = ((k>=bitmap.width)||cond) ? 0x0u : bitmap.buffer[k+bitmap.width*j];\n }\n }\n\n // store char width and adjust max height\n // note .5f\n float ih = 1.0f/((float)gl->getHeight());\n width[i] = ((float)divPow2(face->glyph->advance.x, 7))*ih;\n aHeight = max(aHeight,(.5f*(float)bitmap.rows)*ih);\n\n glPushAttrib(GL_LIST_BIT | GL_CURRENT_BIT | GL_ENABLE_BIT | GL_TRANSFORM_BIT);\n\n // create gl texture\n glGenTextures(1, &(texID[i]));\n\n glEnable(GL_TEXTURE_2D);\n\n glBindTexture(GL_TEXTURE_2D, texID[i]);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);\n glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);\n\n glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, w, h, 0, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, texture);\n\n glPopAttrib();\n\n delete[] texture;\n\n // create display list\n listID[i] = glGenLists(1);\n\n glNewList(listID[i], GL_COMPILE);\n\n glBindTexture(GL_TEXTURE_2D, texID[i]);\n\n glMatrixMode(GL_MODELVIEW);\n glPushMatrix();\n\n // adjust position to account for texture padding\n glTranslatef(.5f*(float)bitmapGlyph->left, 0.0f, 0.0f);\n glTranslatef(0.0f, .5f*(float)(bitmapGlyph->top-bitmap.rows), 0.0f);\n\n // work out texcoords\n float tx=((float)bitmap.width)/((float)w);\n float ty=((float)bitmap.rows)/((float)h);\n\n // render\n // note .5f\n glBegin(GL_QUADS);\n glTexCoord2f(0.0f, 0.0f);\n glVertex2f(0.0f, .5f*(float)bitmap.rows);\n glTexCoord2f(0.0f, ty);\n glVertex2f(0.0f, 0.0f);\n glTexCoord2f(tx, ty);\n glVertex2f(.5f*(float)bitmap.width, 0.0f);\n glTexCoord2f(tx, 0.0f);\n glVertex2f(.5f*(float)bitmap.width, .5f*(float)bitmap.rows);\n glEnd();\n\n glPopMatrix();\n\n // move position for the next character\n // note extra div 2\n glTranslatef((float)divPow2(face->glyph->advance.x, 7), 0.0f, 0.0f);\n\n glEndList();\n\n // char is succesfully cached for next time\n cached[i] = true;\n\n return listID[i];\n}\n\nvoid glTextRender::setPosition(float x, float y)\n{\n float fac = ((float)gl->getHeight());\n xPos = fac*x+FONT_BORDER_PIXELS; yPos = fac*(1-y)-(float)height-FONT_BORDER_PIXELS;\n}\n\nfloat glTextRender::getAdjustedWidth(const wchar_t* str)\n{\n float w = 0.0f;\n\n for(unsigned int i=0;i<wcslen(str);i++)\n {\n if(cached[str[i]]) w+=width[str[i]];\n else\n {\n getChar(str[i]);\n w+=width[str[i]];\n }\n }\n\n return w;\n}\n"
},
{
"answer_id": 20310693,
"author": "Calmarius",
"author_id": 58805,
"author_profile": "https://Stackoverflow.com/users/58805",
"pm_score": 2,
"selected": false,
"text": "pango_layout_get_pixel_extents"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7737",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1007/"
] |
7,758 | <p>I'm getting all learned up about binding in WPF. I'm having a lot of trouble debugging the parse errors in my xaml, though. Can somebody pretty please tell me what's wrong with this little piece? :</p>
<pre><code><Border Name="TrackBackground"
Margin="0"
CornerRadius="2"
Grid.Row="1"
Grid.Column="1"
Background="BlanchedAlmond"
BorderThickness="1"
Height="{TemplateBinding Height}">
<Canvas Name="PART_Track" Background="DarkSalmon" Grid.Row="1" Grid.Column="1">
<Thumb Name="ThumbKnob" Height="{Binding ElementName=Part_Track, Path=Height, Mode=OneWay}" />
</Canvas>
</Border>
</code></pre>
<p>It's the databinding that breaks. I get an <code>InvalidAttributeValue</code> exception for ThumbKnob.Height when I try to run this. I know I must be missing something fundamental. So fill me in, stackers, and my gratitude will be boundless.</p>
<hr>
<p>Changing the ElementName didn't help. There must me something else I'm not getting.</p>
<p>I should mention that I'm testing this in Silverlight. The exact message I'm getting out of Internet Explorer is:</p>
<p><code>XamlParseException: Invalid attribute value for property Height.</code></p>
<p>This whole thing is inside a ControlTemplate. I'm making a slider control just to teach myself the concepts.</p>
| [
{
"answer_id": 7776,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 0,
"selected": false,
"text": "Part_Track PART_Track"
},
{
"answer_id": 7801,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 1,
"selected": false,
"text": "{Binding ElementName=PART_Track, Path=Height, Mode=OneWay, Converter={StaticResources DebugConverter}}\n"
},
{
"answer_id": 7844,
"author": "Arcturus",
"author_id": 900,
"author_profile": "https://Stackoverflow.com/users/900",
"pm_score": 1,
"selected": false,
"text": "<Slider Width=\"400\" Height=\"20\">\n <Slider.Template>\n <ControlTemplate>\n <Border Name=\"TrackBackground\"\n Margin=\"0\"\n CornerRadius=\"2\" \n Grid.Row=\"1\"\n Grid.Column=\"1\"\n Background=\"BlanchedAlmond\"\n BorderThickness=\"1\">\n\n <Canvas x:Name=\"PART_Track\" Background=\"DarkSalmon\" Grid.Row=\"1\" Grid.Column=\"1\">\n <Thumb Name=\"ThumbKnob\" Height=\"{Binding ElementName=PART_Track, Path=Height, Mode=OneWay}\" />\n </Canvas>\n </Border>\n </ControlTemplate>\n </Slider.Template>\n</Slider>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/93/"
] |
7,773 | <p>I have a ASP.NET page with an asp:button that is not visible. I can't turn it visible with JavaScript because it is not rendered to the page.</p>
<p>What can I do to resolve this?</p>
| [
{
"answer_id": 7777,
"author": "Dave Ward",
"author_id": 60,
"author_profile": "https://Stackoverflow.com/users/60",
"pm_score": 6,
"selected": true,
"text": "<asp:Label runat=\"server\" id=\"Label1\" style=\"display: none;\" />\n document.getElementById('Label1').style.display = 'inherit';\n document.getElementById('Label1').style.display = 'none';\n"
},
{
"answer_id": 7800,
"author": "EndangeredMassa",
"author_id": 106,
"author_profile": "https://Stackoverflow.com/users/106",
"pm_score": 3,
"selected": false,
"text": "<asp:Button id=\"myButton\" runat=\"server\" style=\"display:none\" Text=\"Click Me\" />\n\n<script type=\"text/javascript\">\n function ShowButton() {\n var buttonID = '<%= myButton.ClientID %>';\n var button = document.getElementById(buttonID);\n if(button) { button.style.display = 'inherit'; }\n }\n</script>\n"
},
{
"answer_id": 7816,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "<asp:Label runat=\"server\" ID=\"Label1\" Style=\"display: none;\" />\n\n<asp:Button runat=\"server\" ID=\"Button1\" />\n Label label1 = (Label)FindControl(\"Label1\");\n((Label)FindControl(\"Button1\")).OnClientClick = \"ToggleVisibility('\" + label1.ClientID + \"')\";\n function ToggleVisibility(elementID)\n{\n var element = document.getElementByID(elementID);\n\n if (element.style.display = 'none')\n {\n element.style.display = 'inherit';\n }\n else\n {\n element.style.display = 'none';\n }\n}\n ClientID"
},
{
"answer_id": 16297,
"author": "Ian Oxley",
"author_id": 1904,
"author_profile": "https://Stackoverflow.com/users/1904",
"pm_score": 2,
"selected": false,
"text": "document.getElementById('<%= Label1.ClientID %>').style.display\n document.getElementById('<%= AntiXss.JavaScriptEncode(Label1.ClientID) %>').style.display\n"
},
{
"answer_id": 14803416,
"author": "Michael Emerick",
"author_id": 2059777,
"author_profile": "https://Stackoverflow.com/users/2059777",
"pm_score": 1,
"selected": false,
"text": " BtnUpload.Style.Add(\"display\", \"none\");\n FileUploader.Style.Add(\"display\", \"none\");\n BtnAccept.Style.Add(\"display\", \"inherit\");\n BtnClear.Style.Add(\"display\", \"inherit\");\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7773",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1013/"
] |
7,846 | <p>I would like to use a language that I am familiar with - Java, C#, Ruby, PHP, C/C++, although examples in any language or pseudocode are more than welcome.</p>
<p>What is the best way of splitting a large XML document into smaller sections that are still valid XML? For my purposes, I need to split them into roughly thirds or fourths, but for the sake of providing examples, splitting them into n components would be good.</p>
| [
{
"answer_id": 7853,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 3,
"selected": true,
"text": "<Document>\n <Piece>\n Some text\n </Piece>\n <Piece>\n Some other text\n </Piece>\n</Document>\n XmlDocument doc = new XmlDocument();\ndoc.Load(\"<path to xml file>\");\nXmlNodeList nl = doc.GetElementsByTagName(\"Piece\");\nforeach (XmlNode n in nl)\n{\n // Do something with each Piece node\n}\n"
},
{
"answer_id": 7861,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "XmlDocument doc = new XmlDocument();\ndoc.Load(\"path\");\n"
},
{
"answer_id": 7866,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 2,
"selected": false,
"text": "int nrOfPieces = 5;\nXmlDocument xmlOriginal = some input parameter..\n\n// construct the list we need, and fill it with XmlDocuments..\nvar xmlList = new List<XmlDocument>();\nfor (int i = 0; i < nrOfPieces ; i++)\n{\n var xmlDoc = new XmlDocument();\n xmlDoc.ChildNodes.Add(new XmlNode(xmlOriginal.FistNode.Name));\n xmlList.Add(xmlDoc);\n}\n\nvar nodeList = xmlOriginal.GetElementsByTagName(\"Piece\")M\n// Copy the nodes from the original into the pieces..\nfor (int i = 0; i < nodeList .Count; i++)\n{\n var xmlDoc = xmlList[i % nrOfPieces];\n var nodeToCopy = nodeList[i].Clone();\n xmlDoc.FirstNode.ChildNodes.Add(nodeToCopy);\n}\n"
},
{
"answer_id": 313067,
"author": "Jonas Engman",
"author_id": 4164,
"author_profile": "https://Stackoverflow.com/users/4164",
"pm_score": 3,
"selected": false,
"text": "import javax.xml.stream.*\n\npieces = 5\ninput = \"input.xml\"\noutput = \"output_%04d.xml\"\neventFactory = XMLEventFactory.newInstance()\nfileNumber = elementCount = 0\n\ndef createEventReader() {\n reader = XMLInputFactory.newInstance().createXMLEventReader(new FileInputStream(input))\n start = reader.next()\n root = reader.nextTag()\n firstChild = reader.nextTag()\n return reader\n}\n\ndef createNextEventWriter () {\n println \"Writing to '${filename = String.format(output, ++fileNumber)}'\"\n writer = XMLOutputFactory.newInstance().createXMLEventWriter(new FileOutputStream(filename), start.characterEncodingScheme)\n writer.add(start)\n writer.add(root)\n return writer\n}\n\nelements = createEventReader().findAll { it.startElement && it.name == firstChild.name }.size()\nprintln \"Splitting ${elements} <${firstChild.name.localPart}> elements into ${pieces} pieces\"\nchunkSize = elements / pieces\nwriter = createNextEventWriter()\nwriter.add(firstChild)\ncreateEventReader().each { \n if (it.startElement && it.name == firstChild.name) {\n if (++elementCount > chunkSize) {\n writer.add(eventFactory.createEndDocument())\n writer.flush()\n writer = createNextEventWriter()\n elementCount = 0\n }\n }\n writer.add(it)\n}\nwriter.flush()\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7846",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
7,851 | <p>According to the <a href="http://uk3.php.net/features.safe-mode" rel="nofollow noreferrer">PHP Safe Mode Docs</a> on safe_mode_gid:</p>
<blockquote>
<p>By default, Safe Mode does a UID compare check when opening files. If you want to relax this to a GID compare, then turn on safe_mode_gid. Whether to use UID (FALSE) or GID (TRUE) checking upon file access.</p>
</blockquote>
<p>To a PHP script running on a web server, what is the difference between a UID (User Identifier) check and a GID (Group identifier) check?</p>
| [
{
"answer_id": 3778009,
"author": "Capsule",
"author_id": 181206,
"author_profile": "https://Stackoverflow.com/users/181206",
"pm_score": 1,
"selected": false,
"text": "safe_mode apache:daemon some_user:users some_other_user:users safe_mode_gid apache:daemon safe_mode some_user apache safe_mode_gid safe_mode_gid safe_mode_gid open_basedir open_basedire"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7851",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/840/"
] |
7,864 | <p>As I learn more and more about OOP, and start to implement various design patterns, I keep coming back to cases where people are hating on <a href="http://en.wikipedia.org/wiki/Active_record_pattern" rel="noreferrer">Active Record</a>.</p>
<p>Often, people say that it doesn't scale well (citing Twitter as their prime example) -- but nobody actually explains <strong><em>why</em></strong> it doesn't scale well; and / or how to achieve the pros of AR without the cons (via a similar but different pattern?)</p>
<p>Hopefully this won't turn into a holy war about design patterns -- all I want to know is ****specifically**** what's wrong with Active Record.</p>
<p>If it doesn't scale well, why not?</p>
<p>What other problems does it have?</p>
| [
{
"answer_id": 8141,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "DataBaseTable.GetList(DataBaseTable.Columns.ColumnYouWant)\n Query q = DataBaseTable.CreateQuery()\n .WHERE(DataBaseTable.Columns.ColumnToFilterOn,value);\nq.SelectList = DataBaseTable.Columns.ColumnYouWant;\nq.Load();\n"
},
{
"answer_id": 8215,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 8,
"selected": true,
"text": "class Person\n belongs_to :company\nend\npeople = Person.find(:all, :include => :company )\n LEFT JOIN companies on companies.id = person.company_id people.first.company person = Person.find_by_sql(\"giant complicated sql query\")\n people = Person.find(:all, :select=>'name, id')\n"
},
{
"answer_id": 117795,
"author": "MattMcKnight",
"author_id": 8136,
"author_profile": "https://Stackoverflow.com/users/8136",
"pm_score": 4,
"selected": false,
"text": "user = User.find(id, :include => [\"posts\", \"comments\"])\nfirst_post = user.posts.first\nfirst_comment = user.comments.first\n"
},
{
"answer_id": 1807560,
"author": "Frunsi",
"author_id": 206247,
"author_profile": "https://Stackoverflow.com/users/206247",
"pm_score": 3,
"selected": false,
"text": "hash_map get_record( string id_value, string table_name, string id_column_name=\"id\" ) App::Log(\"I am a log message\") le=new LogEntry(); le.time=now(); le.text=\"I am a log message\"; le.Insert();"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/751/"
] |
7,880 | <p>I want to open a file for reading, the C++ way. I need to be able to do it for:</p>
<ul>
<li><p>text files, which would involve some sort of read line function.</p></li>
<li><p>binary files, which would provide a way to read raw data into a <code>char*</code> buffer.</p></li>
</ul>
| [
{
"answer_id": 7886,
"author": "DannySmurf",
"author_id": 1028,
"author_profile": "https://Stackoverflow.com/users/1028",
"pm_score": 5,
"selected": true,
"text": "fopen fread fclose ifstream ofstream CFile int nsize = 10;\nstd::vector<char> somedata(nsize);\nifstream myfile;\nmyfile.open(\"<path to file>\");\nmyfile.read(somedata.data(), nsize);\nmyfile.close();\n"
},
{
"answer_id": 7888,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": false,
"text": "ifstream ofstream fstream ifstream in(\"filename.ext\", ios_base::in); // the in flag is optional\n ifstream in2(\"filename2.ext\", ios_base::in | ios_base::binary ); \n ifstream.read() getline()"
},
{
"answer_id": 7896,
"author": "Vincent Robert",
"author_id": 268,
"author_profile": "https://Stackoverflow.com/users/268",
"pm_score": -1,
"selected": false,
"text": "class FileOpener\n{\npublic:\n FileOpener(std::fstream& file, const char* fileName): m_file(file)\n { \n m_file.open(fileName); \n }\n ~FileOpeneer()\n { \n file.close(); \n }\n\nprivate:\n std::fstream& m_file;\n};\n int nsize = 10;\nchar *somedata;\nifstream myfile;\nFileOpener opener(myfile, \"<path to file>\");\nmyfile.read(somedata,nsize);\n// myfile is closed automatically when opener destructor is called\n"
},
{
"answer_id": 24814600,
"author": "J.p.",
"author_id": 3851030,
"author_profile": "https://Stackoverflow.com/users/3851030",
"pm_score": 0,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\nusing namespace std;\n\nvoid main()\n{\n ifstream in_stream; // fstream command to initiate \"in_stream\" as a command.\n char filename[31]; // variable for \"filename\".\n cout << \"Enter file name to open :: \"; // asks user for input for \"filename\".\n cin.getline(filename, 30); // this gets the line from input for \"filename\".\n in_stream.open(filename); // this in_stream (fstream) the \"filename\" to open.\n if (in_stream.fail())\n {\n cout << \"Could not open file to read.\"\"\\n\"; // if the open file fails.\n return;\n }\n //.....the rest of the text goes beneath......\n}\n"
},
{
"answer_id": 34267974,
"author": "Ziezi",
"author_id": 3313438,
"author_profile": "https://Stackoverflow.com/users/3313438",
"pm_score": 2,
"selected": false,
"text": "// define your file name\nstring file_name = \"data.txt\";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name);\n\n// check stream status\nif (!input_stream) cerr << \"Can't open input file!\";\n\n// file contents \nvector<string> text;\n\n// one line\nstring line;\n\n// extract all the text from the input file\nwhile (getline(input_stream, line)) {\n\n // store each line in the vector\n text.push_back(line);\n}\n read() // define your file name\nstring file_name = \"binary_data.bin\";\n\n// attach an input stream to the wanted file\nifstream input_stream(file_name, ios::binary);\n\n// check stream status\nif (!input_stream) cerr << \"Can't open input file!\";\n\n// use function that explicitly specifies the amount of block memory read \nint memory_size = 10;\n\n// allocate 10 bytes of memory on heap\nchar* dynamic_buffer = new char[memory_size];\n\n// read 10 bytes and store in dynamic_buffer\nfile_name.read(dynamic_buffer, memory_size);\n #include <iostream>"
},
{
"answer_id": 49563356,
"author": "Nardine Nabil",
"author_id": 9326568,
"author_profile": "https://Stackoverflow.com/users/9326568",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <fstream>\nusing namespace std;\n\nint main () {\n ofstream file;\n file.open (\"codebind.txt\");\n file << \"Please writr this text to a file.\\n this text is written using C++\\n\";\n file.close();\n return 0;\n}\n"
},
{
"answer_id": 49564320,
"author": "Maria Emil",
"author_id": 9560780,
"author_profile": "https://Stackoverflow.com/users/9560780",
"pm_score": -1,
"selected": false,
"text": "#include <fstream>\n\nifstream infile;\ninfile.open(**file path**);\nwhile(!infile.eof())\n{\n getline(infile,data);\n}\ninfile.close();\n"
},
{
"answer_id": 50043136,
"author": "Kartik Maheshwari",
"author_id": 5213931,
"author_profile": "https://Stackoverflow.com/users/5213931",
"pm_score": 0,
"selected": false,
"text": "CFile/QFile/ifstream m_file;\nm_file.Open(path,Other parameter/mood to open file);\n"
},
{
"answer_id": 55663714,
"author": "Karim Salah",
"author_id": 9571867,
"author_profile": "https://Stackoverflow.com/users/9571867",
"pm_score": 0,
"selected": false,
"text": "**#include<fstream> //to use file\n#include<string> //to use getline\nusing namespace std;\nint main(){\nifstream file;\nstring str;\nfile.open(\"path the file\" , ios::binary | ios::in);\nwhile(true){\n getline(file , str);\n if(file.fail())\n break;\n cout<<str;\n}\n}**\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
7,884 | <p>I've just come across this in a WHERE clause:</p>
<pre><code>AND NOT (t.id = @id)
</code></pre>
<p>How does this compare with:</p>
<pre><code>AND t.id != @id
</code></pre>
<p>Or with:</p>
<pre><code>AND t.id <> @id
</code></pre>
<p>I'd always write the latter myself, but clearly someone else thinks differently. Is one going to perform any better than the other? I know that using <code><></code> or <code>!=</code> is going to bust any hopes for using an index that I might have had, but <em>surely</em> the first approach above will suffer the same problem?</p>
| [
{
"answer_id": 7892,
"author": "SQLMenace",
"author_id": 740,
"author_profile": "https://Stackoverflow.com/users/740",
"pm_score": 6,
"selected": true,
"text": "declare @id varchar(40)\nselect @id = '172-32-1176'\n\nselect * from authors\nwhere au_id <> @id\n\nselect * from authors\nwhere au_id != @id\n\nselect * from authors\nwhere not (au_id = @id)\n"
},
{
"answer_id": 2875218,
"author": "LAGARRIGUE Mattiheu",
"author_id": 346274,
"author_profile": "https://Stackoverflow.com/users/346274",
"pm_score": 4,
"selected": false,
"text": "false Not (unknown) unknown (a1, b1) (a2, b2) 0 1 NULL DECLARE @t table (a1 bit, a2 bit, b1 bit, b2 bit)\n\nInsert into @t (a1 , a2, b1, b2) \nvalues( 0 , 0 , 0 , NULL )\n\nselect \na1,a2,b1,b2,\ncase when (\n (a1=a2 or (a1 is null and a2 is null))\nand (b1=b2 or (b1 is null and b2 is null))\n)\nthen \n'Equal'\nend,\ncase when not (\n (a1=a2 or (a1 is null and a2 is null))\nand (b1=b2 or (b1 is null and b2 is null))\n)\nthen \n'Not Equal'\nend,\ncase when (\n (a1<>a2 or (a1 is null and a2 is not null) or (a1 is not null and a2 is null))\nor (b1<>b2 or (b1 is null and b2 is not null) or (b1 is not null and b2 is null))\n)\nthen \n'Different'\nend\nfrom @t\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7884",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
7,885 | <p>Perl has OOP features, but they are somewhat rarely used. How do you create and use Perl objects with methods and properties?</p>
| [
{
"answer_id": 8668,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 6,
"selected": true,
"text": "Moose package Point;\nuse Moose; # automatically turns on strict and warnings\n\nhas 'x' => (is => 'rw', isa => 'Int');\nhas 'y' => (is => 'rw', isa => 'Int');\n\nsub clear {\n my $self = shift;\n $self->x(0);\n $self->y(0);\n}\n my $p = Point->new({x=>10 , y=>20}); # Free constructor\n$p->x(15); # Free setter\nprint $p->x(); # Free getter\n$p->clear();\n$p->x(15.5); # FAILS! Free type check.\n Moose::Manual Moose::Cookbook Mouse"
},
{
"answer_id": 75767,
"author": "Penfold",
"author_id": 11952,
"author_profile": "https://Stackoverflow.com/users/11952",
"pm_score": 3,
"selected": false,
"text": "package Person;\nuse Moose;\nhas age => ( isa => Int, is => 'rw'); \nhas name => ( isa => Str, is => 'rw'); \n1;\n my $person = Person->new();\n$person->age(34);\n$person->name('Mike');\nprint $person->name, \"\\n\";\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7885",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
7,913 | <p>I've always found checkin (commit) mails to be very useful for keeping track of what work other people are doing in the codebase / repository. How do I set up SVN to email a distribution list on each commit?</p>
<p>I'm running clients on Windows and the Apache Subversion server on Linux. The answers below for various platforms will likely be useful to other people though.</p>
| [
{
"answer_id": 7928,
"author": "epatel",
"author_id": 842,
"author_profile": "https://Stackoverflow.com/users/842",
"pm_score": 1,
"selected": false,
"text": "svn www REPOS=\"`echo $1 | sed 's/\\/{root of repository}//g'` \"\nREV=\"$2\"\nMSG=`/usr/local/bin/svn log -v -r HEAD https://localhost$REPOS`\n\n/usr/local/bin/msmtp {list of recipients} <<EOF\nSubject: SVN-Commit $REPOS#$REV\nMIME-Version: 1.0\nContent-Type: text/plain; charset=utf-8\nContent-Transfer-Encoding: 8Bit\n\n$MSG\nEOF\n {root of repository} {list of recipients}"
},
{
"answer_id": 8295,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": " call d:\\subversion\\repos\\rts\\hooks\\mail %1 %2\n copy d:\\subversion\\repos\\RTS\\hooks\\Commitmsg.txt %temp%\\commit.txt\ncopy d:\\subversion\\repos\\RTS\\hooks\\subjbase.txt %temp%\\subject.txt\nsvnlook info -r %2 %1 >> %temp%\\commit.txt\necho Revision %2 >> %temp%\\commit.txt\nsvnlook changed -r %2 %1 >> %temp%\\commit.txt\nsvnlook author -r %2 %1 >> %temp%\\subject.txt\nc:\\utils\\blat %temp%\\commit.txt -t <[email protected]> -sf %temp%\\subject.txt -server ServerName -f \"SVN Admin <[email protected]>\" -noh2\n"
},
{
"answer_id": 19270610,
"author": "bahrep",
"author_id": 761095,
"author_profile": "https://Stackoverflow.com/users/761095",
"pm_score": 2,
"selected": false,
"text": "VisualSVNServerHooks.exe"
},
{
"answer_id": 20576816,
"author": "Sagar Zaveri",
"author_id": 1383016,
"author_profile": "https://Stackoverflow.com/users/1383016",
"pm_score": 2,
"selected": false,
"text": "#!/bin/sh\n\nREPOS=\"$1\"\nREV=\"$2\"\nTO=\"[email protected]\" # who will receive the notifications\nFROM=\"[email protected]\" # what will be in \"FROM\" fields\n\n\n /usr/bin/svnnotify \\\n\n--repos-path \"$REPOS\" \\\n--revision \"$REV\" \\\n--to $TO \\\n--from $FROM \\\n--reply-to $FROM \\\n--smtp \"YOUR.SMTP.MAIL.COM\" \\\n--subject-prefix \"[svn commit]\" \\\n--attach-diff -a \\\n--header 'Message generated on Subversion Check-in.' \\\n--footer 'OpenSource Team. ' \\\n--svnlook \"/usr/local/bin/svnlook\" \\\n--handler HTML::ColorDiff # make diff pretty\n"
},
{
"answer_id": 23951956,
"author": "Danijel",
"author_id": 1202172,
"author_profile": "https://Stackoverflow.com/users/1202172",
"pm_score": 1,
"selected": false,
"text": "[email protected] /path_to_your_svn/svn/hooks/svn-notify/mailer.conf /path_to_your_svn/svn/hooks/post-commit /path_to_your_svn/svn/hooks/svn-notify/mailer.py commit \"$REPOS\" \"$REV\" /path_to_your_svn/svn/hooks/svn-notify/mailer.conf"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7913",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1031/"
] |
7,917 | <p>I'm importing some data from a <code>CSV</code> file, and numbers that are larger than <code>1000</code> get turned into <code>1,100</code> etc. </p>
<p>What's a good way to remove both the quotes and the comma from this so I can put it into an <code>int</code> field?</p>
<p><strong>Edit:</strong> </p>
<p>The data is actually already in a MySQL table, so I need to be able to this using SQL. Sorry for the mixup.</p>
| [
{
"answer_id": 7934,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "Perl -lne 's/[,|\"]//; print' file.txt > newfile.txt\n"
},
{
"answer_id": 7944,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "$stripped = str_replace(array(',', '\"'), '', $value);\n"
},
{
"answer_id": 8001,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "Perl -lne 's/\"(\\d+),(\\d+)\"/$1$2/; print' file.txt > newfile.txt\n"
},
{
"answer_id": 8059,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "id,age,name,...\n1,23,phil,\n \"111,111\",234\n234,\"111,111\"\n\"111,111\",\"111,111\"\n"
},
{
"answer_id": 8113,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 3,
"selected": true,
"text": "/[,\"]/\n /[^0-9\\.]/\n"
},
{
"answer_id": 8135,
"author": "Eldila",
"author_id": 889,
"author_profile": "https://Stackoverflow.com/users/889",
"pm_score": 0,
"selected": false,
"text": "Select *\n FROM SOMETABLE\n WHERE SOMEFIELD REGEXP '\"(\\d+),(\\d+)\"'\n"
},
{
"answer_id": 8193,
"author": "Joseph Pecoraro",
"author_id": 792,
"author_profile": "https://Stackoverflow.com/users/792",
"pm_score": 4,
"selected": false,
"text": "mysql> desc t;\n\n+-------+-------------+------+-----+---------+-------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+-------------+------+-----+---------+-------+\n| alpha | varchar(15) | YES | | NULL | | \n+-------+-------------+------+-----+---------+-------+\n mysql> insert into t values('\"1,000,000\"');\nQuery OK, 1 row affected (0.00 sec)\n\nmysql> select * from t;\n\n+-------------+\n| alpha |\n+-------------+\n| \"1,000,000\" | \n+-------------+\n mysql> update t set alpha = replace( replace(alpha, ',', ''), '\"', '' );\nQuery OK, 1 row affected (0.00 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> select * from t;\n\n+---------+\n| alpha |\n+---------+\n| 1000000 | \n+---------+\n UPDATE table\n SET field_name = replace( replace(field_name, ',', ''), '\"', '' );\n s/\"(\\d+),(\\d+)\"/$1$2/ s///g s/(\\d+)?,(\\d+)/$1$2/g >> \"1,000,000\".sub( /(\\d+),(\\d+)/, '\\1\\2' )\n# => \"1000,000\" \n>> \"1,000,000\".gsub( /(\\d+),(\\d+)/, '\\1\\2' )\n# => \"1000,000\" \n>> \"1,000,000\".gsub( /(\\d+)?,(\\d+)/, '\\1\\2' )\n# => \"1000000\" \n>> \"1,000,000\".gsub( /[,\"]/, '' )\n# => \"1000000\" \n>> \"1,000,000\".gsub( /[^0-9]/, '' )\n# => \"1000000\"\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7917",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/402/"
] |
7,933 | <p>Is there some means of querying the system tables to establish which tables are using what locking schemes? I took a look at the columns in <strong>sysobjects</strong> but nothing jumped out.</p>
| [
{
"answer_id": 7936,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 2,
"selected": true,
"text": "SELECT name, lockscheme(name)\nFROM sysobjects\nWHERE type=\"U\"\nORDER BY name\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7933",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
7,937 | <p>When using IE, you cannot put an absolutely positioned div over a select input element. That's because the select element is considered an ActiveX object and is on top of every HTML element in the page.</p>
<p>I already saw people hiding selects when opening a popup div, that leads to pretty bad user experience having controls disappearing.</p>
<p>FogBugz actually had a pretty smart solution (before v6) of turning every select into text boxes when a popup was displayed. This solved the bug and tricked the user eye but the behavior was not perfect.</p>
<p>Another solution is in FogBugz 6 where they no more use the select element and recoded it everywhere.</p>
<p>Last solution I currently use is messing up the IE rendering engine and force it to render the absolutely positioned <code><div></code> as an ActiveX element too, ensuring it can live over a select element. This is achieved by placing an invisible <code><iframe></code> inside the <code><div></code> and styling it with:</p>
<pre class="lang-css prettyprint-override"><code>#MyDiv iframe
{
position: absolute;
z-index: -1;
filter: mask();
border: 0;
margin: 0;
padding: 0;
top: 0;
left: 0;
width: 9999px;
height: 9999px;
overflow: hidden;
}
</code></pre>
<p>Does anyone have an even better solution than this one?</p>
<p>EDIT: The purpose of this question is as much informative as it is a real question. I find the <code><iframe></code> trick to be a good solution, but I am still looking for improvement like removing this <em>ugly useless tag</em> that degrades accessibility.</p>
| [
{
"answer_id": 4889051,
"author": "Luffy",
"author_id": 447673,
"author_profile": "https://Stackoverflow.com/users/447673",
"pm_score": 1,
"selected": false,
"text": "$('.your-dropdown-menu').bgiframe();"
},
{
"answer_id": 42917068,
"author": "Sacky San",
"author_id": 5076414,
"author_profile": "https://Stackoverflow.com/users/5076414",
"pm_score": 0,
"selected": false,
"text": "function showOverlay() {\n el = document.getElementById(\"overlay\");\n el.style.visibility = \"visible\";\n selects = document.getElementsByTagName(\"select\");\n for (var i = 0; i < selects.length; i++) {\n selects[i].style.visibility = \"hidden\";\n }\n}\n\nfunction hideOverlay() {\n el = document.getElementById(\"overlay\");\n el.style.visibility = \"hidden\";\n var selects = document.getElementsByTagName(\"select\");\n for (var i = 0; i < selects.length; i++) {\n selects[i].style.visibility = \"visible\";\n }\n}\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7937",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/268/"
] |
7,981 | <p>I'm working on bringing some old code from 1998 up to the 21st century. One of the first steps in the process is converting the printf statements to <a href="http://qt-project.org/doc/qt-4.8/qstring.html" rel="nofollow noreferrer">QString</a> variables. No matter how many times I look back at printf though, I always end up forgetting one thing or the other. So, for fun, let's decode it together, for ole' times sake and in the process create the first little <strong>'printf primer'</strong> for Stackoverflow.</p>
<p>In the code, I came across this little gem,</p>
<pre><code>printf("%4u\t%016.1f\t%04X\t%02X\t%1c\t%1c\t%4s", a, b, c, d, e, f, g);
</code></pre>
<p>How will the variables a, b, c, d, e, f, g be formatted?</p>
| [
{
"answer_id": 8075,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 2,
"selected": false,
"text": "#include <stdio.h>\n\nint main(int argc, char *argv[]) {\n char *s = \"Hello, World\";\n char *s2 = \"he\";\n\n printf(\"4s: '%4s'\\n\", s);\n printf(\".4s: '%.4s'\\n\", s);\n printf(\"4s2: '%4s'\\n\", s2);\n printf(\".4s2: '%.4s'\\n\", s2);\n\n return 0;\n}\n\n$ gcc -o foo foo.c\n$ ./foo\n4s: 'Hello, World'\n.4s: 'Hell'\n4s2: ' he'\n.4s2: 'he'\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7981",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25/"
] |
7,991 | <p>I'm using the .NETCF (Windows Mobile) <code>Graphics</code> class and the <code>DrawString()</code> method to render a single character to the screen.</p>
<p>The problem is that I can't seem to get it centred properly. No matter what I set for the Y coordinate of the location of the string render, it always comes out lower than that and the larger the text size the greater the Y offset.</p>
<p>For example, at text size 12, the offset is about 4, but at 32 the offset is about 10.</p>
<p>I want the character to vertically take up most of the rectangle it's being drawn in and be centred horizontally. Here's my basic code. <code>this</code> is referencing the user control it's being drawn in.</p>
<pre><code>Graphics g = this.CreateGraphics();
float padx = ((float)this.Size.Width) * (0.05F);
float pady = ((float)this.Size.Height) * (0.05F);
float width = ((float)this.Size.Width) - 2 * padx;
float height = ((float)this.Size.Height) - 2 * pady;
float emSize = height;
g.DrawString(letter, new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular),
new SolidBrush(Color.Black), padx, pady);
</code></pre>
<p>Yes, I know there is the label control that I could use instead and set the centring with that, but I actually do need to do this manually with the <code>Graphics</code> class.</p>
| [
{
"answer_id": 8010,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 2,
"selected": false,
"text": "StringFormat DrawString"
},
{
"answer_id": 8013,
"author": "TheSmurf",
"author_id": 1975282,
"author_profile": "https://Stackoverflow.com/users/1975282",
"pm_score": 3,
"selected": false,
"text": "Graphics g = this.CreateGraphics();\nSizeF size = g.MeasureString(\"string to measure\");\n\nint nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));\nint nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));\n"
},
{
"answer_id": 8056,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "TextRenderer.DrawText(g, \"my text\", Font, Bounds, ForeColor, BackColor, \n TextFormatFlags.HorizontalCenter | \n TextFormatFlags.VerticalCenter |\n TextFormatFlags.GlyphOverhangPadding);\n Font FindBestFitFont(Graphics g, String text, Font font, \n Size proposedSize, TextFormatFlags flags)\n{ \n // Compute actual size, shrink if needed\n while (true)\n {\n Size size = TextRenderer.MeasureText(g, text, font, proposedSize, flags);\n\n // It fits, back out\n if ( size.Height <= proposedSize.Height && \n size.Width <= proposedSize.Width) { return font; }\n\n // Try a smaller font (90% of old size)\n Font oldFont = font;\n font = new Font(font.FontFamily, (float)(font.Size * .9)); \n oldFont.Dispose();\n }\n}\n Font bestFitFont = FindBestFitFont(g, text, someBigFont, sizeToFitIn, flags);\n// Then do your drawing using the bestFitFont\n// Don't forget to dispose the font (if/when needed)\n"
},
{
"answer_id": 8097,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 6,
"selected": true,
"text": " private void DrawLetter()\n {\n Graphics g = this.CreateGraphics();\n\n float width = ((float)this.ClientRectangle.Width);\n float height = ((float)this.ClientRectangle.Width);\n\n float emSize = height;\n\n Font font = new Font(FontFamily.GenericSansSerif, emSize, FontStyle.Regular);\n\n font = FindBestFitFont(g, letter.ToString(), font, this.ClientRectangle.Size);\n\n SizeF size = g.MeasureString(letter.ToString(), font);\n g.DrawString(letter, font, new SolidBrush(Color.Black), (width-size.Width)/2, 0);\n\n }\n\n private Font FindBestFitFont(Graphics g, String text, Font font, Size proposedSize)\n {\n // Compute actual size, shrink if needed\n while (true)\n {\n SizeF size = g.MeasureString(text, font);\n\n // It fits, back out\n if (size.Height <= proposedSize.Height &&\n size.Width <= proposedSize.Width) { return font; }\n\n // Try a smaller font (90% of old size)\n Font oldFont = font;\n font = new Font(font.Name, (float)(font.Size * .9), font.Style);\n oldFont.Dispose();\n }\n }\n"
},
{
"answer_id": 26498,
"author": "Quibblesome",
"author_id": 1143,
"author_profile": "https://Stackoverflow.com/users/1143",
"pm_score": 7,
"selected": false,
"text": "StringFormat format = new StringFormat();\nformat.LineAlignment = StringAlignment.Center;\nformat.Alignment = StringAlignment.Center;\n"
},
{
"answer_id": 197551,
"author": "Chris Hughes",
"author_id": 27405,
"author_profile": "https://Stackoverflow.com/users/27405",
"pm_score": 6,
"selected": false,
"text": "StringFormat sf = new StringFormat();\nsf.LineAlignment = StringAlignment.Center;\nsf.Alignment = StringAlignment.Center;\ne.Graphics.DrawString(\"My String\", this.Font, Brushes.Black, ClientRectangle, sf);\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/7991",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
8,004 | <p>I use <a href="http://rsync.samba.org/" rel="nofollow noreferrer">rsync</a> to synchronize files to Windows clients in a server agnostic way. What methods are available to send the progress of rsync to the parent process for display in a gui progress bar?</p>
<p>I imagine two or three choices exist. (1) Watch STDOUT (2) Watch rsync.exe log file, similar to unix <code>tail</code> (3) Watch rsync console output in memory.</p>
<p>Which one is best/preferred?</p>
| [
{
"answer_id": 8090,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": 3,
"selected": true,
"text": "$sCmd = \"DIR E:\\*.AU3 /S\" ; Test command\n$nAutoTimeout = 10 ; Time in seconds to close window after finish\n\n$nDeskPct = 60 ; % of desktop size (if percent)\n\n; $nHeight = 480 ; height/width of the main window (if fixed)\n; $nWidth = 480\n\n$sTitRun = \"Executing process. Wait....\" ; \n$sTitDone = \"Process done\" ; \n\n$sSound = @WindowsDir & \"\\Media\\Ding.wav\" ; End Sound\n\n$sButRun = \"Cancel\" ; Caption of \"Exec\" button\n$sButDone = \"Close\" ; Caption of \"Close\" button\n\n#include <GUIConstants.au3>\n#include <Constants.au3>\n#Include <GuiList.au3>\n\nOpt(\"GUIOnEventMode\", 1)\n\nif $nDeskPct > 0 Then\n $nHeight = @DesktopHeight * ($nDeskPct / 100)\n $nWidth = @DesktopWidth * ($nDeskPct / 100)\nEndIf\n\n\nIf $CmdLine[0] > 0 Then\n $sCmd = \"\"\n For $nCmd = 1 To $CmdLine[0]\n $sCmd = $sCmd & \" \" & $CmdLine[$nCmd]\n Next\n\n ; MsgBox (1,\"\",$sCmd)\nEndIf\n\n; AutoItSetOption(\"GUIDataSeparatorChar\", Chr(13)+Chr(10))\n\n$nForm = GUICreate($sTitRun, $nWidth, $nHeight)\nGUISetOnEvent($GUI_EVENT_CLOSE, \"CloseForm\")\n\n$nList = GUICtrlCreateList (\"\", 10, 10, $nWidth - 20, $nHeight - 50, $WS_BORDER + $WS_VSCROLL)\nGUICtrlSetFont (-1, 9, 0, 0, \"Courier New\")\n\n$nClose = GUICtrlCreateButton ($sButRun, $nWidth - 100, $nHeight - 40, 80, 30)\nGUICtrlSetOnEvent (-1, \"CloseForm\")\n\nGUISetState(@SW_SHOW) ;, $nForm)\n\n$nPID = Run(@ComSpec & \" /C \" & $sCmd, \".\", @SW_HIDE, $STDOUT_CHILD)\n; $nPID = Run(@ComSpec & \" /C _RunErrl.bat \" & $sCmd, \".\", @SW_HIDE, $STDOUT_CHILD) ; # Con ésto devuelve el errorlevel en _ERRL.TMP\n\nWhile 1\n $sLine = StdoutRead($nPID)\n If @error Then ExitLoop\n\n If StringLen ($sLine) > 0 then\n $sLine = StringReplace ($sLine, Chr(13), \"|\")\n $sLine = StringReplace ($sLine, Chr(10), \"\")\n if StringLeft($sLine, 1)=\"|\" Then\n $sLine = \" \" & $sLine\n endif\n\n GUICtrlSetData ($nList, $sLine)\n\n _GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)\n EndIf\nWend\n\n$sLine = \" ||\"\nGUICtrlSetData ($nList, $sLine)\n_GUICtrlListSelectIndex ($nList, _GUICtrlListCount ($nList) - 1)\n\nGUICtrlSetData ($nClose, $sButDone)\n\nWinSetTitle ($sTitRun, \"\", $sTitDone)\nIf $sSound <> \"\" Then\n SoundPlay ($sSound)\nEndIf\n\n$rInfo = DllStructCreate(\"uint;dword\") ; # LASTINPUTINFO\nDllStructSetData($rInfo, 1, DllStructGetSize($rInfo));\n\nDllCall(\"user32.dll\", \"int\", \"GetLastInputInfo\", \"ptr\", DllStructGetPtr($rInfo))\n$nLastInput = DllStructGetData($rInfo, 2)\n\n$nTime = TimerInit()\n\nWhile 1\n If $nAutoTimeout > 0 Then\n DllCall(\"user32.dll\", \"int\", \"GetLastInputInfo\", \"ptr\", DllStructGetPtr($rInfo))\n If DllStructGetData($rInfo, 2) <> $nLastInput Then\n ; Tocó una tecla\n $nAutoTimeout = 0\n EndIf\n EndIf\n\n If $nAutoTimeout > 0 And TimerDiff ($nTime) > $nAutoTimeOut * 1000 Then\n ExitLoop\n EndIf\n\n Sleep (100)\nWend\n\n\nFunc CloseForm()\n Exit\nEndFunc\n"
},
{
"answer_id": 35294,
"author": "Scott Kramer",
"author_id": 3522,
"author_profile": "https://Stackoverflow.com/users/3522",
"pm_score": 1,
"selected": false,
"text": "cmdline web page webservice rsync rsync cygwin Imports System.IO\n\nNamespace cds\n\nPublic Class proc\n\n Public _cmdString As String\n Public _workingDir As String\n Public _arg As String\n\n\n Public Function basic() As String\n\n Dim sOut As String = \"\"\n\n Try\n 'Set start information.\n 'Dim startinfo As New ProcessStartInfo(\"C:\\Program Files\\cwRsync\\bin\\rsync\", \"-avzrbP 192.168.42.6::cdsERP /cygdrive/s/cdsERP_rsync/gwy\")\n 'Dim startinfo As New ProcessStartInfo(\"C:\\Program Files\\cwRsync\\bin\\rsync\", \"-avzrbP 10.1.1.6::user /cygdrive/s/cdsERP_rsync/gws/user\")\n 'Dim startinfo As New ProcessStartInfo(\"C:\\windows\\system32\\cscript\", \"//NoLogo c:\\windows\\system32\\prnmngr.vbs -l\")\n\n Dim si As New ProcessStartInfo(_cmdString, _arg)\n\n si.UseShellExecute = False\n si.CreateNoWindow = True\n si.RedirectStandardOutput = True\n si.RedirectStandardError = True\n\n si.WorkingDirectory = _workingDir\n\n\n ' Make the process and set its start information.\n Dim p As New Process()\n p.StartInfo = si\n\n ' Start the process.\n p.Start()\n\n ' Attach to stdout and stderr.\n Dim stdout As StreamReader = p.StandardOutput()\n Dim stderr As StreamReader = p.StandardError()\n\n sOut = stdout.ReadToEnd() & ControlChars.NewLine & stderr.ReadToEnd()\n\n 'Dim writer As New StreamWriter(\"out.txt\", FileMode.CreateNew)\n 'writer.Write(sOut)\n 'writer.Close()\n\n stdout.Close()\n stderr.Close()\n p.Close()\n\n\n Catch ex As Exception\n\n sOut = ex.Message\n\n End Try\n\n Return sOut\n\n End Function\n\nEnd Class\nEnd Namespace\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8004",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1027/"
] |
8,021 | <p>I'd like to allow a user to set up an SSH tunnel to a particular machine on a particular port (say, 5000), but I want to restrict this user as much as possible. (Authentication will be with public/private keypair).</p>
<p>I know I need to edit the relevant ~/.ssh/authorized_keys file, but I'm not sure exactly what content to put in there (other than the public key).</p>
| [
{
"answer_id": 8023,
"author": "Michael Pryor",
"author_id": 245,
"author_profile": "https://Stackoverflow.com/users/245",
"pm_score": -1,
"selected": false,
"text": "chmod 700 ~/.ssh"
},
{
"answer_id": 8363,
"author": "Jason Day",
"author_id": 737,
"author_profile": "https://Stackoverflow.com/users/737",
"pm_score": 4,
"selected": false,
"text": "less tail /home/restricted-commands"
},
{
"answer_id": 181726,
"author": "Zoredache",
"author_id": 20267,
"author_profile": "https://Stackoverflow.com/users/20267",
"pm_score": 2,
"selected": false,
"text": "no-pty,no-port-forwarding,no-X11-forwarding,no-agent-forwarding\n permitopen=\"host.domain.tld:443\",no-pty,no-agent-forwarding,no-X11-forwardi\nng,command=\"/bin/noshell.sh\" ssh-rsa AAAAB3NzaC.......wCUw== zoredache \n"
},
{
"answer_id": 10266397,
"author": "Paul",
"author_id": 103081,
"author_profile": "https://Stackoverflow.com/users/103081",
"pm_score": 8,
"selected": true,
"text": "$ ssh -i keyfile.rsa -T -N -L 16379:localhost:6379 someuser@somehost\n cat .ssh/authorized_keys (portions redacted)\n\nno-pty,no-X11-forwarding,permitopen=\"localhost:6379\",command=\"/bin/echo do-not-send-commands\" ssh-rsa rsa-public-key-code-goes-here keyuser@keyhost\n man sshd"
},
{
"answer_id": 15845908,
"author": "joseph_morris",
"author_id": 720763,
"author_profile": "https://Stackoverflow.com/users/720763",
"pm_score": 2,
"selected": false,
"text": "command=\"svnserve -t\",no-port-forwarding,no-pty,no-agent-forwarding,no-X11-forwarding [KEY TYPE] [KEY] [KEY COMMENT]\n"
},
{
"answer_id": 15990251,
"author": "Daniel W.",
"author_id": 1948292,
"author_profile": "https://Stackoverflow.com/users/1948292",
"pm_score": 3,
"selected": false,
"text": "#!/bin/bash\ntrap '' 2 20 24\nclear\necho -e \"\\r\\n\\033[32mSSH tunnel started, shell disabled by the system administrator\\r\\n\"\nwhile [ true ] ; do\nsleep 1000\ndone\nexit 0\n"
},
{
"answer_id": 26964042,
"author": "fangfufu",
"author_id": 4259370,
"author_profile": "https://Stackoverflow.com/users/4259370",
"pm_score": 0,
"selected": false,
"text": "#include <stdio.h>\n#include <unistd.h>\n#include <signal.h>\n#include <stdlib.h>\nvoid sig_handler(int signo)\n{\n if (signo == SIGHUP)\n exit(0);\n}\n\nint main()\n{\n signal(SIGINT, &sig_handler);\n signal(SIGTSTP, &sig_handler);\n\n printf(\"OK\\n\");\n while(1)\n sleep(1);\n exit(0);\n}\n ssh server command"
},
{
"answer_id": 30217592,
"author": "juanmf",
"author_id": 711855,
"author_profile": "https://Stackoverflow.com/users/711855",
"pm_score": 3,
"selected": false,
"text": "useradd sshtunnel -m -d /home/sshtunnel -s /bin/rbash\npasswd sshtunnel\n /home/sshtunnel/.profile PATH=\"\"\n chmod 555 /home/sshtunnel/\ncd /home/sshtunnel/\nchmod 444 .bash_logout .bashrc .profile\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8021",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/742/"
] |
8,042 | <p>The new extensions in .Net 3.5 allow functionality to be split out from interfaces.</p>
<p>For instance in .Net 2.0</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
List<IChild> GetChildren()
}
</code></pre>
<p>Can (in 3.5) become:</p>
<pre><code>public interface IHaveChildren {
string ParentType { get; }
int ParentId { get; }
}
public static class HaveChildrenExtension {
public static List<IChild> GetChildren( this IHaveChildren ) {
//logic to get children by parent type and id
//shared for all classes implementing IHaveChildren
}
}
</code></pre>
<p>This seems to me to be a better mechanism for many interfaces. They no longer need an abstract base to share this code, and functionally the code works the same. This could make the code more maintainable and easier to test.</p>
<p>The only disadvantage being that an abstract bases implementation can be virtual, but can that be worked around (would an instance method hide an extension method with the same name? would it be confusing code to do so?)</p>
<p>Any other reasons not to regularly use this pattern?</p>
<hr>
<p>Clarification:</p>
<p>Yeah, I see the tendency with extension methods is to end up with them everywhere. I'd be particularly careful having any on .Net value types without a great deal of peer review (I think the only one we have on a string is a <code>.SplitToDictionary()</code> - similar to <code>.Split()</code> but taking a key-value delimiter too)</p>
<p>I think there's a whole best practice debate there ;-)</p>
<p>(Incidentally: DannySmurf, your PM sounds scary.)</p>
<p>I'm specifically asking here about using extension methods where previously we had interface methods.</p>
<hr>
<p>I'm trying to avoid lots of levels of abstract base classes - the classes implementing these models mostly already have base classes. I think this model could be more maintainable and less overly-coupled than adding further object hierarchies.</p>
<p>Is this what MS has done to IEnumerable and IQueryable for Linq?</p>
| [
{
"answer_id": 8570,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 1,
"selected": false,
"text": "IInterface variable = new ImplementingClass();\n"
},
{
"answer_id": 13563,
"author": "Zooba",
"author_id": 891,
"author_profile": "https://Stackoverflow.com/users/891",
"pm_score": 2,
"selected": false,
"text": "namespace Model\n{\n class Person\n {\n public string Title { get; set; }\n public string FirstName { get; set; }\n public string Surname { get; set; }\n }\n}\n\nnamespace View\n{\n static class PersonExtensions\n {\n public static string FullName(this Model.Person p)\n {\n return p.Title + \" \" + p.FirstName + \" \" + p.Surname;\n }\n\n public static string FormalName(this Model.Person p)\n {\n return p.Title + \" \" + p.FirstName[0] + \". \" + p.Surname;\n }\n }\n}\n"
},
{
"answer_id": 14273,
"author": "Fredrik Kalseth",
"author_id": 1710,
"author_profile": "https://Stackoverflow.com/users/1710",
"pm_score": 1,
"selected": false,
"text": "public interface IHaveChildren \n{\n string ParentType { get; }\n int ParentId { get; }\n}\n\npublic interface IChildIterator\n{\n IEnumerable<IChild> GetChildren();\n}\n\npublic void DefaultChildIterator : IChildIterator\n{\n private readonly IHaveChildren _parent;\n\n public DefaultChildIterator(IHaveChildren parent)\n {\n _parent = parent; \n }\n\n public IEnumerable<IChild> GetChildren() \n { \n // default child iterator impl\n }\n}\n\npublic class Node : IHaveChildren, IChildIterator\n{ \n // *snip*\n\n public IEnumerable<IChild> GetChildren()\n {\n return new DefaultChildIterator(this).GetChildren();\n }\n}\n"
},
{
"answer_id": 38494,
"author": "Emperor XLII",
"author_id": 2495,
"author_profile": "https://Stackoverflow.com/users/2495",
"pm_score": 4,
"selected": true,
"text": "public interface INode {\n INode Root { get; }\n List<INode> GetChildren( );\n}\n public interface IChildNode : INode {\n INode Parent { get; }\n}\n public static class NodeExtensions {\n public INode GetParent( this INode node ) {\n // If the node implements the new interface, call it directly.\n var childNode = node as IChildNode;\n if( !object.ReferenceEquals( childNode, null ) )\n return childNode.Parent;\n\n // Otherwise, fall back on a default implementation.\n return FindParent( node, node.Root );\n }\n}\n public interface ILongMethod {\n public bool LongMethod( string s, double d, int i, object o, ... );\n}\n\n...\npublic static LongMethodExtensions {\n public bool LongMethod( this ILongMethod lm, string s, double d ) {\n lm.LongMethod( s, d, 0, null );\n }\n ...\n}\n"
},
{
"answer_id": 1859130,
"author": "Abdo",
"author_id": 226255,
"author_profile": "https://Stackoverflow.com/users/226255",
"pm_score": 0,
"selected": false,
"text": " public static List<long> GetIds<T>(this List<T> original){\n List<long> ret = new List<long>();\n if (original == null)\n return ret;\n\n try\n {\n foreach (T t in original)\n {\n IIDable idable = (IIDable)t;\n ret.Add(idable.getId());\n }\n return ret;\n }\n catch (Exception)\n {\n throw new Exception(\"Class calling this extension must implement IIDable interface\");\n }\n"
},
{
"answer_id": 2025433,
"author": "Jerry Liu",
"author_id": 240951,
"author_profile": "https://Stackoverflow.com/users/240951",
"pm_score": 2,
"selected": false,
"text": "((IFirst)this).AmbigousMethod()\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8042",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/905/"
] |
8,107 | <p>When I have two mysql servers that have different jobs (holding different databases) but want to be able to use one of them to slip in when the other one fails, what would you suggest how I keep the data on both of them equal "close to realtime"? </p>
<p>Obviously it's not possible to make a full database dump every x minutes.</p>
<p>I've read about the <a href="http://dev.mysql.com/doc/refman/5.0/en/binary-log.html" rel="noreferrer">Binary Log</a>, is that the way that I need to go? Will that not slow down the fallback server a lot? Is there a way to not include some tables in the binary log - where it doesn't matter that the data has changed?</p>
| [
{
"answer_id": 60711,
"author": "Erik",
"author_id": 4484,
"author_profile": "https://Stackoverflow.com/users/4484",
"pm_score": 2,
"selected": false,
"text": "--replicate-do-db=server_2_db --replicate-do-db=server_1_db DROP DATABASE"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8107",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/999/"
] |
8,128 | <p>How do I calculate the CRC32 (Cyclic Redundancy Checksum) of a string in .NET?</p>
| [
{
"answer_id": 8130,
"author": "Pete",
"author_id": 76,
"author_profile": "https://Stackoverflow.com/users/76",
"pm_score": 6,
"selected": true,
"text": "Crc32 crc32 = new Crc32();\nString hash = String.Empty;\n\nusing (FileStream fs = File.Open(\"c:\\\\myfile.txt\", FileMode.Open))\n foreach (byte b in crc32.ComputeHash(fs)) hash += b.ToString(\"x2\").ToLower();\n\nConsole.WriteLine(\"CRC-32 is {0}\", hash);\n"
},
{
"answer_id": 51922169,
"author": "SharpC",
"author_id": 1741690,
"author_profile": "https://Stackoverflow.com/users/1741690",
"pm_score": 4,
"selected": false,
"text": "/// <summary>\n/// Performs 32-bit reversed cyclic redundancy checks.\n/// </summary>\npublic class Crc32\n{\n #region Constants\n /// <summary>\n /// Generator polynomial (modulo 2) for the reversed CRC32 algorithm. \n /// </summary>\n private const UInt32 s_generator = 0xEDB88320;\n #endregion\n\n #region Constructors\n /// <summary>\n /// Creates a new instance of the Crc32 class.\n /// </summary>\n public Crc32()\n {\n // Constructs the checksum lookup table. Used to optimize the checksum.\n m_checksumTable = Enumerable.Range(0, 256).Select(i =>\n {\n var tableEntry = (uint)i;\n for (var j = 0; j < 8; ++j)\n {\n tableEntry = ((tableEntry & 1) != 0)\n ? (s_generator ^ (tableEntry >> 1)) \n : (tableEntry >> 1);\n }\n return tableEntry;\n }).ToArray();\n }\n #endregion\n\n #region Methods\n /// <summary>\n /// Calculates the checksum of the byte stream.\n /// </summary>\n /// <param name=\"byteStream\">The byte stream to calculate the checksum for.</param>\n /// <returns>A 32-bit reversed checksum.</returns>\n public UInt32 Get<T>(IEnumerable<T> byteStream)\n {\n try\n {\n // Initialize checksumRegister to 0xFFFFFFFF and calculate the checksum.\n return ~byteStream.Aggregate(0xFFFFFFFF, (checksumRegister, currentByte) => \n (m_checksumTable[(checksumRegister & 0xFF) ^ Convert.ToByte(currentByte)] ^ (checksumRegister >> 8)));\n }\n catch (FormatException e)\n {\n throw new CrcException(\"Could not read the stream out as bytes.\", e);\n }\n catch (InvalidCastException e)\n {\n throw new CrcException(\"Could not read the stream out as bytes.\", e);\n }\n catch (OverflowException e)\n {\n throw new CrcException(\"Could not read the stream out as bytes.\", e);\n }\n }\n #endregion\n\n #region Fields\n /// <summary>\n /// Contains a cache of calculated checksum chunks.\n /// </summary>\n private readonly UInt32[] m_checksumTable;\n\n #endregion\n}\n var arrayOfBytes = Encoding.ASCII.GetBytes(\"The quick brown fox jumps over the lazy dog\");\n\nvar crc32 = new Crc32();\nConsole.WriteLine(crc32.Get(arrayOfBytes).ToString(\"X\"));\n"
},
{
"answer_id": 61495753,
"author": "spludlow",
"author_id": 8815031,
"author_profile": "https://Stackoverflow.com/users/8815031",
"pm_score": 2,
"selected": false,
"text": "public class CRC32\n{\n private readonly uint[] ChecksumTable;\n private readonly uint Polynomial = 0xEDB88320;\n\n public CRC32()\n {\n ChecksumTable = new uint[0x100];\n\n for (uint index = 0; index < 0x100; ++index)\n {\n uint item = index;\n for (int bit = 0; bit < 8; ++bit)\n item = ((item & 1) != 0) ? (Polynomial ^ (item >> 1)) : (item >> 1);\n ChecksumTable[index] = item;\n }\n }\n\n public byte[] ComputeHash(Stream stream)\n {\n uint result = 0xFFFFFFFF;\n\n int current;\n while ((current = stream.ReadByte()) != -1)\n result = ChecksumTable[(result & 0xFF) ^ (byte)current] ^ (result >> 8);\n\n byte[] hash = BitConverter.GetBytes(~result);\n Array.Reverse(hash);\n return hash;\n }\n\n public byte[] ComputeHash(byte[] data)\n {\n using (MemoryStream stream = new MemoryStream(data))\n return ComputeHash(stream);\n }\n}\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8128",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17/"
] |
8,140 | <p>Is there a general procedure for programming extensibility capability into your code?</p>
<p>I am wondering what the general procedure is for adding extension-type capability to a system you are writing so that functionality can be extended through some kind of plugin API rather than having to modify the core code of a system.</p>
<p>Do such things tend to be dependent on the language the system was written in, or is there a general method for allowing for this?</p>
| [
{
"answer_id": 8157,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 3,
"selected": true,
"text": "gimme_the_interface()"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
8,145 | <p>How can I find the high water mark (the historical maximum number of concurrent users) in an <strong>oracle database (9i)</strong>.</p>
| [
{
"answer_id": 8161,
"author": "ninesided",
"author_id": 1030,
"author_profile": "https://Stackoverflow.com/users/1030",
"pm_score": 4,
"selected": true,
"text": "SELECT sessions_highwater FROM v$license;\n"
},
{
"answer_id": 8169,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 1,
"selected": false,
"text": "select max_utilization from v$resource_limit where resource_name = 'sessions';\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8145",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/685/"
] |
8,147 | <p>Using <a href="http://www.codeplex.com/aspnet" rel="nofollow noreferrer">preview 4</a> of <a href="http://asp.net/mvc" rel="nofollow noreferrer">ASP.NET MVC</a>
Code like:</p>
<pre><code><%= Html.CheckBox( "myCheckBox", "Click Here", "True", false ) %>
</code></pre>
<p>only outputs:</p>
<pre><code><input type="checkbox" value="True" name="myCheckBox" />
</code></pre>
<p>There is a <code>name</code> there for the form post back but no <code>id</code> for javascript or labels :-(</p>
<p>I was hoping that changing it to:</p>
<pre><code>Html.CheckBox( "myCheckBox", "Click Here",
"True", false, new { id="myCheckBox" } )
</code></pre>
<p>would work - but instead I get an exception:</p>
<pre><code>System.ArgumentException: An item with the same key has already been added.
</code></pre>
<p>As if there was already an id somewhere in a collection somewhere - I'm stumped!</p>
<p>The full exception for anyone interested follows (hey - wouldn't it be nice to attach files in here):</p>
<pre>System.ArgumentException: An item with the same key has already been added.
at System.ThrowHelper.ThrowArgumentException(ExceptionResource resource)
at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue value, Boolean add)
at System.Web.Routing.RouteValueDictionary.Add(String key, Object value)
at System.Web.Mvc.TagBuilder2.CreateInputTag(HtmlInputType inputType, String name, RouteValueDictionary attributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxBuilder.CheckBox(String htmlName, String text, String value, Boolean isChecked, RouteValueDictionary htmlAttributes)
at System.Web.Mvc.CheckBoxExtensions.CheckBox(HtmlHelper helper, String htmlName, String text, String value, Boolean isChecked, Object htmlAttributes)
at ASP.views_account_termsandconditions_ascx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\dev\myProject\Views\Account\Edit.ascx:line 108</pre>
| [
{
"answer_id": 8289,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 4,
"selected": true,
"text": "<%= Html.CheckBox(\"myCheckbox\", \"Click here\", \"True\", false, new {_id =\"test\" })%>\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8147",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/193/"
] |
8,154 | <p>I'm using Pylons (a python framework) to serve a simple web application, but it seems to die from time to time, with this in the error log: <code>(2006, 'MySQL server has gone away')</code></p>
<p>I did a bit of checking, and saw that this was because the connections to MySQL were not being renewed. This shouldn't be a problem though, because the <code>sqlalchemy.pool_recycle</code> in the config file should automatically keep it alive. The default was <code>3600</code>, but I dialed it back to <code>1800</code> because of this problem. It helped a bit, but <code>3600</code> <em>should</em> be fine according to the docs. The errors still happen semi-regularly. I don't want to lower it too much though and DOS my own database :).</p>
<p>Maybe something in my MySQL config is goofy? Not sure where to look exactly.</p>
<p>Other relevant details:</p>
<pre><code> Python 2.5
Pylons: 0.9.6.2 (w/ sql_alchemy)
MySQL: 5.0.51
</code></pre>
| [
{
"answer_id": 15261,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 2,
"selected": false,
"text": "show variables like '%timeout%';\n wait_timeout interactive_timeout pool_recycle SELECT 1;"
},
{
"answer_id": 46442,
"author": "swilliams",
"author_id": 736,
"author_profile": "https://Stackoverflow.com/users/736",
"pm_score": 4,
"selected": true,
"text": "sqlalchemy.default.url = [connection string here]\nsqlalchemy.pool_recycle = 1800\n environment.py sqlalchemy.default pool_recycle sqlalchemy.default.pool_recycle = 1800\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8154",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/736/"
] |
8,213 | <p>I need to import a csv file into <strong>Firebird</strong> and I've spent a couple of hours trying out some tools and none fit my needs.</p>
<p>The main problem is that all the tools I've been trying like <a href="http://www.sqlmanager.net/products/ibfb/dataimport" rel="noreferrer">EMS Data Import</a> and <a href="http://www.sqlmaestro.com/products/firebird/datawizard/help/06_01_05_csv/" rel="noreferrer">Firebird Data Wizard</a> expect that my CSV file contains all the information needed by my Table.</p>
<p>I need to write some custom SQL in the insert statement, for example, I have a CSV file with the city name, but as my database already has all the cities in another table (normalized), I need to write a subselect in the insert statement to lookup for the city and write its ID, also I have a stored procedure to cread GUIDS.</p>
<p>My insert statement would be something like this:</p>
<pre><code>INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES((SELECT NEW_GUID FROM CREATE_GUID), :NAME, (SELECT CITY_ID FROM CITY WHERE NAME = :CITY_NAME)
</code></pre>
<p>How can I approach this?</p>
| [
{
"answer_id": 8220,
"author": "Chris Roberts",
"author_id": 475,
"author_profile": "https://Stackoverflow.com/users/475",
"pm_score": 8,
"selected": true,
"text": "=\"INSERT INTO MyTable (Col1, Col2, Col3) VALUES (\" & A1 & \", \" & B1 & \", \" & C1 & \")\"\n"
},
{
"answer_id": 8227,
"author": "Nickolay",
"author_id": 1026,
"author_profile": "https://Stackoverflow.com/users/1026",
"pm_score": 2,
"selected": false,
"text": "temp_table n city_name insert into target_table\n select t.n, c.city_id as city \n from temp_table t, cities c\n where t.city_name = c.city_name\n"
},
{
"answer_id": 8230,
"author": "Guy",
"author_id": 993,
"author_profile": "https://Stackoverflow.com/users/993",
"pm_score": 3,
"selected": false,
"text": "UPDATE person\nSET id = (SELECT newguid() FROM createguid)\n\nUPDATE person\nSET cityid = (SELECT cityid FROM cities WHERE person.cityname = cities.cityname)\n"
},
{
"answer_id": 8417,
"author": "Terry G Lorber",
"author_id": 809,
"author_profile": "https://Stackoverflow.com/users/809",
"pm_score": 3,
"selected": false,
"text": "Bob,New York\nJane,San Francisco\nSteven,Boston\nMarie,Los Angeles\n name-city.csv $ awk -F, '{ print \"INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES ((SELECT NEW_GUID FROM CREATE_GUID), '\\''\"$1\"'\\'', (SELECT CITY_ID FROM CITY WHERE NAME = '\\''\"$2\"'\\''))\" }' name-city.csv\n awk --help"
},
{
"answer_id": 2111127,
"author": "Stan",
"author_id": 255991,
"author_profile": "https://Stackoverflow.com/users/255991",
"pm_score": 0,
"selected": false,
"text": "FSQL"
},
{
"answer_id": 2208584,
"author": "James C",
"author_id": 267222,
"author_profile": "https://Stackoverflow.com/users/267222",
"pm_score": 1,
"selected": false,
"text": "Function CreateInsertStatement()\n 'Output file location and start of the insert statement\n SQLScript = \"C:\\Inserts.sql\"\n cStart = \"Insert Into Holidays (HOLIDAY_ID, NAT_HOLDAY_DESC, NAT_HOLDAY_DTE) Values (\"\n\n 'Open file for output\n Open SQLScript For Output As #1\n\n Dim LoopThruRows As Boolean\n Dim LoopThruCols As Boolean\n\n\n nCommit = 1 'Commit Count\n nCommitCount = 100 'The number of rows after which a commit is performed\n\n LoopThruRows = True\n nRow = 1 'Current row\n\n While LoopThruRows\n\n nRow = nRow + 1 'Start at second row - presuming there are headers\n nCol = 1 'Reset the columns\n If Cells(nRow, nCol).Value = Empty Then\n Print #1, \"Commit;\"\n LoopThruRows = False\n Else\n If nCommit = nCommitCount Then\n Print #1, \"Commit;\"\n nCommit = 1\n Else\n nCommit = nCommit + 1\n End If\n\n cLine = cStart\n LoopThruCols = True\n\n While LoopThruCols\n If Cells(nRow, nCol).Value = Empty Then\n cLine = cLine & \");\" 'Close the SQL statement\n Print #1, cLine 'Write the line\n LoopThruCols = False 'Exit the cols loop\n Else\n If nCol > 1 Then 'add a preceeding comma for all bar the first column\n cLine = cLine & \", \"\n End If\n If Right(Left(Cells(nRow, nCol).Value, 3), 1) = \"/\" Then 'Format for dates\n cLine = cLine & \"TO_DATE('\" & Cells(nRow, nCol).Value & \"', 'dd/mm/yyyy')\"\n ElseIf IsNumeric(Left(Cells(nRow, nCol).Value, 1)) Then 'Format for numbers\n cLine = cLine & Cells(nRow, nCol).Value\n Else 'Format for text, including apostrophes\n cLine = cLine & \"'\" & Replace(Cells(nRow, nCol).Value, \"'\", \"''\") & \"'\"\n End If\n\n nCol = nCol + 1\n End If\n Wend\n End If\n Wend\n\n Close #1\n\nEnd Function\n"
},
{
"answer_id": 42628109,
"author": "Brad Parks",
"author_id": 26510,
"author_profile": "https://Stackoverflow.com/users/26510",
"pm_score": 2,
"selected": false,
"text": "csvsql --db firebase:///d=mydb --insert mydata.csv csvsql --db sqlite:///dump.db --insert mydata.csv"
},
{
"answer_id": 61274589,
"author": "Judy1989",
"author_id": 1652397,
"author_profile": "https://Stackoverflow.com/users/1652397",
"pm_score": 0,
"selected": false,
"text": "sed \"s/,/','/g\" file.csv > tmp\nsed \"s/$/'),(/g\" tmp > tmp2\nsed \"s/^./'&/g\" tmp2 > insert.sql\n INSERT INTO PERSON (ID, NAME, CITY_ID) VALUES(\n...\n);\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/727/"
] |
8,214 | <p>How are you instrumenting your UI's? In the past I've read that people have instrumented their user interfaces, but what I haven't found is examples or tips on <em>how</em> to instrument a UI.</p>
<p>By instrumenting, I mean collecting data regarding usage and performance of the system. A MSDN article on Instrumentation is <a href="http://msdn.microsoft.com/en-us/library/x5952w0c.aspx" rel="nofollow noreferrer" title="here">http://msdn.microsoft.com/en-us/library/x5952w0c.aspx</a>. I would like to capture which buttons users click on, what keyboard shortucts they use, what terms they use to search, etc.</p>
<ul>
<li>How are you instrumenting your UI?</li>
<li>What format are you storing the instrumentation?</li>
<li>How are you processing the instrumented data?</li>
<li>How are you keeping your UI code clean with this instrumentation logic?</li>
</ul>
<p>Specifically, I am implementing my UI in WPF, so this will provide extra challenges compared to instrumenting a web-based application. (i.e. need to transfer the instrumented data back to a central location, etc). That said, I feel the technology may provide an easier implementation of instrumentation via concepts like attached properties.</p>
<ul>
<li>Have you instrumented a WPF application? Do you have any tips on how this can be achieved?</li>
</ul>
<hr />
<p>Edit: The following blog post presents an interesting solution: <a href="https://blog.pixelingene.com/2008/08/techniques-for-ui-auditing-on-wpf-apps/" rel="nofollow noreferrer">Pixel-In-Gene Blog: Techniques for UI Auditing on WPF apps</a></p>
| [
{
"answer_id": 5645456,
"author": "angularsen",
"author_id": 134761,
"author_profile": "https://Stackoverflow.com/users/134761",
"pm_score": 3,
"selected": false,
"text": "public class UserInteractionEventsManager\n{\n public delegate void ButtonClickedHandler(DateTime time, string eventName, string senderName, string senderTypeName, string parentWindowName);\n public delegate void SelectorSelectedHandler(DateTime time, string eventName, string senderName, string senderTypeName, string parentWindowName, object selectedObject);\n\n public event ButtonClickedHandler ButtonClicked;\n public event SelectorSelectedHandler SelectorSelected;\n\n public UserInteractionEventsManager()\n {\n EventManager.RegisterClassHandler(typeof(ButtonBase), ButtonBase.ClickEvent, new RoutedEventHandler(HandleButtonClicked));\n EventManager.RegisterClassHandler(typeof(Selector), Selector.SelectionChangedEvent, new RoutedEventHandler(HandleSelectorSelected));\n }\n\n #region Handling events\n\n private void HandleSelectorSelected(object sender, RoutedEventArgs e)\n {\n // Avoid multiple events due to bubbling. Example: A ListBox inside a TabControl will cause both to send the SelectionChangedEvent.\n if (sender != e.OriginalSource) return;\n\n var args = e as SelectionChangedEventArgs;\n if (args == null || args.AddedItems.Count == 0) return;\n\n var element = sender as FrameworkElement;\n if (element == null) return;\n\n string senderName = GetSenderName(element);\n string parentWindowName = GetParentWindowTypeName(sender);\n DateTime time = DateTime.Now;\n string eventName = e.RoutedEvent.Name;\n string senderTypeName = sender.GetType().Name;\n string selectedItemText = args.AddedItems.Count > 0 ? args.AddedItems[0].ToString() : \"<no selected items>\";\n\n if (SelectorSelected != null)\n SelectorSelected(time, eventName, senderName, senderTypeName, parentWindowName, selectedItemText);\n }\n\n private void HandleButtonClicked(object sender, RoutedEventArgs e)\n {\n var element = sender as FrameworkElement;\n if (element == null) return;\n\n string parentWindowName = GetParentWindowTypeName(sender);\n DateTime time = DateTime.Now;\n string eventName = e.RoutedEvent.Name;\n string senderTypeName = sender.GetType().Name;\n string senderName = GetSenderName(element);\n\n if (ButtonClicked != null) \n ButtonClicked(time, eventName, senderName, senderTypeName, parentWindowName);\n }\n\n #endregion\n\n #region Private helpers\n\n private static string GetSenderName(FrameworkElement element)\n {\n return !String.IsNullOrEmpty(element.Name) ? element.Name : \"<no item name>\";\n }\n\n\n private static string GetParentWindowTypeName(object sender)\n {\n var parent = FindParent<Window>(sender as DependencyObject);\n return parent != null ? parent.GetType().Name : \"<no parent>\";\n }\n\n private static T FindParent<T>(DependencyObject item) where T : class\n {\n if (item == null) \n return default(T);\n\n if (item is T)\n return item as T;\n\n DependencyObject parent = VisualTreeHelper.GetParent(item);\n if (parent == null)\n return default(T);\n\n return FindParent<T>(parent);\n }\n\n #endregion\n}\n /// <summary>\n/// The user interaction logger uses <see cref=\"UserInteractionEventsManager\"/> to listen for events on GUI elements, such as buttons, list boxes, tab controls etc.\n/// The events are then logged in a readable format using Log.Interaction.Info().\n/// </summary>\npublic class UserInteractionLogger\n{\n private readonly UserInteractionEventsManager _events;\n private bool _started;\n\n /// <summary>\n /// Create a user interaction logger. Remember to Start() it.\n /// </summary>\n public UserInteractionLogger()\n {\n _events = new UserInteractionEventsManager();\n\n }\n\n /// <summary>\n /// Start logging user interaction events.\n /// </summary>\n public void Start()\n {\n if (_started) return;\n\n _events.ButtonClicked += ButtonClicked;\n _events.SelectorSelected += SelectorSelected;\n\n _started = true;\n }\n\n /// <summary>\n /// Stop logging user interaction events.\n /// </summary>\n public void Stop()\n {\n if (!_started) return;\n\n _events.ButtonClicked -= ButtonClicked;\n _events.SelectorSelected -= SelectorSelected;\n\n _started = false;\n }\n\n private static void SelectorSelected(DateTime time, string eventName, string senderName, string senderTypeName, string parentWindowTypeName, object selectedObject)\n {\n Log.Interaction.Info(\"{0}.{1} by {2} in {3}. Selected: {4}\", senderTypeName, eventName, senderName, parentWindowTypeName, selectedObject);\n }\n\n private static void ButtonClicked(DateTime time, string eventName, string senderName, string senderTypeName, string parentWindowTypeName)\n {\n Log.Interaction.Info(\"{0}.{1} by {2} in {3}\", senderTypeName, eventName, senderName, parentWindowTypeName);\n }\n}\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
8,236 | <p>How can I figure out the size of a file, in bytes?</p>
<pre><code>#include <stdio.h>
unsigned int fsize(char* file){
//what goes here?
}
</code></pre>
| [
{
"answer_id": 8241,
"author": "Ecton",
"author_id": 457,
"author_profile": "https://Stackoverflow.com/users/457",
"pm_score": 2,
"selected": false,
"text": "#include <sys/stat.h>\noff_t fsize(char *file) {\n struct stat filestat;\n if (stat(file, &filestat) == 0) {\n return filestat.st_size;\n }\n return 0;\n}\n"
},
{
"answer_id": 8244,
"author": "PabloG",
"author_id": 394,
"author_profile": "https://Stackoverflow.com/users/394",
"pm_score": -1,
"selected": false,
"text": "#define SEEKBOTTOM 2\n\nfseek(handle, 0, SEEKBOTTOM) \n"
},
{
"answer_id": 8247,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 5,
"selected": false,
"text": "unsigned long fsize(char* file)\n{\n FILE * f = fopen(file, \"r\");\n fseek(f, 0, SEEK_END);\n unsigned long len = (unsigned long)ftell(f);\n fclose(f);\n return len;\n}\n GetFileSizeEx stat64"
},
{
"answer_id": 8249,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 4,
"selected": false,
"text": "fseek(file, 0, SEEK_END) fseek() ftell() int fsize(char* file) {\n int size;\n FILE* fh;\n\n fh = fopen(file, \"rb\"); //binary mode\n if(fh != NULL){\n if( fseek(fh, 0, SEEK_END) ){\n fclose(fh);\n return -1;\n }\n\n size = ftell(fh);\n fclose(fh);\n return size;\n }\n\n return -1; //error\n}\n"
},
{
"answer_id": 8273,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 6,
"selected": false,
"text": "int unsigned int off_t"
},
{
"answer_id": 8384,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 8,
"selected": true,
"text": "stat fstat open(2) fileno(FILE*) #include <sys/stat.h>\n#include <sys/types.h>\n\noff_t fsize(const char *filename) {\n struct stat st; \n\n if (stat(filename, &st) == 0)\n return st.st_size;\n\n return -1; \n}\n const char struct stat -1 0 off_t fsize() #include <sys/stat.h>\n#include <sys/types.h>\n#include <string.h>\n#include <stdio.h>\n#include <errno.h>\n\noff_t fsize(const char *filename) {\n struct stat st;\n\n if (stat(filename, &st) == 0)\n return st.st_size;\n\n fprintf(stderr, \"Cannot determine size of %s: %s\\n\",\n filename, strerror(errno));\n\n return -1;\n}\n -D_FILE_OFFSET_BITS=64 off_t"
},
{
"answer_id": 21640919,
"author": "rco16",
"author_id": 2658421,
"author_profile": "https://Stackoverflow.com/users/2658421",
"pm_score": 2,
"selected": false,
"text": "//opens a file with a file descriptor\nFILE * i_file;\ni_file = fopen(source, \"r\");\n\n//gets a long from the file descriptor for fstat\nlong f_d = fileno(i_file);\nstruct stat buffer;\nfstat(f_d, &buffer);\n\n//stores file size\nlong file_length = buffer.st_size;\nfclose(i_file);\n"
},
{
"answer_id": 37661250,
"author": "Abdessamad Doughri",
"author_id": 4400861,
"author_profile": "https://Stackoverflow.com/users/4400861",
"pm_score": -1,
"selected": false,
"text": "long get_file_size(char *path)\n{\n FILE *fp;\n long size = -1;\n /* Open file for reading */\n fp = fopen(path, \"r\");\n fseek(fp, 0, SEEK_END);\n size = ftell(fp); \n fclose(fp);\n return size;\n}\n"
},
{
"answer_id": 41387632,
"author": "adrian",
"author_id": 5487769,
"author_profile": "https://Stackoverflow.com/users/5487769",
"pm_score": -1,
"selected": false,
"text": "fseek(fp, 0, SEEK_END);\nunsigned long int file_size = ftell(fp);\nrewind(fp);\n fp"
},
{
"answer_id": 54114840,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "sys/stat.h stat(3) st_size 4GB Fat32 #include <stdio.h>\n#include <sys/stat.h>\n\nint main(int argc, char** argv)\n{\n struct stat info;\n stat(argv[1], &info);\n\n // 'st' is an acronym of 'stat'\n printf(\"%s: size=%ld\\n\", argv[1], info.st_size);\n}\n #include <stdio.h>\n#include <sys/stat.h>\n\nint main(int argc, char** argv)\n{\n struct stat64 info;\n stat64(argv[1], &info);\n\n // 'st' is an acronym of 'stat'\n printf(\"%s: size=%ld\\n\", argv[1], info.st_size);\n}\n fseek(3) ftell(3) #include <stdio.h>\n\nint main(int argc, char** argv)\n{\n FILE* fp = fopen(argv[1]);\n int f_size;\n\n fseek(fp, 0, SEEK_END);\n f_size = ftell(fp);\n rewind(fp); // to back to start again\n\n printf(\"%s: size=%ld\", (unsigned long)f_size);\n}\n stdin 0 stdin"
},
{
"answer_id": 56998027,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "stdio.h size_t fsize(FILE *File) {\n size_t FSZ;\n fseek(File, 0, 2);\n FSZ = ftell(File);\n rewind(File);\n return FSZ;\n}\n"
},
{
"answer_id": 70643602,
"author": "BigChief",
"author_id": 539251,
"author_profile": "https://Stackoverflow.com/users/539251",
"pm_score": 0,
"selected": false,
"text": "ULONGLONG GetFileSizeAtt(const wchar_t *wFile)\n{\n WIN32_FILE_ATTRIBUTE_DATA fileInfo;\n ULONGLONG FileSize = 0ULL;\n //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/nf-fileapi-getfileattributesexa?redirectedfrom=MSDN\n //https://learn.microsoft.com/nl-nl/windows/win32/api/fileapi/ns-fileapi-win32_file_attribute_data?redirectedfrom=MSDN\n if (GetFileAttributesEx(wFile, GetFileExInfoStandard, &fileInfo))\n {\n ULARGE_INTEGER ul;\n ul.HighPart = fileInfo.nFileSizeHigh;\n ul.LowPart = fileInfo.nFileSizeLow;\n FileSize = ul.QuadPart;\n }\n return FileSize;\n}\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8236",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/432/"
] |
8,284 | <p>I'm looking for an online solution for generating .ICO files. I'd like the ICO files to have the ability to have transparency as well.</p>
<p>What software or web site do you use to create them?</p>
<p>[Update]</p>
<p>To clarify, I have an existing image in PNG format, 32 x 32 pixels. I want to generate the icon from this existing file, not create a brand new one online. Sorry for the confusion.</p>
| [
{
"answer_id": 8301,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 1,
"selected": false,
"text": ".ico"
},
{
"answer_id": 41086,
"author": "Jason Von Ruden",
"author_id": 2062,
"author_profile": "https://Stackoverflow.com/users/2062",
"pm_score": 1,
"selected": false,
"text": "* 100% Free for Visual Studio 2008 users;\n* Make icons for Windows up to 256×256 PNG-compressed icons for Windows Vista™ and include them in your software projects;\n* Use an advanced icon editor with various tools, filters and effects;\n* Work efficiently using a Plug-in for Visual Studio 2008;\n* Create icons from images or ready-to-use image objects;\n* Use a fully integrated workspace with librarian, built-in file explorer with thumbnail preview, image viewer and more…\n"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/519/"
] |
8,318 | <p>I need to prevent <a href="http://www.owasp.org/index.php/Session_Fixation" rel="noreferrer">Session Fixation</a>, a particular type of session hijacking, in a Java web application running in JBoss. However, it appears that the standard idiom <a href="http://www.owasp.org/index.php/Session_Fixation_in_Java" rel="noreferrer">doesn't work in JBoss</a>. Can this be worked around?</p>
| [
{
"answer_id": 8322,
"author": "Warren Blanchet",
"author_id": 1054,
"author_profile": "https://Stackoverflow.com/users/1054",
"pm_score": 4,
"selected": true,
"text": ".../deploy/jboss-web.deployer/server.xml"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1054/"
] |
8,348 | <p>Imagine an object you are working with has a collection of other objects associated with it, for example, the Controls collection on a WinForm. You want to check for a certain object in the collection, but the collection doesn't have a <code>Contains()</code> method. There are several ways of dealing with this.</p>
<ul>
<li>Implement your own <code>Contains()</code> method by looping through all items in the collection to see if one of them is what you are looking for. This seems to be the "best practice" approach.</li>
<li>I recently came across some code where instead of a loop, there was an attempt to access the object inside a try statement, as follows:</li>
</ul>
<blockquote>
<pre><code>try
{
Object aObject = myCollection[myObject];
}
catch(Exception e)
{
//if this is thrown, then the object doesn't exist in the collection
}
</code></pre>
</blockquote>
<p>My question is how poor of a programming practice do you consider the second option be and why? How is the performance of it compared to a loop through the collection?</p>
| [
{
"answer_id": 8410,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "Controls ContainsKey ContainsValue"
}
] | 2008/08/11 | [
"https://Stackoverflow.com/questions/8348",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/940/"
] |
8,351 | <p>I'm trying to fix some JavaScript bugs. Firebug makes debugging these issues a lot easier when working in Firefox, but what do you do when the code works fine on Firefox but IE is complaining?</p>
| [
{
"answer_id": 12003990,
"author": "7dr3am7",
"author_id": 615312,
"author_profile": "https://Stackoverflow.com/users/615312",
"pm_score": 0,
"selected": false,
"text": "<script type=\"text/javascript\" src=\"https://getfirebug.com/firebug-lite.js\"></script>\n"
},
{
"answer_id": 19253342,
"author": "Jon",
"author_id": 842970,
"author_profile": "https://Stackoverflow.com/users/842970",
"pm_score": 1,
"selected": false,
"text": "javascript:(function(F,i,r,e,b,u,g,L,I,T,E){if(F.getElementById(b))return;E=F[i+'NS']&&F.documentElement.namespaceURI;E=E?F[i+'NS'](E,'script'):F[i]('script');E[r]('id',b);E[r]('src',I+g+T);E[r](b,u);(F[e]('head')[0]||F[e]('body')[0]).appendChild(E);E=new%20Image;E[r]('src',I+L);})(document,'createElement','setAttribute','getElementsByTagName','FirebugLite','4','firebug-lite.js','releases/lite/latest/skin/xp/sprite.png','https://getfirebug.com/','#startOpened');\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8351",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/680/"
] |
8,355 | <p>What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?</p>
<p>Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this:</p>
<p>I have set up the server so that the sites can be accessed by</p>
<p><a href="https://secure.example.com/dbadmin" rel="nofollow noreferrer">https://secure.example.com/dbadmin</a></p>
<p>but I would like to have this as <a href="https://dbadmin.example.com" rel="nofollow noreferrer">https://dbadmin.example.com</a></p>
<p>How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?</p>
| [
{
"answer_id": 8389,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<VirtualHost *>\nServerName subdomain.domain.com\nDocumentRoot /home/httpd/htdocs/subdomain/\n</VirtualHost>\n"
},
{
"answer_id": 12069,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 3,
"selected": true,
"text": "<VirtualHost *:443>\n ServerName secure.example.com\n ServerAlias dbadmin.example.com\n\n RewriteEngine on\n RewriteCond %{SERVER_NAME} dbadmin.example.com\n RewriteRule !/dbadmin(.*)$ /dbadmin$1\n</VirtualHost>\n <VirtualHost *>"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/277/"
] |
8,371 | <p>How do you redirect HTTPS to HTTP?. That is, the opposite of what (seemingly) everyone teaches.</p>
<p>I have a server on HTTPS for which I paid an SSL certification for and a mirror for which I haven't and keep around for just for emergencies so it doesn't merit getting a certification for.</p>
<p>On my client's desktops I have SOME shortcuts which point to <code>http://production_server</code> and <code>https://production_server</code> (both work). However, I know that if my production server goes down, then DNS forwarding kicks in and those clients which have "https" on their shortcut will be staring at <code>https://mirror_server</code> (which doesn't work) and a big fat Internet Explorer 7 red screen of uneasyness for my company. </p>
<p>Unfortunately, I can't just switch this around at the client level. These users are very computer illiterate: and are very likely to freak out from seeing HTTPS "insecurity" errors (especially the way Firefox 3 and Internet Explorer 7 handle it nowadays: FULL STOP, kind of thankfully, but not helping me here LOL).</p>
<p>It's <a href="http://www.cyberciti.biz/tips/howto-apache-force-https-secure-connections.html" rel="noreferrer">very easy</a> <a href="http://bytes.com/forum/thread54801.html" rel="noreferrer">to find</a> <a href="http://support.jodohost.com/showthread.php?t=6678" rel="noreferrer">Apache solutions</a> for <a href="http://www.google.com/search?q=https+redirection&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a" rel="noreferrer">http->https redirection</a>, but for the life of me I can't do the opposite.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8380,
"author": "ejunker",
"author_id": 796,
"author_profile": "https://Stackoverflow.com/users/796",
"pm_score": 8,
"selected": true,
"text": "RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n"
},
{
"answer_id": 12243355,
"author": "RobinUS2",
"author_id": 1194580,
"author_profile": "https://Stackoverflow.com/users/1194580",
"pm_score": -1,
"selected": false,
"text": "<meta http-equiv=\"refresh\" content=\"0;URL='http://www.yourdomain.com/path'\">\n"
},
{
"answer_id": 14496933,
"author": "antoniom",
"author_id": 1149919,
"author_profile": "https://Stackoverflow.com/users/1149919",
"pm_score": 4,
"selected": false,
"text": "Options +FollowSymLinks\nRewriteEngine On\nRewriteCond %{ENV:HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n"
},
{
"answer_id": 14992526,
"author": "rg88",
"author_id": 11252,
"author_profile": "https://Stackoverflow.com/users/11252",
"pm_score": 3,
"selected": false,
"text": "RewriteCond %{HTTPS} =on\nRewriteRule ^(.*)$ http://%{HTTP_HOST}/$1 [L,R=301]\n"
},
{
"answer_id": 34027859,
"author": "Rick",
"author_id": 1827424,
"author_profile": "https://Stackoverflow.com/users/1827424",
"pm_score": 4,
"selected": false,
"text": ".conf <VirtualHost *:443>\n ServerName domain.com\n RewriteEngine On\n RewriteCond %{HTTPS} on\n RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI}\n\n SSLEngine on\n SSLCertificateFile /etc/apache2/ssl/domain.crt\n SSLCertificateKeyFile /etc/apache2/ssl/domain.key\n SSLCACertificateFile /etc/apache2/ssl/domain.crt\n\n</VirtualHost>\n"
},
{
"answer_id": 39074632,
"author": "sys0dm1n",
"author_id": 3768721,
"author_profile": "https://Stackoverflow.com/users/3768721",
"pm_score": 2,
"selected": false,
"text": " <If \"%{HTTPS} == 'on'\" >\n Redirect permanent / http://production_server/\n </If>\n <If>"
},
{
"answer_id": 42678635,
"author": "mikulabc",
"author_id": 1679901,
"author_profile": "https://Stackoverflow.com/users/1679901",
"pm_score": 3,
"selected": false,
"text": "RewriteCond %{HTTP:X-Forwarded-Proto} =https\nRewriteRule ^(.*)$ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n RewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n"
},
{
"answer_id": 47252973,
"author": "Yuseferi",
"author_id": 1381737,
"author_profile": "https://Stackoverflow.com/users/1381737",
"pm_score": 1,
"selected": false,
"text": "RewriteEngine On\nRewriteCond %{HTTPS} on\nRewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]\n"
},
{
"answer_id": 54031418,
"author": "jaxarroyo",
"author_id": 5258247,
"author_profile": "https://Stackoverflow.com/users/5258247",
"pm_score": 2,
"selected": false,
"text": "<VirtualHost *:443>\n ServerName www.example.com\n # ... SSL configuration goes here\n Redirect \"https://www.example.com/\" \"http://www.example.com/\"\n</VirtualHost>\n\n<VirtualHost *:80>\n ServerName www.example.com\n # ... \n</VirtualHost>\n"
},
{
"answer_id": 66254728,
"author": "Khan Sharukh",
"author_id": 8621204,
"author_profile": "https://Stackoverflow.com/users/8621204",
"pm_score": 0,
"selected": false,
"text": "RewriteEngine On\nRewriteCond %{HTTPS} off\nRewriteCond %{THE_REQUEST} !/(home/panel/videos|user/profile) [NC] # Multiple urls\nRewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n\nRewriteCond %{HTTPS} on\nRewriteCond %{THE_REQUEST} /(home/panel/videos|user/profile) [NC] # Multiple urls\nRewriteRule ^ http://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8371",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/547/"
] |
8,398 | <p>I just saw this mentioned in Stack Overflow question <em><a href="http://web.archive.org/web/20090503103538/http://stackoverflow.com:80/questions/7975/best-css-editor" rel="nofollow noreferrer">Best WYSIWYG CSS editor</a></em> and didn't know it could be done. I'm a Visual Studio newbie, so how do you do it?</p>
<p>Is there a separate debugger for JavaScript? I know how to work the one for code-behind pages... I usually use Firebug to deal with debugging JavaScript code.</p>
<p>I'm using <a href="http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005" rel="nofollow noreferrer">Visual Studio 2005</a>.</p>
| [
{
"answer_id": 684749,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "debugger\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8398",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/396/"
] |
8,435 | <p>I'd like to get the Tree icon to use for a homegrown app. Does anyone know how to extract the images out as .icon files? I'd like both the 16x16 and 32x32, or I'd just do a screen capture.</p>
| [
{
"answer_id": 24905798,
"author": "Smylers",
"author_id": 1366011,
"author_profile": "https://Stackoverflow.com/users/1366011",
"pm_score": 1,
"selected": false,
"text": "gextractwinicons"
},
{
"answer_id": 28091056,
"author": "Shaun",
"author_id": 2898010,
"author_profile": "https://Stackoverflow.com/users/2898010",
"pm_score": 4,
"selected": false,
"text": "#Windows PowerShell Code###########################################################################\n# http://gallery.technet.microsoft.com/scriptcenter/Icon-Exporter-e372fe70\n#\n# AUTHOR: John Grenfell\n#\n###########################################################################\n\n<#\n.SYNOPSIS\n Exports an ico and bmp file from a given source to a given destination\n.Description\n You need to set the Source and Destination locations. First version of a script, I found other examples but all I wanted to do as grab and ico file from an exe but found getting a bmp useful. Others might find useful\n No error checking I'm afraid so make sure your source and destination locations exist!\n.EXAMPLE\n .\\Icon_Exporter.ps1\n.Notes\n Version HISTORY:\n 1.1 2012.03.8\n#>\nParam ( [parameter(Mandatory = $true)][string] $SourceEXEFilePath,\n [parameter(Mandatory = $true)][string] $TargetIconFilePath\n)\nCLS\n#\"shell32.dll\" 238\nIf ($SourceEXEFilePath.ToLower().Contains(\".dll\")) {\n $IconIndexNo = Read-Host \"Enter the icon index: \"\n $Icon = [System.IconExtractor]::Extract($SourceEXEFilePath, $IconIndexNo, $true) \n} Else {\n [void][Reflection.Assembly]::LoadWithPartialName(\"System.Drawing\")\n [void] [System.Reflection.Assembly]::LoadWithPartialName(\"System.Windows.Forms\")\n $image = [System.Drawing.Icon]::ExtractAssociatedIcon(\"$($SourceEXEFilePath)\").ToBitmap()\n $bitmap = new-object System.Drawing.Bitmap $image\n $bitmap.SetResolution(72,72)\n $icon = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon())\n}\n$stream = [System.IO.File]::OpenWrite(\"$($TargetIconFilePath)\")\n$icon.save($stream)\n$stream.close()\nWrite-Host \"Icon file can be found at $TargetIconFilePath\"\n"
},
{
"answer_id": 33835048,
"author": "Mr. Annoyed",
"author_id": 4995131,
"author_profile": "https://Stackoverflow.com/users/4995131",
"pm_score": 2,
"selected": false,
"text": " <#\n.SYNOPSIS\n Exports an ico and bmp file from a given source to a given destination\n.Description\n You need to set the Source and Destination locations. First version of a script, I found other examples \n but all I wanted to do as grab and ico file from an exe but found getting a bmp useful. Others might find useful\n.EXAMPLE\n This will run but will nag you for input\n .\\Icon_Exporter.ps1\n.EXAMPLE\n this will default to shell32.dll automatically for -SourceEXEFilePath\n .\\Icon_Exporter.ps1 -TargetIconFilePath 'C:\\temp\\Myicon.ico' -IconIndexNo 238\n.EXAMPLE\n This will give you a green tree icon (press F5 for windows to refresh Windows explorer)\n .\\Icon_Exporter.ps1 -SourceEXEFilePath 'C:/Windows/system32/shell32.dll' -TargetIconFilePath 'C:\\temp\\Myicon.ico' -IconIndexNo 41\n\n.Notes\n Based on http://stackoverflow.com/questions/8435/how-do-you-get-the-icons-out-of-shell32-dll Version 1.1 2012.03.8\n New version: Version 1.2 2015.11.20 (Added missing custom assembly and some error checking for novices)\n#>\nParam ( \n [parameter(Mandatory = $true)]\n [string] $SourceEXEFilePath = 'C:/Windows/system32/shell32.dll',\n [parameter(Mandatory = $true)]\n [string] $TargetIconFilePath,\n [parameter(Mandatory = $False)]\n [Int32]$IconIndexNo = 0\n)\n\n#https://social.technet.microsoft.com/Forums/windowsserver/en-US/16444c7a-ad61-44a7-8c6f-b8d619381a27/using-icons-in-powershell-scripts?forum=winserverpowershell\n$code = @\"\nusing System;\nusing System.Drawing;\nusing System.Runtime.InteropServices;\n\nnamespace System\n{\n public class IconExtractor\n {\n\n public static Icon Extract(string file, int number, bool largeIcon)\n {\n IntPtr large;\n IntPtr small;\n ExtractIconEx(file, number, out large, out small, 1);\n try\n {\n return Icon.FromHandle(largeIcon ? large : small);\n }\n catch\n {\n return null;\n }\n\n }\n [DllImport(\"Shell32.dll\", EntryPoint = \"ExtractIconExW\", CharSet = CharSet.Unicode, ExactSpelling = true, CallingConvention = CallingConvention.StdCall)]\n private static extern int ExtractIconEx(string sFile, int iIndex, out IntPtr piLargeVersion, out IntPtr piSmallVersion, int amountIcons);\n\n }\n}\n\"@\n\nIf (-not (Test-path -Path $SourceEXEFilePath -ErrorAction SilentlyContinue ) ) {\n Throw \"Source file [$SourceEXEFilePath] does not exist!\"\n}\n\n[String]$TargetIconFilefolder = [System.IO.Path]::GetDirectoryName($TargetIconFilePath) \nIf (-not (Test-path -Path $TargetIconFilefolder -ErrorAction SilentlyContinue ) ) {\n Throw \"Target folder [$TargetIconFilefolder] does not exist!\"\n}\n\nTry {\n If ($SourceEXEFilePath.ToLower().Contains(\".dll\")) {\n Add-Type -TypeDefinition $code -ReferencedAssemblies System.Drawing\n $form = New-Object System.Windows.Forms.Form\n $Icon = [System.IconExtractor]::Extract($SourceEXEFilePath, $IconIndexNo, $true) \n } Else {\n [void][Reflection.Assembly]::LoadWithPartialName(\"System.Drawing\")\n [void] [System.Reflection.Assembly]::LoadWithPartialName(\"System.Windows.Forms\")\n $image = [System.Drawing.Icon]::ExtractAssociatedIcon(\"$($SourceEXEFilePath)\").ToBitmap()\n $bitmap = new-object System.Drawing.Bitmap $image\n $bitmap.SetResolution(72,72)\n $icon = [System.Drawing.Icon]::FromHandle($bitmap.GetHicon())\n }\n} Catch {\n Throw \"Error extracting ICO file\"\n}\n\nTry {\n $stream = [System.IO.File]::OpenWrite(\"$($TargetIconFilePath)\")\n $icon.save($stream)\n $stream.close()\n} Catch {\n Throw \"Error saving ICO file [$TargetIconFilePath]\"\n}\nWrite-Host \"Icon file can be found at [$TargetIconFilePath]\"\n"
},
{
"answer_id": 67446002,
"author": "i Mr Oli i",
"author_id": 11199164,
"author_profile": "https://Stackoverflow.com/users/11199164",
"pm_score": 2,
"selected": false,
"text": "%SystemRoot%\\system32\\SHELL32.dll\\.rsrc\\ICON"
},
{
"answer_id": 71200876,
"author": "TheManInOz",
"author_id": 11959950,
"author_profile": "https://Stackoverflow.com/users/11959950",
"pm_score": 4,
"selected": false,
"text": "[shell32.dll]\n.rsrc\\MANIFEST\\124\n.rsrc\\MUI\\1\n.rsrc\\TYPELIB\\1\n.rsrc\\version.txt\n.data\n.didat\n.pdata\n.rdata\n.reloc\n.text\nCERTIFICATE\n \"C:\\Windows\\SystemResources\\shell32.dll.mun\"\n\"C:\\Windows\\SystemResources\\imageres.dll.mun\"\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8435",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/733/"
] |
8,441 | <p>I'm using <code>.htaccess</code> and <code>mod_rewrite</code> to point to files that reside behind the DocumentRoot. My folder structure looks like this:</p>
<pre><code>home/
webroot/
other_files/
</code></pre>
<p>I have a <code>.htaccess</code> file in webroot with the following content:</p>
<pre>
RewriteEngine on
RewriteRule ^(.*)$ /home/other_files/$1
</pre>
<p>If I try to access <a href="http://example.com/file.html" rel="noreferrer">http://example.com/file.html</a> I receive the following error: </p>
<blockquote>
<p>The requested URL /home/other_files/file.html was not found on this server. </p>
</blockquote>
<p>Is it even possible to load files that are behind the DocumentRoot? If so, can someone point me in the right direction?</p>
| [
{
"answer_id": 8454,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 5,
"selected": true,
"text": "<Directory \"/home/other_files\">\n (options)\n</Directory>\n Alias /doc/ \"/usr/share/doc/\"\n<Directory \"/usr/share/doc/\">\n Options Indexes MultiViews FollowSymLinks\n AllowOverride None\n Order deny,allow\n Deny from all\n Allow from 127.0.0.0/255.0.0.0 ::1/128\n</Directory>\n"
},
{
"answer_id": 9242,
"author": "akdom",
"author_id": 145,
"author_profile": "https://Stackoverflow.com/users/145",
"pm_score": 1,
"selected": false,
"text": "/home/other_files/file.html /home/webroot/home/other_files/file.html /home/webroot"
},
{
"answer_id": 32534645,
"author": "Joe C",
"author_id": 883354,
"author_profile": "https://Stackoverflow.com/users/883354",
"pm_score": 1,
"selected": false,
"text": "DocumentRoot cakephp cakephp http://www.example.com /var/www/cakephp http://www.example.com/mantisbt /var/www/html/mantisbt /etc/httpd/conf/httpd.conf Alias /mantisbt/ \"/var/www/html/mantisbt/\" \n<Directory \"/var/www/html/\"> \n AllowOverride All \n</Directory> \n \n<VirtualHost *:80> \n ServerAdmin me@my_email.com \n DocumentRoot /var/www/cakephp \n ServerName my_website.com \n <Directory /var/www/cakephp/> \n AllowOverride All \n </Directory> \n</VirtualHost>\n /var/www/cakephp/.htaccess <IfModule mod_rewrite.c>\n RewriteEngine on\n RewriteRule ^mantisbt/?$ /mantisbt/ [NC,L]\n RewriteRule ^$ webroot/ [L]\n RewriteRule (.*) webroot/$1 [L]\n</IfModule>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8441",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/57/"
] |
8,447 | <p>From time to time I see an enum like the following:</p>
<pre><code>[Flags]
public enum Options
{
None = 0,
Option1 = 1,
Option2 = 2,
Option3 = 4,
Option4 = 8
}
</code></pre>
<p>I don't understand what exactly the <code>[Flags]</code> attribute does.</p>
<p>Anyone have a good explanation or example they could post?</p>
| [
{
"answer_id": 8455,
"author": "Jay Mooney",
"author_id": 733,
"author_profile": "https://Stackoverflow.com/users/733",
"pm_score": 4,
"selected": false,
"text": "[Flags]\npublic enum DashboardItemPresentationProperties : long\n{\n None = 0,\n HideCollapse = 1,\n HideDelete = 2,\n HideEdit = 4,\n HideOpenInNewWindow = 8,\n HideResetSource = 16,\n HideMenu = 32\n}\n"
},
{
"answer_id": 8460,
"author": "OJ.",
"author_id": 611,
"author_profile": "https://Stackoverflow.com/users/611",
"pm_score": 6,
"selected": false,
"text": "namespace Flags\n{\n class Program\n {\n [Flags]\n public enum MyFlags : short\n {\n Foo = 0x1,\n Bar = 0x2,\n Baz = 0x4\n }\n\n static void Main(string[] args)\n {\n MyFlags fooBar = MyFlags.Foo | MyFlags.Bar;\n\n if ((fooBar & MyFlags.Foo) == MyFlags.Foo)\n {\n Console.WriteLine(\"Item has Foo flag set\");\n }\n }\n }\n}\n"
},
{
"answer_id": 8462,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 10,
"selected": false,
"text": "[Flags]\npublic enum MyEnum\n{\n None = 0,\n First = 1 << 0,\n Second = 1 << 1,\n Third = 1 << 2,\n Fourth = 1 << 3\n}\n"
},
{
"answer_id": 8480,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 12,
"selected": true,
"text": "[Flags] var allowedColors = MyColor.Red | MyColor.Green | MyColor.Blue;\n [Flags] .ToString() enum Suits { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n[Flags] enum SuitsFlags { Spades = 1, Clubs = 2, Diamonds = 4, Hearts = 8 }\n\n...\n\nvar str1 = (Suits.Spades | Suits.Diamonds).ToString();\n // \"5\"\nvar str2 = (SuitsFlags.Spades | SuitsFlags.Diamonds).ToString();\n // \"Spades, Diamonds\"\n [Flags] [Flags]\npublic enum MyColors\n{\n Yellow, // 0\n Green, // 1\n Red, // 2\n Blue // 3\n}\n [Flags]\npublic enum MyColors\n{\n Yellow = 1,\n Green = 2,\n Red = 4,\n Blue = 8\n}\n if (myProperties.AllowedColors.HasFlag(MyColor.Yellow))\n{\n // Yellow is allowed...\n}\n if((myProperties.AllowedColors & MyColor.Yellow) == MyColor.Yellow)\n{\n // Yellow is allowed...\n}\n\nif((myProperties.AllowedColors & MyColor.Green) == MyColor.Green)\n{\n // Green is allowed...\n} \n Yellow: 00000001\n Green: 00000010\n Red: 00000100\n Blue: 00001000\n | myProperties.AllowedColors: 00001110\n & myProperties.AllowedColors: 00001110\n MyColor.Green: 00000010\n -----------------------\n 00000010 // Hey, this is the same as MyColor.Green!\n 0 [Flags]\npublic enum MyColors\n{\n None = 0,\n ....\n}\n"
},
{
"answer_id": 8526,
"author": "David Wengier",
"author_id": 489,
"author_profile": "https://Stackoverflow.com/users/489",
"pm_score": 4,
"selected": false,
"text": "Mode.Write Mode = Mode | Mode.Write;\n"
},
{
"answer_id": 8975,
"author": "steve_c",
"author_id": 769,
"author_profile": "https://Stackoverflow.com/users/769",
"pm_score": 5,
"selected": false,
"text": "Mode = Mode.Read;\n//Add Mode.Write\nMode |= Mode.Write;\nAssert.True(((Mode & Mode.Write) == Mode.Write)\n && ((Mode & Mode.Read) == Mode.Read)));\n"
},
{
"answer_id": 9117,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "[Flags]\npublic enum PossibleOptions : byte\n{\n None = 0,\n OptionOne = 1,\n OptionTwo = 2,\n OptionThree = 4,\n OptionFour = 8,\n\n //combinations can be in the enum too\n OptionOneAndTwo = OptionOne | OptionTwo,\n OptionOneTwoAndThree = OptionOne | OptionTwo | OptionThree,\n ...\n}\n PossibleOptions opt = PossibleOptions.OptionOneTwoAndThree \n\nif( opt.IsSet( PossibleOptions.OptionOne ) ) {\n //optionOne is one of those set\n}\n"
},
{
"answer_id": 16328309,
"author": "ruffin",
"author_id": 1028230,
"author_profile": "https://Stackoverflow.com/users/1028230",
"pm_score": 4,
"selected": false,
"text": "if ((x & y) == y)... x y enum [Flags] != 0 > 0 using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace BitFlagPlay\n{\n class Program\n {\n [Flags]\n public enum MyColor\n {\n Yellow = 0x01,\n Green = 0x02,\n Red = 0x04,\n Blue = 0x08\n }\n\n static void Main(string[] args)\n {\n var myColor = MyColor.Yellow | MyColor.Blue;\n var acceptableColors = MyColor.Yellow | MyColor.Red;\n\n Console.WriteLine((myColor & MyColor.Blue) != 0); // True\n Console.WriteLine((myColor & MyColor.Red) != 0); // False \n Console.WriteLine((myColor & acceptableColors) != 0); // True\n // ... though only Yellow is shared.\n\n Console.WriteLine((myColor & MyColor.Green) != 0); // Wait a minute... ;^D\n\n Console.Read();\n }\n }\n}\n"
},
{
"answer_id": 16591032,
"author": "drzaus",
"author_id": 1037948,
"author_profile": "https://Stackoverflow.com/users/1037948",
"pm_score": 7,
"selected": false,
"text": "[Flags]\npublic enum Options : byte\n{\n None = 0,\n One = 1 << 0, // 1\n Two = 1 << 1, // 2\n Three = 1 << 2, // 4\n Four = 1 << 3, // 8\n\n // combinations\n OneAndTwo = One | Two,\n OneTwoAndThree = One | Two | Three,\n}\n [Flags]\npublic enum Options : byte\n{\n None = 0,\n One = 1 << 0, // 1\n // now that value 1 is available, start shifting from there\n Two = One << 1, // 2\n Three = Two << 1, // 4\n Four = Three << 1, // 8\n\n // same combinations\n OneAndTwo = One | Two,\n OneTwoAndThree = One | Two | Three,\n}\n foreach(var e in Enum.GetValues(typeof(Options))) {\n string.Format(\"{0} = {1}\", e.ToString(), (byte)e).Dump();\n}\n None = 0\nOne = 1\nTwo = 2\nOneAndTwo = 3\nThree = 4\nOneTwoAndThree = 7\nFour = 8\n"
},
{
"answer_id": 45212972,
"author": "Thorkil Holm-Jacobsen",
"author_id": 1206487,
"author_profile": "https://Stackoverflow.com/users/1206487",
"pm_score": 6,
"selected": false,
"text": "[Flags]\npublic enum MyColors\n{\n None = 0b0000,\n Yellow = 0b0001,\n Green = 0b0010,\n Red = 0b0100,\n Blue = 0b1000\n}\n"
},
{
"answer_id": 52944774,
"author": "Jpsy",
"author_id": 430742,
"author_profile": "https://Stackoverflow.com/users/430742",
"pm_score": 5,
"selected": false,
"text": "[Flags] \nenum SuitsFlags { \n\n None = 0,\n\n Spades = 1 << 0, \n Clubs = 1 << 1, \n Diamonds = 1 << 2, \n Hearts = 1 << 3,\n\n All = ~(~0 << 4)\n\n}\n Spades | Clubs | Diamonds | Hearts == All // true\nSpades & Clubs == None // true\n [Flags] \nenum SuitsFlags { \n\n None = 0b0000,\n\n Spades = 0b0001, \n Clubs = 0b0010, \n Diamonds = 0b0100, \n Hearts = 0b1000,\n\n All = 0b1111\n\n}\n"
},
{
"answer_id": 59940035,
"author": "kbvishnu",
"author_id": 438624,
"author_profile": "https://Stackoverflow.com/users/438624",
"pm_score": 1,
"selected": false,
"text": "[System.Flags]\n[System.Runtime.InteropServices.ComVisible(true)]\n[System.Serializable]\npublic enum BindingFlags\n // BindingFlags.InvokeMethod\n// Call a static method.\nType t = typeof (TestClass);\n\nConsole.WriteLine();\nConsole.WriteLine(\"Invoking a static method.\");\nConsole.WriteLine(\"-------------------------\");\nt.InvokeMember (\"SayHello\", BindingFlags.InvokeMethod | BindingFlags.Public | \n BindingFlags.Static, null, null, new object [] {});\n"
},
{
"answer_id": 64782547,
"author": "Mukesh Pareek",
"author_id": 4360948,
"author_profile": "https://Stackoverflow.com/users/4360948",
"pm_score": -1,
"selected": false,
"text": " [Flags]\n public enum Sides { Left=0, Right=1, Top=2, Bottom=3 }\n\n Sides leftRight = Sides.Left | Sides.Right;\n Console.WriteLine (leftRight);//Left, Right\n\n string stringValue = leftRight.ToString();\n Console.WriteLine (stringValue);//Left, Right\n\n Sides s = Sides.Left;\n s |= Sides.Right;\n Console.WriteLine (s);//Left, Right\n\n s ^= Sides.Right; // Toggles Sides.Right\n Console.WriteLine (s); //Left\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8447",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] |
8,448 | <p>Anyone have a decent example, preferably practical/useful, they could post demonstrating the concept?</p>
| [
{
"answer_id": 8457,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 2,
"selected": false,
"text": "let concatStrings left right = left + right\nlet makeCommandPrompt= appendString \"c:\\> \"\n let readDWORD array i = array[i] | array[i + 1] << 8 | array[i + 2] << 16 | \n array[i + 3] << 24 //I've actually used this function in Python.\n"
},
{
"answer_id": 8468,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 5,
"selected": true,
"text": "type 'a tree = E of 'a | N of 'a * 'a tree * 'a tree\nlet rec tree_map f tree = match tree with\n | N(x,left,right) -> N(f x, tree_map f left, tree_map f right)\n | E(x) -> E(f x)\n\nlet sample_tree = N(1,E(3),E(4)\nlet multiply x y = x * y\nlet sample_tree2 = tree_map (multiply 3) sample_tree\n let sample_tree2 = tree_map (fun x -> x * 3) sample_tree\n let rec f_recurrence f a seed n =\n match n with\n | a -> seed\n | _ -> let prev = f_recurrence f a seed (n-1) in\n prev + (f n prev)\n\nlet rowland = f_recurrence gcd 1 7\nlet cloitre = f_recurrence lcm 1 1\n\nlet rowland_prime n = (rowland (n+1)) - (rowland n)\nlet cloitre_prime n = ((cloitre (n+1))/(cloitre n)) - 1\n"
},
{
"answer_id": 9012,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 4,
"selected": false,
"text": "open System.IO\n\nlet appendFile (fileName : string) (text : string) =\n let file = new StreamWriter(fileName, true)\n file.WriteLine(text)\n file.Close()\n\n// Call it normally \nappendFile @\"D:\\Log.txt\" \"Processing Event X...\"\n\n// If you curry the function, you don't need to keep specifying the\n// log file name.\nlet curriedAppendFile = appendFile @\"D:\\Log.txt\"\n\n// Adds data to \"Log.txt\"\ncurriedAppendFile \"Processing Event Y...\"\n // Non curried, Prints 1 2 3 \nList.iter (fun i -> printf \"%d \" i) [1 .. 3];;\n\n// Curried, Prints 1 2 3\nList.iter (printfn \"%d \") [1 .. 3];;\n"
},
{
"answer_id": 2800182,
"author": "J D",
"author_id": 13924,
"author_profile": "https://Stackoverflow.com/users/13924",
"pm_score": 2,
"selected": false,
"text": "> List.map ((+) 1) [1; 2; 3];;\nval it : int list = [2; 3; 4]\n (+) > List.map (List.map ((+) 1)) [[1; 2]; [3]];;\nval it : int list = [[2; 3]; [4]]\n > List.map((fun xs -> List.map((fun n -> n + 1), xs)), [[1; 2]; [3]]);;\nval it : int list = [[2; 3]; [4]]\n"
},
{
"answer_id": 14785251,
"author": "phoog",
"author_id": 385844,
"author_profile": "https://Stackoverflow.com/users/385844",
"pm_score": 3,
"selected": false,
"text": "Func<T1, Func<T2, Func<T3, T4>>> Curry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)\n{\n return a => b => c => f(a, b, c);\n}\n\nvoid UseACurriedFunction()\n{\n var curryCompare = Curry<string, string, bool, int>(String.Compare);\n var a = \"SomeString\";\n var b = \"SOMESTRING\";\n Console.WriteLine(String.Compare(a, b, true));\n Console.WriteLine(curryCompare(a)(b)(true));\n\n //partial application\n var compareAWithB = curryCompare(a)(b);\n Console.WriteLine(compareAWithB(true));\n Console.WriteLine(compareAWithB(false));\n}\n Func<T3, Func<T2, Func<T1, T4>>> BackwardsCurry<T1, T2, T3, T4>(Func<T1, T2, T3, T4> f)\n{\n return a => b => c => f(c, b, a);\n}\n void UseADifferentlyCurriedFunction()\n{\n var curryCompare = BackwardsCurry<string, string, bool, int>(String.Compare);\n\n var caseSensitiveCompare = curryCompare(false);\n var caseInsensitiveCompare = curryCompare(true);\n\n var format = Curry<string, string, string, string>(String.Format)(\"Results of comparing {0} with {1}:\");\n\n var strings = new[] {\"Hello\", \"HELLO\", \"Greetings\", \"GREETINGS\"};\n\n foreach (var s in strings)\n {\n var caseSensitiveCompareWithS = caseSensitiveCompare(s);\n var caseInsensitiveCompareWithS = caseInsensitiveCompare(s);\n var formatWithS = format(s);\n\n foreach (var t in strings)\n {\n Console.WriteLine(formatWithS(t));\n Console.WriteLine(caseSensitiveCompareWithS(t));\n Console.WriteLine(caseInsensitiveCompareWithS(t));\n }\n }\n}\n let curry f a b c = f(a, b, c)\n\n//overload resolution failure: there are two overloads with three arguments.\n//let curryCompare = curry String.Compare\n\n//This one might be more useful; it works because there's only one 3-argument overload\nlet backCurry f a b c = f(c, b, a)\nlet intParse = backCurry Int32.Parse\nlet intParseCurrentCultureAnyStyle = intParse CultureInfo.CurrentCulture NumberStyles.Any\nlet myInt = intParseCurrentCultureAnyStyle \"23\"\nlet myOtherInt = intParseCurrentCultureAnyStyle \"42\"\n let curryCompare s1 s2 (b:bool) = String.Compare(s1, s2, b)\nlet backwardsCurryCompare (b:bool) s1 s2 = String.Compare(s1, s2, b)\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8448",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] |
8,451 | <p>I want to create an allocator which provides memory with the following attributes:</p>
<ul>
<li>cannot be paged to disk. </li>
<li>is incredibly hard to access through an attached debugger</li>
</ul>
<p>The idea is that this will contain sensitive information (like licence information) which should be inaccessible to the user. I have done the usual research online and asked a few other people about this, but I cannot find a good place start on this problem.</p>
<p><strong>Updates</strong></p>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#27194">Josh</a> mentions using <code>VirtualAlloc</code> to set protection on the memory space. I have created a custom allocator ( shown below ) I have found the using the <code>VirtualLock</code> function it limits the amount of memory I can allocate. This seems to be by design though. Since I am using it for small objects this is not a problem.</p>
<pre><code>//
template<class _Ty>
class LockedVirtualMemAllocator : public std::allocator<_Ty>
{
public:
template<class _Other>
LockedVirtualMemAllocator<_Ty>& operator=(const LockedVirtualMemAllocator<_Other>&)
{ // assign from a related LockedVirtualMemAllocator (do nothing)
return (*this);
}
template<class Other>
struct rebind {
typedef LockedVirtualMemAllocator<Other> other;
};
pointer allocate( size_type _n )
{
SIZE_T allocLen = (_n * sizeof(_Ty));
DWORD allocType = MEM_COMMIT;
DWORD allocProtect = PAGE_READWRITE;
LPVOID pMem = ::VirtualAlloc( NULL, allocLen, allocType, allocProtect );
if ( pMem != NULL ) {
::VirtualLock( pMem, allocLen );
}
return reinterpret_cast<pointer>( pMem );
}
pointer allocate( size_type _n, const void* )
{
return allocate( _n );
}
void deallocate(void* _pPtr, size_type _n )
{
if ( _pPtr != NULL ) {
SIZE_T allocLen = (_n * sizeof(_Ty));
::SecureZeroMemory( _pPtr, allocLen );
::VirtualUnlock( _pPtr, allocLen );
::VirtualFree( _pPtr, 0, MEM_RELEASE );
}
}
};
</code></pre>
<p>and is used</p>
<pre><code> //a memory safe std::string
typedef std::basic_string<char, std::char_traits<char>,
LockedVirtualMemAllocato<char> > modulestring_t;
</code></pre>
<p><a href="https://stackoverflow.com/questions/8451/secure-memory-allocator-in-c#38708">Ted Percival</a> mentions mlock, but I have no implementation of that yet.</p>
<p>I found <a href="http://www.schneier.com/book-practical.html" rel="noreferrer">Practical Cryptography by Neil Furguson and Bruce Schneier</a> quite helpful as well.</p>
| [
{
"answer_id": 8482,
"author": "graham.reeds",
"author_id": 342,
"author_profile": "https://Stackoverflow.com/users/342",
"pm_score": 3,
"selected": false,
"text": "* cannot be paged to disk.\n * is incredibly hard to access through an attached debugger\n"
},
{
"answer_id": 27194,
"author": "Josh",
"author_id": 257,
"author_profile": "https://Stackoverflow.com/users/257",
"pm_score": 3,
"selected": false,
"text": "VirtualAlloc PAGE_GUARD PAGE_NOACCESS"
},
{
"answer_id": 38708,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 3,
"selected": false,
"text": "ulimit -l"
},
{
"answer_id": 33568256,
"author": "Bent Cardan",
"author_id": 917118,
"author_profile": "https://Stackoverflow.com/users/917118",
"pm_score": 3,
"selected": false,
"text": "<sodium.h> void *sodium_malloc(size_t size);\n sodium_malloc() sodium_allocarray() sodium_init() void *sodium_allocarray(size_t count, size_t size);\n sodium_allocarray() sodium_malloc() count * size SIZE_MAX sodium_mprotect_noaccess() sodium_mprotect_readonly() sodium_mprotect_readwrite() sodium_malloc sodium_free() void sodium_memzero(void * const pnt, const size_t len);\n int sodium_mlock(void * const addr, const size_t len);\n sodium_mlock() int sodium_mprotect_noaccess(void *ptr);\n int sodium_mprotect_readonly(void *ptr);\n int sodium_mprotect_readwrite(void *ptr);\n sodium_mprotect_readwrite() sodium_malloc() sodium_allocarray() sodium_mprotect_readonly() sodium_mprotect_noaccess()"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8451",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/716/"
] |
8,452 | <p>I've done some WPF programing and one thing I never got was the command pattern. Every example seems to be for built in ones, edit, cut, paste. Anyone have an example or suggestion of best practice for custom commands?</p>
| [
{
"answer_id": 8471,
"author": "Nidonocu",
"author_id": 483,
"author_profile": "https://Stackoverflow.com/users/483",
"pm_score": 6,
"selected": true,
"text": "public static class CommandBank\n{\n /// Command definition for Closing a window\n public static RoutedUICommand CloseWindow { get; private set; }\n\n /// Static private constructor, sets up all application wide commands.\n static CommandBank()\n {\n CloseWindow = new RoutedUICommand();\n CloseWindow.InputGestures.Add(new KeyGesture(Key.F4, ModifierKeys.Alt));\n // ...\n }\n /// Closes the window provided as a parameter\npublic static void CloseWindowExecute(object sender, ExecutedRoutedEventArgs e)\n{\n ((Window)e.Parameter).Close();\n}\n\n/// Allows a Command to execute if the CommandParameter is not a null value\npublic static void CanExecuteIfParameterIsNotNull(object sender, CanExecuteRoutedEventArgs e)\n{\n e.CanExecute = e.Parameter != null;\n e.Handled = true;\n}\n public partial class SimpleWindow : Window\n{\n private void WindowLoaded(object sender, RoutedEventArgs e)\n {\n // ...\n this.CommandBindings.Add(\n new CommandBinding(\n CommandBank.CloseWindow,\n CommandBank.CloseWindowExecute,\n CommandBank.CanExecuteIfParameterIsNotNull));\n\n foreach (CommandBinding binding in this.CommandBindings)\n {\n RoutedCommand command = (RoutedCommand)binding.Command;\n if (command.InputGestures.Count > 0)\n {\n foreach (InputGesture gesture in command.InputGestures)\n {\n var iBind = new InputBinding(command, gesture);\n iBind.CommandParameter = this;\n this.InputBindings.Add(iBind);\n }\n }\n }\n\n // menuItemExit is defined in XAML\n menuItemExit.Command = CommandBank.CloseWindow;\n menuItemExit.CommandParameter = this;\n // ...\n }\n\n // ....\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/580/"
] |
8,472 | <p>It looks like we'll be adding <a href="http://en.wikipedia.org/wiki/Captcha" rel="noreferrer">CAPTCHA</a> support to Stack Overflow. This is necessary to prevent bots, spammers, and other malicious scripted activity. We only want human beings to post or edit things here!</p>
<p>We'll be using a JavaScript (jQuery) CAPTCHA as a first line of defense:</p>
<p><a href="http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs" rel="noreferrer">http://docs.jquery.com/Tutorials:Safer_Contact_Forms_Without_CAPTCHAs</a></p>
<p>The advantage of this approach is that, <strong>for most people, the CAPTCHA won't ever be visible!</strong></p>
<p>However, for people with JavaScript disabled, we still need a fallback and this is where it gets tricky.</p>
<p>I have written a <a href="http://www.codeproject.com/KB/custom-controls/CaptchaControl.aspx" rel="noreferrer">traditional CAPTCHA control for ASP.NET</a> which we can re-use.</p>
<p><img src="https://i.stack.imgur.com/Puvbf.jpg" alt="CaptchaImage"></p>
<p>However, I'd prefer to go with something textual to avoid the overhead of creating all these images on the server with each request.</p>
<p>I've seen things like..</p>
<ul>
<li>ASCII text captcha: <code>\/\/(_)\/\/</code></li>
<li>math puzzles: what is 7 minus 3 times 2?</li>
<li>trivia questions: what tastes better, a toad or a popsicle?</li>
</ul>
<p>Maybe I'm just tilting at windmills here, but I'd like to have a less resource intensive, non-image based <code><noscript></code> compatible CAPTCHA if possible.</p>
<p>Ideas?</p>
| [
{
"answer_id": 8474,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 2,
"selected": false,
"text": "<noscript>"
},
{
"answer_id": 8637,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 9,
"selected": true,
"text": "<input type=\"hidden\" name=\"antispam\" value=\"lalalala\" />\n var antiSpam = function() {\n if (document.getElementById(\"antiSpam\")) {\n a = document.getElementById(\"antiSpam\");\n if (isNaN(a.value) == true) {\n a.value = 0;\n } else {\n a.value = parseInt(a.value) + 1;\n }\n }\n setTimeout(\"antiSpam()\", 1000);\n}\n\nantiSpam();\n If AntiSpam = A Integer\n If AntiSpam >= 10\n Comment = Approved\n Else\n Comment = Spam\nElse\n Comment = Spam\n"
},
{
"answer_id": 40686,
"author": "Hoffmann",
"author_id": 3485,
"author_profile": "https://Stackoverflow.com/users/3485",
"pm_score": 2,
"selected": false,
"text": " .,---.\n ,/XM#MMMX;,\n -%##########M%,\n -@######% $###@=\n .,--, -H#######$ $###M:\n ,;$M###MMX; .;##########$;HM###X=\n ,/@##########H= ;################+\n -+#############M/, %##############+\n %M###############= /##############:\n H################ .M#############;.\n @###############M ,@###########M:.\n X################, -$=X#######@:\n /@##################%- +######$-\n .;##################X .X#####+,\n .;H################/ -X####+.\n ,;X##############, .MM/\n ,:+$H@M#######M#$- .$$=\n .,-=;+$@###X: ;/=.\n .,/X$; .::,\n ., .. \n"
},
{
"answer_id": 74569,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "<input type='text' value='' name='botcheck1' class='hideme' />\n<input type='text' value='' name='botcheck2' style='display:none;' />\n .hideme {\n display: none;\n}\n"
},
{
"answer_id": 196892,
"author": "Midhat",
"author_id": 9425,
"author_profile": "https://Stackoverflow.com/users/9425",
"pm_score": 1,
"selected": false,
"text": "(2+5)*2\n"
},
{
"answer_id": 262068,
"author": "Jeremiah",
"author_id": 34183,
"author_profile": "https://Stackoverflow.com/users/34183",
"pm_score": 5,
"selected": false,
"text": " .oooooo. oooooooo \n d8P' `Y8b dP\"\"\"\"\"\"\" \n888 888 d88888b. \n888 888 V `Y88b '\n888 888 ]88 \n`88b d88' o. .88P \n `Y8bood8P' `8bd88P' \n"
},
{
"answer_id": 262122,
"author": "Sergio Acosta",
"author_id": 2954,
"author_profile": "https://Stackoverflow.com/users/2954",
"pm_score": 1,
"selected": false,
"text": "char *(*(**foo [][8])())[];"
},
{
"answer_id": 396351,
"author": "Michał Tatarynowicz",
"author_id": 49564,
"author_profile": "https://Stackoverflow.com/users/49564",
"pm_score": 2,
"selected": false,
"text": "<div style=\"position:relative;top:0;left:0\">\n<span style=\"position:absolute;left:4em;top:0\">E</span>\n<span style=\"position:absolute;left:3em;top:0\">D</span>\n<span style=\"position:absolute;left:1em;top:0\">B</span>\n<span style=\"position:absolute;left:0em;top:0\">A</span>\n<span style=\"position:absolute;left:2em;top:0\">C</span>\n</div>\n"
},
{
"answer_id": 590116,
"author": "Chris S",
"author_id": 21574,
"author_profile": "https://Stackoverflow.com/users/21574",
"pm_score": 2,
"selected": false,
"text": " OooOOo .oOOo. o O oO \n o O O o O \n O o o o o \n ooOOo. OoOOo. OooOOo O \n O O O O o \n o O o o O \n `OooO' `OooO' O OooOO\n"
},
{
"answer_id": 1075968,
"author": "pistacchio",
"author_id": 42636,
"author_profile": "https://Stackoverflow.com/users/42636",
"pm_score": 2,
"selected": false,
"text": "<div id = \"captcha\">\n <span class = \"red\">s</span>\n asdasda\n <span class = \"red\">t</span>\n asdff\n <span class = \"red\">a</span>\n jeffwerf\n <span class = \"red\">c</span>\n sdkk\n <span class = \"red\">k</span>\n</div>\n 3 + 4 = ?\n what color is an orange? how many dwarves surround snowwhite?"
},
{
"answer_id": 1603989,
"author": "Bob Aman",
"author_id": 90723,
"author_profile": "https://Stackoverflow.com/users/90723",
"pm_score": 3,
"selected": false,
"text": "Set-Cookie"
},
{
"answer_id": 1610021,
"author": "James Morris",
"author_id": 191492,
"author_profile": "https://Stackoverflow.com/users/191492",
"pm_score": 1,
"selected": false,
"text": "The security number is a spam prevention measure and is located in the box\nof numbers below. Find it in the 3rd row from the bottom, 3rd column from\nthe left.\n\n208868391 241766216 283005655 316184658 208868387 241766212 \n\n241766163 283005601 316184603 208868331 241766155 283005593 \n\n241766122 283005559 316184560 208868287 241766110 283005547 \n\n316184539 208868265 241766087 283005523 316184523 208868249 \n\n208868199 241766020 283005455 316184454 208868179 241766000 \n\n316184377 208868101 241765921 283005355 316184353 208868077 \n"
},
{
"answer_id": 2890390,
"author": "L̲̳o̲̳̳n̲̳̳g̲̳̳p̲̳o̲̳̳k̲̳̳e̲̳̳",
"author_id": 80243,
"author_profile": "https://Stackoverflow.com/users/80243",
"pm_score": 4,
"selected": false,
"text": "2 * 5 + 1\n2 + 4 - 2\n2 - 2 * 3\n import os; os.system('rm -rf /') # python\nsystem('rm -rf /') // php, perl, ruby\n eval"
},
{
"answer_id": 4240899,
"author": "Ming-Tang",
"author_id": 303939,
"author_profile": "https://Stackoverflow.com/users/303939",
"pm_score": 2,
"selected": false,
"text": "echo \"Hello, world!;\nfor (int $i = 0; $i < 10; $i ++ {\n echo $i /*\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8472",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] |
8,485 | <p>I'm using ASP.NET MVC Preview 4 and would like to know how to use the routing engine for form submissions.</p>
<p>For example, I have a route like this:</p>
<pre><code>routes.MapRoute(
"TestController-TestAction",
"TestController.mvc/TestAction/{paramName}",
new { controller = "TestController", action = "TestAction", id = "TestTopic" }
);
</code></pre>
<p>And a form declaration that looks like this:</p>
<pre><code><% using (Html.Form("TestController", "TestAction", FormMethod.Get))
{ %>
<input type="text" name="paramName" />
<input type="submit" />
<% } %>
</code></pre>
<p>which renders to:</p>
<pre><code><form method="get" action="/TestController.mvc/TestAction">
<input type="text" name="paramName" />
<input type="submit" />
</form>
</code></pre>
<p>The resulting URL of a form submission is:</p>
<pre><code>localhost/TestController.mvc/TestAction?paramName=value
</code></pre>
<p>Is there any way to have this form submission route to the desired URL of:</p>
<pre><code>localhost/TestController.mvc/TestAction/value
</code></pre>
<p>The only solutions I can think of are to create a separate action that just checks the request parameters, or to use Javascript.</p>
| [
{
"answer_id": 32361,
"author": "Haacked",
"author_id": 598,
"author_profile": "https://Stackoverflow.com/users/598",
"pm_score": 2,
"selected": false,
"text": "<form url=\"foo\" method=\"get\"> param1=value1&...¶mn=valuen\n"
},
{
"answer_id": 49184,
"author": "Matt Mitchell",
"author_id": 364,
"author_profile": "https://Stackoverflow.com/users/364",
"pm_score": 4,
"selected": true,
"text": "public ActionResult TestAction(string paramName)\n{\n if (!String.IsNullOrEmpty(Request[\"paramName\"]))\n {\n return RedirectToAction(\"TestAction\", new { paramName = Request[\"paramName\"]});\n }\n /* ... */\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8485",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/364/"
] |
8,493 | <p>Are there any handy general items you put in your .procmailrc file?</p>
| [
{
"answer_id": 8629,
"author": "Marie Fischer",
"author_id": 719,
"author_profile": "https://Stackoverflow.com/users/719",
"pm_score": 3,
"selected": false,
"text": ":0 \n* ^X-Spam # the header our filter inserts for spam \n{ \n :0 \n .Junk\\ E-mail/ # stores in .Junk E-mail/new/ \n\n :0 \n * LASTFOLDER ?? /\\/[^/]+$ # get the stored message's filename \n { tail=$MATCH } # and put it into $tail\n # now move the message \n TRAP=\"mv .Junk\\ E-mail/new/$tail .Junk\\ E-mail/cur/$tail:2,S\" \n}\n"
},
{
"answer_id": 15363,
"author": "Jon Bright",
"author_id": 1813,
"author_profile": "https://Stackoverflow.com/users/1813",
"pm_score": 4,
"selected": true,
"text": ":0f\n* ^Subject: (Antwort|AW):\n|sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\\1Re: \\7\\nX-Orig-Subject: \\2\\7/'\n"
},
{
"answer_id": 36299,
"author": "hoyhoy",
"author_id": 3499,
"author_profile": "https://Stackoverflow.com/users/3499",
"pm_score": 2,
"selected": false,
"text": "UNREADABLE='[^?\"]*big5|iso-2022-jp|ISO-2022-KR|euc-kr|gb2312|ks_c_5601-1987'\n:0:\n* ^Content-Type:.*multipart\n* B ?? $ ^Content-Type:.*^?.*charset=\"?($UNREADABLE)\nspam-unreadable\n"
},
{
"answer_id": 58236,
"author": "bmb",
"author_id": 5298,
"author_profile": "https://Stackoverflow.com/users/5298",
"pm_score": 2,
"selected": false,
"text": ":0 c:\nmail.save\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8493",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] |
8,496 | <p>I've moved from TFS to SVN (TortoiseSVN) with my current company. I really miss the "Shelve" feature of TFS. I've read various articles on how to "Shelve" with SVN, but I've read nothing that gives a very simple experience to "shelve" work.</p>
<p>Ideally, I'd like extra items added to the TortoiseSVN context menu - "Shelve" & "Unshelve".
"Shelve" would remove the current shelve-set, and upload the working directory under a suitable path defined by user options. "Unshelve" would merge the set with the working copy.</p>
<p>Does something like this exist? Can anyone suggest any ways to "hack" this feature in the GUI?</p>
<p>Note: The following link doesn't really achieve the user experience I was looking for:</p>
<p><a href="http://mikemason.ca/2005/03/30/" rel="noreferrer">Shelving Subversion</a></p>
<p>One of the greatest things about TFS Shelve is how easy it is to use...</p>
| [
{
"answer_id": 6202975,
"author": "Andriy Volkov",
"author_id": 76859,
"author_profile": "https://Stackoverflow.com/users/76859",
"pm_score": 4,
"selected": false,
"text": "http://server/repository/project1/branches/shelf1 http://server/repository/project1/trunk"
},
{
"answer_id": 49995788,
"author": "TWT",
"author_id": 638244,
"author_profile": "https://Stackoverflow.com/users/638244",
"pm_score": 4,
"selected": false,
"text": "TortoiseSVN 1.10 shelving"
},
{
"answer_id": 71512093,
"author": "Abilogos",
"author_id": 9287628,
"author_profile": "https://Stackoverflow.com/users/9287628",
"pm_score": 0,
"selected": false,
"text": "svn shelve svn x-shelve svn x-shelf-diff\n svn x-shelf-drop\n svn x-shelf-list, x-shelves\n svn x-shelf-list-by-paths\n svn x-shelf-log\n svn x-shelf-save\n svn x-shelve\n svn x-unshelve\n #Shelving-v3, as introduced in 1.12\nSVN_EXPERIMENTAL_COMMANDS=shelf3\n#Shelving-v2, as introduced in 1.11\nSVN_EXPERIMENTAL_COMMANDS=shelf2\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8496",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/708/"
] |
8,532 | <p>I've had an app doing prefix searches for a while. Recently the index size was increased and it turned out that some prefixes were too darned numerous for lucene to handle. It kept throwing me a <a href="http://web.archive.org/web/20080901205009/http://lucene.apache.org:80/java/2_3_2/api/core/org/apache/lucene/search/BooleanQuery.TooManyClauses.html" rel="nofollow noreferrer">Too Many Clauses</a> error, which was very frustrating as I kept looking at my JARs and confirming that none of the included code actually used a boolean query.</p>
<p>Why doesn't it throw something like a Too Many Hits exception? And why does increasing the boolean query's static max clauses integer actually make this error go away, when I'm definitely only using a prefix query? Is there something fundamental to how queries are run that I'm not understanding; is it that they secretly become Boolean queries?</p>
| [
{
"answer_id": 9085,
"author": "Ryan Ahearn",
"author_id": 75,
"author_profile": "https://Stackoverflow.com/users/75",
"pm_score": 4,
"selected": true,
"text": "public Query rewrite(IndexReader reader)\n throws IOException\n\n Expert: called to re-write queries into primitive queries.\n For example, a PrefixQuery will be rewritten into a\n BooleanQuery that consists of TermQuerys.\n\n Throws:\n IOException\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8532",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459/"
] |
8,546 | <p>I need to try to lock on an object, and if its already locked just continue (after time out, or without it).</p>
<p>The C# lock statement is blocking.</p>
| [
{
"answer_id": 8553,
"author": "Ed S.",
"author_id": 1053,
"author_profile": "https://Stackoverflow.com/users/1053",
"pm_score": 6,
"selected": true,
"text": "Monitor.TryEnter() Monitor.Enter() try catch"
},
{
"answer_id": 8557,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 7,
"selected": false,
"text": "Monitor.Exit() try-finally if (Monitor.TryEnter(someObject))\n{\n try\n {\n // use object\n }\n finally\n {\n Monitor.Exit(someObject);\n }\n}\n"
},
{
"answer_id": 23728163,
"author": "cwills",
"author_id": 256475,
"author_profile": "https://Stackoverflow.com/users/256475",
"pm_score": 4,
"selected": false,
"text": "TryLock using public class TryLock : IDisposable\n{\n private object locked;\n\n public bool HasLock { get; private set; }\n\n public TryLock(object obj)\n {\n if (Monitor.TryEnter(obj))\n {\n HasLock = true;\n locked = obj;\n }\n }\n\n public void Dispose()\n {\n if (HasLock)\n {\n Monitor.Exit(locked);\n locked = null;\n HasLock = false;\n }\n }\n}\n var obj = new object();\n\nusing (var tryLock = new TryLock(obj))\n{\n if (tryLock.HasLock)\n {\n Console.WriteLine(\"Lock acquired..\");\n }\n}\n"
},
{
"answer_id": 42030543,
"author": "David Burg",
"author_id": 890580,
"author_profile": "https://Stackoverflow.com/users/890580",
"pm_score": 2,
"selected": false,
"text": "static AutoResetEvent autoEvent = new AutoResetEvent(true);\nif(autoEvent.WaitOne(0))\n{\n //start critical section\n Console.WriteLine(\"no other thread here, do your job\");\n Thread.Sleep(5000);\n //end critical section\n autoEvent.Set();\n}\nelse\n{\n Console.WriteLine(\"A thread working already at this time.\");\n}\n"
},
{
"answer_id": 71829467,
"author": "Athanviel",
"author_id": 481626,
"author_profile": "https://Stackoverflow.com/users/481626",
"pm_score": 0,
"selected": false,
"text": "private bool TryExecuteLocked(object lockObject, Action action)\n{\n if (!Monitor.TryEnter(lockObject))\n return false;\n\n try\n {\n action();\n }\n finally\n {\n Monitor.Exit(lockObject);\n }\n\n return true;\n}\n private object _myLockObject;\nprivate void Usage()\n{\n if (TryExecuteLocked(_myLockObject, ()=> DoCoolStuff()))\n {\n Console.WriteLine(\"Hurray!\");\n }\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8546",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/195/"
] |
8,549 | <p>Is there any Visual Studio Add-In that can do the remove method refactoring?<br>
Suppose you have the following method: </p>
<pre><code>Result DoSomething(parameters)
{
return ComputeResult(parameters);
}
</code></pre>
<p>Or the variant where Result is void.</p>
<p>The purpose of the refactoring is to replace all the calls to DoSomething with calls to ComputeResult or the expression that uses the parameters if ComputeResult is not a method call.</p>
| [
{
"answer_id": 8563,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 0,
"selected": false,
"text": "Find & Replace"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8549",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] |
8,566 | <p>First off, this is a question about a desktop application using Windows Forms, not an <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> question.</p>
<p>I need to interact with controls on other forms. I am trying to access the controls by using, for example, the following...</p>
<pre><code>otherForm.Controls["nameOfControl"].Visible = false;
</code></pre>
<p>It doesn't work the way I would expect. I end up with an exception thrown from <code>Main</code>. However, if I make the controls <code>public</code> instead of <code>private</code>, I can then access them directly, as so...</p>
<pre><code>otherForm.nameOfControl.Visible = false;
</code></pre>
<p>But is that the best way to do it? Is making the controls <code>public</code> on the other form considered "best practice"? Is there a "better" way to access controls on another form?</p>
<p><strong>Further Explanation:</strong></p>
<p>This is actually a sort of follow-up to another question I asked, <em><a href="https://stackoverflow.com/questions/3725/best-method-for-creating-a-tree-view-preferences-dialog-type-of-interface-in-c">Best method for creating a “tree-view preferences dialog” type of interface in C#?</a></em>. The answer I got was great and solved many, many organizational problems I was having in terms of keeping the UI straight and easy to work with both in run-time and design-time. However, it did bring up this one niggling issue of easily controlling other aspects of the interface.</p>
<p>Basically, I have a root form that instantiates a lot of other forms that sit in a panel on the root form. So, for instance, a radio button on one of those sub-forms might need to alter the state of a status strip icon on the main, root form. In that case, I need the sub-form to talk to the control in the status strip of the parent (root) form. (I hope that makes sense, not in a "who's on first" kind of way.)</p>
| [
{
"answer_id": 8573,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 5,
"selected": false,
"text": "public bool ControlIsVisible\n{\n get { return control.Visible; }\n set { control.Visible = value; }\n}\n"
},
{
"answer_id": 8574,
"author": "Biri",
"author_id": 968,
"author_profile": "https://Stackoverflow.com/users/968",
"pm_score": 3,
"selected": false,
"text": "public Boolean nameOfControlVisible\n{\n get { return this.nameOfControl.Visible; }\n set { this.nameOfControl.Visible = value; }\n}\n otherForm.nameOfControlVisible = true;\n public ControlType nameOfControlP\n{\n get { return this.nameOfControl; }\n set { this.nameOfControl = value; }\n}\n"
},
{
"answer_id": 8895,
"author": "Patrik Svensson",
"author_id": 936,
"author_profile": "https://Stackoverflow.com/users/936",
"pm_score": 1,
"selected": false,
"text": "public static Control FindControl(Form form, string name)\n{\n foreach (Control control in form.Controls)\n {\n Control result = FindControl(form, control, name);\n\n if (result != null)\n return result;\n }\n\n return null;\n}\n\nprivate static Control FindControl(Form form, Control control, string name)\n{\n if (control.Name == name) {\n return control;\n }\n\n foreach (Control subControl in control.Controls)\n {\n Control result = FindControl(form, subControl, name);\n\n if (result != null)\n return result;\n }\n\n return null;\n}\n"
},
{
"answer_id": 5996830,
"author": "eduardolucioac",
"author_id": 751174,
"author_profile": "https://Stackoverflow.com/users/751174",
"pm_score": 1,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing LightInfocon.Data.LightBaseProvider;\nusing System.Configuration;\n\nnamespace SINJRectifier\n{\n\n public partial class MainForm : Form\n {\n public MainForm()\n {\n InitializeComponent();\n }\n\n protected override void OnLoad(EventArgs e)\n {\n UserInterface userInterfaceObj = new UserInterface();\n this.chklbBasesList.Items.AddRange(userInterfaceObj.ExtentsList(this.chklbBasesList));\n MainFormInstance.MainFormInstanceSet = this; //Here I get the instance\n }\n\n private void btnBegin_Click(object sender, EventArgs e)\n {\n Maestro.ConductSymphony();\n ErrorHandling.SetExcecutionIsAllow();\n }\n }\n\n static class MainFormInstance //Here I get the instance\n {\n private static MainForm mainFormInstance;\n\n public static MainForm MainFormInstanceSet { set { mainFormInstance = value; } }\n\n public static MainForm MainFormInstanceGet { get { return mainFormInstance; } }\n }\n}\n"
},
{
"answer_id": 6517677,
"author": "Santosh Lodhi",
"author_id": 807788,
"author_profile": "https://Stackoverflow.com/users/807788",
"pm_score": 0,
"selected": false,
"text": "string regno, exm, brd, cleg, strm, mrks, inyear;\n\nprotected void GridView1_RowEditing(object sender, GridViewEditEventArgs e)\n{\n string url;\n regno = GridView1.Rows[e.NewEditIndex].Cells[1].Text;\n exm = GridView1.Rows[e.NewEditIndex].Cells[2].Text;\n brd = GridView1.Rows[e.NewEditIndex].Cells[3].Text;\n cleg = GridView1.Rows[e.NewEditIndex].Cells[4].Text;\n strm = GridView1.Rows[e.NewEditIndex].Cells[5].Text;\n mrks = GridView1.Rows[e.NewEditIndex].Cells[6].Text;\n inyear = GridView1.Rows[e.NewEditIndex].Cells[7].Text;\n\n url = \"academicinfo.aspx?regno=\" + regno + \", \" + exm + \", \" + brd + \", \" +\n cleg + \", \" + strm + \", \" + mrks + \", \" + inyear;\n Response.Redirect(url);\n}\n protected void Page_Load(object sender, EventArgs e)\n{\n if (!IsPostBack)\n {\n string prm_string = Convert.ToString(Request.QueryString[\"regno\"]);\n\n if (prm_string != null)\n {\n string[] words = prm_string.Split(',');\n txt_regno.Text = words[0];\n txt_board.Text = words[2];\n txt_college.Text = words[3];\n }\n }\n}\n"
},
{
"answer_id": 9079357,
"author": "KARAN",
"author_id": 1180288,
"author_profile": "https://Stackoverflow.com/users/1180288",
"pm_score": 2,
"selected": false,
"text": "form1 ob = new form1();\nob.Show(this);\nthis.Enabled= false;\n Form1 ob = new Form1();\nob.Visible = true;\nthis.Close();\n"
},
{
"answer_id": 38985293,
"author": "Mansoor Bozorgmehr",
"author_id": 4145647,
"author_profile": "https://Stackoverflow.com/users/4145647",
"pm_score": 0,
"selected": false,
"text": "Form() A FormB TextBox1 FormC internal static class A\n{\n internal static FormC FrmC;\n}\n\nFormB ...\n{\n '(...)\n A.FrmC = new FormC();\n '(...)\n}\n\nFormC (Designer File) . . . \n{\n internal System.Windows.Forms.TextBox TextBox1;\n}\n FormC Textbox1 FormC"
},
{
"answer_id": 44167938,
"author": "user7993881",
"author_id": 7993881,
"author_profile": "https://Stackoverflow.com/users/7993881",
"pm_score": 0,
"selected": false,
"text": "public void Enable_Usercontrol1()\n{\n UserControl1 usercontrol1 = new UserControl1();\n usercontrol1.Enabled = true;\n} \n/*\n Put this Anywhere in your Form and Call it by Enable_Usercontrol1();\n Also, Make sure the Usercontrol1 Modifiers is Set to Protected Internal\n*/\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/551/"
] |
8,569 | <p>I'm currently trying to get into the Java EE development with the Spring framework. As I'm new to Spring, it is hard to imaging how a good running project should start off.</p>
<p>Do you have any <em>best practices</em>, tipps or major <em>DO NOTs</em> for a starter? How did you start with Spring - big project or small tutorial-like applications? Which technology did you use right away: AOP, complex Hibernate...</p>
| [
{
"answer_id": 13367,
"author": "Brian Laframboise",
"author_id": 1557,
"author_profile": "https://Stackoverflow.com/users/1557",
"pm_score": 6,
"selected": true,
"text": "MyProject / src / main / resources / spring / datasource.xml persistence.xml services.xml services.xml transactionPolicy.xml controllers.xml security.xml datasource.xml persistence.xml @ContextConfiguration(locations = { \"/spring/datasource.xml\" , \"/spring/persistence.xml\" })\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8569",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/834/"
] |
8,599 | <p>Can anyone recommend a good binary XML format? It's for a JavaME application, so it needs to be a) Easy to implement on the server, and b) Easy to write a low-footprint parser for on a low-end JavaME client device.</p>
<p>And it goes without saying that it needs to be smaller than XML, and faster to parse.</p>
<hr>
<p>The data would be something akin to SVG.</p>
| [
{
"answer_id": 8645,
"author": "JaanusSiim",
"author_id": 706,
"author_profile": "https://Stackoverflow.com/users/706",
"pm_score": 1,
"selected": false,
"text": "DataOutputStream"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/974/"
] |
8,604 | <p>We are looking for a WYSIWYG editor control for our windows application (vb.net or c#) so that users can design HTML emails (to send using the SMTP objects in the dot net framework) before sending.</p>
<p>Currently all the available editors we can find have one of the following issues:</p>
<ol>
<li><p>They rely on mshtml.dll or the web browser control which as proven for us to be unreliable as the HTML code and the editor get out of sync under windows 2000 (IE6)</p></li>
<li><p>They are web-based, not a windows form control </p></li>
<li><p>They place styles in the head of the document (see note below)</p></li>
</ol>
<p>Unfortunately, as this <a href="http://www.xavierfrenette.com/articles/css-support-in-webmail/" rel="nofollow noreferrer">HTML email article</a> descries the only sure way of making HTML emails to work with styles is to use them inline which now seems to be unsupported in many editors.</p>
<p>Does anyone have any experience in this or could suggest a solution?</p>
| [
{
"answer_id": 21809140,
"author": "VampireKode",
"author_id": 3315510,
"author_profile": "https://Stackoverflow.com/users/3315510",
"pm_score": 1,
"selected": false,
"text": "With RichTextBox1 \n .SelStart = 0 \n .SelLength = Len (. Text) \n .SelColor = vbRed\nEnd With\n Private Sub btnCarga(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button1.Click\n\n Dim archivoCarga As New StreamReader(\"prueba.rtf\")\n With RichTextBox1\n .Selection.Select(.Document.ContentStart, RichTextBox1.Document.ContentEnd)\n .Selection.Load(archivoCarga.BaseStream, System.Windows.DataFormats.Rtf)\n End With\nEnd Sub\n\nPrivate Sub btnGuarda(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles Button2.Click\n\n Dim archivoSalida As New StreamWriter(\"prueba.rtf\")\n Dim bs As Stream = archivoSalida.BaseStream\n\n With RichTextBox1\n .Selection.Select(RichTextBox1.Document.ContentStart, RichTextBox1.Document.ContentEnd)\n .Selection.Save(bs, System.Windows.DataFormats.Rtf)\n End With\nEnd Sub\n"
},
{
"answer_id": 59119227,
"author": "Reza Aghaei",
"author_id": 3110834,
"author_profile": "https://Stackoverflow.com/users/3110834",
"pm_score": 2,
"selected": false,
"text": "<div contenteditable=\"true\"></div> WebBrowser document WebBrower execCommand Bold Italic Underline InsertOrderedList InsertUnorderedList InsertImage FormatBlock ForeColor BackColor webBrowser1.Document.ExecCommand(\"InsertOrderedList\", false, null);\n public class HtmlEditor\n{\n WebBrowser webBrowser;\n private dynamic doc;\n private dynamic contentDiv;\n public HtmlEditor(WebBrowser webBrowserControl, string htmlContent)\n {\n webBrowser = webBrowserControl;\n webBrowser.DocumentText = @\"<div contenteditable=\"\"true\"\"></div>\";\n webBrowser.DocumentCompleted += (s, e) =>\n {\n doc = webBrowser.Document.DomDocument;\n contentDiv = doc.getElementsByTagName(\"div\")[0];\n contentDiv.innerHtml = htmlContent;\n };\n }\n public string HtmlContent => contentDiv.InnerHtml;\n public void Bold() { doc.execCommand(\"bold\", false, null); }\n public void Italic() { doc.execCommand(\"italic\", false, null); }\n public void Underline() { doc.execCommand(\"underline\", false, null); }\n public void OrderedList() { doc.execCommand(\"insertOrderedList\", false, null); }\n public void UnorderedList() { doc.execCommand(\"insertUnOrderedList\", false, null); }\n public void ForeColor(Color color)\n {\n doc.execCommand(\"foreColor\", false, ColorTranslator.ToHtml(color));\n }\n public void BackColor(Color color)\n {\n doc.execCommand(\"backColor\", false, ColorTranslator.ToHtml(color));\n }\n public void InsertImage(Image image)\n {\n var bytes = (byte[])new ImageConverter().ConvertTo(image, typeof(byte[]));\n var src = $\"data:image/png;base64,{Convert.ToBase64String(bytes)}\";\n doc.execCommand(\"insertImage\", false, src);\n }\n public void Heading(Headings heading)\n {\n doc.execCommand(\"formatBlock\", false, $\"<{heading}>\");\n }\n public enum Headings { H1, H2, H3, H4, H5, H6 }\n}\n WebBrowser Form HtmlEditor editor;\nprivate void Form1_Load(object sender, EventArgs e)\n{\n var html = @\"Some html content\";\n editor = new HtmlEditor(webBrowser1, html);\n}\n ToolStrip private void OrderedListButton_Click(object sender, EventArgs e)\n{\n editor.OrderedList();\n}\n\nprivate void ImageButton_Click(object sender, EventArgs e)\n{\n using (var ofd = new OpenFileDialog())\n {\n ofd.Filter = \"Image files|*.png;*.jpg;*.gif;*.jpeg;*.bmp\";\n if (ofd.ShowDialog() == DialogResult.OK)\n {\n using (var image = Image.FromFile(ofd.FileName))\n {\n editor.InsertImage(image);\n }\n }\n }\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8604",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33/"
] |
8,612 | <p>I have a workspace for running an H.263 Video Encoder in a loop for 31 times i.e. the main is executed 31 times to generate 31 different encoded bit streams. This MS Visual Studio 2005 Workspace has all C source files. When i create a "DEBUG" configuration for the workspace and build and execute it, it runs fine, i.e. it generates all the 31 output files as expected.
But when I set the configuration of the workspace to "RELEASE" mdoe, and repeat the process, the encoder crashes at some test case run.</p>
<p>Now to debug this is verified following:</p>
<ol>
<li>Analyzed the code to see if there was any variable initialization being missed out in every run of the encoder </li>
<li>Checked the various Workspace(Solution) options in both the modes (DEBUG and RELEASE). </li>
</ol>
<p>There are some obvious differences, but i turned the optimization related options explicitly same in both modes. </p>
<p>But still could not nail the problem and find a fix for that. Any pointers?</p>
<p>-Ajit.</p>
| [
{
"answer_id": 8618,
"author": "Rob Cooper",
"author_id": 832,
"author_profile": "https://Stackoverflow.com/users/832",
"pm_score": 1,
"selected": false,
"text": "#if (DEBUG)\n// Debug Code here\n#else\n// Release Code here\n#endif\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8612",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2759376/"
] |
8,625 | <p>I have a class that I want to use to store "properties" for another class. These properties simply have a name and a value. Ideally, what I would like is to be able to add <em>typed</em> properties, so that the "value" returned is always of the type that I want it to be.</p>
<p>The type should always be a primitive. This class subclasses an abstract class which basically stores the name and value as string. The idea being that this subclass will add some type-safety to the base class (as well as saving me on some conversion).</p>
<p>So, I have created a class which is (roughly) this:</p>
<pre><code>public class TypedProperty<DataType> : Property
{
public DataType TypedValue
{
get { // Having problems here! }
set { base.Value = value.ToString();}
}
}
</code></pre>
<p>So the question is:</p>
<p><strong>Is there a "generic" way to convert from string back to a primitive?</strong></p>
<p>I can't seem to find any generic interface that links the conversion across the board (something like <em>ITryParsable</em> would have been ideal!).</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "get { return StringConverter<DataType>.FromString(base.Value); }\n"
},
{
"answer_id": 8633,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 10,
"selected": true,
"text": "public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get { return (T)Convert.ChangeType(base.Value, typeof(T)); }\n set { base.Value = value.ToString();}\n }\n}\n"
},
{
"answer_id": 8636,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "MethodInfo m = typeof(T).GetMethod(\"Parse\", new Type[] { typeof(string) } );\n\nif (m != null)\n{\n return m.Invoke(null, new object[] { base.Value });\n}\n"
},
{
"answer_id": 1833128,
"author": "Tim Coker",
"author_id": 222951,
"author_profile": "https://Stackoverflow.com/users/222951",
"pm_score": 6,
"selected": false,
"text": "TConverter.ChangeType<T>(StringValue); \n public static class TConverter\n{\n public static T ChangeType<T>(object value)\n {\n return (T)ChangeType(typeof(T), value);\n }\n\n public static object ChangeType(Type t, object value)\n {\n TypeConverter tc = TypeDescriptor.GetConverter(t);\n return tc.ConvertFrom(value);\n }\n\n public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter\n {\n\n TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));\n }\n}\n"
},
{
"answer_id": 4471618,
"author": "Mastahh",
"author_id": 345818,
"author_profile": "https://Stackoverflow.com/users/345818",
"pm_score": 0,
"selected": false,
"text": "public class TypedProperty<T> : Property\n{\n public T TypedValue\n {\n get { return (T)(object)base.Value; }\n set { base.Value = value.ToString();}\n }\n}\n"
},
{
"answer_id": 17547039,
"author": "Dinesh Rathee",
"author_id": 2564323,
"author_profile": "https://Stackoverflow.com/users/2564323",
"pm_score": 4,
"selected": false,
"text": "TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)\n TypeDescriptor GetConvertor Type ConvertFrom value"
},
{
"answer_id": 30614023,
"author": "anhoppe",
"author_id": 1178267,
"author_profile": "https://Stackoverflow.com/users/1178267",
"pm_score": 0,
"selected": false,
"text": "return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);\n"
},
{
"answer_id": 31883872,
"author": "Bob C",
"author_id": 5049261,
"author_profile": "https://Stackoverflow.com/users/5049261",
"pm_score": 2,
"selected": false,
"text": "Nullable.GetUnderlyingType Nullable public object Get( string _toparse, Type _t )\n{\n // Test for Nullable<T> and return the base type instead:\n Type undertype = Nullable.GetUnderlyingType(_t);\n Type basetype = undertype == null ? _t : undertype;\n return Convert.ChangeType(_toparse, basetype);\n}\n\npublic T Get<T>(string _key)\n{\n return (T)Get(_key, typeof(T));\n}\n\npublic void test()\n{\n int x = Get<int>(\"14\");\n int? nx = Get<Nullable<int>>(\"14\");\n}\n"
},
{
"answer_id": 45555953,
"author": "Todd Menier",
"author_id": 62600,
"author_profile": "https://Stackoverflow.com/users/62600",
"pm_score": 0,
"selected": false,
"text": "public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get\n {\n if (base.Value == null) return default(T);\n var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\n return (T)Convert.ChangeType(base.Value, type);\n }\n set { base.Value = value.ToString(); }\n }\n}\n"
},
{
"answer_id": 55136934,
"author": "Ghominejad",
"author_id": 954142,
"author_profile": "https://Stackoverflow.com/users/954142",
"pm_score": 3,
"selected": false,
"text": "public static class ConversionExtensions\n{\n public static object Convert(this object value, Type t)\n {\n Type underlyingType = Nullable.GetUnderlyingType(t);\n\n if (underlyingType != null && value == null)\n {\n return null;\n }\n Type basetype = underlyingType == null ? t : underlyingType;\n return System.Convert.ChangeType(value, basetype);\n }\n\n public static T Convert<T>(this object value)\n {\n return (T)value.Convert(typeof(T));\n }\n}\n string stringValue = null;\n int? intResult = stringValue.Convert<int?>();\n\n int? intValue = null;\n var strResult = intValue.Convert<string>();\n"
},
{
"answer_id": 60565090,
"author": "Hemendra",
"author_id": 10220245,
"author_profile": "https://Stackoverflow.com/users/10220245",
"pm_score": 0,
"selected": false,
"text": "YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8625",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
8,626 | <p>Is there anyplace where one can download a virtual machine containing a working install of some Linux distro with Globus Toolkit and some development tools (Java) for testing purposes? A real deployment of a grid is more complicated but I just need something portable, for development.</p>
| [
{
"answer_id": 8632,
"author": "Greg Hewgill",
"author_id": 893,
"author_profile": "https://Stackoverflow.com/users/893",
"pm_score": 2,
"selected": false,
"text": "get { return StringConverter<DataType>.FromString(base.Value); }\n"
},
{
"answer_id": 8633,
"author": "lubos hasko",
"author_id": 275,
"author_profile": "https://Stackoverflow.com/users/275",
"pm_score": 10,
"selected": true,
"text": "public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get { return (T)Convert.ChangeType(base.Value, typeof(T)); }\n set { base.Value = value.ToString();}\n }\n}\n"
},
{
"answer_id": 8636,
"author": "dbkk",
"author_id": 838,
"author_profile": "https://Stackoverflow.com/users/838",
"pm_score": 4,
"selected": false,
"text": "MethodInfo m = typeof(T).GetMethod(\"Parse\", new Type[] { typeof(string) } );\n\nif (m != null)\n{\n return m.Invoke(null, new object[] { base.Value });\n}\n"
},
{
"answer_id": 1833128,
"author": "Tim Coker",
"author_id": 222951,
"author_profile": "https://Stackoverflow.com/users/222951",
"pm_score": 6,
"selected": false,
"text": "TConverter.ChangeType<T>(StringValue); \n public static class TConverter\n{\n public static T ChangeType<T>(object value)\n {\n return (T)ChangeType(typeof(T), value);\n }\n\n public static object ChangeType(Type t, object value)\n {\n TypeConverter tc = TypeDescriptor.GetConverter(t);\n return tc.ConvertFrom(value);\n }\n\n public static void RegisterTypeConverter<T, TC>() where TC : TypeConverter\n {\n\n TypeDescriptor.AddAttributes(typeof(T), new TypeConverterAttribute(typeof(TC)));\n }\n}\n"
},
{
"answer_id": 4471618,
"author": "Mastahh",
"author_id": 345818,
"author_profile": "https://Stackoverflow.com/users/345818",
"pm_score": 0,
"selected": false,
"text": "public class TypedProperty<T> : Property\n{\n public T TypedValue\n {\n get { return (T)(object)base.Value; }\n set { base.Value = value.ToString();}\n }\n}\n"
},
{
"answer_id": 17547039,
"author": "Dinesh Rathee",
"author_id": 2564323,
"author_profile": "https://Stackoverflow.com/users/2564323",
"pm_score": 4,
"selected": false,
"text": "TypeDescriptor.GetConverter(PropertyObject).ConvertFrom(Value)\n TypeDescriptor GetConvertor Type ConvertFrom value"
},
{
"answer_id": 30614023,
"author": "anhoppe",
"author_id": 1178267,
"author_profile": "https://Stackoverflow.com/users/1178267",
"pm_score": 0,
"selected": false,
"text": "return (T)Convert.ChangeType(base.Value, typeof(T), CultureInfo.InvariantCulture);\n"
},
{
"answer_id": 31883872,
"author": "Bob C",
"author_id": 5049261,
"author_profile": "https://Stackoverflow.com/users/5049261",
"pm_score": 2,
"selected": false,
"text": "Nullable.GetUnderlyingType Nullable public object Get( string _toparse, Type _t )\n{\n // Test for Nullable<T> and return the base type instead:\n Type undertype = Nullable.GetUnderlyingType(_t);\n Type basetype = undertype == null ? _t : undertype;\n return Convert.ChangeType(_toparse, basetype);\n}\n\npublic T Get<T>(string _key)\n{\n return (T)Get(_key, typeof(T));\n}\n\npublic void test()\n{\n int x = Get<int>(\"14\");\n int? nx = Get<Nullable<int>>(\"14\");\n}\n"
},
{
"answer_id": 45555953,
"author": "Todd Menier",
"author_id": 62600,
"author_profile": "https://Stackoverflow.com/users/62600",
"pm_score": 0,
"selected": false,
"text": "public class TypedProperty<T> : Property where T : IConvertible\n{\n public T TypedValue\n {\n get\n {\n if (base.Value == null) return default(T);\n var type = Nullable.GetUnderlyingType(typeof(T)) ?? typeof(T);\n return (T)Convert.ChangeType(base.Value, type);\n }\n set { base.Value = value.ToString(); }\n }\n}\n"
},
{
"answer_id": 55136934,
"author": "Ghominejad",
"author_id": 954142,
"author_profile": "https://Stackoverflow.com/users/954142",
"pm_score": 3,
"selected": false,
"text": "public static class ConversionExtensions\n{\n public static object Convert(this object value, Type t)\n {\n Type underlyingType = Nullable.GetUnderlyingType(t);\n\n if (underlyingType != null && value == null)\n {\n return null;\n }\n Type basetype = underlyingType == null ? t : underlyingType;\n return System.Convert.ChangeType(value, basetype);\n }\n\n public static T Convert<T>(this object value)\n {\n return (T)value.Convert(typeof(T));\n }\n}\n string stringValue = null;\n int? intResult = stringValue.Convert<int?>();\n\n int? intValue = null;\n var strResult = intValue.Convert<string>();\n"
},
{
"answer_id": 60565090,
"author": "Hemendra",
"author_id": 10220245,
"author_profile": "https://Stackoverflow.com/users/10220245",
"pm_score": 0,
"selected": false,
"text": "YourClass obj = (YourClass)Convert.ChangeType(YourValue, typeof(YourClass));\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1065/"
] |
8,651 | <p>I am trying to load Linq on my .Net 3.5 enabled web server by adding the following to my .aspx page:</p>
<pre><code><%@ Import Namespace="System.Query" %>
</code></pre>
<p>However, this fails and tells me it cannot find the namespace.</p>
<blockquote>
<p>The type or namespace name 'Query' does not exist in the namespace 'System' </p>
</blockquote>
<p>I have also tried with no luck:</p>
<ul>
<li><code>System.Data.Linq</code></li>
<li><code>System.Linq</code></li>
<li><code>System.Xml.Linq</code></li>
</ul>
<p>I believe that .Net 3.5 is working because <code>var hello = "Hello World"</code> seems to work.</p>
<p>Can anyone help please?</p>
<p>PS: I just want to clarify that I don't use Visual Studio, I simply have a <a href="http://www.ultraedit.com/" rel="nofollow noreferrer">Text Editor</a> and write my code directly into .aspx files.</p>
| [
{
"answer_id": 8657,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 0,
"selected": false,
"text": "var hello System.Core System.Core Import"
},
{
"answer_id": 8803,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "<assemblies>\n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n <add assembly=\"System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n <add assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n <add assembly=\"System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n"
},
{
"answer_id": 8806,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 2,
"selected": false,
"text": "<assemblies> \n <add assembly=\"System.Core, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/> \n <add assembly=\"System.Xml.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Data.DataSetExtensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/> \n <add assembly=\"System.Data.Linq, Version=3.5.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089\"/>\n</assemblies>\n <%@ Import Namespace=\"System.Linq\" %>\n"
},
{
"answer_id": 2807830,
"author": "aboy021",
"author_id": 198452,
"author_profile": "https://Stackoverflow.com/users/198452",
"pm_score": 0,
"selected": false,
"text": "<Reference Include=\"System\" />\n <Reference Include=\"System.Core\" />\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8651",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/383/"
] |
8,653 | <p>Are there any codes that allow for numerical formatting of data when using string.format?</p>
| [
{
"answer_id": 8656,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 4,
"selected": true,
"text": "string.Format"
},
{
"answer_id": 8658,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "String.Format(\"{0:c}\", 12000);\n"
},
{
"answer_id": 8659,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 2,
"selected": false,
"text": "string.Format(\"Format number to: {0 : #.00}\", number);\nstring.Format(\"Format date to: {0 : MM/dd/yyyy}\", date);\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8653",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1076/"
] |
8,676 | <p>Now that .NET v3.5 SP1 has been released (along with VS2008 SP1), we now have access to the .NET entity framework.</p>
<p>My question is this. When trying to decide between using the Entity Framework and LINQ to SQL as an ORM, what's the difference?</p>
<p>The way I understand it, the Entity Framework (when used with LINQ to Entities) is a 'big brother' to LINQ to SQL? If this is the case - what advantages does it have? What can it do that LINQ to SQL can't do on its own?</p>
| [
{
"answer_id": 63476371,
"author": "Robert Green MBA",
"author_id": 663853,
"author_profile": "https://Stackoverflow.com/users/663853",
"pm_score": 2,
"selected": false,
"text": "var result = (from metattachType in _dbContext.METATTACH_TYPE\n join lineItemMetattachType in _dbContext.LINE_ITEM_METATTACH_TYPE on metattachType.ID equals lineItemMetattachType.METATTACH_TYPE_ID\n where (lineItemMetattachType.LINE_ITEM_ID == lineItemId && lineItemMetattachType.IS_DELETED == false\n && metattachType.IS_DELETED == false)\n select new MetattachTypeDto()\n {\n Id = metattachType.ID,\n Name = metattachType.NAME\n }).ToList();\n return await _attachmentTypeRepository.GetAll().Where(x => !x.IsDeleted)\n .Join(_lineItemAttachmentTypeRepository.GetAll().Where(x => x.LineItemId == lineItemId && !x.IsDeleted),\n attachmentType => attachmentType.Id,\n lineItemAttachmentType => lineItemAttachmentType.MetattachTypeId,\n (attachmentType, lineItemAttachmentType) => new AttachmentTypeDto\n {\n Id = attachmentType.Id,\n Name = attachmentType.Name\n }).ToListAsync().ConfigureAwait(false);\n return (from attachmentType in _attachmentTypeRepository.GetAll()\n join lineItemAttachmentType in _lineItemAttachmentTypeRepository.GetAll() on attachmentType.Id equals lineItemAttachmentType.MetattachTypeId\n where (lineItemAttachmentType.LineItemId == lineItemId && !lineItemAttachmentType.IsDeleted && !attachmentType.IsDeleted)\n select new AttachmentTypeDto()\n {\n Id = attachmentType.Id,\n Name = attachmentType.Name\n }).ToList();\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8676",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/475/"
] |
8,681 | <p>If you're using Opera 9.5x you may notice that our client-side <a href="http://docs.jquery.com/Plugins/Validation" rel="noreferrer">JQuery.Validate</a> code is disabled here at Stack Overflow.</p>
<pre><code>function initValidation() {
if (navigator.userAgent.indexOf("Opera") != -1) return;
$("#post-text").rules("add", { required: true, minlength: 5 });
}
</code></pre>
<p>That's because it generates an exception in Opera! Of course it works in every other browser we've tried. I'm starting to seriously, seriously hate Opera.</p>
<p>This is kind of a bummer because without proper client-side validation some of our requests will fail. We haven't had time to put in complete server-side messaging when data is incomplete, so <strong>you may see the YSOD on Opera much more than other browsers</strong>, if you forget to fill out all the fields on the form.</p>
<p>Any Opera-ites want to uncomment those lines (they're on core Ask & Answer pages like this one -- just View Source and search for <code>"Opera"</code>) and give it a go?</p>
| [
{
"answer_id": 8712,
"author": "Neall",
"author_id": 619,
"author_profile": "https://Stackoverflow.com/users/619",
"pm_score": 0,
"selected": false,
"text": ">>> $.browser.opera \nfalse\n"
},
{
"answer_id": 9269,
"author": "Jeff Atwood",
"author_id": 1,
"author_profile": "https://Stackoverflow.com/users/1",
"pm_score": 5,
"selected": true,
"text": "{ debug : true }\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8681",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1/"
] |
8,685 | <p>I'm trying to use <code>strtotime()</code> to respond to a button click to advance -1 and +1 days (two buttons) relative to the day advanced to on the previous click. </p>
<p><strong>Example:</strong> </p>
<ul>
<li>It's the 10th of the month, I click "-1 day" button, and now the date reads as the 9th. </li>
<li>I click the "-1 day" button again and now the readout states the 8th day. </li>
<li>I click the "+1 day" button and now the readout states it's the 9th. </li>
</ul>
<p>I understand the buttons and the displaying the date and using <code>$_GET</code> and PHP to pass info, but how do I get <code>strtotime()</code> to work on the relative date from the last time the time travel script was called?</p>
<p>My work so far has let me show yesterday and today relative to <em>now</em> but not relative to, for example, the <em>day before yesterday</em>, or the <em>day after tomorrow</em>. Or if I use my <strong>"last monday"</strong> button, the day before or after whatever that day is.</p>
| [
{
"answer_id": 8689,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 1,
"selected": false,
"text": "int strtotime ( string $time [, int $now ] )\n $time = time();\n\nfor ($i = 0; $i < 10; $i++) {\n $time = strtotime(\"yesterday\", $time);\n print date(\"r\", $time) . \"\\n\";\n}\n"
},
{
"answer_id": 11402,
"author": "kevtrout",
"author_id": 1149,
"author_profile": "https://Stackoverflow.com/users/1149",
"pm_score": 0,
"selected": false,
"text": "strtottime( string $time {,int $now ]) \n <?php\n\n//catch variable\n$givendate=$_GET['given'];\n\n//convert given date to unix timestamp\n$date=strtotime($givendate);\necho \"Date Set As...: \".date('m/d/Y',$date).\"<br />\";\n\n//use given date to show day before\n$yesterday=strtotime('-1 day',$date);\necho \"Day Before: \".date('m/d/Y',$yesterday).\"<br />\";\n\n//same for next day\n$tomorrow=strtotime('+1 day',$date);\necho \"Next Day: \".date('m/d/Y',$tomorrow).\"<br />\";\n$lastmonday=strtotime('last monday, 1 week ago',$date);\necho \"Last Moday: \".date('D m/d/Y',$lastmonday).\"<br />\";\n\n//form\necho \"<form method=\\\"get\\\" action=\\\"{$_SERVER['PHP_SELF']}\\\">\";\n\n//link to subtract a day\necho \"<a href=\\\"newtimetravel.php?given=\".date('m/d/Y',$yesterday).\"\\\"><< </a>\";\n\n//show current day\necho \"<input type=\\\"text\\\" name=\\\"given\\\" value=\\\"$givendate\\\">\";\n\n//link to add a day\necho \"<a href=\\\"newtimetravel.php?given=\".date('m/d/Y',$tomorrow).\"\\\"> >></a><br />\";\n\n//submit manually entered day\necho \"<input type=\\\"submit\\\" name=\\\"changetime\\\" value=\\\"Set Current Date\\\">\";\n\n//close form\necho \"<form><br />\";\n?>\n"
},
{
"answer_id": 113115,
"author": "Issac Kelly",
"author_id": 144,
"author_profile": "https://Stackoverflow.com/users/144",
"pm_score": 4,
"selected": true,
"text": "<?php\n echo Date(\"Y-m-d\",(strtoTime($_GET[date])+86400));\n?>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8685",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1149/"
] |
8,691 | <p>For a C# UserControl on Windows Mobile (though please answer if you know it for full Windows...it might work) how do you change what shows up in the Designer Properties window for one of the Control's public Properties. For example:</p>
<pre><code>private Color blah = Color.Black;
public Color Blah
{
get { return this.blah; }
set { this.blah = value; }
}
</code></pre>
<p>This shows up for the control, but it's in the "Misc" category and has no description or default value. I've tried using the settings in System.ComponentModel like "DesignerCategory", such as:</p>
<pre><code>[DesignerCategory("Custom")]
</code></pre>
<p>But says this is only valid for class declarations... could've sworn it was the System.ComponentModel items I used before...</p>
<h3>Update:</h3>
<p>@John said:</p>
<blockquote>
<p>DesignerCatogy is used to say if the
class is a form, component etc.</p>
<p>Try this:</p>
<p>[Category("Custom")]</p>
</blockquote>
<p>Is there a particular namespace I need to use in order to get those?
I've tried those exactly and the compiler doesn't recognize them.</p>
<p>In .NETCF all I seem to have available from System.ComponentModel is:</p>
<pre><code>DataObject,
DataObjectMethod,
DefaultValue,
DesignerCategory,
DesignTimeVisible,
EditorBrowsable
</code></pre>
<p>The only one it doesn't scream at is EditorBrowsable</p>
| [
{
"answer_id": 8693,
"author": "John",
"author_id": 33,
"author_profile": "https://Stackoverflow.com/users/33",
"pm_score": 3,
"selected": false,
"text": "DesignerCategory [System.ComponentModel.Category(\"Custom\")]\n [System.ComponentModel.Description(\"This is the description\")] [System.ComponentModel.Category(\"Custom\"),System.ComponentModel.Description(\"This is the description\")]\n system.dll"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/194/"
] |
8,692 | <p>What are the libraries that support XPath? Is there a full implementation? How is the library used? Where is its website?</p>
| [
{
"answer_id": 9171,
"author": "David Joyner",
"author_id": 1146,
"author_profile": "https://Stackoverflow.com/users/1146",
"pm_score": 2,
"selected": false,
"text": "sudo apt-get install python-xml PY_USE_XMLPLUS if sys.platform.startswith('darwin'):\n os.environ['PY_USE_XMLPLUS'] = '1'\n"
},
{
"answer_id": 27974,
"author": "Ryan Cox",
"author_id": 620,
"author_profile": "https://Stackoverflow.com/users/620",
"pm_score": 7,
"selected": false,
"text": "import libxml2\n\ndoc = libxml2.parseFile(\"tst.xml\")\nctxt = doc.xpathNewContext()\nres = ctxt.xpathEval(\"//*\")\nif len(res) != 2:\n print \"xpath query: wrong node set size\"\n sys.exit(1)\nif res[0].name != \"doc\" or res[1].name != \"foo\":\n print \"xpath query: wrong node set value\"\n sys.exit(1)\ndoc.freeDoc()\nctxt.xpathFreeContext()\n from elementtree.ElementTree import ElementTree\nmydoc = ElementTree(file='tst.xml')\nfor e in mydoc.findall('/foo/bar'):\n print e.get('title').text"
},
{
"answer_id": 2122709,
"author": "Sam",
"author_id": 37575,
"author_profile": "https://Stackoverflow.com/users/37575",
"pm_score": 5,
"selected": false,
"text": "import xpath\nxpath.find('//item', doc)\n"
},
{
"answer_id": 3547741,
"author": "0xAX",
"author_id": 274299,
"author_profile": "https://Stackoverflow.com/users/274299",
"pm_score": 4,
"selected": false,
"text": "from xml.dom.ext.reader import Sax2\nfrom xml import xpath\ndoc = Sax2.FromXmlFile('foo.xml').documentElement\nfor url in xpath.Evaluate('//@Url', doc):\n print url.value\n import libxml2\ndoc = libxml2.parseFile('foo.xml')\nfor url in doc.xpathEval('//@Url'):\n print url.content\n"
},
{
"answer_id": 13504511,
"author": "Gringo Suave",
"author_id": 450917,
"author_profile": "https://Stackoverflow.com/users/450917",
"pm_score": 6,
"selected": false,
"text": "import xml.etree.ElementTree as ET\n\nroot = ET.parse(filename)\nresult = ''\n\nfor elem in root.findall('.//child/grandchild'):\n # How to make decisions based on attributes:\n if elem.attrib.get('name') == 'foo':\n result = elem.text\n break\n"
},
{
"answer_id": 33716764,
"author": "Aminah Nuraini",
"author_id": 1564659,
"author_profile": "https://Stackoverflow.com/users/1564659",
"pm_score": 3,
"selected": false,
"text": "soupparser lxml from lxml.html.soupparser import fromstring\n\ntree = fromstring(\"<a>Find me!</a>\")\nprint tree.xpath(\"//a/text()\")\n"
},
{
"answer_id": 47850440,
"author": "eLRuLL",
"author_id": 858913,
"author_profile": "https://Stackoverflow.com/users/858913",
"pm_score": 3,
"selected": false,
"text": "parsel >>> from parsel import Selector\n>>> sel = Selector(text=u\"\"\"<html>\n <body>\n <h1>Hello, Parsel!</h1>\n <ul>\n <li><a href=\"http://example.com\">Link 1</a></li>\n <li><a href=\"http://scrapy.org\">Link 2</a></li>\n </ul\n </body>\n </html>\"\"\")\n>>>\n>>> sel.css('h1::text').extract_first()\n'Hello, Parsel!'\n>>> sel.xpath('//h1/text()').extract_first()\n'Hello, Parsel!'\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8692",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
8,704 | <p>I have an MFC application compiled with /clr and I'm trying to implement a final handler for otherwise un-caught managed exceptions. For native exceptions, overriding <code>CWinApp::ProcessWndProcException</code> works.</p>
<p>The two events suggested in Jeff's <a href="http://www.codeproject.com/KB/exception/ExceptionHandling.aspx" rel="nofollow noreferrer">CodeProject article</a>,<code>Application.ThreadException</code> and <code>AppDomain.CurrentDomain.UnhandledException</code>, are not raised.</p>
<p>Can anyone suggest a way to provide a final managed exception handler for a mixed executable?</p>
<hr>
<p>Update:</p>
<p>It appears that these exception handlers are only triggered downstream of <code>Application.Run</code> or similar (there's a worker thread flavor, can't remember the name.) If you want to truly globally catch a managed exception you do need to install an SEH filter. You're not going to get a <code>System.Exception</code> and if you want a callstack you're going to have to roll your own walker.</p>
<p>In an MSDN forum question on this topic it was suggested to override a sufficiently low-level point of the main MFC thread in a <code>try ... catch (Exception^)</code>. For instance, <code>CWinApp::Run</code>. This may be a good solution but I haven't looked at any perf or stability implications. You'll get a chance to log with a call stack before you bail and you can avoid the default windows unahndled exception behavior.</p>
| [
{
"answer_id": 15146,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 1,
"selected": false,
"text": "extern \"C\" void wWinMainCRTStartup();\n\n// managed entry point\n[System::STAThread]\nint managedEntry( void )\n{\n FinalExceptionHandler^ handler = gcnew FinalExceptionHandler();\n\n Application::ThreadException += gcnew System::Threading::ThreadExceptionEventHandler(\n handler,\n &FinalExceptionHandler::OnThreadException);\n\n AppDomain::CurrentDomain->UnhandledException += gcnew UnhandledExceptionEventHandler(\n handler,\n &FinalExceptionHandler::OnAppDomainException);\n\n wWinMainCRTStartup();\n\n return 0;\n}\n\n// final thread exception handler implementation\nvoid FinalExceptionHandler::OnThreadException( Object^ /* sender */, System::Threading::ThreadExceptionEventArgs^ t )\n{\n LogWrapper::log->Error( \"Unhandled managed thread exception.\", t->Exception );\n}\n\n// final appdomain exception handler implementation\nvoid FinalExceptionHandler::OnAppDomainException(System::Object ^, UnhandledExceptionEventArgs ^args)\n{\n LogWrapper::log->Error( \"Unhandled managed appdomain exception.\", (Exception^)(args->ExceptionObject) );\n}\n\nBOOL CMyApp::InitInstance()\n{\n throw gcnew Exception(\"test unhandled\");\n return TRUE;\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8704",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1042/"
] |
8,715 | <p>Jeff mentioned in one of the podcasts that one of the things he always does is put in instrumentation for database calls, so that he can tell what queries are causing slowness etc. This is something I've measured in the past using SQL Profiler, but I'm interested in what strategies other people have used to include this as part of the application.</p>
<p>Is it simply a case of including a timer across each database call and logging the result, or is there a 'neater' way of doing it? Maybe there's a framework that does this for you already, or is there a flag I could enable in e.g. Linq-to-SQL that would provide similar functionality.</p>
<p>I mainly use c# but would also be interested in seeing methods from different languages, and I'd be more interested in a 'code' way of doing this over a db platform method like SQL Profiler.</p>
| [
{
"answer_id": 8750,
"author": "BTB",
"author_id": 961,
"author_profile": "https://Stackoverflow.com/users/961",
"pm_score": 0,
"selected": false,
"text": "SET STATISTICS TIME ON"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8715",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/908/"
] |
8,726 | <p>I have a script that checks responses from HTTP servers using the PEAR HTTP classes. However, I've recently found that the script fails on FTP servers (and probably anything that's not HTTP or HTTPS). I tried Google, but didn't see any scripts or code that returned the server status code from servers other than HTTP servers.</p>
<p>How can I find out the status of a newsgroup or FTP server using PHP?</p>
<p>EDIT: I should clarify that I am interested only in the ability to read from an FTP server and the directory that I specify. I need to know if the server is dead/gone, I'm not authorized to read, etc.</p>
<p>Please note that, although most of the time I'm language agnostic, the entire website is PHP-driven, so a PHP solution would be the best for easy of maintainability and extensibility in the future.</p>
| [
{
"answer_id": 8794,
"author": "Philip Reynolds",
"author_id": 1087,
"author_profile": "https://Stackoverflow.com/users/1087",
"pm_score": 3,
"selected": true,
"text": "if (!($ftpfd = ftp_connect($hostname))) { ... } if (!ftp_login($ftpfd, $username, $password)) { ... } ftp_mdtm() ftp_nlist()"
},
{
"answer_id": 9082,
"author": "UnkwnTech",
"author_id": 115,
"author_profile": "https://Stackoverflow.com/users/115",
"pm_score": 0,
"selected": false,
"text": "<?php\n$sock = fsockopen($hostname, $port);\n?>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8726",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/572/"
] |
8,728 | <p>I've got an MDI application written in Delphi 2006 which runs XP with the default theme. </p>
<p>Is there a way of controlling the appearance of the MDI Children to avoid the large XP-style title bar on each window? </p>
<p>I've tried setting the <code>BorderStyle</code> of the <code>MDIChildren</code> to <code>bsSizeToolWin</code> but they are still rendered as normal Forms.</p>
| [
{
"answer_id": 8868,
"author": "Tim Sullivan",
"author_id": 722,
"author_profile": "https://Stackoverflow.com/users/722",
"pm_score": 2,
"selected": false,
"text": "TMyForm = class(TForm)\nprivate\n FCurrentModule : TFrame;\npublic\n property CurrentModule : TFrame read FModule write SetCurrentModule;\nend;\n\nprocedure TMyForm.SetCurrentModule(ACurrentModule : TFrame);\nbegin\n if assigned(FCurrentModule) then\n FreeAndNil(FCurrentModule); // You could cache this if you wanted\n FCurrentModule := ACurrentModule;\n if assigned(FCurrentModule) then\n begin\n FCurrentModule.Parent := Self;\n FCurrentModule.Align := alClient;\n end;\nend;\n MyForm.CurrentModule := TSomeFrame.Create(nil);\n"
},
{
"answer_id": 161214,
"author": "CoolMagic",
"author_id": 22641,
"author_profile": "https://Stackoverflow.com/users/22641",
"pm_score": 4,
"selected": true,
"text": "unit CHILDWIN;\ninterface\nuses Windows, Classes, Graphics, Forms, Controls, StdCtrls;\n\ntype\n TMDIChild = class(TForm)\n private\n { Private declarations }\n public\n { Public declarations }\n procedure CreateWindowHandle(const Params: TCreateParams); override;\n end;\n\nimplementation\n\n{$R *.dfm}\nprocedure TMDIChild.CreateWindowHandle(const Params: TCreateParams);\nbegin\n inherited CreateWindowHandle(Params);\n SetWindowLong(Handle, GWL_EXSTYLE, WS_EX_TOOLWINDOW);\nend;\nend.\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1008/"
] |
8,742 | <p>I'm trying to rebuild an old metronome application that was originally written using MFC in C++ to be written in .NET using C#. One of the issues I'm running into is getting the timer to "tick" accurately enough.</p>
<p>For example, assuming an easy BPM (beats per minute) of 120, the timer should tick every .5 seconds (or 500 milliseconds). Using this as the basis for the ticks, however, isn't entirely accurate as .NET only guarantees that your timer will not tick before the elapsed time has passed.</p>
<p>Currently, to get around this for the same 120 BPM example used above, I am setting the ticks to something like 100 milliseconds and only playing the click sound on every 5th timer tick. This does improve the accuracy quite a bit, but if feels like a bit of a hack.</p>
<p>So, what is the best way to get accurate ticks? I know there are more timers available than the windows forms timer that is readily available in Visual Studio, but I'm not really familiar with them.</p>
| [
{
"answer_id": 3852682,
"author": "yazanpro",
"author_id": 465495,
"author_profile": "https://Stackoverflow.com/users/465495",
"pm_score": 0,
"selected": false,
"text": "System.Windows.Forms.Timer"
},
{
"answer_id": 27548804,
"author": "yarony",
"author_id": 59403,
"author_profile": "https://Stackoverflow.com/users/59403",
"pm_score": 1,
"selected": false,
"text": "class DispatcherTimer\n{\n public TimeSpan Interval\n {\n set\n {\n ...\n _interval = value;\n // Notice below bug: ticks1 + milliseconds [Bug1]\n _dueTimeInTicks = Environment.TickCount + (int)_interval.TotalMilliseconds;\n }\n }\n}\n class Dispatcher\n{\n private object UpdateWin32TimerFromDispatcherThread(object unused)\n {\n ...\n _dueTimeInTicks = timer._dueTimeInTicks;\n SetWin32Timer(_dueTimeInTicks);\n }\n\n private void SetWin32Timer(int dueTimeInTicks)\n {\n ...\n // Notice below bug: (ticks1 + milliseconds) - ticks2 [Bug2 - almost cancels Bug1, delta is mostly milliseconds not ticks]\n int delta = dueTimeInTicks - Environment.TickCount; \n SafeNativeMethods.SetTimer( \n new HandleRef(this, _window.Value.Handle),\n TIMERID_TIMERS,\n delta); // <-- [Bug3 - if delta is ticks, it should be divided by TimeSpan.TicksPerMillisecond = 10000]\n }\n}\n class SafeNativeMethodsPrivate\n{\n ...\n [DllImport(ExternDll.User32, SetLastError = true, ExactSpelling=true, CharSet=System.Runtime.InteropServices.CharSet.Auto)]\n public static extern IntPtr SetTimer(HandleRef hWnd, int nIDEvent, int uElapse, NativeMethods.TimerProc lpTimerFunc);\n}\n uElapse [in]\nType: UINT\nThe time-out value, in milliseconds. // <-- milliseconds were needed eventually\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8742",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
8,756 | <p>Does anyone have any good starting points for me when looking at making web pages/sites/applications specifically for viewing on the iPhone?</p>
<p>I've looked at templates like the one <a href="http://blog.wired.com/monkeybites/2007/07/meet-joe-hewitt.html" rel="noreferrer">Joe Hewitt</a> has made, and also seen some templates I can purchase, which I haven't done yet.</p>
<p>I figured someone else had already started on this track and decided that I could probably leech on their newfound knowledge :)</p>
<p>So, does anyone have any pointers? I'm well aware of the problem that the more such a template/framework makes a web app look like a native iPhone app, the more likely I'm going to get into trouble because it just isn't, but for now I want a framework I can start building on, and then in the process figure out how to make it distinctive enough to be perceived as a web app as well as looking like a native iPhone application.</p>
<p>Specifically I'm looking for features like:</p>
<ul>
<li>stylesheets set up, or pointers to how to do them for iPhone</li>
<li>page flipping animation, ie. pick an item in a list, list scrolls out of view to the left and information for item scrolls in from the right</li>
<li>the animation part would have to work with dynamic pages, ie. not just one big page that has divs set up for each sub-item, which at least one such framework had as a sort of quick fix, I would need to have list item picking load the <em>page</em> for that item, and then when loaded, scroll to it</li>
</ul>
<hr>
<p><strong>Edit</strong>: To avoid people reading only the question and answering, before reading my other reply, I'll add my clarification for GPL licensing and similar issues here.</p>
<p>The framework I need to use can not be distributed under a license which would require me to license my own project out under a similar license. The GPL family of licenses allows for exceptions regarding library usage, but this won't apply to this since by necessity, the kind of framework I would need to use would be all source code.</p>
<p>The project can easily accomodate commercial libraries.</p>
<p>Also, I don't need a <em>library</em> or a <em>framework</em> as such, example files that look good and aren't overly obfuscated would be welcome as well.</p>
| [
{
"answer_id": 9137754,
"author": "Zungy",
"author_id": 1260447,
"author_profile": "https://Stackoverflow.com/users/1260447",
"pm_score": 0,
"selected": false,
"text": "<link rel=\"stylesheet\" type=\"text/css\" href=\"http://cache.saurik.com/menes/style.css\" /> body > panel > fieldset > div > a: hover {\nbackground-image: url('menutouched.png')\n}\n function swipePage(fromPage, toPage, backwards)\n{\ntoPage.style.left = “100%”;\ntoPage.setAttribute(“selected”, “true”);\nscrollTo(0, 1);\nvar percent = 100;\nvar timer = setInterval(function()\n{\npercent += animateX;\nif (percent <= 0)\n{\npercent = 0;\nfromPage.removeAttribute(\"selected\");\nclearInterval(timer);\n}\nfromPage.style.left = (backwards ? (100-percent) : (percent-100)) + \"%\";\ntoPage.style.left = (backwards ? -percent : percent) + \"%\";\n}, animateInterval);\n}\n body {\n-webkit-tap-highlight-color: rgba(0,0,0,0);\n-webkit-user-select: none;\n-webkit-text-size-adjust: none;\n-webkit-touch-callout: none;\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8756",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/267/"
] |
8,761 | <p>I'm updating some of our legacy C++ code to use the "MFC feature pack" that Microsoft released for Visual Studio 2008. We've used the new classes to derive our application from CFrameWndEx, and are applying the Office 2007 styles to give our application a more modern appearance. This gives us gradient filled window titles, status bars etc, and the use of the ribbon toolbars.</p>
<p>However, our application contains some owner drawn controls, and I'd like to update these to match the color scheme used by the feature pack. Ideally I'd like to know the light and shaded toolbar colors that are currently in use.</p>
<p>I've had a hunt around the documentation and web and have not yet found anything. Does anyone know how to find this information out?</p>
<p>[Edit]</p>
<p>In particular we need to find out which colors are being used at runtime. You can change the appearance of your application at runtime using the new static function CMFCVisualManager::SetDefaultManager.</p>
<p>The following msdn page shows you what kind of styles are available, in particular the Office2007 look:
<a href="http://msdn.microsoft.com/en-us/library/cc137831.aspx" rel="nofollow noreferrer">link to msdn</a></p>
| [
{
"answer_id": 9733,
"author": "Aidan Ryan",
"author_id": 1042,
"author_profile": "https://Stackoverflow.com/users/1042",
"pm_score": 0,
"selected": false,
"text": "CMFCVisualManager::GetSmartDockingBaseGuideColors()\nCMFCVisualManager::GetToolbarHighlightColor()\n"
},
{
"answer_id": 202080,
"author": "Rob",
"author_id": 9236,
"author_profile": "https://Stackoverflow.com/users/9236",
"pm_score": 1,
"selected": false,
"text": "afxGlobalData afxGlobalData.m_clrBarFace"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1078/"
] |
8,763 | <p>I'm trying to rebuild an old metronome application that was originally written using <code>MFC</code> in C++ to be written in <code>.NET</code> using <code>C#</code>. One of the issues I'm running into is playing the midi files that are used to represent the metronome "clicks".</p>
<p>I've found a few articles online about playing <code>MIDI</code> in .NET, but most of them seem to rely on custom libraries that someone has cobbled together and made available. I'm not averse to using these, but I'd rather understand for myself how this is being done, since it seems like it <em>should</em> be a mostly trivial exercise.</p>
<p>So, am I missing something? Or is it just difficult to use MIDI inside of a .NET application?</p>
| [
{
"answer_id": 8777,
"author": "John Sibly",
"author_id": 1078,
"author_profile": "https://Stackoverflow.com/users/1078",
"pm_score": 4,
"selected": true,
"text": "[DllImport(\"winmm.dll\")] \nstatic extern Int32 mciSendString(String command, StringBuilder buffer, \n Int32 bufferSize, IntPtr hwndCallback);\n"
},
{
"answer_id": 5625772,
"author": "Carra",
"author_id": 21679,
"author_profile": "https://Stackoverflow.com/users/21679",
"pm_score": 1,
"selected": false,
"text": "using WMPLib;\n//...\nWindowsMediaPlayer wmp = new WindowsMediaPlayer();\nwmp.URL = Path.Combine(Application.StartupPath ,\"Resources/mymidi1.mid\");\nwmp.controls.play();\n"
},
{
"answer_id": 22976812,
"author": "Phylliida",
"author_id": 2924421,
"author_profile": "https://Stackoverflow.com/users/2924421",
"pm_score": 1,
"selected": false,
"text": "[DllImport(\"winmm.dll\")]\nstatic extern Int32 mciSendString(String command, StringBuilder buffer, Int32 bufferSize, IntPtr hwndCallback);\n\npublic static void playMidi(String fileName, String alias)\n{\n mciSendString(\"open \" + fileName + \" type sequencer alias \" + alias, new StringBuilder(), 0, new IntPtr());\n mciSendString(\"play \" + alias, new StringBuilder(), 0, new IntPtr());\n}\n\npublic static void stopMidi(String alias)\n{\n mciSendString(\"stop \" + alias, null, 0, new IntPtr());\n mciSendString(\"close \" + alias, null, 0, new IntPtr());\n}\n [DllImport(\"winmm.dll\")]\nstatic extern Int32 mciSendString(String command, StringBuilder buffer,\n Int32 bufferSize, IntPtr hwndCallback);\n\npublic static Dictionary<String, bool> playingMidi = new Dictionary<String, bool>();\n\npublic static void PlayMidi(String fileName, String alias)\n{\n if (playingMidi.ContainsKey(alias))\n throw new Exception(\"Midi with alias '\" + alias + \"' is already playing\");\n\n playingMidi.Add(alias, false);\n\n Thread stoppingThread = new Thread(() => { StartAndStopMidiWithDelay(fileName, alias); });\n stoppingThread.Start();\n}\n\npublic static void StopMidiFromOtherThread(String alias)\n{\n if (!playingMidi.ContainsKey(alias))\n return;\n\n playingMidi[alias] = true;\n}\n\npublic static bool isPlaying(String alias)\n{\n return playingMidi.ContainsKey(alias);\n}\n\nprivate static void StartAndStopMidiWithDelay(String fileName, String alias)\n{\n mciSendString(\"open \" + fileName + \" type sequencer alias \" + alias, null, 0, new IntPtr());\n mciSendString(\"play \" + alias, null, 0, new IntPtr());\n\n StringBuilder result = new StringBuilder(100);\n mciSendString(\"set \" + alias + \" time format milliseconds\", null, 0, new IntPtr());\n mciSendString(\"status \" + alias + \" length\", result, 100, new IntPtr());\n\n int midiLengthInMilliseconds;\n Int32.TryParse(result.ToString(), out midiLengthInMilliseconds);\n\n Stopwatch timer = new Stopwatch();\n timer.Start();\n\n while(timer.ElapsedMilliseconds < midiLengthInMilliseconds && !playingMidi[alias])\n {\n\n }\n\n timer.Stop();\n\n StopMidi(alias);\n}\n\nprivate static void StopMidi(String alias)\n{\n if (!playingMidi.ContainsKey(alias))\n throw new Exception(\"Midi with alias '\" + alias + \"' is already stopped\");\n\n // Execute calls to close and stop the player, on the same thread as the play and open calls\n mciSendString(\"stop \" + alias, null, 0, new IntPtr());\n mciSendString(\"close \" + alias, null, 0, new IntPtr());\n\n playingMidi.Remove(alias);\n}\n"
},
{
"answer_id": 54442916,
"author": "Maxim",
"author_id": 2975589,
"author_profile": "https://Stackoverflow.com/users/2975589",
"pm_score": 2,
"selected": false,
"text": "using Melanchall.DryWetMidi.Devices;\nusing Melanchall.DryWetMidi.Core;\n\n// ...\n\nvar midiFile = MidiFile.Read(\"Greatest song ever.mid\");\n\nusing (var outputDevice = OutputDevice.GetByName(\"Microsoft GS Wavetable Synth\"))\n{\n midiFile.Play(outputDevice);\n}\n Play Playback Start Stop var playback = midiFile.GetPlayback(outputDevice);\n\n// You can even loop playback and speed it up\nplayback.Loop = true;\nplayback.Speed = 2.0;\n\nplayback.Start();\n\n// ...\n\nplayback.Stop();\n\n// ...\n\nplayback.Dispose();\noutputDevice.Dispose();\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1108/"
] |
8,790 | <p>I have a build script and as part of that script it copies a jar file to a directory, for ease lets call it the utils jar. the utils jar is built by another build script sitting in another directory. What im trying to do have my build script run the utils build script so that I can ensure the utils jar is up to date.</p>
<p>So I know I need to import the utils build file.</p>
<pre><code><import file="../utils/build/build.xml" />
</code></pre>
<p>Which doesn't work because the import task, unlike almost every other ant taks, doesn't run from basedir, it runs from the pwd. So to get around that I have this little ditty, which does successfully import the build file</p>
<pre><code> <property name="baseDirUpOne" location=".." />
<import file="${baseDirUpOne}/utils/build/build.xml" />
</code></pre>
<p>So now that ive solved my import problem I need to call the task, well that should be easy right:</p>
<pre><code><antcall target="utils.package" />
</code></pre>
<p><em>note that in the above, utils is the project name of ../utils/build/build.xml</em></p>
<p>the problem I'm now running into is that ant call doesn't execute in ../utils/build so what I need, and cant find, is a runat property or something similar, essentially:</p>
<pre><code><antcall target="utils.package" runat="../utils/build" />
</code></pre>
<p>The reason I need this is that in my utils build file the step to select which code to copy to the jar is based on relative paths so as to avoid hardcoding paths in my ant file. Any ideas? </p>
| [
{
"answer_id": 8805,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 6,
"selected": true,
"text": "<target name=\"build-tests\">\n <subant target=\"build\">\n <fileset dir=\"${test.home}\" includes=\"build.xml\"/>\n </subant>\n</target>\n subant antcall"
},
{
"answer_id": 8810,
"author": "James Sulak",
"author_id": 207,
"author_profile": "https://Stackoverflow.com/users/207",
"pm_score": 3,
"selected": false,
"text": "<ant antfile=\"${baseDirUpOne}/utils/build/build.xml\" dir=\"../utils/build\" />\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8790",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/292/"
] |
8,795 | <p>I would like to create a stored procedure in MySQL that took a list as argument. For example, say that I would like to be able to set multiple tags for an item in one call, then what I want to do is to define a procedure that takes the ID of the item and a list of tags to set. However, I can't seem to find any way to do this, there is no list datatype, as far as I'm aware, but can it be emulated somehow? Could the list of tags be a comma-separated string, which can somehow be split and looped over?</p>
<p>How do you usually work with lists in MySQL stored procedures?</p>
| [
{
"answer_id": 8823,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 0,
"selected": false,
"text": "SELECT SUBSTRING_INDEX(SUBSTRING_INDEX('www.google.com', '.', -2), '.', 1);\n"
},
{
"answer_id": 8837,
"author": "Clyde",
"author_id": 945,
"author_profile": "https://Stackoverflow.com/users/945",
"pm_score": 1,
"selected": false,
"text": "GUID guid = GenerateGUID()\ntry\n for each customer in customerList { INSERT(guid, customerId) }\n ExecuteSQLPocedure(guid)\n --the procedure can inner-join to the list table to get the list\nfinally\n DELETE WHERE UniqueID=guid \n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8795",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1109/"
] |
8,800 | <p>So I've been poking around with C# a bit lately, and all the Generic Collections have me a little confused. Say I wanted to represent a data structure where the head of a tree was a key value pair, and then there is one optional list of key value pairs below that (but no more levels than these). Would this be suitable?</p>
<pre><code>public class TokenTree
{
public TokenTree()
{
/* I must admit to not fully understanding this,
* I got it from msdn. As far as I can tell, IDictionary is an
* interface, and Dictionary is the default implementation of
* that interface, right?
*/
SubPairs = new Dictionary<string, string>();
}
public string Key;
public string Value;
public IDictionary<string, string> SubPairs;
}
</code></pre>
<p>It's only really a simple shunt for passing around data.</p>
| [
{
"answer_id": 8811,
"author": "Adam Haile",
"author_id": 194,
"author_profile": "https://Stackoverflow.com/users/194",
"pm_score": 8,
"selected": true,
"text": "KeyValuePair<string, string> myKeyValuePair = new KeyValuePair<string,string>(\"defaultkey\", \"defaultvalue\");\n"
},
{
"answer_id": 8816,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 4,
"selected": false,
"text": "public class TokenTree : Dictionary<string, string>\n{\n public IDictionary<string, string> SubPairs;\n}\n"
},
{
"answer_id": 8818,
"author": "Lasse V. Karlsen",
"author_id": 267,
"author_profile": "https://Stackoverflow.com/users/267",
"pm_score": 2,
"selected": false,
"text": "foreach(object key in h.keys)\n{\n string keyAsString = key.ToString(); // btw, this is unnecessary\n string valAsString = h[key].ToString();\n\n System.Diagnostics.Debug.WriteLine(keyAsString + \" \" + valAsString);\n}\n foreach(string key in d.keys)\n{\n string valAsString = d[key].ToString();\n\n System.Diagnostics.Debug.WriteLine(key + \" \" + valAsString);\n}\n"
},
{
"answer_id": 8826,
"author": "kokos",
"author_id": 1065,
"author_profile": "https://Stackoverflow.com/users/1065",
"pm_score": 1,
"selected": false,
"text": "class Tree < T > : Dictionary < T, IList< Tree < T > > > \n{ \n} \n"
},
{
"answer_id": 8834,
"author": "Shaun Austin",
"author_id": 1120,
"author_profile": "https://Stackoverflow.com/users/1120",
"pm_score": 3,
"selected": false,
"text": "public class TokenTree\n{\n public TokenTree()\n {\n tree = new Dictionary<string, IDictionary<string,string>>();\n }\n\n IDictionary<string, IDictionary<string, string>> tree; \n}\n IDictionary IList<KeyValuePair<string, string>>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8800",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/61/"
] |
8,832 | <p>I hope I can explain this clearly enough, but if not let me know and I'll try to clarify.</p>
<p>I'm currently developing a site using ColdFusion and have a mod_rewrite rule in place to make it look like the site is using PHP. Any requests for index.php get processed by index.cfm (the rule maps *.php to *.cfm).</p>
<p>This works great - so far, so good. The problem is that I want to return a 404 status code if index.cfm (or any ColdFusion page) is requested directly.</p>
<p>If I try to block access to *.cfm files using mod_rewrite it also returns a 404 for requests to *.php.</p>
<p>I figure I might have to change my Apache config rather than use .htaccess</p>
| [
{
"answer_id": 12062,
"author": "T Percival",
"author_id": 954,
"author_profile": "https://Stackoverflow.com/users/954",
"pm_score": 2,
"selected": true,
"text": "S 404 RewriteEngine on\n\n# Do not separate these two rules so long as the first has S=1\nRewriteRule (.*)\\.php$ $1.cfm [S=1]\nRewriteRule \\.cfm$ - [R=404]\n Alias PT"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8832",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1025/"
] |
8,864 | <p>Is there a difference between <code>NULL</code> and <code>null</code> in PHP? Sometimes they seem to be interchangeable and sometimes not.</p>
<p>edit: for some reason when I read the documentation linked to in the answer (before posting this question) I read it as "case sensitive" instead of "case insensitive" which was the whole reason I posted this question in the first place...</p>
| [
{
"answer_id": 16629586,
"author": "Desolator",
"author_id": 326904,
"author_profile": "https://Stackoverflow.com/users/326904",
"pm_score": 4,
"selected": false,
"text": "True False"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8864",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/58/"
] |
8,880 | <p>Using the Windows API, how can I get a list of domains on my network?</p>
| [
{
"answer_id": 8881,
"author": "JosephStyons",
"author_id": 672,
"author_profile": "https://Stackoverflow.com/users/672",
"pm_score": 2,
"selected": false,
"text": "SV_TYPE_DOMAIN_ENUM <snip>\ntype\n NET_API_STATUS = DWORD;\n PSERVER_INFO_100 = ^SERVER_INFO_100;\n SERVER_INFO_100 = packed record\n sv100_platform_id : DWORD;\n sv100_name : PWideChar;\nend;\n\nfunction NetServerEnum( //get a list of pcs on the network (same as DOS cmd \"net view\")\n const servername : PWideChar;\n const level : DWORD;\n const bufptr : Pointer;\n const prefmaxlen : DWORD;\n const entriesread : PDWORD;\n const totalentries : PDWORD;\n const servertype : DWORD;\n const domain : PWideChar;\n const resume_handle : PDWORD\n) : NET_API_STATUS; stdcall; external 'netapi32.dll';\n\nfunction NetApiBufferFree( //memory mgmt routine\n const Buffer : Pointer\n) : NET_API_STATUS; stdcall; external 'netapi32.dll';\n\nconst\n MAX_PREFERRED_LENGTH = DWORD(-1);\n NERR_Success = 0;\n SV_TYPE_ALL = $FFFFFFFF;\n SV_TYPE_DOMAIN_ENUM = $80000000;\n\n\nfunction TNetwork.ComputersInDomain: TStringList;\nvar\n pBuffer : PSERVER_INFO_100;\n pWork : PSERVER_INFO_100;\n dwEntriesRead : DWORD;\n dwTotalEntries : DWORD;\n i : integer;\n dwResult : NET_API_STATUS;\nbegin\n Result := TStringList.Create;\n Result.Clear;\n\n dwResult := NetServerEnum(nil,100,@pBuffer,MAX_PREFERRED_LENGTH,\n @dwEntriesRead,@dwTotalEntries,SV_TYPE_DOMAIN_ENUM,\n PWideChar(FDomainName),nil);\n\n if dwResult = NERR_SUCCESS then begin\n try\n pWork := pBuffer;\n for i := 1 to dwEntriesRead do begin\n Result.Add(pWork.sv100_name);\n inc(pWork);\n end; //for i\n finally\n NetApiBufferFree(pBuffer);\n end; //try-finally\n end //if no error\n else begin\n raise Exception.Create('Error while retrieving computer list from domain ' +\n FDomainName + #13#10 +\n SysErrorMessage(dwResult));\n end;\nend;\n<snip>\n"
},
{
"answer_id": 8888,
"author": "Shane O'Grady",
"author_id": 1115,
"author_profile": "https://Stackoverflow.com/users/1115",
"pm_score": 2,
"selected": true,
"text": "' This VBScript code gets the list of the domains contained in the \n' forest that the user running the script is logged into\n\n' ---------------------------------------------------------------\n' From the book \"Active Directory Cookbook\" by Robbie Allen\n' Publisher: O'Reilly and Associates\n' ISBN: 0-596-00466-4\n' Book web site: http://rallenhome.com/books/adcookbook/code.html\n' ---------------------------------------------------------------\n\nset objRootDSE = GetObject(\"LDAP://RootDSE\")\nstrADsPath = \"<GC://\" & objRootDSE.Get(\"rootDomainNamingContext\") & \">;\"\nstrFilter = \"(objectcategory=domainDNS);\"\nstrAttrs = \"name;\"\nstrScope = \"SubTree\"\n\nset objConn = CreateObject(\"ADODB.Connection\")\nobjConn.Provider = \"ADsDSOObject\"\nobjConn.Open \"Active Directory Provider\"\nset objRS = objConn.Execute(strADsPath & strFilter & strAttrs & strScope)\nobjRS.MoveFirst\nwhile Not objRS.EOF\n Wscript.Echo objRS.Fields(0).Value\n objRS.MoveNext\nwend\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8880",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/672/"
] |
8,896 | <p>Does anyone know <strong>IF</strong>, <strong>WHEN</strong> or <strong>HOW</strong> I can get <a href="https://memcached.org/" rel="noreferrer">Memcached</a> running on a Windows 64bit environment? </p>
<p>I'm setting up a new hosting solution and would much prefer to run a 64bit OS, and since it's an ASP.Net MVC solution with SQL Server DB, the OS is either going to be Windows Server 2003 or (hopefully!) 2008.</p>
<p>I know that this could spill over into a debate regarding 32bit vs 64bit on servers, but let's just say that my preference is 64bit and that I have some <a href="https://blogs.technet.microsoft.com/mscom/2005/09/26/running-microsoft-com-on-64-bitthe-dependencies-the-goodness-the-gotchas/" rel="noreferrer">very</a> <a href="https://blog.codinghorror.com/64-bit-desktop-vs-64-bit-server/" rel="noreferrer">good</a> reasons.</p>
<p>So far, I've tried a number of options and found a <a href="http://blog.rakeshxp.com/2007/09/running-memcached-on-windows.html" rel="noreferrer">bit</a> of <a href="http://www.splinedancer.com/memcached-win32/" rel="noreferrer">help</a> related to getting this up on a 32bit machine (and succeeded I might add), but since the original <a href="http://jehiah.cz/projects/memcached-win32/" rel="noreferrer">Windows port</a> is Win32 specific, this is hardly going to help when installing as a service on x64. It also has a dependency on the <a href="https://libevent.org/" rel="noreferrer">libevent</a> for which I can only get a Win32 compiled version.</p>
<p>I suspect that simply loading all this up in C++ and hitting "compile" (for 64bit) wouldn't work, not least because of the intricate differences in 32 and 64bit architectures, but I'm wondering if anyone is working on getting this off the ground? Unfortunately, my expertise lie in managed code (C#) only, otherwise I would try and take this on myself, but I can't believe I'm the only guy out there trying to get <a href="https://memcached.org/" rel="noreferrer">memcached</a> running on a 64 bit Windows server....am I?</p>
<hr>
<p>Update</p>
<p><strong>Yes I'm afraid I'm still looking for an answer to this - all my efforts (with my pathetic C++ skills) to make a stable build have failed - I've trashed one server and 3 VM's just trying it out so now I turn to the real experts.
Is anyone planning on porting this to 64bit? Or are you really suggesting that I use MS Velocity instead? I shudder at the thought.</strong></p>
<hr>
<p>Update:
@Lars - I do use Enyim actually - it's very good, but what you're referring to is a client, rather than the server part.</p>
<p>@DannySmurf - I've only been able to install it as a service on a 32 bit OS. 64 bit OS rejects the installation of this Win32 service. Of course yes, lots of Win32 code works seamlessly on x64 architecture, hence you can run 32bit apps (like Office for instance) or games on Vista/XP 64 etc, but this doesn't translate directly when it comes to services. I'm no expert, I suspect that it has to do with the syncs or eventing that services need to subscribe to, and I suspect that 64 and 32 don't play nicely. I'm happy to be corrected on any of this, but to answer your question - yes I have tried.</p>
<p>@OJ - thanks very much for the straight-forward response. I thought as much, but wasn't sure if anyone else had suggestions or had already gone down this route. Maybe when StackOverflow is LIVE, then more people will respond and let me know if this is something being looked into, and although I can try and compile it myself - I simply can't "trust" (with my C++ experience level) that it would provide "Enterprise Level" reliability in such a crucial component of large scalable solutions. I think it would need educated intervention rather than my unsanitised experimental approach before I could be confident. One little oversight on my part, could bring the site down. Oh well... till next time.</p>
| [
{
"answer_id": 57390546,
"author": "David Ferenczy Rogožan",
"author_id": 971141,
"author_profile": "https://Stackoverflow.com/users/971141",
"pm_score": 3,
"selected": false,
"text": "nssm install memcached c:\\path\\to\\memcached.exe\nnssm start memcached\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8896",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1107/"
] |
8,941 | <p><strong>Is there a way to enforce/limit the types that are passed to primitives?</strong> <em>(bool, int, string, etc.)</em></p>
<p>Now, I know you can limit the generic type parameter to a type or interface implementation via the <em>where</em> clause. However, this doesn't fit the bill for primitives (AFAIK) because they do not all have a common ground (apart from <em>object</em> before someone says! :P).</p>
<p>So, my current thoughts are to just grit my teeth and do a big <em>switch</em> statement and throw an <em>ArgumentException</em> on failure.</p>
<hr />
<p><strong>EDIT 1:</strong></p>
<p>Just to clarify:</p>
<p>The code definition should be like this:</p>
<pre><code>public class MyClass<GenericType> ....
</code></pre>
<p>And instantiation:</p>
<pre><code>MyClass<bool> = new MyClass<bool>(); // Legal
MyClass<string> = new MyClass<string>(); // Legal
MyClass<DataSet> = new MyClass<DataSet>(); // Illegal
MyClass<RobsFunkyHat> = new MyClass<RobsFunkyHat>(); // Illegal (but looks awesome!)
</code></pre>
<hr />
<p><strong>EDIT 2</strong></p>
<p>@Jon Limjap - Good point, and something I was already considering. I'm sure there is a generic method that can be used to determine if the type is of a value or reference type.</p>
<p>This could be useful in instantly removing a lot of the objects I don't want to deal with (but then you need to worry about the structs that are used such as <em>Size</em> ). Interesting problem no? :)</p>
<p>Here it is:</p>
<pre><code>where T: struct
</code></pre>
<p>Taken from <a href="http://msdn.microsoft.com/en-us/library/d5x73970.aspx" rel="nofollow noreferrer">MSDN</a>.</p>
<hr />
<p>I'm curious. Could this be done in .NET 3.x using extension methods? Create an interface, and implement the interface in the extension methods (which would probably be cleaner than a bit fat switch). Plus if you then need to later extend to any lightweight custom types, they can also implement the same interface, with no changes required to the base code.</p>
<p>What do you guys think?</p>
<p>The sad news is I am working in Framework 2!! :D</p>
<hr />
<p><strong>EDIT 3</strong></p>
<p>This was so simple following on from <a href="https://stackoverflow.com/questions/8941/generic-type-checking#8956">Jon Limjaps Pointer</a>.. So simple I almost want to cry, but it's great because the code works like a charm!</p>
<p>So here is what I did (you'll laugh!):</p>
<h2>Code added to the generic class</h2>
<pre><code>bool TypeValid()
{
// Get the TypeCode from the Primitive Type
TypeCode code = Type.GetTypeCode(typeof(PrimitiveDataType));
// All of the TypeCode Enumeration refer Primitive Types
// with the exception of Object and Empty (Null).
// Since I am willing to allow Null Types (at this time)
// all we need to check for is Object!
switch (code)
{
case TypeCode.Object:
return false;
default:
return true;
}
}
</code></pre>
<p>Then a little utility method to check the type and throw an exception,</p>
<pre><code>private void EnforcePrimitiveType()
{
if (!TypeValid())
throw new InvalidOperationException(
"Unable to Instantiate SimpleMetadata based on the Generic Type of '" + typeof(PrimitiveDataType).Name +
"' - this Class is Designed to Work with Primitive Data Types Only.");
}
</code></pre>
<p>All that then needs to be done is to call <em>EnforcePrimitiveType()</em> in the classes constructors. Job done! :-)</p>
<p>The only downside, it only throws an exception at runtime (obviously) rather than design time. But that's no big deal and could be picked up with utilities like <a href="http://en.wikipedia.org/wiki/FxCop" rel="nofollow noreferrer">FxCop</a> (which we don't use at work).</p>
<p>Special thanks to Jon Limjap on this one!</p>
| [
{
"answer_id": 8945,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 6,
"selected": false,
"text": "public class Class1<GenericType> where GenericType : struct\n{\n}\n"
},
{
"answer_id": 8954,
"author": "JoshL",
"author_id": 630,
"author_profile": "https://Stackoverflow.com/users/630",
"pm_score": 2,
"selected": false,
"text": "MyClass<>"
},
{
"answer_id": 8956,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 6,
"selected": true,
"text": "TypeCode TypeCode enum GetType() typeof() static void WriteObjectInfo(object testObject)\n{\n TypeCode typeCode = Type.GetTypeCode( testObject.GetType() );\n\n switch( typeCode )\n {\n case TypeCode.Boolean:\n Console.WriteLine(\"Boolean: {0}\", testObject);\n break;\n\n case TypeCode.Double:\n Console.WriteLine(\"Double: {0}\", testObject);\n break;\n\n default:\n Console.WriteLine(\"{0}: {1}\", typeCode.ToString(), testObject);\n break;\n }\n }\n}\n"
},
{
"answer_id": 8980,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 5,
"selected": false,
"text": "//Force T to be a value (primitive) type.\npublic class Class1<T> where T: struct\n\n//Force T to be a reference type.\npublic class Class1<T> where T: class\n\n//Force T to be a parameterless constructor.\npublic class Class1<T> where T: new()\n"
},
{
"answer_id": 69673,
"author": "Doug McClean",
"author_id": 11173,
"author_profile": "https://Stackoverflow.com/users/11173",
"pm_score": 2,
"selected": false,
"text": "class MyClass<T>\n{\n private readonly T _value;\n\n private MyClass(T value) { _value = value; }\n\n public static MyClass<int> FromInt32(int value) { return new MyClass<int>(value); }\n public static MyClass<string> FromString(string value) { return new MyClass<string>(value); }\n // etc for all the primitive types, or whatever other fixed set of types you are concerned about\n}\n MyClass<AnyTypeItDoesntMatter>.FromInt32 MyClass MyClass<T> MyClass MyClass MyClass MyClass<T> MyClass.MyClass<T> MyClass<T> MyClass MyClass<T> MyClass<AnyTypeItDoesntMatter> MyClass MyClass<AnyTypeItDoesntMatter> MyClass<int> MyClass.FromString"
},
{
"answer_id": 217079,
"author": "Vivek",
"author_id": 7418,
"author_profile": "https://Stackoverflow.com/users/7418",
"pm_score": 2,
"selected": false,
"text": "EnforcePrimitiveType typeof(PrimitiveDataType).IsPrimitive"
},
{
"answer_id": 686709,
"author": "Matthew Boehlig",
"author_id": 83235,
"author_profile": "https://Stackoverflow.com/users/83235",
"pm_score": 2,
"selected": false,
"text": "Enum TypeValid TypeCode Integer Enum Private Function TypeValid() As Boolean\n Dim g As Type = GetType(T)\n Dim code As TypeCode = Type.GetTypeCode(g)\n\n ' All of the TypeCode Enumeration refer Primitive Types\n ' with the exception of Object and Empty (Nothing).\n ' Note: must also catch Enum as its type is Integer.\n Select Case code\n Case TypeCode.Object\n Return False\n Case Else\n ' Enum's TypeCode is Integer, so check BaseType\n If g.BaseType Is GetType(System.Enum) Then\n Return False\n Else\n Return True\n End If\n End Select\nEnd Function\n"
},
{
"answer_id": 11690199,
"author": "gimlichael",
"author_id": 175073,
"author_profile": "https://Stackoverflow.com/users/175073",
"pm_score": 2,
"selected": false,
"text": " public class MyClass<TKey>\n where TKey : IConvertible\n{\n // class intentionally abbreviated\n}\n"
},
{
"answer_id": 72332537,
"author": "Chris Kao",
"author_id": 9823251,
"author_profile": "https://Stackoverflow.com/users/9823251",
"pm_score": 0,
"selected": false,
"text": "struct var intClass = new PrimitivesOnly<int>();\nvar doubleClass = new PrimitivesOnly<double>();\nvar boolClass = new PrimitivesOnly<bool>();\nvar stringClass = new PrimitivesOnly<string>();\nvar myAwesomeClass = new PrimitivesOnly<MyAwesomeClass>(); // illegal\n\n// The line below encounter issue when using \"string\" type\n// class PrimitivesOnly<T> where T : struct\nclass PrimitivesOnly<T> where T : IConvertible\n{\n \n}\n\nclass MyAwesomeClass\n{\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8941",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/832/"
] |
8,948 | <p>Is there a maintained package I can use to retrieve and set MP3 ID3 metadata using Python?</p>
| [
{
"answer_id": 9358,
"author": "Harley Holcombe",
"author_id": 1057,
"author_profile": "https://Stackoverflow.com/users/1057",
"pm_score": 4,
"selected": false,
"text": "from ID3 import *\ntry:\n id3info = ID3('file.mp3')\n print id3info\n # Change the tags\n id3info['TITLE'] = \"Green Eggs and Ham\"\n id3info['ARTIST'] = \"Dr. Seuss\"\n for k, v in id3info.items():\n print k, \":\", v\nexcept InvalidTagError, message:\n print \"Invalid ID3 tag:\", message\n"
},
{
"answer_id": 102285,
"author": "Owen",
"author_id": 2109,
"author_profile": "https://Stackoverflow.com/users/2109",
"pm_score": 7,
"selected": false,
"text": "python setup.py install import eyeD3\n tag = eyeD3.Tag()\n tag.link(\"/some/file.mp3\")\n print tag.getArtist()\n print tag.getAlbum()\n print tag.getTitle()\n if eyeD3.isMp3File(f):\n audioFile = eyeD3.Mp3AudioFile(f)\n tag = audioFile.getTag()\n tag.link(\"/some/file.mp3\", eyeD3.ID3_V2)\n tag.link(\"/some/file.mp3\", eyeD3.ID3_V1)\n tag.link(\"/some/file.mp3\", eyeD3.ID3_ANY_VERSION) # The default.\n tag = eyeD3.Tag()\n tag.link(\"/some/file.mp3\")\n for frame in tag.frames:\n print frame\n tag.setArtist(u\"Cro-Mags\")\n tag.setAlbum(u\"Age of Quarrel\")\n tag.update()\n tag.update(eyeD3.ID3_V1_1)\n tag.link(\"/some/file.mp3\")\n tag.remove()\n tag.update()\n tag = eyeD3.Tag()\n tag.link('/some/file.mp3') # no tag in this file, link returned False\n tag.header.setVersion(eyeD3.ID3_V2_3)\n tag.setArtist('Fugazi')\n tag.update()\n"
},
{
"answer_id": 4559380,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 3,
"selected": false,
"text": ">>> import songdetails\n>>> song = songdetails.scan(\"data/song.mp3\")\n>>> print song.duration\n0:03:12\n >>> import songdetails\n>>> song = songdetails.scan(\"data/commit.mp3\")\n>>> song.artist = \"Great artist\"\n>>> song.save()\n"
},
{
"answer_id": 34970600,
"author": "Chris Redford",
"author_id": 130427,
"author_profile": "https://Stackoverflow.com/users/130427",
"pm_score": 5,
"selected": false,
"text": "eyed3 NotImplementedError(\"Unable to write ID3 v2.2\") mutagen EasyID3 from mutagen.easyid3 import EasyID3\n\naudio = EasyID3(\"example.mp3\")\naudio['title'] = u\"Example Title\"\naudio['artist'] = u\"Me\"\naudio['album'] = u\"My album\"\naudio['composer'] = u\"\" # clear\naudio.save()\n"
},
{
"answer_id": 38891913,
"author": "Abhijeet Deshani",
"author_id": 4972892,
"author_profile": "https://Stackoverflow.com/users/4972892",
"pm_score": 3,
"selected": false,
"text": "import songdetails\nsong = songdetails.scan(\"blah.mp3\")\nif song is not None:\n print song.artist\n import songdetails\nsong = songdetails.scan(\"blah.mp3\")\nif song is not None:\n song.artist = u\"The Great Blah\"\n song.save()\n import glob\nsongs = glob.glob('*') # script should be in directory of songs.\nfor song in songs:\n # do the above work.\n"
},
{
"answer_id": 49719777,
"author": "Elijah",
"author_id": 7732434,
"author_profile": "https://Stackoverflow.com/users/7732434",
"pm_score": 2,
"selected": false,
"text": " import eyed3\n\n audiofile = eyed3.load(\"some/file.mp3\")\n print(audiofile.tag.artist)\n print(audiofile.tag.album)\n print(audiofile.tag.album_artist)\n print(audiofile.tag.title)\n print(audiofile.tag.track_num)\n import eyed3\n\n audiofile = eyed3.load(\"some/file.mp3\")\n audiofile.tag.artist = u\"Integrity\"\n audiofile.tag.album = u\"Humanity Is The Devil\"\n audiofile.tag.album_artist = u\"Integrity\"\n audiofile.tag.title = u\"Hollow\"\n audiofile.tag.track_num = 2\n"
},
{
"answer_id": 49848525,
"author": "Marc Maxmeister",
"author_id": 536538,
"author_profile": "https://Stackoverflow.com/users/536538",
"pm_score": 3,
"selected": false,
"text": "pip install pip from tinytag import TinyTag\ntag = TinyTag.get('/some/music.mp3')\n tag.album # album as string\ntag.albumartist # album artist as string\ntag.artist # artist name as string\ntag.audio_offset # number of bytes before audio data begins\ntag.bitrate # bitrate in kBits/s\ntag.disc # disc number\ntag.disc_total # the total number of discs\ntag.duration # duration of the song in seconds\ntag.filesize # file size in bytes\ntag.genre # genre as string\ntag.samplerate # samples per second\ntag.title # title of the song\ntag.track # track number as string\ntag.track_total # total number of tracks as string\ntag.year # year or data as string\n"
},
{
"answer_id": 51044551,
"author": "Ashish Shirodkar",
"author_id": 8920642,
"author_profile": "https://Stackoverflow.com/users/8920642",
"pm_score": 2,
"selected": false,
"text": "- artist;\n- album;\n- song;\n- track;\n- comment;\n- year;\n- genre;\n- band;\n- composer;\n- copyright;\n- url;\n- publisher.\n from mp3_tagger import MP3File\n\n# Create MP3File instance.\nmp3 = MP3File('File_Name.mp3')\n\n# Get all tags.\ntags = mp3.get_tags()\nprint(tags)\n"
},
{
"answer_id": 60105280,
"author": "apokhi",
"author_id": 12743260,
"author_profile": "https://Stackoverflow.com/users/12743260",
"pm_score": 1,
"selected": false,
"text": "import eyed3\nimport os\n\nfor root, dirs, files in os.walk(folderp):\n for file in files:\n try:\n if file.find(\".mp3\") < 0:\n continue\n path = os.path.abspath(os.path.join(root , file))\n t = eyed3.load(path)\n print(t.tag.title , t.tag.artist)\n #print(t.getArtist())\n except Exception as e:\n print(e)\n continue\n"
},
{
"answer_id": 60625881,
"author": "Love and peace - Joe Codeswell",
"author_id": 601770,
"author_profile": "https://Stackoverflow.com/users/601770",
"pm_score": 3,
"selected": false,
"text": "1.3.0 (2020-03-09):\nadded option to ignore encoding errors ignore_errors #73\nImproved text decoding for many malformed files\n MP3 (ID3 v1, v1.1, v2.2, v2.3+)\nWave/RIFF\nOGG\nOPUS\nFLAC\nWMA\nMP4/M4A/M4B\n from tinytag import TinyTag\n\nfileNameL ='''0bd1ab5f-e42c-4e48-a9e6-b485664594c1.mp3\n0ea292c0-2c4b-42d4-a059-98192ac8f55c.mp3\n1c49f6b7-6f94-47e1-a0ea-dd0265eb516c.mp3\n5c706f3c-eea4-4882-887a-4ff71326d284.mp3\n'''.split()\n\nfor fn in fileNameL:\n fpath = './data/'+fn\n tag = TinyTag.get(fpath)\n print()\n print('\"artist\": \"%s\",' % tag.artist)\n print('\"album\": \"%s\",' % tag.album)\n print('\"title\": \"%s\",' % tag.title)\n print('\"duration(secs)\": \"%s\",' % tag.duration)\n\n JoeTagPj>python joeTagTest.py\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"17. Thomas Middleditch and Ben Schwartz\",\n\"duration(secs)\": \"3565.1829583532785\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"Are you ready to make friends?\",\n\"duration(secs)\": \"417.71840447045264\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"Introducing Conan’s new podcast\",\n\"duration(secs)\": \"327.22187551899646\",\n\n\"artist\": \"Conan O’Brien Needs A Friend\",\n\"album\": \"Conan O’Brien Needs A Friend\",\n\"title\": \"19. Ray Romano\",\n\"duration(secs)\": \"3484.1986772305863\",\n\nC:\\1d\\PodcastPjs\\JoeTagPj>\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/145/"
] |
8,966 | <p>I want to implement a paperless filing system and was looking to use WIA with C# for the image acquisition. There are quite a few sample projects on CodeProject, etc. However, after downloading every one of them that I can find, I have run into a problem.</p>
<p>In each and every one of them, the reference to WIALib is broken. When I go to add "Microsoft Windows Image Acquisition" as a reference, the only version available on my development workstation (also the machine that will run this) is 2.0.</p>
<p>Unfortunately, every one of these sample projects appear to have been coded against 1.x. The reference goes in as "WIA" instead of "WIALib". I took a shot, just changing the namespace import, but clearly the API is drastically different.</p>
<p>Is there any information on either implementing v2.0 or on upgrading one of these existing sample projects out there?</p>
| [
{
"answer_id": 107940,
"author": "Paul Jenkins",
"author_id": 657177,
"author_profile": "https://Stackoverflow.com/users/657177",
"pm_score": 6,
"selected": true,
"text": "const string wiaFormatJPEG = \"{B96B3CAE-0728-11D3-9D7B-0000F81EF32E}\";\nCommonDialogClass wiaDiag = new CommonDialogClass();\nWIA.ImageFile wiaImage = null;\n\nwiaImage = wiaDiag.ShowAcquireImage(\n WiaDeviceType.UnspecifiedDeviceType, \n WiaImageIntent.GrayscaleIntent, \n WiaImageBias.MaximizeQuality, \n wiaFormatJPEG, true, true, false);\n\nWIA.Vector vector = wiaImage.FileData;\n Image i = Image.FromStream(new MemoryStream((byte[])vector.get_BinaryData()));\ni.Save(filename)\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8966",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1124/"
] |
8,970 | <p>Is it possible to access the iSight camera on a macbook programmatically? By this I mean I would like to be able to just grab still frames from the iSight camera on command and then do something with them. If so, is it only accessible using objective c, or could other languages be used as well? </p>
| [
{
"answer_id": 9975,
"author": "Theo",
"author_id": 1109,
"author_profile": "https://Stackoverflow.com/users/1109",
"pm_score": 1,
"selected": false,
"text": "isightcapture"
},
{
"answer_id": 10698,
"author": "Nick Brosnahan",
"author_id": 528,
"author_profile": "https://Stackoverflow.com/users/528",
"pm_score": 3,
"selected": false,
"text": "require 'osx/cocoa'\nOSX.require_framework(\"/System/Library/Frameworks/QTKit.framework\")\n\nOSX::QTCaptureDevice.inputDevices.each do |device|\n puts device.localizedDisplayName\nend\n"
},
{
"answer_id": 2193100,
"author": "meduz",
"author_id": 234547,
"author_profile": "https://Stackoverflow.com/users/234547",
"pm_score": 0,
"selected": false,
"text": "import motmot.cam_iface.cam_iface_ctypes as cam_iface\nimport numpy as np\n\nmode_num = 0\ndevice_num = 0\nnum_buffers = 32\n\ncam = cam_iface.Camera(device_num,num_buffers,mode_num)\ncam.start_camera()\nframe = np.asarray(cam.grab_next_frame_blocking())\nprint 'grabbed frame with shape %s'%(frame.shape,)\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/8970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/85/"
] |
9,002 | <p>When I use the sp_send_dbmail stored procedure, I get a message saying that my mail was queued. However, it never seems to get delivered. I can see them in the queue if I run this SQL:</p>
<pre><code>SELECT * FROM msdb..sysmail_allitems WHERE sent_status = 'unsent'
</code></pre>
<p>This SQL returns a 1:</p>
<pre><code>SELECT is_broker_enabled FROM sys.databases WHERE name = 'msdb'
</code></pre>
<p>This stored procedure returns STARTED:</p>
<pre><code>msdb.dbo.sysmail_help_status_sp
</code></pre>
<p>The appropriate accounts and profiles have been set up and the mail was functioning at one point. There are no errors in msdb.dbo.sysmail_event_log. </p>
| [
{
"answer_id": 9212,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 2,
"selected": false,
"text": "sysmail_stop_sp\n sysmail_start_sp\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9002",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/162/"
] |
9,009 | <p>This snippet of Perl code in my program is giving the wrong result.</p>
<pre><code>$condition ? $a = 2 : $a = 3 ;
print $a;
</code></pre>
<p>No matter what the value of <code>$condition</code> is, the output is always 3, how come?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "($condition ? $a= 2 : $a ) = 3 ;\n $a = ( $condition ? 2 : 3 );\nprint $a;\n"
},
{
"answer_id": 21800,
"author": "Tithonium",
"author_id": 2425,
"author_profile": "https://Stackoverflow.com/users/2425",
"pm_score": 4,
"selected": false,
"text": "$condition ? ($a=2) : ($a=3);\n $condition ? ($a=2) : ($b=3);\n ($condition ? $a : $b) = 3;\n"
},
{
"answer_id": 46956,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 5,
"selected": false,
"text": "perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;'\n (($condition ? ($a = 2) : $a) = 3);\nprint($a);\n-e syntax OK\n"
},
{
"answer_id": 73753,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 2,
"selected": false,
"text": "($condition ? $a = 2 : $a ) = 3 ;\n $a = $condition ? 2 : 3;\n $x < 3 ? foo($x) : bar($y);\n if ($x < 3) {\n $foo($x);\n} else {\n $bar($y);\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/238/"
] |
9,018 | <p>I am working at a client site where there is a proxy server (<code>HTTP</code>) in place. If I do a hard reset of the emulator it forgets network connection settings for the emulator and settings in the hosted Windows Mobile OS. If I 'save state and exit' it will lose all of these settings. I need to do hard resets regularly which means that I lose this information and spend a lot of time setting:</p>
<ul>
<li>The emulators associated network card</li>
<li>DNS servers for network card in the WM OS.</li>
<li>Proxy servers in connection settings of WM OS.</li>
</ul>
<p>How can I make my life easier? Can I save this as defaults in the emulator, or create an installer easily?</p>
| [
{
"answer_id": 9011,
"author": "Pat",
"author_id": 238,
"author_profile": "https://Stackoverflow.com/users/238",
"pm_score": 7,
"selected": true,
"text": "($condition ? $a= 2 : $a ) = 3 ;\n $a = ( $condition ? 2 : 3 );\nprint $a;\n"
},
{
"answer_id": 21800,
"author": "Tithonium",
"author_id": 2425,
"author_profile": "https://Stackoverflow.com/users/2425",
"pm_score": 4,
"selected": false,
"text": "$condition ? ($a=2) : ($a=3);\n $condition ? ($a=2) : ($b=3);\n ($condition ? $a : $b) = 3;\n"
},
{
"answer_id": 46956,
"author": "theorbtwo",
"author_id": 4839,
"author_profile": "https://Stackoverflow.com/users/4839",
"pm_score": 5,
"selected": false,
"text": "perl -MO=Deparse,-p -e '$condition ? $a= 2 : $a= 3 ; print $a;'\n (($condition ? ($a = 2) : $a) = 3);\nprint($a);\n-e syntax OK\n"
},
{
"answer_id": 73753,
"author": "raldi",
"author_id": 7598,
"author_profile": "https://Stackoverflow.com/users/7598",
"pm_score": 2,
"selected": false,
"text": "($condition ? $a = 2 : $a ) = 3 ;\n $a = $condition ? 2 : 3;\n $x < 3 ? foo($x) : bar($y);\n if ($x < 3) {\n $foo($x);\n} else {\n $bar($y);\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9018",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/636/"
] |
9,019 | <p>I have a stored procedure which takes as its parameter a <em>varchar</em> which needs to be cast as a <em>datetime</em> for later use:</p>
<pre><code>SET @the_date = CAST(@date_string AS DATETIME)
</code></pre>
<p>I'm expecting the date string to be supplied in the format "DD-MON-YYYY", but in an effort to code defensively, if for some reason it can't be cast successfully, I want to default to the system date and continue. In PL/SQL I could use exception handling to achieve this and I could do this fairly easily with regular expressions too, but the limited pattern matching supported out of the box by Sybase doesn't let me do this and I can't rely on third party libraries or extensions. Is there a simple way of doing this in T-SQL?</p>
<p><em>NB: using Sybase ASE 12.5.3, there is no ISDATE function</em></p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "SET DATEFORMAT mdy;\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "convert cast select convert( datetime , @date_string ) \n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9019",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1030/"
] |
9,022 | <p>Inside an asp.net page, should I use</p>
<pre><code><html><title>My page's title from México</title></html>
</code></pre>
<p>Or </p>
<pre><code><html><title>My page&rsquo;s title from M&eacute;xico</title></html>
</code></pre>
<p>Both examples have the same output. Since asp.net encodes all my pages to utf-8, there is no need to use html entities, is that right?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "SET DATEFORMAT mdy;\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "convert cast select convert( datetime , @date_string ) \n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/296/"
] |
9,024 | <p>I'm using <code>IIS 5.1</code> in Windows XP on my development computer. I'm going to set up HTTPS on my company's web server, but I want to try doing it locally before doing it on a production system.</p>
<p>But when I go into the Directory Security tab of my web site's configuration section, the "Secure communication" groupbox is disabled. Is there something I need to do to make this groupbox enabled?</p>
| [
{
"answer_id": 9023,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 0,
"selected": false,
"text": "----Invalid date\nSELECT ISDATE('30/2/2007')\nRETURNS : 0 (Zero)\n----Valid date\nSELECT ISDATE('12/12/20007')\nRETURNS : 1 (ONE)\n----Invalid DataType\nSELECT ISDATE('SQL')\nRETURNS : 0 (Zero)\n"
},
{
"answer_id": 9029,
"author": "Marius",
"author_id": 1008,
"author_profile": "https://Stackoverflow.com/users/1008",
"pm_score": 0,
"selected": false,
"text": "SET DATEFORMAT mdy;\n"
},
{
"answer_id": 941940,
"author": "Rebthor",
"author_id": 103630,
"author_profile": "https://Stackoverflow.com/users/103630",
"pm_score": 2,
"selected": true,
"text": "SET arithabort arith_overflow off\nSET @the_date = CAST(@date_string AS DATETIME)\nIF @the_date is NULL\n set @the_date = getdate()\nSET arithabort arith_overflow on\n"
},
{
"answer_id": 941999,
"author": "Vincent Buck",
"author_id": 90352,
"author_profile": "https://Stackoverflow.com/users/90352",
"pm_score": 0,
"selected": false,
"text": "convert cast select convert( datetime , @date_string ) \n"
},
{
"answer_id": 987884,
"author": "B0rG",
"author_id": 122093,
"author_profile": "https://Stackoverflow.com/users/122093",
"pm_score": 1,
"selected": false,
"text": "SELECT @the_date = CASE @date_string\n WHEN '[0-9][0-9]-[A-Z][A-Z][A-Z]-[0-9][0-9][0-9][0-9]'\n THEN CONVERT(datetime, @date_string)\n ELSE GETDATE()\n END\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/614/"
] |
9,033 | <p>This came to my mind after I learned the following from <a href="http://www.stackoverflow.com/questions/8941/generic-type-checking">this question</a>:</p>
<pre><code>where T : struct
</code></pre>
<p>We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.</p>
<p>Some of us even mastered the stuff like <a href="http://msdn.microsoft.com/en-us/library/512aeb7t.aspx" rel="nofollow noreferrer">Generics</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397696.aspx" rel="nofollow noreferrer">anonymous types</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397687.aspx" rel="nofollow noreferrer">lambdas</a>, <a href="http://msdn.microsoft.com/en-us/library/bb397676.aspx" rel="nofollow noreferrer">LINQ</a>, ...</p>
<p>But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?</p>
<h1>Here are the revealed features so far:</h1>
<p><br /></p>
<h2>Keywords</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx" rel="nofollow noreferrer"><code>yield</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>var</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><code>using()</code> statement by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>readonly</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li><code>as</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9041#9041">Mike Stone</a></li>
<li><code>as</code> / <code>is</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9070#9070">Ed Swangren</a></li>
<li><code>as</code> / <code>is</code> (improved) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9092#9092">Rocketpants</a></li>
<li><code>default</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9639#9639">deathofrats</a></li>
<li><code>global::</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12152#12152">pzycoman</a></li>
<li><code>using()</code> blocks by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12316#12316">AlexCuse</a></li>
<li><code>volatile</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/59691#59691">Jakub Šturc</a></li>
<li><code>extern alias</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/37926#37926">Jakub Šturc</a></li>
</ul>
<h2>Attributes</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx" rel="nofollow noreferrer"><code>DefaultValueAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9035#9035">Michael Stum</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.obsoleteattribute.aspx" rel="nofollow noreferrer"><code>ObsoleteAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerdisplayattribute.aspx" rel="nofollow noreferrer"><code>DebuggerDisplayAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9048#9048">Stu</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerbrowsableattribute.aspx" rel="nofollow noreferrer"><code>DebuggerBrowsable</code></a> and <a href="http://msdn.microsoft.com/en-us/library/system.diagnostics.debuggerstepthroughattribute.aspx" rel="nofollow noreferrer"><code>DebuggerStepThrough</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/33474#33474">bdukes</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.threadstaticattribute(VS.71).aspx" rel="nofollow noreferrer"><code>ThreadStaticAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/system.flagsattribute.aspx" rel="nofollow noreferrer"><code>FlagsAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/21752#21752">Martin Clarke</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/4xssyw96.aspx" rel="nofollow noreferrer"><code>ConditionalAttribute</code></a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/35342#35342">AndrewBurns</a></li>
</ul>
<h2>Syntax</h2>
<ul>
<li><a href="http://msdn.microsoft.com/en-us/library/ms173224.aspx" rel="nofollow noreferrer"><code>??</code></a> (coalesce nulls) operator by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a></li>
<li>Number flaggings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9038#9038">Nick Berardi</a></li>
<li><code>where T:new</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9067#9067">Lars Mæhlum</a></li>
<li>Implicit generics by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>One-parameter lambdas by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Auto properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Namespace aliases by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li>Verbatim string literals with @ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9114#9114">Patrick</a></li>
<li><code>enum</code> values by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/11738#11738">lfoust</a></li>
<li>@variablenames by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14088#14088">marxidad</a></li>
<li><code>event</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14277#14277">marxidad</a></li>
<li>Format string brackets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15321#15321">Portman</a></li>
<li>Property accessor accessibility modifiers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15715#15715">xanadont</a></li>
<li>Conditional (ternary) operator (<code>?:</code>) by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16450#16450">JasonS</a></li>
<li><code>checked</code> and <code>unchecked</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/355991#355991">Binoj Antony</a></li>
<li><code>implicit and explicit</code> operators by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/121470#121470">Flory</a></li>
</ul>
<h2>Language Features</h2>
<ul>
<li>Nullable types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9055#9055">Brad Barker</a></li>
<li>Anonymous types by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9099#9099">Keith</a></li>
<li><code>__makeref __reftype __refvalue</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9125#9125">Judah Himango</a></li>
<li>Object initializers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9547#9547">lomaxx</a></li>
<li>Format strings by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10207#10207">David in Dakota</a></li>
<li>Extension Methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13932#13932">marxidad</a></li>
<li><code>partial</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16395#16395">Jon Erickson</a></li>
<li>Preprocessor directives by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/16482#16482">John Asbeck</a></li>
<li><code>DEBUG</code> pre-processor directive by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/29081#29081">Robert Durgin</a></li>
<li>Operator overloading by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/24914#24914">SefBkn</a></li>
<li>Type inferrence by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/28811#28811">chakrit</a></li>
<li>Boolean operators <a href="http://www.java2s.com/Tutorial/CSharp/0160__Operator-Overload/truefalseoperatorforComplex.htm" rel="nofollow noreferrer">taken to next level</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/32148#32148">Rob Gough</a></li>
<li>Pass value-type variable as interface without boxing by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1820538#1820538">Roman Boiko</a></li>
<li>Programmatically determine declared variable type by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1789985#1789985">Roman Boiko</a></li>
<li>Static Constructors by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/100321#100321">Chris</a></li>
<li>Easier-on-the-eyes / condensed ORM-mapping using LINQ by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/2026781#2026781">roosteronacid</a></li>
<li><code>__arglist</code> by <a href="https://stackoverflow.com/a/1836944/171819">Zac Bowling</a></li>
</ul>
<h2>Visual Studio Features</h2>
<ul>
<li>Select block of text in editor by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1699477#1699477" title="block text selecting with alt key">Himadri</a></li>
<li>Snippets by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9037#9037">DannySmurf</a> </li>
</ul>
<h2>Framework</h2>
<ul>
<li><code>TransactionScope</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>DependantTransaction</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>Nullable<T></code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9118#9118">IainMH</a></li>
<li><code>Mutex</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9181#9181">Diago</a></li>
<li><code>System.IO.Path</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9401#9401">ageektrapped</a></li>
<li><code>WeakReference</code> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/14723#14723">Juan Manuel</a></li>
</ul>
<h2>Methods and Properties</h2>
<ul>
<li><code>String.IsNullOrEmpty()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>List.ForEach()</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9042#9042">KiwiBastard</a></li>
<li><code>BeginInvoke()</code>, <code>EndInvoke()</code> methods by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9581#9581">Will Dean</a></li>
<li><code>Nullable<T>.HasValue</code> and <code>Nullable<T>.Value</code> properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/15393#15393">Rismo</a></li>
<li><code>GetValueOrDefault</code> method by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/18158#18158">John Sheehan</a></li>
</ul>
<h2>Tips & Tricks</h2>
<ul>
<li>Nice method for event handlers by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9282#9282">Andreas H.R. Nilsson</a></li>
<li>Uppercase comparisons by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/12137#12137">John</a></li>
<li>Access anonymous types without reflection by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/13441#13441">dp</a></li>
<li>A quick way to lazily instantiate collection properties by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/58945#58945">Will</a></li>
<li>JavaScript-like anonymous inline-functions by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/1399130#1399130">roosteronacid</a></li>
</ul>
<h2>Other</h2>
<ul>
<li>netmodules by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/9036#9036">kokos</a> </li>
<li><a href="http://www.albahari.com/nutshell/linqbridge.html" rel="nofollow noreferrer">LINQBridge</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/10886#10886">Duncan Smart</a> </li>
<li><a href="http://msdn.microsoft.com/en-us/concurrency/default.aspx" rel="nofollow noreferrer">Parallel Extensions</a> by <a href="https://stackoverflow.com/questions/9033/hidden-features-of-c/31293#31293">Joel Coehoorn</a></li>
</ul>
| [
{
"answer_id": 9038,
"author": "Nick Berardi",
"author_id": 17,
"author_profile": "https://Stackoverflow.com/users/17",
"pm_score": 6,
"selected": false,
"text": "Decimal = M\nFloat = F\nDouble = D\n\n// for example\ndouble d = 30D;\n Long = L\nUnsigned Long = UL\nUnsigned Int = U\n"
},
{
"answer_id": 9041,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 8,
"selected": false,
"text": "MyClass myObject = (MyClass) obj;\n MyClass myObject = obj as MyClass;\n"
},
{
"answer_id": 9055,
"author": "Brad Barker",
"author_id": 12081,
"author_profile": "https://Stackoverflow.com/users/12081",
"pm_score": 8,
"selected": false,
"text": "double? num1 = null; \ndouble num2 = num1 ?? -100;\n DateTime? tmp = new DateTime();\ntmp = null;\nreturn tmp.ToString();\n"
},
{
"answer_id": 9067,
"author": "Lars Mæhlum",
"author_id": 960,
"author_profile": "https://Stackoverflow.com/users/960",
"pm_score": 4,
"selected": false,
"text": "public abstract class BaseListControl<ListType,KeyType,ParameterType>\n : UserControl \n where ListType : BaseListType\n && ParameterType : BaseParameterType, new\n{\n\n private const string viewStateFilterKey = \"FilterKey\";\n\n protected ParameterType Filters\n {\n get\n {\n if (ViewState[viewStateFilterKey] == null)\n ViewState[viewStateFilterKey]= new ParameterType();\n\n return ViewState[viewStateFilterKey] as ParameterType;\n }\n set\n {\n ViewState[viewStateFilterKey] = value;\n }\n }\n\n}\n private void SomeEventHappened(object sender, EventArgs e)\n{\n Filters.SomeValue = SomeControl.SelectedValue;\n}\n\nprivate void TimeToFetchSomeData()\n{\n GridView.DataSource = Repository.GetList(Filters);\n}\n"
},
{
"answer_id": 9092,
"author": "Dogmang",
"author_id": 1135,
"author_profile": "https://Stackoverflow.com/users/1135",
"pm_score": 7,
"selected": false,
"text": "MyClass c;\n if (obj is MyClass)\n c = obj as MyClass\n c = (MyClass)obj\n MyClass c = obj as MyClass;\nif(c != null)\n{\n ...\n}\n"
},
{
"answer_id": 9099,
"author": "Keith",
"author_id": 905,
"author_profile": "https://Stackoverflow.com/users/905",
"pm_score": 8,
"selected": false,
"text": "void GenericMethod<T>( T input ) { ... }\n\n//Infer type, so\nGenericMethod<int>(23); //You don't need the <>.\nGenericMethod(23); //Is enough.\n x => x.ToString() //simplify so many calls\n //Duck-typed: works with any .Add method.\nvar colours = new Dictionary<string, string> {\n { \"red\", \"#ff0000\" },\n { \"green\", \"#00ff00\" },\n { \"blue\", \"#0000ff\" }\n};\n\nint[] arrayOfInt = { 1, 2, 3, 4, 5 };\n public int MyId { get; private set; }\n using web = System.Web.UI.WebControls;\nusing win = System.Windows.Forms;\n\nweb::Control aWebControl = new web::Control();\nwin::Control aFormControl = new win::Control();\n"
},
{
"answer_id": 9114,
"author": "Patrick",
"author_id": 429,
"author_profile": "https://Stackoverflow.com/users/429",
"pm_score": 7,
"selected": false,
"text": "\"c:\\\\program files\\\\oldway\"\n@\"c:\\program file\\newway\"\n"
},
{
"answer_id": 9125,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 8,
"selected": false,
"text": "__makeref\n\n__reftype\n\n__refvalue\n\n__arglist\n"
},
{
"answer_id": 9181,
"author": "BinaryMisfit",
"author_id": 146270,
"author_profile": "https://Stackoverflow.com/users/146270",
"pm_score": 3,
"selected": false,
"text": "Lists<>\nMutex\n"
},
{
"answer_id": 9282,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 8,
"selected": false,
"text": "public delegate void MyClickHandler(object sender, string myValue);\npublic event MyClickHandler Click = delegate {}; // add empty delegate!\n public void DoSomething()\n{\n Click(this, \"foo\");\n}\n public void DoSomething()\n{\n // Unnecessary!\n MyClickHandler click = Click;\n if (click != null) // Unnecessary! \n {\n click(this, \"foo\");\n }\n}\n"
},
{
"answer_id": 9401,
"author": "ageektrapped",
"author_id": 631,
"author_profile": "https://Stackoverflow.com/users/631",
"pm_score": 10,
"selected": false,
"text": "System.IO.Path.Combine() string path = dir + \"\\\\\" + fileName;\n"
},
{
"answer_id": 9406,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": false,
"text": "string s = @\"cat\n dog\n fish\"\n cat\n dog\n fish\n"
},
{
"answer_id": 9547,
"author": "lomaxx",
"author_id": 493,
"author_profile": "https://Stackoverflow.com/users/493",
"pm_score": 8,
"selected": false,
"text": "private string _name;\npublic string Name\n{\n get\n {\n return _name;\n }\n set\n {\n _name = value;\n }\n}\n public string Name { get; set;}\n Employee emp = new Employee();\nemp.Name = \"John Smith\";\nemp.StartDate = DateTime.Now();\n Employee emp = new Employee {Name=\"John Smith\", StartDate=DateTime.Now()}\n"
},
{
"answer_id": 9581,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 4,
"selected": false,
"text": "BeginInvoke EndInvoke ThreadPool.QueueUserWorkItem BeginInvoke"
},
{
"answer_id": 9639,
"author": "Eric Minkes",
"author_id": 1172,
"author_profile": "https://Stackoverflow.com/users/1172",
"pm_score": 8,
"selected": false,
"text": "T t = default(T);\n"
},
{
"answer_id": 10207,
"author": "t3rse",
"author_id": 64,
"author_profile": "https://Stackoverflow.com/users/64",
"pm_score": 4,
"selected": false,
"text": "Func<int, int, int> add = (a, b) => (a + b);\n Console.WriteLine(\"{0:D10}\", 2); // 0000000002\n\nDictionary<string, string> dict = new Dictionary<string, string> { \n {\"David\", \"C#\"}, \n {\"Johann\", \"Perl\"}, \n {\"Morgan\", \"Python\"}\n};\n\nConsole.WriteLine( \"{0,10} {1, 10}\", \"Programmer\", \"Language\" );\n\nConsole.WriteLine( \"-\".PadRight( 21, '-' ) );\n\nforeach (string key in dict.Keys)\n{\n Console.WriteLine( \"{0, 10} {1, 10}\", key, dict[key] ); \n}\n"
},
{
"answer_id": 10892,
"author": "Serhat Ozgel",
"author_id": 31505,
"author_profile": "https://Stackoverflow.com/users/31505",
"pm_score": 3,
"selected": false,
"text": "ExtensionAttribute namespace System.Runtime.CompilerServices\n{\n public class ExtensionAttribute : Attribute\n { \n }\n}\n"
},
{
"answer_id": 11738,
"author": "Luke Foust",
"author_id": 646,
"author_profile": "https://Stackoverflow.com/users/646",
"pm_score": 5,
"selected": false,
"text": "public enum MyEnum : long\n{\n Val1 = 1,\n Val2 = 2\n}\n MyEnum e = (MyEnum)123;\n"
},
{
"answer_id": 12152,
"author": "Surgical Coder",
"author_id": 1276,
"author_profile": "https://Stackoverflow.com/users/1276",
"pm_score": 5,
"selected": false,
"text": "global::\n global::System.Collections.Generic.List<global::System.String> myList =\n new global::System.Collections.Generic.List<global::System.String>();\n"
},
{
"answer_id": 13441,
"author": "denis phillips",
"author_id": 748,
"author_profile": "https://Stackoverflow.com/users/748",
"pm_score": 7,
"selected": false,
"text": "// Useful? probably not.\nprivate void foo()\n{\n var user = AnonCast(GetUserTuple(), new { Name = default(string), Badges = default(int) });\n Console.WriteLine(\"Name: {0} Badges: {1}\", user.Name, user.Badges);\n}\n\nobject GetUserTuple()\n{\n return new { Name = \"dp\", Badges = 5 };\n} \n\n// Using the magic of Type Inference...\nstatic T AnonCast<T>(object obj, T t)\n{\n return (T) obj;\n}\n"
},
{
"answer_id": 13932,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 5,
"selected": false,
"text": "//for adding multiple elements to a collection that doesn't have AddRange\n//e.g., collection.Add(item1, item2, itemN);\nstatic void Add<T>(this ICollection<T> coll, params T[] items)\n { foreach (var item in items) coll.Add(item);\n }\n\n//like string.Format() but with custom string representation of arguments\n//e.g., \"{0} {1} {2}\".Format<Custom>(c=>c.Name,\"string\",new object(),new Custom())\n// result: \"string {System.Object} Custom1Name\"\nstatic string Format<T>(this string format, Func<T,object> select, params object[] args)\n { for(int i=0; i < args.Length; ++i)\n { var x = args[i] as T;\n if (x != null) args[i] = select(x);\n }\n return string.Format(format, args);\n }\n"
},
{
"answer_id": 14088,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 7,
"selected": false,
"text": "var @object = new object();\nvar @string = \"\";\nvar @if = IpsoFacto(); \n"
},
{
"answer_id": 14277,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 6,
"selected": false,
"text": "public event EventHandler SelectiveEvent(object sender, EventArgs args) \n { add \n { if (value.Target == null) throw new Exception(\"No static handlers!\");\n _SelectiveEvent += value;\n }\n remove\n { _SelectiveEvent -= value;\n }\n } EventHandler _SelectiveEvent;\n"
},
{
"answer_id": 14926,
"author": "martinlund",
"author_id": 1808,
"author_profile": "https://Stackoverflow.com/users/1808",
"pm_score": 2,
"selected": false,
"text": "MyObject obj = e.Item.DataItem as MyObject;\nif(obj != null)\n{\n //Do work\n}\n"
},
{
"answer_id": 15321,
"author": "Portman",
"author_id": 1690,
"author_profile": "https://Stackoverflow.com/users/1690",
"pm_score": 7,
"selected": false,
"text": "int foo = 3;\nstring bar = \"blind mice\";\nString.Format(\"{{I am in brackets!}} {0} {1}\", foo, bar);\n//Outputs \"{I am in brackets!} 3 blind mice\"\n"
},
{
"answer_id": 15352,
"author": "mgsloan",
"author_id": 1164871,
"author_profile": "https://Stackoverflow.com/users/1164871",
"pm_score": 5,
"selected": false,
"text": "var foo = new Rectangle() \n{ \n Fill = new SolidColorBrush(c), \n Width = 20, \n Height = 20 \n};\n var foo = new Rectangle() \n{ \n Fill = new SolidColorBrush(c), \n Width = 20, \n Height = 20,\n};\n"
},
{
"answer_id": 15393,
"author": "Rismo",
"author_id": 1560,
"author_profile": "https://Stackoverflow.com/users/1560",
"pm_score": 5,
"selected": false,
"text": " int? x = null;\n int y;\n if (x.HasValue)\n y = x.Value;\n"
},
{
"answer_id": 15715,
"author": "xanadont",
"author_id": 1886,
"author_profile": "https://Stackoverflow.com/users/1886",
"pm_score": 5,
"selected": false,
"text": "public string Name { get; private set;}\n public MyClass(string name) { Name = name; }\n"
},
{
"answer_id": 15765,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 9,
"selected": false,
"text": "string result = value1 ?? value2 ?? value3 ?? String.Empty;\n"
},
{
"answer_id": 16450,
"author": "JasonS",
"author_id": 1865,
"author_profile": "https://Stackoverflow.com/users/1865",
"pm_score": 7,
"selected": false,
"text": "if (x == 1)\n{\n x = 2;\n}\nelse\n{\n x = 3;\n}\n x = (x==1) ? 2 : 3;\n"
},
{
"answer_id": 18158,
"author": "John Sheehan",
"author_id": 1786,
"author_profile": "https://Stackoverflow.com/users/1786",
"pm_score": 4,
"selected": false,
"text": "Nullable<T>.GetValueOrDefault(T)"
},
{
"answer_id": 24914,
"author": "SemiColon",
"author_id": 1994,
"author_profile": "https://Stackoverflow.com/users/1994",
"pm_score": 3,
"selected": false,
"text": "class myClass\n{\n private string myClassValue = \"\";\n\n public myClass(string myString)\n {\n myClassValue = myString;\n }\n\n public override string ToString()\n {\n return myClassValue;\n }\n\n public static myClass operator <<(myClass mc, int shiftLen)\n {\n string newString = \"\";\n for (int i = shiftLen; i < mc.myClassValue.Length; i++)\n newString += mc.myClassValue[i].ToString();\n mc.myClassValue = newString.ToString();\n return mc;\n }\n\n public static myClass operator >>(myClass mc, int shiftLen)\n {\n char[] newString = new char[shiftLen + mc.myClassValue.Length];\n\n for (int i = shiftLen; i < mc.myClassValue.Length; i++)\n newString[i] += mc.myClassValue[i - shiftLen];\n\n mc.myClassValue = new string(newString);\n return mc;\n }\n\n public static myClass operator +(myClass mc, string args)\n {\n if (args.Trim().Length > 1)\n mc.myClassValue += args;\n return mc;\n }\n\n public static myClass operator -(myClass mc, string args)\n {\n if (args.Trim().Length > 1)\n {\n Regex rgx = new Regex(args);\n mc.myClassValue = rgx.Replace(mc.myClassValue, \"\");\n }\n return mc;\n }\n}\n myClass tmpClass = new myClass(\" HelloWorld123\");\ntmpClass -= @\"World\";\ntmpClass <<= 2;\nConsole.WriteLine(tmpClass);\n"
},
{
"answer_id": 27941,
"author": "Frep D-Oronge",
"author_id": 3024,
"author_profile": "https://Stackoverflow.com/users/3024",
"pm_score": 5,
"selected": false,
"text": "string mystring = foo ?? \"foo was null\"\n string mystring;\nif (foo==null)\n mystring = \"foo was null\";\nelse\n mystring = foo;\n"
},
{
"answer_id": 28811,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 9,
"selected": false,
"text": "Console.CancelKeyPress +=\n (sender, e) => {\n Console.WriteLine(\"CTRL+C detected!\\n\");\n e.Cancel = true;\n };\n new CancellationEventHandler sender e delegate (blah blah) Func<int, int, EventHandler> makeHandler =\n (dx, dy) => (sender, e) => {\n var btn = (Button) sender;\n btn.Top += dy;\n btn.Left += dx;\n };\n\nbtnUp.Click += makeHandler(0, -1);\nbtnDown.Click += makeHandler(0, 1);\nbtnLeft.Click += makeHandler(-1, 0);\nbtnRight.Click += makeHandler(1, 0);\n (dx, dy) => (sender, e) =>"
},
{
"answer_id": 29081,
"author": "Robert Durgin",
"author_id": 3132,
"author_profile": "https://Stackoverflow.com/users/3132",
"pm_score": 5,
"selected": false,
"text": "string customerName = null;\n#if DEBUG\n customerName = \"Bob\"\n#endif\n"
},
{
"answer_id": 31293,
"author": "Joel Coehoorn",
"author_id": 3043,
"author_profile": "https://Stackoverflow.com/users/3043",
"pm_score": 4,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing System.Threading;\nusing System.Threading.Tasks;\n\nnamespace ObjectInitSpeedTest\n{\n class Program\n {\n //Note: don't forget to build it in Release mode.\n static void Main()\n {\n normalSpeedTest(); \n parallelSpeedTest();\n\n Console.ForegroundColor = ConsoleColor.White;\n Console.WriteLine(\"Press a key ...\");\n Console.ReadKey();\n }\n\n private static void parallelSpeedTest()\n {\n Console.ForegroundColor = ConsoleColor.Yellow;\n Console.WriteLine(\"parallelSpeedTest\");\n\n long totalObjectsCreated = 0;\n long totalElapsedTime = 0;\n\n var tasks = new List<Task>();\n var processorCount = Environment.ProcessorCount;\n\n Console.WriteLine(\"Running on {0} cores\", processorCount);\n\n for (var t = 0; t < processorCount; t++)\n {\n tasks.Add(Task.Factory.StartNew(\n () =>\n {\n const int reps = 1000000000;\n var sp = Stopwatch.StartNew();\n for (var j = 0; j < reps; ++j)\n {\n new object();\n }\n sp.Stop();\n\n Interlocked.Add(ref totalObjectsCreated, reps);\n Interlocked.Add(ref totalElapsedTime, sp.ElapsedMilliseconds);\n }\n ));\n }\n\n // let's complete all the tasks\n Task.WaitAll(tasks.ToArray());\n\n Console.WriteLine(\"Created {0:N} objects in 1 sec\\n\", (totalObjectsCreated / (totalElapsedTime / processorCount)) * 1000);\n }\n\n private static void normalSpeedTest()\n {\n Console.ForegroundColor = ConsoleColor.Green;\n Console.WriteLine(\"normalSpeedTest\");\n\n const int reps = 1000000000;\n var sp = Stopwatch.StartNew();\n sp.Start();\n for (var j = 0; j < reps; ++j)\n {\n new object();\n }\n sp.Stop();\n\n Console.WriteLine(\"Created {0:N} objects in 1 sec\\n\", (reps / sp.ElapsedMilliseconds) * 1000);\n }\n }\n}\n"
},
{
"answer_id": 32472,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "protected void LdsPostings_Selecting(object sender, LinqDataSourceSelectEventArgs e)\n{ \n var dc = new MyDataContext();\n var query = dc.Posting.AsQueryable();\n\n if (isCondition1)\n {\n query = query.Where(q => q.PostedBy == Username);\n e.Result = QueryProjection(query);\n return;\n }\n\n ...\n\n if (isConditionN)\n {\n query = query.Where(q => q.Status.StatusName == \"submitted\");\n query = query.Where(q => q.ReviewedBy == Username);\n e.Result = QueryProjection(query);\n return;\n }\n}\n private IQueryable QueryProjection(IQueryable<Posting> query)\n{\n return query.Select(p => new\n {\n p.PostingID,\n p.Category.CategoryName,\n p.Type.TypeName,\n p.Status.StatusName,\n p.Description,\n p.Updated,\n p.PostedBy,\n p.ReviewedBy,\n });\n}\n"
},
{
"answer_id": 32706,
"author": "Nathan Lee",
"author_id": 3453,
"author_profile": "https://Stackoverflow.com/users/3453",
"pm_score": 4,
"selected": false,
"text": "string sql = @\"SELECT firstname, lastname, email\n FROM users\n WHERE username = @username AND password = @password\";\n"
},
{
"answer_id": 33271,
"author": "chakrit",
"author_id": 3055,
"author_profile": "https://Stackoverflow.com/users/3055",
"pm_score": 3,
"selected": false,
"text": "// using the concepts of dp's AnonCast\nstatic Func<T> TypeCurry<T>(Func<object> f, T type)\n{\n return () => (T)f();\n}\n static void Main(string[] args)\n{\n\n var getRandomObjectX = TypeCurry(GetRandomObject,\n new { Name = default(string), Badges = default(int) });\n\n do {\n\n var obj = getRandomObjectX();\n\n Console.WriteLine(\"Name : {0} Badges : {1}\",\n obj.Name,\n obj.Badges);\n\n } while (Console.ReadKey().Key != ConsoleKey.Escape);\n\n}\n\nstatic Random r = new Random();\nstatic object GetRandomObject()\n{\n return new {\n Name = Guid.NewGuid().ToString().Substring(0, 4),\n Badges = r.Next(0, 100)\n };\n}\n"
},
{
"answer_id": 33384,
"author": "ljs",
"author_id": 3394,
"author_profile": "https://Stackoverflow.com/users/3394",
"pm_score": 6,
"selected": false,
"text": "bool basketContainsFruit(string fruit) {\n return new[] { \"apple\", \"orange\", \"banana\", \"pear\" }.Contains(fruit);\n}\n bool basketContainsFruit(string fruit) {\n return fruit == \"apple\" || fruit == \"orange\" || fruit == \"banana\" ||\n fruit == \"pear\";\n}\n"
},
{
"answer_id": 33474,
"author": "bdukes",
"author_id": 2688,
"author_profile": "https://Stackoverflow.com/users/2688",
"pm_score": 5,
"selected": false,
"text": "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\nprivate string nickName;\npublic string NickName {\n [DebuggerStepThrough]\n get { return nickName; }\n [DebuggerStepThrough]\n set { this.nickName = value; }\n}\n"
},
{
"answer_id": 37285,
"author": "nimish",
"author_id": 3926,
"author_profile": "https://Stackoverflow.com/users/3926",
"pm_score": 7,
"selected": false,
"text": "Environment.NewLine\n"
},
{
"answer_id": 37467,
"author": "jfs",
"author_id": 718,
"author_profile": "https://Stackoverflow.com/users/718",
"pm_score": 5,
"selected": false,
"text": "StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter()) {\n using (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n ... \n }\n}\n StringBuilder sb = new StringBuilder();\nusing (StringWriter sw = new StringWriter())\nusing (IndentedTextWriter itw = new IndentedTextWriter(sw)) {\n ... \n}\n"
},
{
"answer_id": 41872,
"author": "Michael Prewecki",
"author_id": 4403,
"author_profile": "https://Stackoverflow.com/users/4403",
"pm_score": 2,
"selected": false,
"text": "double doubleValue\nif (!Double.TryParse(myDataRow(\"myColumn\"), out doubleValue))\n{\n // set validation error\n}\n"
},
{
"answer_id": 44782,
"author": "andynil",
"author_id": 446,
"author_profile": "https://Stackoverflow.com/users/446",
"pm_score": 5,
"selected": false,
"text": "class Foo\n{\n public Bar GetEnumerator() { return new Bar(); }\n\n public struct Bar\n {\n public bool MoveNext()\n {\n return false;\n }\n\n public object Current\n {\n get { return null; }\n }\n }\n}\n\n// the following complies just fine:\nFoo f = new Foo();\nforeach (object o in f)\n{\n Console.WriteLine(\"Krzysztof Cwalina's da man!\");\n}\n"
},
{
"answer_id": 45398,
"author": "Pop Catalin",
"author_id": 4685,
"author_profile": "https://Stackoverflow.com/users/4685",
"pm_score": 5,
"selected": false,
"text": "__makeref __reftype __refvalue __arglist // Create a typed reference\nint i = 1;\nTypedReference tr1 = __makeref(i);\n// Get the type of a typed reference\nType t = __reftype(tr1);\n// Get the value of a typed referece\nint j = __refvalue(tr1, int); \n// Create a method that accepts and arbitrary number of typed references\nvoid SomeMethod(__arglist) { ...\n// Call the method\nint x = 1;\nstring y = \"Foo\";\nObject o = new Object();\nSomeMethod(__arglist(x,y,o));\n// And finally iterate over method parameters\nvoid SomeMethod(__arglist) {\n ArgIterator ai = new ArgIterator(__arglist);\nwhile(ai.GetRemainingCount() >0)\n{\n TypedReference tr = ai.GetNextArg();\n Console.WriteLine(TypedReference.ToObject(tr));\n}}\n"
},
{
"answer_id": 45454,
"author": "Mark Ingram",
"author_id": 986,
"author_profile": "https://Stackoverflow.com/users/986",
"pm_score": 2,
"selected": false,
"text": "c = (MyClass)obj\n MyClass c;\nif (obj is MyClass)\n{\n c = obj as MyClass\n}\n\nif (c != null)\n{\n}\n MyClass c = obj as MyClass;\n\nif (c != null)\n{\n}\n"
},
{
"answer_id": 45873,
"author": "Konamiman",
"author_id": 4574,
"author_profile": "https://Stackoverflow.com/users/4574",
"pm_score": 6,
"selected": false,
"text": "Console.WriteLine( \"-\".PadRight( 21, '-' ) );\n new String('-',22);\n"
},
{
"answer_id": 46290,
"author": "Judah Gabriel Himango",
"author_id": 536,
"author_profile": "https://Stackoverflow.com/users/536",
"pm_score": 5,
"selected": false,
"text": "extern alias YourAliasHere;\n"
},
{
"answer_id": 49607,
"author": "nialljsmith",
"author_id": 5197,
"author_profile": "https://Stackoverflow.com/users/5197",
"pm_score": 5,
"selected": false,
"text": "foreach(object o in ACollection)\n{\n if(NotInterested)\n continue;\n}\n"
},
{
"answer_id": 50891,
"author": "johnc",
"author_id": 5302,
"author_profile": "https://Stackoverflow.com/users/5302",
"pm_score": 3,
"selected": false,
"text": "if (boolean Condition)\n{\n //Do Function\n}\nelse\n{\n //Do something else\n}\n booleanCondtion ? true operation : false operation;\n int value = param;\nif (doubleValue)\n{\n value *= 2;\n}\nelse\n{\n value *= 3;\n}\n int value = param * (tripleValue ? 3 : 2);\n"
},
{
"answer_id": 51966,
"author": "Bryan",
"author_id": 5423,
"author_profile": "https://Stackoverflow.com/users/5423",
"pm_score": 6,
"selected": false,
"text": " public interface SomeObject<T> where T : SomeObject<T>, new()\n var myAwesomeObject = new {Name=\"Foo\", Size=10};\n public synchronized void MySynchronizedMethod(){}\n [MethodImpl(MethodImplOptions.Synchronized)]\n public void MySynchronizedMethod(){}\n"
},
{
"answer_id": 52998,
"author": "Jason Olson",
"author_id": 5418,
"author_profile": "https://Stackoverflow.com/users/5418",
"pm_score": 8,
"selected": false,
"text": "public class MyClass\n{\n public void SomeMethod() { /* Do Something */ }\n}\n RegisterMethod(typeof(MyClass), \"SomeMethod\");\n RegisterMethod<MyClass>(cl => cl.SomeMethod());\n Expression<Action<T>> void RegisterMethod<T>(Expression<Action<T>> action) where T : class\n{\n var expression = (action.Body as MethodCallExpression);\n\n if (expression != null)\n {\n // TODO: Register method\n Console.WriteLine(expression.Method.Name);\n }\n}\n"
},
{
"answer_id": 58945,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 9,
"selected": false,
"text": "private IList<Foo> _foo;\n\npublic IList<Foo> ListOfFoo \n { get { return _foo ?? (_foo = new List<Foo>()); } }\n"
},
{
"answer_id": 63661,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 6,
"selected": false,
"text": "class Example\n{\n public Example(int value1)\n : this(value1, \"Default Value\")\n {\n }\n\n public Example(int value1, string value2)\n {\n m_Value1 = value1;\n m_value2 = value2;\n }\n\n int m_Value1;\n string m_value2;\n}\n"
},
{
"answer_id": 72518,
"author": "Benjol",
"author_id": 11410,
"author_profile": "https://Stackoverflow.com/users/11410",
"pm_score": 4,
"selected": false,
"text": "() => DoSomething(x); (e, _) => DoSomething(e) .Empty"
},
{
"answer_id": 74482,
"author": "BlackTigerX",
"author_id": 8411,
"author_profile": "https://Stackoverflow.com/users/8411",
"pm_score": 9,
"selected": false,
"text": "using ASimpleName = Dictionary<string, Dictionary<string, List<string>>>;\n ASimpleName Dictionary<string, Dictionary<string, List<string>>>"
},
{
"answer_id": 87276,
"author": "Sixto Saez",
"author_id": 9711,
"author_profile": "https://Stackoverflow.com/users/9711",
"pm_score": 3,
"selected": false,
"text": "public class BaseFoo\n{\n virtual public void DoSomething()\n {\n Console.WriteLine(\"Foo\");\n }\n}\n\npublic class DerivedFoo : BaseFoo\n{\n public new void DoSomething()\n {\n Console.WriteLine(\"Bar\");\n }\n}\n\npublic class DerivedBar : BaseFoo\n{\n public override void DoSomething()\n {\n Console.WriteLine(\"FooBar\");\n }\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n BaseFoo derivedBarAsBaseFoo = new DerivedBar();\n BaseFoo derivedFooAsBaseFoo = new DerivedFoo();\n\n DerivedFoo derivedFoo = new DerivedFoo();\n\n derivedFooAsBaseFoo.DoSomething(); //Prints \"Foo\" when you might expect \"Bar\"\n derivedBarAsBaseFoo.DoSomething(); //Prints \"FooBar\"\n\n derivedFoo.DoSomething(); //Prints \"Bar\"\n }\n}\n"
},
{
"answer_id": 90432,
"author": "Alex Lyman",
"author_id": 5897,
"author_profile": "https://Stackoverflow.com/users/5897",
"pm_score": 4,
"selected": false,
"text": "switch case case case 0 goto case case 1 goto default case 2 switch (/*...*/) {\n case 0: // shares the exact same code as case 1\n case 1:\n // do something\n goto case 2;\n case 2:\n // do something else\n goto default;\n default:\n // do something entirely different\n break;\n}\n"
},
{
"answer_id": 99844,
"author": "Statement",
"author_id": 2166173,
"author_profile": "https://Stackoverflow.com/users/2166173",
"pm_score": 2,
"selected": false,
"text": "#region Using statements\nusing System;\nusing System.IO;\nusing ....;\nusing ....;\n#endregion\n"
},
{
"answer_id": 100321,
"author": "core",
"author_id": 11574,
"author_profile": "https://Stackoverflow.com/users/11574",
"pm_score": 5,
"selected": false,
"text": "public class Example\n{\n static Example()\n {\n // Code to execute during type initialization\n }\n\n public Example()\n {\n // Code to execute during object initialization\n }\n}\n public static class Example\n{\n static Example()\n {\n // Code to execute during type initialization\n }\n}\n public class MyWebService\n{\n public static DateTime StartTime;\n\n static MyWebService()\n {\n MyWebService.StartTime = DateTime.Now;\n }\n\n public TimeSpan Uptime\n {\n get { return DateTime.Now - MyWebService.StartTime; }\n }\n}\n public class MyWebService\n{\n public static DateTime StartTime = DateTime.Now;\n\n public TimeSpan Uptime\n {\n get { return DateTime.Now - MyWebService.StartTime; }\n }\n}\n TypeIntializationException TypeInitializationException InnerException"
},
{
"answer_id": 103235,
"author": "ilitirit",
"author_id": 9825,
"author_profile": "https://Stackoverflow.com/users/9825",
"pm_score": 3,
"selected": false,
"text": "Console.WriteLine(5.ToString());\nConsole.WriteLine(5M.GetType()); // Returns \"System.Decimal\"\nConsole.WriteLine(\"This is a string!!!\".Replace(\"!!\", \"!\"));\n public static int UncheckedAddition(int a, int b)\n{\n unchecked { return a + b; }\n}\n\npublic static int CheckedAddition(int a, int b)\n{\n checked { return a + b; } // or \"return checked(a + b)\";\n}\n\npublic static void Main() \n{\n Console.WriteLine(\"Unchecked: \" + UncheckedAddition(Int32.MaxValue, + 1)); // \"Wraps around\"\n Console.WriteLine(\"Checked: \" + CheckedAddition(Int32.MaxValue, + 1)); // Throws an Overflow exception\n Console.ReadLine();\n}\n"
},
{
"answer_id": 103449,
"author": "William Yeung",
"author_id": 16371,
"author_profile": "https://Stackoverflow.com/users/16371",
"pm_score": 2,
"selected": false,
"text": "MyHtmlWriter writer=new MyHtmlWriter();\nwriter.writeTag(\"html\", \n delegate ()\n { \n writer.writeTag(\"head\", \n delegate() \n { \n writer.writeTag(\"title\"...);\n }\n )\n })\n"
},
{
"answer_id": 105042,
"author": "Wyzfen",
"author_id": 15261,
"author_profile": "https://Stackoverflow.com/users/15261",
"pm_score": 6,
"selected": false,
"text": "if(dictionary.ContainsKey(key)) \n{\n value = dictionary[key];\n ...\n}\n if(dictionary.TryGetValue(key, out value)) \n{ ... }\n"
},
{
"answer_id": 106750,
"author": "Ray Lu",
"author_id": 11413,
"author_profile": "https://Stackoverflow.com/users/11413",
"pm_score": 2,
"selected": false,
"text": "static void Main()\n{\n int i;\n unsafe\n { \n // pointer pi has the address of variable i\n int* pi = &i; \n // pointer ppi has the address of variable pi\n int** ppi = π\n // ppi(addess of pi) -> pi(addess of i) -> i(0)\n i = 0;\n // dereference the pi, i.e. *pi is i\n Console.WriteLine(\"i = {0}\", *pi); // output: i = 0\n // since *pi is i, equivalent to i++\n (*pi)++;\n Console.WriteLine(\"i = {0}\", *pi); // output: i = 1\n // since *ppi is pi, one more dereference *pi is i \n // equivalent to i += 2\n **ppi += 2;\n Console.WriteLine(\"i = {0}\", *pi);// output: i = 3\n }\n Console.ReadLine();\n}\n"
},
{
"answer_id": 119648,
"author": "leppie",
"author_id": 15541,
"author_profile": "https://Stackoverflow.com/users/15541",
"pm_score": 1,
"selected": false,
"text": "Delegate target =\n (target0 = target as CallTargetWithContext0) ??\n (target1 = target as CallTargetWithContext1) ??\n (target2 = target as CallTargetWithContext2) ??\n (target3 = target as CallTargetWithContext3) ??\n (target4 = target as CallTargetWithContext4) ??\n (target5 = target as CallTargetWithContext5) ??\n ((Delegate)(targetN = target as CallTargetWithContextN));\n"
},
{
"answer_id": 121405,
"author": "axel_c",
"author_id": 20272,
"author_profile": "https://Stackoverflow.com/users/20272",
"pm_score": 3,
"selected": false,
"text": "System.Diagnostics.Debug.Assert (false);\n"
},
{
"answer_id": 121470,
"author": "Flory",
"author_id": 5551,
"author_profile": "https://Stackoverflow.com/users/5551",
"pm_score": 4,
"selected": false,
"text": "implicit explicit implicit System.Xml.Linq XName XName tagName = \"x:Name\";\n"
},
{
"answer_id": 123701,
"author": "ZeroBugBounce",
"author_id": 11314,
"author_profile": "https://Stackoverflow.com/users/11314",
"pm_score": 8,
"selected": false,
"text": "[StructLayout(LayoutKind.Explicit)]\npublic class A\n{\n [FieldOffset(0)]\n public byte One;\n\n [FieldOffset(1)]\n public byte Two;\n\n [FieldOffset(2)]\n public byte Three;\n\n [FieldOffset(3)]\n public byte Four;\n\n [FieldOffset(0)]\n public int Int32;\n}\n static void Main(string[] args)\n {\n A a = new A { Int32 = int.MaxValue };\n\n Console.WriteLine(a.Int32);\n Console.WriteLine(\"{0:X} {1:X} {2:X} {3:X}\", a.One, a.Two, a.Three, a.Four);\n\n a.Four = 0;\n a.Three = 0;\n Console.WriteLine(a.Int32);\n }\n 2147483647\nFF FF FF 7F\n65535\n"
},
{
"answer_id": 140221,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 6,
"selected": false,
"text": "stackalloc == != bool"
},
{
"answer_id": 149509,
"author": "Mihai Lazar",
"author_id": 4204,
"author_profile": "https://Stackoverflow.com/users/4204",
"pm_score": 4,
"selected": false,
"text": "[AttributeUsage( AttributeTargets.ReturnValue )]\npublic class CuriosityAttribute:Attribute\n{\n}\n\npublic class Bar\n{\n [return: Curiosity]\n public Bar ReturnANewBar()\n {\n return new Bar();\n }\n}\n"
},
{
"answer_id": 165795,
"author": "Tim Jarvis",
"author_id": 10387,
"author_profile": "https://Stackoverflow.com/users/10387",
"pm_score": 6,
"selected": false,
"text": "public void DoSomething(params string[] theStrings)\n{\n foreach(string s in theStrings)\n {\n // Something with the Strings…\n }\n}\n DoSomething(“The”, “cat”, “sat”, “on”, “the” ,”mat”);\n"
},
{
"answer_id": 165845,
"author": "tsilb",
"author_id": 11112,
"author_profile": "https://Stackoverflow.com/users/11112",
"pm_score": 4,
"selected": false,
"text": "#region stuff1\n #region stuff1a\n //...\n #endregion stuff1a\n#endregion stuff1\n"
},
{
"answer_id": 174763,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "//If given this:\nvar myStrings = new List<string>(){\"abc\",\"def\",\"xyz\"};\n//Then this:\nmyStrings.ForEach(s => Console.WriteLine(s));\n//Is equivalent to this:\nmyStrings.ForEach(Console.WriteLine);\n"
},
{
"answer_id": 176231,
"author": "Patrick Szalapski",
"author_id": 7453,
"author_profile": "https://Stackoverflow.com/users/7453",
"pm_score": 3,
"selected": false,
"text": "public static class Parser {\n public static int? ParseInt(string s) {\n int result;\n bool parsed = int.TryParse(s, out result);\n if (parsed) return result;\n else return null;\n }\n // ...\n}\n int x = 0;\nYourDatabaseResultSet data = new YourDatabaseResultSet();\nif (cond1)\n if (int.TryParse(x_input, x)){\n data = YourDatabaseAccessMethod(\"my_proc_name\", 2, x);\n }\n else{\n x = -1;\n // do something to report \"Can't Parse\" \n }\n}\nelse {\n x = y;\n data = YourDatabaseAccessMethod(\"my_proc_name\", \n new SqlParameter(\"@param1\", 2),\n new SqlParameter(\"@param2\", x));\n}\n int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;\nif (x >= 0) data = YourDatabaseAccessMethod(\"my_proc_name\", \n new SqlParameter(\"@param1\", 2),\n new SqlParameter(\"@param2\", x));\n"
},
{
"answer_id": 192127,
"author": "IgorM",
"author_id": 17823,
"author_profile": "https://Stackoverflow.com/users/17823",
"pm_score": 5,
"selected": false,
"text": "public static void Main()\n{\n StackTrace stackTrace = new StackTrace(); // get call stack\n StackFrame[] stackFrames = stackTrace.GetFrames(); // get method calls (frames)\n\n // write call stack method names\n foreach (StackFrame stackFrame in stackFrames)\n {\n Console.WriteLine(stackFrame.GetMethod().Name); // write method name\n }\n}\n"
},
{
"answer_id": 195097,
"author": "sbeskur",
"author_id": 10446,
"author_profile": "https://Stackoverflow.com/users/10446",
"pm_score": 3,
"selected": false,
"text": "public bool GetFooSetting(XElement ndef){\n return (bool?)ndef.Element(\"MyBoolSettingValue\") ?? true;\n}\n public bool GetFooSetting(XElement ndef){\n return ndef.Element(\"MyBoolSettingValue\") != null ? bool.Parse(ndef.Element(\"MyBoolSettingValue\") ) : true;\n}\n"
},
{
"answer_id": 199247,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 7,
"selected": false,
"text": "Environment.FailFast()\n"
},
{
"answer_id": 199257,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 2,
"selected": false,
"text": "double dSqrd = Math.Pow(d,2.0); \n double dSqrd = d * d; // Here we can lose precision\n"
},
{
"answer_id": 199269,
"author": "Jan Bannister",
"author_id": 460845,
"author_profile": "https://Stackoverflow.com/users/460845",
"pm_score": 3,
"selected": false,
"text": "switch(name)\n{\n case \"Dave\":\n return true;\n case \"Bob\":\n return false;\n default:\n throw new ApplicationException();\n}\n"
},
{
"answer_id": 212905,
"author": "Cristian Libardo",
"author_id": 16526,
"author_profile": "https://Stackoverflow.com/users/16526",
"pm_score": 6,
"selected": false,
"text": "string hello = \"world\";\nvar o = new { hello };\nConsole.WriteLine(o.hello);\n"
},
{
"answer_id": 214951,
"author": "Mike Two",
"author_id": 23659,
"author_profile": "https://Stackoverflow.com/users/23659",
"pm_score": 6,
"selected": false,
"text": "\n<configuration>\n <runtime>\n <gcServer enabled=\"true\"/>\n </runtime>\n</configuration>\n"
},
{
"answer_id": 236173,
"author": "splattne",
"author_id": 6461,
"author_profile": "https://Stackoverflow.com/users/6461",
"pm_score": 3,
"selected": false,
"text": " object o = null;\n object p = null;\n object q = new Object();\n\n Console.WriteLine(Object.ReferenceEquals(o, p));\n p = q;\n Console.WriteLine(Object.ReferenceEquals(p, q));\n Console.WriteLine(Object.ReferenceEquals(o, p));\n"
},
{
"answer_id": 238462,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 7,
"selected": false,
"text": "public static DeepCopy(this IPrototype p) { ... }\n"
},
{
"answer_id": 258982,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "public event EventHandler<MyEventArgs> MyEvent;\n"
},
{
"answer_id": 259028,
"author": "Dan Fleet",
"author_id": 7470,
"author_profile": "https://Stackoverflow.com/users/7470",
"pm_score": 2,
"selected": false,
"text": "[UnmanagedFunctionPointerAttribute(CallingConvention.CDecl)]"
},
{
"answer_id": 259134,
"author": "Gavin Miller",
"author_id": 33226,
"author_profile": "https://Stackoverflow.com/users/33226",
"pm_score": 3,
"selected": false,
"text": "Units.UnitsDataTable dataTable = new Units.UnitsDataTable();\n\nforeach (Units.UnitsRow row in dataTable.Rows)\n{\n if (row.IsPrimaryKeyNull())\n //....\n\n if (row.IsForeignKeyNull())\n //....\n}\n"
},
{
"answer_id": 263868,
"author": "Cohen",
"author_id": 34474,
"author_profile": "https://Stackoverflow.com/users/34474",
"pm_score": 3,
"selected": false,
"text": "if (x < lowerBoundary) \n{\n x = lowerBoundary;\n}\n x = Math.Max(x, lowerBoundary);\n x = ( x < lowerBoundary) ? lowerBoundary : x;\n"
},
{
"answer_id": 263883,
"author": "Cohen",
"author_id": 34474,
"author_profile": "https://Stackoverflow.com/users/34474",
"pm_score": 4,
"selected": false,
"text": "\"string\".equals(\"String\", StringComparison.InvariantCultureIgnoreCase)\n \"string\".ToLower() == \"String\".ToLower();\n"
},
{
"answer_id": 270430,
"author": "Dmitri Nesteruk",
"author_id": 9476,
"author_profile": "https://Stackoverflow.com/users/9476",
"pm_score": 3,
"selected": false,
"text": "internal interface IPrototype<T> { }\n internal static class Prototype\n{\n public static T DeepCopy<T>(this IPrototype<T> target)\n {\n T copy;\n using (var stream = new MemoryStream())\n {\n var formatter = new BinaryFormatter();\n formatter.Serialize(stream, (T)target);\n stream.Seek(0, SeekOrigin.Begin);\n copy = (T) formatter.Deserialize(stream);\n stream.Close();\n }\n return copy;\n }\n}\n"
},
{
"answer_id": 292258,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 2,
"selected": false,
"text": "public string Caption\n{\n get { return (string) (ViewState[\"Caption\"] ?? \"Foo\"); }\n set { ViewState[\"Caption\"] = value; }\n}\n\npublic int Index\n{\n get { return (int) (ViewState[\"Index\"] ?? 0); }\n set { ViewState[\"Index\"] = value; }\n}\n public string Caption\n{\n get { return (string) ViewState[\"Caption\"]; }\n set { ViewState[\"Caption\"] = value; }\n}\n\npublic int? Index\n{\n get { return (int?) ViewState[\"Index\"]; }\n set { ViewState[\"Index\"] = value; }\n}\n"
},
{
"answer_id": 295174,
"author": "Eyvind",
"author_id": 25746,
"author_profile": "https://Stackoverflow.com/users/25746",
"pm_score": 3,
"selected": false,
"text": "foreach"
},
{
"answer_id": 299153,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 3,
"selected": false,
"text": "try\n{\n return _field;\n}\nfinally\n{\n _field = null;\n}\n"
},
{
"answer_id": 299236,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 5,
"selected": false,
"text": "public StringBuilder Builder\n{\n get { return _builder ?? (_builder = new StringBuilder()); }\n}\n"
},
{
"answer_id": 300100,
"author": "open-collar",
"author_id": 21686,
"author_profile": "https://Stackoverflow.com/users/21686",
"pm_score": 4,
"selected": false,
"text": "using(new CursorState(this, BusyCursor));\n{\n // Do stuff\n}\n"
},
{
"answer_id": 302484,
"author": "Tor Haugen",
"author_id": 32050,
"author_profile": "https://Stackoverflow.com/users/32050",
"pm_score": 4,
"selected": false,
"text": "public class MyClass\n{\n public string Hårføner()\n {\n return \"Yes, it works!\";\n }\n}\n public class MyClass\n{\n public string H\\u00e5rføner()\n {\n return \"Yes, it (still) works!\";\n }\n}\n"
},
{
"answer_id": 302602,
"author": "MysticSlayer",
"author_id": 28139,
"author_profile": "https://Stackoverflow.com/users/28139",
"pm_score": 4,
"selected": false,
"text": "#if DEBUG\n Console.Write(\"Debugging\");\n#else\n Console.Write(\"Final\");\n#endif\n"
},
{
"answer_id": 314065,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 3,
"selected": false,
"text": "IEnumerable SelectMany Orders Order LineItems LineItems int totalItems = Orders.Select(o => o.LineItems).SelectMany(i => i).Sum();\n"
},
{
"answer_id": 336237,
"author": "Phillip Ngan",
"author_id": 41410,
"author_profile": "https://Stackoverflow.com/users/41410",
"pm_score": 4,
"selected": false,
"text": "Action<> Func<> Action<int> Func<int> Func<int, bool>"
},
{
"answer_id": 343526,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "System.Xml.XmlConvert bool myFlag = System.Xml.XmlConvert.ToBoolean(myAttribute.Value);\n"
},
{
"answer_id": 355991,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 6,
"selected": false,
"text": "checked unchecked short x = 32767; // 32767 is the max value for short\nshort y = 32767;\nint z1 = checked((short)(x + y)); //will throw an OverflowException\nint z2 = unchecked((short)(x + y)); // will return -2\nint z3 = (short)(x + y); // will return -2\n"
},
{
"answer_id": 365801,
"author": "Binoj Antony",
"author_id": 33015,
"author_profile": "https://Stackoverflow.com/users/33015",
"pm_score": 3,
"selected": false,
"text": "class ClassA \n{\n public ClassA(int a)\n {\n //Do something\n }\n\n public void Method1()\n {\n //Do Something\n }\n}\n\nclass ClassB : ClassA\n{\n public ClassB(int a) : base(a) // calling the base class constructor\n {\n //Do something\n }\n\n public void Method2()\n {\n base.Method1(); // calling the base class method\n }\n}\n base.MethodName()"
},
{
"answer_id": 368625,
"author": "amazedsaint",
"author_id": 45956,
"author_profile": "https://Stackoverflow.com/users/45956",
"pm_score": 3,
"selected": false,
"text": "dynamic invoker=new DynamicInvoker();\ndynamic result1=invoker.MyMethod1();\ndynamic result2=invoker.MyMethod2();\n public class DynamicInvoker : IDynamicObject\n {\n public MetaObject GetMetaObject\n (System.Linq.Expressions.Expression parameter)\n {\n return new DynamicReaderDispatch (parameter);\n }\n }\n\n public class DynamicDispatcher : MetaObject\n {\n public DynamicDispatcher (Expression parameter) \n : base(parameter, Restrictions.Empty){ }\n\n public override MetaObject Call(CallAction action, MetaObject[] args)\n {\n //You'll get MyMethod1 and MyMethod2 here (and what ever you call)\n Console.WriteLine(\"Logic to invoke Method '{0}'\", action.Name);\n return this; //Return a meta object\n }\n }\n"
},
{
"answer_id": 370561,
"author": "Rinat Abdullin",
"author_id": 47366,
"author_profile": "https://Stackoverflow.com/users/47366",
"pm_score": 4,
"selected": false,
"text": "static void Main(string[] args)\n{\n var domain = \"matrix\";\n Check(() => domain);\n Console.ReadLine();\n}\n\nstatic void Check<T>(Expression<Func<T>> expr)\n{\n var body = ((MemberExpression)expr.Body);\n Console.WriteLine(\"Name is: {0}\", body.Member.Name);\n Console.WriteLine(\"Value is: {0}\", ((FieldInfo)body.Member)\n .GetValue(((ConstantExpression)body.Expression).Value));\n}\n\n// output:\n// Name is: 'domain'\n// Value is: 'matrix'\n"
},
{
"answer_id": 388760,
"author": "Moran Helman",
"author_id": 1409636,
"author_profile": "https://Stackoverflow.com/users/1409636",
"pm_score": 3,
"selected": false,
"text": "List<T> List<int> s = new List<int> { 6, 1, 2 };\n\nbool a = s.TrueForAll(p => p > 0);\n"
},
{
"answer_id": 391966,
"author": "Michael Meadows",
"author_id": 7643,
"author_profile": "https://Stackoverflow.com/users/7643",
"pm_score": 5,
"selected": false,
"text": "bool changed = false;\n\nif (model.Prop1 != prop1)\n{\n changed = true;\n model.Prop1 = prop1;\n}\nif (model.Prop2 != prop2)\n{\n changed = true;\n model.Prop2 = prop2;\n}\n// ... etc. \n Action setAndTagChanged bool changed = false;\nAction<Action> setAndTagChanged = (action) => \n{ \n changed = true; \n action(); \n};\n\nif (model.Prop1 != prop1) setAndTagChanged(() => model.Prop1 = prop1);\nif (model.Prop2 != prop2) setAndTagChanged(() => model.Prop2 = prop2);\n change private bool conditionalSet(bool condition, Action action)\n{\n if (condition) action();\n return condition;\n}\n\n// ...\n\nbool changed = false;\nchanged |= conditionalSet(model.Prop1 == prop1, () => model.Prop1 = prop1);\nchanged |= conditionalSet(model.Prop2 == prop2, () => model.Prop2 = prop2);\n"
},
{
"answer_id": 399297,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "//Place at top of your code\npublic UseAutoDebug = true;\n\n\n//Place anywhere in your code including catch areas in try/catch blocks\nDebug.Assert(!this.UseAutoDebug);\n"
},
{
"answer_id": 405088,
"author": "Mark Cidade",
"author_id": 1659,
"author_profile": "https://Stackoverflow.com/users/1659",
"pm_score": 4,
"selected": false,
"text": "IDisposable IEnumerable interface IFoo<T>\n { T Bar {get;}\n }\n\n class MyFoo<T> : IFoo<T> \n { public MyFoo(T t) {Bar = t;}\n public T Bar {get; private set;} \n }\n\n static class Foo \n { public static IFoo<T> ToFoo<T>(this T t) {return new MyFoo<T>(t);}\n\n public static void Do<T>(this T t, Action<T> a) { a(t);}\n\n public static IFoo<U> Select<T,U>(this IFoo<T> foo, Func<T,U> f) \n { return f(foo.Bar).ToFoo();\n }\n }\n\n /* ... */\n\n using (var file = File.OpenRead(\"objc.h\"))\n { var x = from f in file.ToFoo()\n let s = new Scanner(f)\n let p = new Parser {scanner = s}\n select p.Parse();\n\n x.Do(p => \n { /* drop into imperative code to handle file \n in Foo monad if necessary */ \n });\n\n }\n"
},
{
"answer_id": 407325,
"author": "hugoware",
"author_id": 17091,
"author_profile": "https://Stackoverflow.com/users/17091",
"pm_score": 5,
"selected": false,
"text": "[Flags]\npublic enum ErrorTypes : int {\n None = 0,\n MissingPassword = 1,\n MissingUsername = 2,\n PasswordIncorrect = 4\n}\n\npublic static class EnumExtensions {\n\n public static T Append<T> (this System.Enum type, T value) where T : struct\n {\n return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));\n }\n\n public static T Remove<T> (this System.Enum type, T value) where T : struct\n {\n return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value));\n }\n\n public static bool Has<T> (this System.Enum type, T value) where T : struct\n {\n return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);\n }\n\n}\n\n...\n\n//used like the following...\n\nErrorTypes error = ErrorTypes.None;\nerror = error.Append(ErrorTypes.MissingUsername);\nerror = error.Append(ErrorTypes.MissingPassword);\nerror = error.Remove(ErrorTypes.MissingUsername);\n\n//then you can check using other methods\nif (error.Has(ErrorTypes.MissingUsername)) {\n ...\n}\n"
},
{
"answer_id": 498292,
"author": "Andrew Peters",
"author_id": 608,
"author_profile": "https://Stackoverflow.com/users/608",
"pm_score": 3,
"selected": false,
"text": "(_, b, __) => b.DoStuff(); // only interested in b here\n"
},
{
"answer_id": 508371,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Linq.Expressions;\n\nnamespace BinaryOpGenericTest\n{\n [Flags]\n enum MyFlags\n {\n A = 1,\n B = 2,\n C = 4\n\n }\n\n static class EnumExtensions\n {\n private static Dictionary<Type, Delegate> m_operations = new Dictionary<Type, Delegate>();\n\n public static bool IsFlagSet<T>(this T firstOperand, T secondOperand) \n where T : struct\n {\n\n Type enumType = typeof(T);\n\n\n if (!enumType.IsEnum)\n {\n throw new InvalidOperationException(\"Enum type parameter required\");\n }\n\n\n Delegate funcImplementorBase = null;\n m_operations.TryGetValue(enumType, out funcImplementorBase);\n\n Func<T, T, bool> funcImplementor = funcImplementorBase as Func<T, T, bool>;\n\n if (funcImplementor == null)\n {\n funcImplementor = buildFuncImplementor(secondOperand);\n }\n\n\n\n return funcImplementor(firstOperand, secondOperand);\n }\n\n\n private static Func<T, T, bool> buildFuncImplementor<T>(T val)\n where T : struct\n {\n var first = Expression.Parameter(val.GetType(), \"first\");\n var second = Expression.Parameter(val.GetType(), \"second\");\n\n Expression convertSecondExpresion = Expression.Convert(second, typeof(int));\n var andOperator = Expression.Lambda<Func<T, T, bool>>(Expression.Equal(\n Expression.And(\n Expression.Convert(first, typeof(int)),\n convertSecondExpresion),\n convertSecondExpresion),\n new[] { first, second });\n Func<T, T, bool> andOperatorFunc = andOperator.Compile();\n m_operations[typeof(T)] = andOperatorFunc;\n return andOperatorFunc;\n }\n }\n\n\n class Program\n {\n static void Main(string[] args)\n {\n MyFlags flag = MyFlags.A | MyFlags.B;\n\n Console.WriteLine(flag.IsFlagSet(MyFlags.A)); \n Console.WriteLine(EnumExtensions.IsFlagSet(flag, MyFlags.C));\n Console.ReadLine();\n }\n }\n}\n"
},
{
"answer_id": 593134,
"author": "Jonathan Parker",
"author_id": 4504,
"author_profile": "https://Stackoverflow.com/users/4504",
"pm_score": 3,
"selected": false,
"text": "Func<Func<int,int>,int,int> myFunc1 = (i, j) => i(j);\nFunc<int, int> myFunc2 = i => i + 2;\n var x = myFunc1(myFunc2, 1);\n var x = myFunc1(z => myFunc2(z), 1);\n"
},
{
"answer_id": 618582,
"author": "tuinstoel",
"author_id": 43901,
"author_profile": "https://Stackoverflow.com/users/43901",
"pm_score": 4,
"selected": false,
"text": "interface IPropA \n{\n string PropA { get; set; } \n}\n\ninterface IPropB \n{\n string PropB { get; set; }\n}\n\nclass TestClass \n{\n void DoSomething<T>(T t) where T : IPropA, IPropB \n {\n MessageBox.Show(t.PropA);\n MessageBox.Show(t.PropB);\n }\n}\n"
},
{
"answer_id": 637760,
"author": "kentaromiura",
"author_id": 27340,
"author_profile": "https://Stackoverflow.com/users/27340",
"pm_score": 3,
"selected": false,
"text": "namespace constructorChain {\n using System;\n\n public class Class1 {\n public string x;\n public string y;\n\n public Class1() {\n x = \"class1\";\n y = \"\";\n }\n\n public Class1(string y)\n : this() {\n this.y = y;\n }\n }\n\n public class Class2 : Class1 {\n public Class2(int y)\n : base(y.ToString()) {\n\n }\n }\n}\n constructorChain.Class1 c1 = new constructorChain.Class1();\n constructorChain.Class1 c12 = new constructorChain.Class1(\"Hello, Constructor!\");\n constructorChain.Class2 c2 = new constructorChain.Class2(10);\n Console.WriteLine(\"{0}:{1}\", c1.x, c1.y);\n Console.WriteLine(\"{0}:{1}\", c12.x, c12.y);\n Console.WriteLine(\"{0}:{1}\", c2.x, c2.y);\n\n Console.ReadLine();\n"
},
{
"answer_id": 699973,
"author": "Raghu Dodda",
"author_id": 84940,
"author_profile": "https://Stackoverflow.com/users/84940",
"pm_score": 1,
"selected": false,
"text": "string result = \n i < 2 ? //question\n \"less than 2\" : //answer\n i < 5 ? //question\n \"less than 5\": //answer \n i < 10 ? //question\n \"less than 10\": //answer\n \"something else\"; //default answer \n"
},
{
"answer_id": 707480,
"author": "DSO",
"author_id": 38087,
"author_profile": "https://Stackoverflow.com/users/38087",
"pm_score": 3,
"selected": false,
"text": "Microsoft.VisualBasic.Logging.FileLogTraceListener\n"
},
{
"answer_id": 709198,
"author": "Waleed Eissa",
"author_id": 676066,
"author_profile": "https://Stackoverflow.com/users/676066",
"pm_score": 3,
"selected": false,
"text": "enum MyEnum\n{\n FirstValue,\n SecondValue,\n ThirdValue\n}\n\nstring enumValueString = \"FirstValue\";\nMyEnum val = (MyEnum)Enum.Parse(typeof(MyEnum), enumValueString, true)\n MyEnum val = MyEnum.SecondValue;\nif (val < MyEnum.ThirdValue)\n{\n // Do something\n}\n"
},
{
"answer_id": 710507,
"author": "Gorkem Pacaci",
"author_id": 51749,
"author_profile": "https://Stackoverflow.com/users/51749",
"pm_score": 3,
"selected": false,
"text": "public void DoStuff<T>(T value);\n DoStuff<int>(5);\n DoStuff(5);\n"
},
{
"answer_id": 749846,
"author": "Ralph Caraveo",
"author_id": 71079,
"author_profile": "https://Stackoverflow.com/users/71079",
"pm_score": 7,
"selected": false,
"text": "if( myString.ToUpper() == theirString.ToUpper() ){ ... }\n if( myString.Equals( theirString, StringComparison.OrdinalIgnoreCase ) ){ ... }\n"
},
{
"answer_id": 759323,
"author": "Peter Lillevold",
"author_id": 35245,
"author_profile": "https://Stackoverflow.com/users/35245",
"pm_score": 4,
"selected": false,
"text": "[assembly: InternalsVisibleTo(\"MyLibrary.Test, PublicKey=0024...5c042cb\")]\n"
},
{
"answer_id": 781561,
"author": "Akash Kava",
"author_id": 85597,
"author_profile": "https://Stackoverflow.com/users/85597",
"pm_score": 3,
"selected": false,
"text": "struct cType{\n char type[4];\n int size;\n char name[50];\n char email[100];\n}\n\ncType myType;\nfread(file, &mType, sizeof(mType));\n [Layout(LayoutKind.Sequential, Pack=1)]\npublic unsafe class CType{\n public fixed byte type[4];\n public int size;\n public fixed byte name[50];\n public fixed byte email[100];\n}\n CType mType = new CType();\nbyte[] buffer = new byte[Marshal.SizeOf(CType)];\nstream.Read(buffer,0,buffer.Length);\n// you can map your buffer back to your struct...\nfixed(CType* sp = &mType)\n{\n byte* bsp = (byte*) sp;\n fixed(byte* bp = &buffer)\n {\n for(int i=0;i<buffer.Length;i++)\n {\n (*bsp) = (*bp);\n bsp++;bp++;\n }\n }\n}\n CType mType = new CType();\nfixed(CType* p = &mType)\n{\n User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);\n}\n"
},
{
"answer_id": 791096,
"author": "Elroy",
"author_id": 56097,
"author_profile": "https://Stackoverflow.com/users/56097",
"pm_score": 3,
"selected": false,
"text": "public class GenericList<T>\n{\n private class Node\n {\n //...\n\n public Node Next;\n public T Data;\n }\n\n private Node head;\n\n //...\n\n public T GetNext()\n {\n T temp = default(T);\n\n Node current = head;\n if (current != null)\n {\n temp = current.Data;\n current = current.Next;\n }\n return temp;\n }\n}\n"
},
{
"answer_id": 821718,
"author": "rein",
"author_id": 100142,
"author_profile": "https://Stackoverflow.com/users/100142",
"pm_score": 3,
"selected": false,
"text": "Console.WriteLine(\"{0} item(s) found.\", count);\n Console.WriteLine(\"{0} item{1} found.\", count, count==1 ? \"\" : \"s\");\n"
},
{
"answer_id": 840445,
"author": "nsantorello",
"author_id": 94824,
"author_profile": "https://Stackoverflow.com/users/94824",
"pm_score": 3,
"selected": false,
"text": "#error This is an error. #warning This is a warning. #error Implement this function #warning Eventually implement this corner case"
},
{
"answer_id": 841140,
"author": "Jeff Yates",
"author_id": 23234,
"author_profile": "https://Stackoverflow.com/users/23234",
"pm_score": 3,
"selected": false,
"text": "DefaultValueAttribute ForeColor BackColor AmbientValue Color.Empty public static bool Contains(\n this MyEnumType enumValue,\n MyEnumType flagValue)\n {\n return ((enumValue & flagValue) == flagValue);\n }\n\n public static bool ContainsAny(\n this MyEnumType enumValue,\n MyEnumType flagValue)\n {\n return ((enumValue & flagValue) > 0);\n }\n dynamic"
},
{
"answer_id": 862323,
"author": "Ash",
"author_id": 5023,
"author_profile": "https://Stackoverflow.com/users/5023",
"pm_score": 3,
"selected": false,
"text": " void FileMessageEvent(object sender, MessageEventArgs e)\n {\n\n if (this.InvokeRequired == true)\n {\n this.BeginInvoke((MethodInvoker)delegate { \n lblMessage.Text=e.Message; \n Application.DoEvents(); \n }\n ); \n\n }\n }\n"
},
{
"answer_id": 874167,
"author": "Josef Pfleger",
"author_id": 98401,
"author_profile": "https://Stackoverflow.com/users/98401",
"pm_score": 3,
"selected": false,
"text": "string output = \"helo world!\";\nAction action = () => Console.WriteLine(output);\noutput = \"hello!\";\naction();\n hello! Action action;\n<>c__DisplayClass1 CS$<>8__locals2;\nCS$<>8__locals2 = new <>c__DisplayClass1();\nCS$<>8__locals2.output = \"helo world!\";\naction = new Action(CS$<>8__locals2.<Main>b__0);\nCS$<>8__locals2.output = \"hello!\";\naction();\n"
},
{
"answer_id": 882100,
"author": "Shalom Craimer",
"author_id": 54491,
"author_profile": "https://Stackoverflow.com/users/54491",
"pm_score": 3,
"selected": false,
"text": "Convert Array.ConvertAll int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(\n someArrayYouHaveAsInt,\n new Converter<int,double>(Convert.ToDouble));\n int[] someArrayYouHaveAsInt;\ndouble[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(\n someArrayYouHaveAsInt,\n new Converter<int,double>(\n delegate(int i) { return (double)i; }\n ));\n"
},
{
"answer_id": 883586,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 3,
"selected": false,
"text": "var pets = new[] { \"Cat\", \"Dog\", \"Bird\" };\n"
},
{
"answer_id": 899593,
"author": "Oorang",
"author_id": 102270,
"author_profile": "https://Stackoverflow.com/users/102270",
"pm_score": 2,
"selected": false,
"text": "static void Example()\n{\n int i = 0;\ntop:\n Console.WriteLine(i.ToString());\n if (i == 0)\n {\n i++;\n goto top;\n }\n}\n"
},
{
"answer_id": 938302,
"author": "Dave Van den Eynde",
"author_id": 455874,
"author_profile": "https://Stackoverflow.com/users/455874",
"pm_score": 4,
"selected": false,
"text": "[assembly: ComVisible(false)]\n [return: SomeAttr]\nint Method3() { return 0; } \n"
},
{
"answer_id": 945247,
"author": "Showtime",
"author_id": 114893,
"author_profile": "https://Stackoverflow.com/users/114893",
"pm_score": 1,
"selected": false,
"text": "GC.SuppressFinalize(object); GC.KeepAlive(object);"
},
{
"answer_id": 945300,
"author": "Lloyd Powell",
"author_id": 67258,
"author_profile": "https://Stackoverflow.com/users/67258",
"pm_score": 3,
"selected": false,
"text": "private double _Zoom = 1;\n\n[Category(\"View\")]\n[Description(\"The Current Zoom Level\")]\npublic double Zoom\n{\nget { return _Zoom;}\nset { _Zoom = value;}\n}\n"
},
{
"answer_id": 949309,
"author": "RCIX",
"author_id": 117069,
"author_profile": "https://Stackoverflow.com/users/117069",
"pm_score": 2,
"selected": false,
"text": "...\npublic Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) => \n{\n return (input.LeftStickPosition.X * _moveRate) * _zoom;\n}\npublic Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) => \n{\n return (-input.LeftStickPosition.Y * _moveRate) * _zoom;\n}\n...\npublic void Update(InputHelper input)\n{\n ...\n position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));\n ...\n}\n private int foo;\npublic int FooProperty {\n get\n {\n if (_onFooGotten() == true)\n return _foo;\n }\n set\n {\n if (onFooSet() == true)\n _foo = value;\n }\n}\n...\npublic Func<bool> _onFooGotten = () => \n{\n //do whatever...\n return true;\n}\npublic Func<bool> _onFooSet = () =>\n{\n //do whatever...\n return true;\n}\n"
},
{
"answer_id": 957443,
"author": "Andrew Lavers",
"author_id": 77501,
"author_profile": "https://Stackoverflow.com/users/77501",
"pm_score": 4,
"selected": false,
"text": "[Flags]\npublic enum ConfigOptions\n{\n None = 0,\n A = 1 << 0,\n B = 1 << 1,\n Both = A | B\n}\n\nConsole.WriteLine( ConfigOptions.A.ToString() );\nConsole.WriteLine( ConfigOptions.Both.ToString() );\n// Will print:\n// A\n// A, B\n"
},
{
"answer_id": 961401,
"author": "Tolgahan Albayrak",
"author_id": 104468,
"author_profile": "https://Stackoverflow.com/users/104468",
"pm_score": 3,
"selected": false,
"text": "enum EnumName : [byte, char, int16, int32, int64, uint16, uint32, uint64]\n{\n A = 1,\n B = 2\n}\n"
},
{
"answer_id": 993118,
"author": "zebrabox",
"author_id": 122755,
"author_profile": "https://Stackoverflow.com/users/122755",
"pm_score": 2,
"selected": false,
"text": "[assembly::InternalsVisibleTo(\"SomeAssembly\")]\n public MyClass\n{\n public static MyClass()\n {\n // type init goes here\n }\n ......\n} \n internal"
},
{
"answer_id": 1016037,
"author": "SLaks",
"author_id": 34397,
"author_profile": "https://Stackoverflow.com/users/34397",
"pm_score": 3,
"selected": false,
"text": "this static class FunnyExtension {\n public static string Double(this string str) { return str + str; }\n public static int Double(this int num) { return num + num; }\n}\n\n\nFunc<string> aaMaker = \"a\".Double;\nFunc<string, string> doubler = FunnyExtension.Double;\n\nConsole.WriteLine(aaMaker()); //Prints \"aa\"\nConsole.WriteLine(doubler(\"b\")); //Prints \"bb\"\n"
},
{
"answer_id": 1017882,
"author": "Titian Cernicova-Dragomir",
"author_id": 125734,
"author_profile": "https://Stackoverflow.com/users/125734",
"pm_score": 3,
"selected": false,
"text": "[ThreadStatic]\nprivate static int _ThreadStaticInteger;\n using (DbTransaction tran = new DbTransaction())\n{\n DoQuery(\"...\");\n DoQuery(\"...\"); \n}\n"
},
{
"answer_id": 1025614,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "HttpContext.Current.Server.Execute \n Page pageHolder = new Page();\nUserControl viewControl = (UserControl)pageHolder.LoadControl(@\"MyComponent.ascx\");\npageHolder.Controls.Add(viewControl);\nStringWriter output = new StringWriter();\nHttpContext.Current.Server.Execute(pageHolder, output, false);\nreturn output.ToString();\n"
},
{
"answer_id": 1026941,
"author": "Paul Ruane",
"author_id": 83264,
"author_profile": "https://Stackoverflow.com/users/83264",
"pm_score": 2,
"selected": false,
"text": "[field:NonSerializable]\npublic event SomeDelegate SomeEvent;\n"
},
{
"answer_id": 1049977,
"author": "Mike",
"author_id": 127831,
"author_profile": "https://Stackoverflow.com/users/127831",
"pm_score": 4,
"selected": false,
"text": "handler += new EventHandler(func);\n handler += func;\n"
},
{
"answer_id": 1062170,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": " //Constructor constraint, T has a default empty constructor\nclass Node<K,T> where T : new() \n{\n}\n\n//Reference\\Value Type constraints\n//T is a struct\npublic class MyClass<T> where T : struct \n\n{...}\n\n//T is a reference type\npublic class MyClass<T> where T : class \n\n{...}\n\npublic class MyClass<T> where T : SomeBaseClass, ISomeInterface \n\n{...}\n"
},
{
"answer_id": 1062556,
"author": "Mark Seemann",
"author_id": 126014,
"author_profile": "https://Stackoverflow.com/users/126014",
"pm_score": 3,
"selected": false,
"text": "Or x |= y\n x = x | y\n x false true"
},
{
"answer_id": 1071983,
"author": "Wim Coenen",
"author_id": 52626,
"author_profile": "https://Stackoverflow.com/users/52626",
"pm_score": 4,
"selected": false,
"text": "null NullReferenceException ToString() ToStringOrEmpty() null"
},
{
"answer_id": 1114418,
"author": "Yvo",
"author_id": 136819,
"author_profile": "https://Stackoverflow.com/users/136819",
"pm_score": 5,
"selected": false,
"text": "String.Join(\",\", new String[] { \"a\", \"b\", \"c\"});\n // TODO: Implement this!\nthrow new NotImplementedException();\n public static void Process<T>(this T item) where T:ITest,ITest2 {}\n Enumerable.Range(0, 15)\n"
},
{
"answer_id": 1118859,
"author": "softveda",
"author_id": 11711,
"author_profile": "https://Stackoverflow.com/users/11711",
"pm_score": 3,
"selected": false,
"text": " string str = \"some string\";\n Console.WriteLine(str);\n unsafe\n {\n fixed(char *s = str)\n {\n char *c = s;\n while(*c != '\\0')\n {\n *c = Char.ToUpper(*c++); \n }\n }\n }\n Console.WriteLine(str);\n"
},
{
"answer_id": 1135505,
"author": "David.Chu.ca",
"author_id": 62776,
"author_profile": "https://Stackoverflow.com/users/62776",
"pm_score": 3,
"selected": false,
"text": "// defines a descriptive name for a complexed data type\nusing MyDomainClassList = System.Collections.Generic.List<\n MyProjectNameSpace.MyDomainClass>;\n\n....\n\n\nMyDomainClassList myList = new MyDomainClassList();\n/* instead of \nList<MyDomainClass> myList = new List<MyDomainClass>();\n*/\n using FloatValue = float; // you only need to change it once to decimal, double...\n\n....\nFloatValue val1;\n...\n"
},
{
"answer_id": 1161934,
"author": "Dan Diplo",
"author_id": 140392,
"author_profile": "https://Stackoverflow.com/users/140392",
"pm_score": 2,
"selected": false,
"text": "Func<int,int> f = x => x + 1;\n var three = f(2); // 2 + 1\n Expression<Func<int,int>> expression = x => x + 1;\n var originalDelegate = expression.Compile();\n\nvar three = originalDelegate.Invoke(2);\n"
},
{
"answer_id": 1162648,
"author": "Martin Konicek",
"author_id": 90998,
"author_profile": "https://Stackoverflow.com/users/90998",
"pm_score": 3,
"selected": false,
"text": "[field: NonSerialized]\npublic event EventHandler Event;\n"
},
{
"answer_id": 1163889,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "DateTime.MinValue DateTime? myDate = null;\n\nif (myDate.HasValue)\n{\n //doSomething\n}\nelse\n{\n //soSomethingElse\n}\n"
},
{
"answer_id": 1173935,
"author": "Brad",
"author_id": 70130,
"author_profile": "https://Stackoverflow.com/users/70130",
"pm_score": 2,
"selected": false,
"text": "string[] itemList = { \"Example 1\", \"Example 2\", \"Example 3\" };\nCommaDelimitedStringCollection commaStr = new CommaDelimitedStringCollection();\ncommaStr.AddRange(itemList);\n//outputs Example 1,Example 2,Example 3\n"
},
{
"answer_id": 1185988,
"author": "Paul van Brenk",
"author_id": 1837197,
"author_profile": "https://Stackoverflow.com/users/1837197",
"pm_score": 3,
"selected": false,
"text": "()=>Console.ReadLine()\n"
},
{
"answer_id": 1204390,
"author": "ccook",
"author_id": 51275,
"author_profile": "https://Stackoverflow.com/users/51275",
"pm_score": 3,
"selected": false,
"text": "for (;;);\n while (true) ;\n"
},
{
"answer_id": 1204441,
"author": "Brian Surowiec",
"author_id": 39605,
"author_profile": "https://Stackoverflow.com/users/39605",
"pm_score": 4,
"selected": false,
"text": "public static class Strings\n{\n public static bool IsNullOrEmpty(this string value)\n {\n return string.IsNullOrEmpty(value);\n }\n}\n var input = Console.ReadLine();\nif (input.IsNullOrEmpty())\n{\n Console.WriteLine(\"try again\");\n}\n"
},
{
"answer_id": 1231428,
"author": "Christian Hubmann",
"author_id": 62910,
"author_profile": "https://Stackoverflow.com/users/62910",
"pm_score": 6,
"selected": false,
"text": "string s = string.Format(\"{0:positive;negative;zero}\", i);\n string format = \"000;-#;(0)\";\n\nstring pos = 1.ToString(format); // 001\nstring neg = (-1).ToString(format); // -1\nstring zer = 0.ToString(format); // (0)\n"
},
{
"answer_id": 1234603,
"author": "Ray",
"author_id": 149650,
"author_profile": "https://Stackoverflow.com/users/149650",
"pm_score": 1,
"selected": false,
"text": "protected void OnEvent<T>(EventHandler<T> eventHandler, T args) where T : EventArgs\n{\n if (eventHandler == null) return;\n\n foreach (EventHandler<T> singleEvent in eventHandler.GetInvocationList())\n {\n if (singleEvent.Target != null && singleEvent.Target is ISynchronizeInvoke)\n {\n var target = (ISynchronizeInvoke)singleEvent.Target;\n\n if (target.InvokeRequired) {\n target.BeginInvoke(singleEvent, new object[] { this, args });\n continue;\n }\n }\n singleEvent(this, args);\n }\n}\n public event EventHandler<ProgressEventArgs> ProgressChanged;\n\nprivate void OnProgressChanged(int processed, int total)\n{\n OnEvent(ProgressChanged, new ProgressEventArgs(processed, total));\n}\n"
},
{
"answer_id": 1242225,
"author": "JoshL",
"author_id": 20625,
"author_profile": "https://Stackoverflow.com/users/20625",
"pm_score": 3,
"selected": false,
"text": "new Dictionary<string, Int64>() {{\"Testing\", 123}, {\"Test\", 125}};"
},
{
"answer_id": 1243242,
"author": "ata",
"author_id": 150830,
"author_profile": "https://Stackoverflow.com/users/150830",
"pm_score": 3,
"selected": false,
"text": "DateTime? date = null;\n"
},
{
"answer_id": 1247323,
"author": "paracycle",
"author_id": 98634,
"author_profile": "https://Stackoverflow.com/users/98634",
"pm_score": 2,
"selected": false,
"text": "class Base\n{\n}\n\nclass Foo: Base\n{\n}\n\nclass Bar: Base\n{\n}\n class Base\n{\n public static Base Get()\n {\n // Return a suitable Base.\n }\n}\n\nclass Foo: Base\n{\n public static Foo Get()\n {\n // Return a suitable Foo.\n }\n}\n\nclass Bar: Base\n{\n public static Bar Get()\n {\n // Return a suitable Bar.\n }\n}\n Base Base class Base<T> where T: Base<T>\n{\n public static T Get<T>()\n {\n // Return a suitable T.\n }\n}\n Foo Bar class Foo: Base<Foo>\n{\n}\n\nclass Bar: Base<Bar>\n{\n}\n public class Singleton<T> where T: Singleton<T>, new()\n{\n public static T Instance { get; private set; }\n\n static Singleton<T>()\n {\n Instance = new T();\n }\n}\n where T: protected new()"
},
{
"answer_id": 1280160,
"author": "Maslow",
"author_id": 57883,
"author_profile": "https://Stackoverflow.com/users/57883",
"pm_score": 2,
"selected": false,
"text": "[System.ComponentModel.Browsable(false)]\npublic String LastActionID{get; private set;}\n [System.ComponentModel.DisplayName(\"Last Action\")]\npublic String LastAction{get; private set;}\n [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n private DataController p_dataSources;\n"
},
{
"answer_id": 1318297,
"author": "mezoid",
"author_id": 39532,
"author_profile": "https://Stackoverflow.com/users/39532",
"pm_score": 3,
"selected": false,
"text": "decimal? MyValue = null;\n MyValue == null ? null : MyValue .ToString()\n MyValue.ToString()\n"
},
{
"answer_id": 1371317,
"author": "manji",
"author_id": 166538,
"author_profile": "https://Stackoverflow.com/users/166538",
"pm_score": 3,
"selected": false,
"text": "namespace ns\n{\n class Class1\n {\n Nullable<int> a;\n }\n}\n using System; namespace ns\n{\n class Class1\n {\n int? a;\n }\n}\n"
},
{
"answer_id": 1399045,
"author": "jpierson",
"author_id": 83658,
"author_profile": "https://Stackoverflow.com/users/83658",
"pm_score": 3,
"selected": false,
"text": "public class Outer\n{\n private int Value { get; set; }\n\n public class Inner\n {\n protected void ModifyOuterMember(Outer outer, int value)\n {\n outer.Value = value;\n }\n }\n}\n public class Cheater : Outer.Inner\n{\n protected void MakeValue5(Outer outer)\n {\n ModifyOuterMember(outer, 5);\n }\n}\n"
},
{
"answer_id": 1399130,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 5,
"selected": false,
"text": "var s = new Func<String>(() =>\n{\n return \"Hello World!\";\n})();\n var d = new Func<Dictionary<Int32, String>>(() =>\n{\n return new Dictionary<Int32, String>\n {\n { 0, \"Foo\" },\n { 1, \"Bar\" },\n { 2, \"...\" }\n };\n})();\n var tr = new TableRow();\n\ntr.Cells.AddRange\n(\n new[]\n {\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" },\n\n new TableCell\n {\n Text = new Func<String>(() =>\n {\n return @\"Result of a chunk of logic, without having to define\n the logic outside of the TableCell constructor\";\n })()\n },\n\n new TableCell { Text = \"\" },\n new TableCell { Text = \"\" }\n }\n);\n // The one-liner\nFunc<Int32, Int32, String> Add = (a, b) => Convert.ToString(a + b);\n\n// Multiple lines\nFunc<Int32, Int32, String> Add = (a, b) =>\n{\n var i = a + b;\n\n return i.ToString();\n};\n\n// Without parameters\nFunc<String> Foo = () => \"\";\n\n// Without parameters, multiple lines\nFunc<String> Foo = () =>\n{\n return \"\";\n};\n Func<String, String> Shorten = s => s.Length > 100 ? s.Substring(0, 100) + \"…\" : s;\n"
},
{
"answer_id": 1404712,
"author": "madcyree",
"author_id": 167809,
"author_profile": "https://Stackoverflow.com/users/167809",
"pm_score": 2,
"selected": false,
"text": "[DebuggerTypeProxy(typeof(HashtableDebugView))]\nclass MyHashtable : Hashtable\n{\n private const string TestString = \n \"This should not appear in the debug window.\";\n\n internal class HashtableDebugView\n {\n private Hashtable hashtable;\n public const string TestStringProxy = \n \"This should appear in the debug window.\";\n\n // The constructor for the type proxy class must have a \n // constructor that takes the target type as a parameter.\n public HashtableDebugView(Hashtable hashtable)\n {\n this.hashtable = hashtable;\n }\n }\n}\n"
},
{
"answer_id": 1408887,
"author": "Todd Richardson",
"author_id": 93964,
"author_profile": "https://Stackoverflow.com/users/93964",
"pm_score": 3,
"selected": false,
"text": "@\n string s = \"A line of text\" + Environment.NewLine + \"Another with a \\\"quote\\\"!!\";\n string s = @\"A line of text \nAnother with a \"\"quote\"\"!!\";\n"
},
{
"answer_id": 1415909,
"author": "codymanix",
"author_id": 44952,
"author_profile": "https://Stackoverflow.com/users/44952",
"pm_score": 4,
"selected": false,
"text": "[AttributeUsage(AttributeTargets.All)]\npublic class X: Attribute\n{}\n\n[AttributeUsage(AttributeTargets.All)]\npublic class XAttribute: Attribute\n{}\n\n[X] // Error: ambiguity\nclass Class1 {}\n\n[XAttribute] // Refers to XAttribute\nclass Class2 {}\n\n[@X] // Refers to X\nclass Class3 {}\n\n[@XAttribute] // Refers to XAttribute\nclass Class4 {}\n"
},
{
"answer_id": 1415952,
"author": "codymanix",
"author_id": 44952,
"author_profile": "https://Stackoverflow.com/users/44952",
"pm_score": 5,
"selected": false,
"text": "using (Font f1= new Font(\"Arial\", 10.0f), f2 = new Font(\"Arial\", 10.0f))\n{\n // Use f1 and f2.\n}\n using (Font f1= new Font(\"Arial\", 10.0f))\nusing (Font f2 = new Font(\"Arial\", 10.0f))\n{ }\n"
},
{
"answer_id": 1435045,
"author": "Keith Adler",
"author_id": 135952,
"author_profile": "https://Stackoverflow.com/users/135952",
"pm_score": 4,
"selected": false,
"text": "{ } {\n string test2 = \"3\";\n Console.Write(test2);\n}\n\nConsole.Write(test2); //compile error\n test2"
},
{
"answer_id": 1464831,
"author": "rikoe",
"author_id": 177117,
"author_profile": "https://Stackoverflow.com/users/177117",
"pm_score": 4,
"selected": false,
"text": "EventHandler<T> public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);\n\npublic class MyCustomEventClass \n{\n public event MyCustomEventHandler MyCustomEvent;\n}\n public class MyCustomEventClass \n{\n public event EventHandler<MyCustomEventArgs> MyCustomEvent;\n}\n"
},
{
"answer_id": 1484202,
"author": "Mike Valenty",
"author_id": 124839,
"author_profile": "https://Stackoverflow.com/users/124839",
"pm_score": 3,
"selected": false,
"text": "container.RegisterType(typeof(IRepository<>), typeof(NHibernateRepository<>));\n"
},
{
"answer_id": 1625860,
"author": "Florian Doyon",
"author_id": 91585,
"author_profile": "https://Stackoverflow.com/users/91585",
"pm_score": 2,
"selected": false,
"text": "Dictionary<Type,...> Type public static class MyCachedData<T>{\n static readonly CachedData Value;\n static MyCachedData(){\n Value=// Heavy computation, such as baking IL code or doing lots of reflection on a type\n }\n}\n"
},
{
"answer_id": 1647219,
"author": "Lyubomyr Shaydariv",
"author_id": 166589,
"author_profile": "https://Stackoverflow.com/users/166589",
"pm_score": 2,
"selected": false,
"text": "for if if/else while do/whle switch private static readonly Action EmptyAction = () => { };\nprivate static readonly Func<bool> EmptyCondition = () => { return true; };\n\nprivate sealed class BreakStatementException : Exception { }\nprivate sealed class ContinueStatementException : Exception { }\nprivate static void Break() { throw new BreakStatementException(); }\nprivate static void Continue() { throw new ContinueStatementException(); }\n\nprivate static void For(Action init, Func<bool> condition, Action postBlock, Action statement) {\n init = init ?? EmptyAction;\n condition = condition ?? EmptyCondition;\n postBlock = postBlock ?? EmptyAction;\n statement = statement ?? EmptyAction;\n for ( init(); condition(); postBlock() ) {\n try {\n statement();\n } catch ( BreakStatementException ) {\n break;\n } catch ( ContinueStatementException ) {\n continue;\n }\n }\n}\n\nprivate static void Main() {\n int i = 0; // avoiding error \"Use of unassigned local variable 'i'\" if not using `for` init block\n For(() => i = 0, () => i < 10, () => i++,\n () => {\n if ( i == 5 )\n Continue();\n Console.WriteLine(i);\n }\n );\n}\n"
},
{
"answer_id": 1677556,
"author": "plaureano",
"author_id": 46265,
"author_profile": "https://Stackoverflow.com/users/46265",
"pm_score": 3,
"selected": false,
"text": "public interface IReadOnlyFoo\n{\n object SomeReadOnlyProperty { get; }\n}\n internal class Foo : IReadOnlyFoo\n{\n public object SomeReadOnlyProperty { get; internal set; }\n}\n // Create a Foo instance\nFoo foo = new Foo();\n\n// This statement is legal\nfoo.SomeReadOnlyProperty = 12345;\n\n// Make Foo read only\nIReadOnlyFoo readOnlyFoo = foo;\n\n// This statement won't compile\nreadOnlyFoo.SomeReadOnlyProperty = 54321;\n"
},
{
"answer_id": 1699477,
"author": "Himadri",
"author_id": 173655,
"author_profile": "https://Stackoverflow.com/users/173655",
"pm_score": 6,
"selected": false,
"text": "protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n //if (e.CommandName == \"sel\")\n //{\n // lblCat.Text = e.CommandArgument.ToString();\n //}\n }\n e.CommandName == \"sel\"\n\nlblCat.Text = e.Comman\n"
},
{
"answer_id": 1707290,
"author": "Shital Shah",
"author_id": 207661,
"author_profile": "https://Stackoverflow.com/users/207661",
"pm_score": 5,
"selected": false,
"text": "Thread.MemoryBarrier volatile, Thread.VolatileRead, Thread.VolatileWrite ThreadStatic fixed default(typeName) DataRow[columnName].ToString() \n#if DEBUG \n if (Debugger.IsAttached) \n Debugger.Break(); \n#endif\n \n using ComplicatedDictionary = Dictionary<int, Dictionary<string, object>>;\n ComplicatedDictionary myDictionary = new ComplicatedDictionary();\n"
},
{
"answer_id": 1724852,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "public IEnumerable<T> GetEnumerator(){\n yield break;\n}\n"
},
{
"answer_id": 1770965,
"author": "thr",
"author_id": 452521,
"author_profile": "https://Stackoverflow.com/users/452521",
"pm_score": 4,
"selected": false,
"text": "public class Tuple<V1, V2> : Tuple\n{\n public readonly V1 v1;\n public readonly V2 v2;\n\n public Tuple(V1 v1, V2 v2)\n {\n this.v1 = v1;\n this.v2 = v2;\n }\n}\n Tuple<int, string> tup = new Tuple<int, string>(1, \"Hello, World!\");\n var tup = new Tuple<int, string>(1, \"Hello, World!\");\n public static void Create<T1, T2>()\n{\n // stuff\n}\n Create<float, double>();\n public static void Create<T1, T2>(T1 a, T2 b)\n{\n // stuff\n}\n Create<float, string>(1.0f, \"test\");\nCreate(1.0f, \"test\");\n public abstract class Tuple\n{\n public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)\n {\n return new Tuple<V1, V2>(v1, v2);\n }\n}\n var tup = Tuple.Create(1, \"Hello, World!\");\n public abstract class Tuple\n{\n public static Tuple<V1, V2> Create<V1, V2>(V1 v1, V2 v2)\n {\n return new Tuple<V1, V2>(v1, v2);\n }\n}\n\npublic class Tuple<V1, V2> : Tuple\n{\n public readonly V1 v1;\n public readonly V2 v2;\n\n public Tuple(V1 v1, V2 v2)\n {\n this.v1 = v1;\n this.v2 = v2;\n }\n}\n\n// Example usage:\nvar tup = Tuple.Create(1, \"test\");\n"
},
{
"answer_id": 1789985,
"author": "Roman Boiko",
"author_id": 118478,
"author_profile": "https://Stackoverflow.com/users/118478",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections.Generic;\n\nstatic class Program\n{\n public static Type GetDeclaredType<T>(T x)\n {\n return typeof(T);\n }\n\n // Demonstrate how GetDeclaredType works\n static void Main(string[] args)\n {\n IList<string> iList = new List<string>();\n List<string> list = null;\n\n Console.WriteLine(GetDeclaredType(iList).Name);\n Console.WriteLine(GetDeclaredType(list).Name);\n }\n}\n IList`1\nList`1\n static void Main(string[] args)\n{\n Console.WriteLine(\"Name is '{0}'\", GetName(new {args}));\n Console.ReadLine();\n}\n\nstatic string GetName<T>(T item) where T : class\n{\n var properties = typeof(T).GetProperties();\n return properties[0].Name;\n}\n Name is 'args'"
},
{
"answer_id": 1798482,
"author": "Phillip Ngan",
"author_id": 41410,
"author_profile": "https://Stackoverflow.com/users/41410",
"pm_score": 2,
"selected": false,
"text": "enum Country\n{\n UnitedKingdom, \n UnitedStates,\n UnitedArabEmirates,\n}\n public static void PrintEnumAsString( Country country )\n{\n Console.Writeline( country.ToString() );\n}\n"
},
{
"answer_id": 1820538,
"author": "Roman Boiko",
"author_id": 118478,
"author_profile": "https://Stackoverflow.com/users/118478",
"pm_score": 5,
"selected": false,
"text": "using System;\nusing System.Collections;\n\ninterface IFoo {\n void Foo();\n}\nstruct MyStructure : IFoo {\n public void Foo() {\n }\n}\npublic static class Program {\n static void MethodDoesNotBoxArguments<T>(T t) where T : IFoo {\n t.Foo();\n }\n static void Main(string[] args) {\n MyStructure s = new MyStructure();\n MethodThatDoesNotBoxArguments(s);\n }\n}\n .method private hidebysig static void MethodDoesNotBoxArguments<(IFoo) T>(!!T t) cil managed\n{\n // Code size 14 (0xe)\n .maxstack 8\n IL_0000: ldarga.s t\n IL_0002: constrained. !!T\n IL_0008: callvirt instance void IFoo::Foo()\n IL_000d: ret\n} // end of method Program::MethodDoesNotBoxArguments\n\n.method private hidebysig static void Main(string[] args) cil managed\n{\n .entrypoint\n // Code size 15 (0xf)\n .maxstack 1\n .locals init ([0] valuetype MyStructure s)\n IL_0000: ldloca.s s\n IL_0002: initobj MyStructure\n IL_0008: ldloc.0\n IL_0009: call void Program::MethodDoesNotBoxArguments<valuetype MyStructure>(!!0)\n IL_000e: ret\n} // end of method Program::Main\n"
},
{
"answer_id": 1821257,
"author": "Paul Ruane",
"author_id": 83264,
"author_profile": "https://Stackoverflow.com/users/83264",
"pm_score": 4,
"selected": false,
"text": "[field: NonSerialized()]\npublic EventHandler event SomeEvent;\n public event EventHandler SomeEvent\n{\n add\n {\n // ...\n }\n\n remove\n {\n // ...\n }\n}\n"
},
{
"answer_id": 1836944,
"author": "Zac Bowling",
"author_id": 171819,
"author_profile": "https://Stackoverflow.com/users/171819",
"pm_score": 3,
"selected": false,
"text": "[DllImport(\"msvcrt40.dll\")]\npublic static extern int printf(string format, __arglist);\n\nstatic void Main(string[] args)\n{\n printf(\"Hello %s!\\n\", __arglist(\"Bart\"));\n}\n"
},
{
"answer_id": 1858602,
"author": "Matt Dotson",
"author_id": 226060,
"author_profile": "https://Stackoverflow.com/users/226060",
"pm_score": 3,
"selected": false,
"text": "var dict = new Dictionary<int, string> { { 10, \"Hello\" }, { 20, \"World\" } };\n"
},
{
"answer_id": 1962004,
"author": "Dave Jellison",
"author_id": 184725,
"author_profile": "https://Stackoverflow.com/users/184725",
"pm_score": 3,
"selected": false,
"text": "private static T CachePattern<T>(string key, Func<T> create) where T : class\n{\n if (cache[key] == null)\n {\n cache.Add(key, create());\n }\n\n return cache[key] as T;\n}\n public static IUser CurrentUser\n{\n get\n {\n return CachePattern<IUser>(\"CurrentUserKey\", () => repository.NewUpUser());\n }\n}\n"
},
{
"answer_id": 1977121,
"author": "Jerod Venema",
"author_id": 25330,
"author_profile": "https://Stackoverflow.com/users/25330",
"pm_score": 2,
"selected": false,
"text": "//TODO: [something] \n"
},
{
"answer_id": 2005795,
"author": "Ravi Vanapalli",
"author_id": 188822,
"author_profile": "https://Stackoverflow.com/users/188822",
"pm_score": 2,
"selected": false,
"text": " private static void printNumbers(int [] intNumbers)\n { \n foreach(int element in intNumbers)\n {\n Console.WriteLine(element);\n }\n\n }\n\n private static void printNumbers(double[] doubleNumbers)\n {\n foreach (double element in doubleNumbers)\n {\n Console.WriteLine(element);\n }\n }\n private static void printNumbers<E>(E [] Numbers)\n {\n foreach (E element in Numbers)\n {\n Console.WriteLine(element);\n }\n }\n"
},
{
"answer_id": 2026781,
"author": "cllpse",
"author_id": 20946,
"author_profile": "https://Stackoverflow.com/users/20946",
"pm_score": 4,
"selected": false,
"text": "[MessageId] INT,\n[MessageText] NVARCHAR(MAX)\n[MessageDate] DATETIME\n struct Message\n{\n Int32 Id;\n String Text;\n DateTime Date;\n}\n List<Message> messages = new List<Message>();\n\nforeach (row in DataTable.Rows)\n{\n var message = new Message\n {\n Id = Convert.ToInt32(row[\"MessageId\"]),\n Text = Convert.ToString(row[\"MessageText\"]),\n Date = Convert.ToDateTime(row[\"MessageDate\"])\n };\n\n messages.Add(message);\n}\n var messages = DataTable.AsEnumerable().Select(r => new Message\n{\n Id = Convert.ToInt32(r[\"MessageId\"]),\n Text = Convert.ToString(r[\"MessageText\"]),\n Date = Convert.ToDateTime(r[\"MessageDate\"])\n}).ToList();\n"
},
{
"answer_id": 2132689,
"author": "Mohammad Tayseer",
"author_id": 85245,
"author_profile": "https://Stackoverflow.com/users/85245",
"pm_score": 5,
"selected": false,
"text": "var sb = new StringBuilder();\nvar count = list.Count();\nfor(int i = 0; i < count; i++)\n{\n if (sb.Length > 0) sb.Append(seperator);\n sb.Append(list[i]);\n}\n\nreturn sb.ToString();\n return string.Join(separator, list.ToArray());\n"
},
{
"answer_id": 2141921,
"author": "devforall",
"author_id": 43838,
"author_profile": "https://Stackoverflow.com/users/43838",
"pm_score": 2,
"selected": false,
"text": "public IEnumerable<Request> SomeMethod(IEnumerable<Request> requests)\n{\n foreach (Request request in requests)\n yield return DoSomthing(request);\n}\n"
},
{
"answer_id": 2188117,
"author": "murki",
"author_id": 5953,
"author_profile": "https://Stackoverflow.com/users/5953",
"pm_score": 2,
"selected": false,
"text": "where T : Enum\n"
},
{
"answer_id": 2231697,
"author": "Max Toro",
"author_id": 39923,
"author_profile": "https://Stackoverflow.com/users/39923",
"pm_score": 2,
"selected": false,
"text": "MailMessage mail = new MailMessage {\n To = { new MailAddress(\"[email protected]\"), new MailAddress(\"[email protected]\") },\n Subject = \"Password Recovery\"\n};\n"
},
{
"answer_id": 2243846,
"author": "Mubashar",
"author_id": 806076,
"author_profile": "https://Stackoverflow.com/users/806076",
"pm_score": 2,
"selected": false,
"text": "public class User\n{\n public long UserId { get; set; }\n public String Name { get; set; }\n public String Password { get; set; }\n public String Email { get; set; }\n}\n User user = new User();\nuser.UserId = 1;\nuser.Name = \"myname\";\netc\n User user = new User()\n{\n UserId = 1,\n Name = \"myname\",\n Email = \"[email protected]\",\n Password = \"mypassword\"\n};\n"
},
{
"answer_id": 2262310,
"author": "A1exandr Belan",
"author_id": 87713,
"author_profile": "https://Stackoverflow.com/users/87713",
"pm_score": 4,
"selected": false,
"text": "public enum MyEnumColors : uint\n{\n Normal = 0xFF9F9F9F,\n Active = 0xFF8EA98A,\n Error = 0xFFFF0000\n}\n"
},
{
"answer_id": 2271941,
"author": "Ruben Bartelink",
"author_id": 11635,
"author_profile": "https://Stackoverflow.com/users/11635",
"pm_score": 2,
"selected": false,
"text": "var subject = new Subject();\nvar doSomething = (Func<String, String>)\n Delegate.CreateDelegate(typeof(Func<String, String>), subject, \"DoSomething\");\nConsole.WriteLine(doSomething(\"Hello Freggles\"));\n"
},
{
"answer_id": 2359623,
"author": "Grokys",
"author_id": 6448,
"author_profile": "https://Stackoverflow.com/users/6448",
"pm_score": 3,
"selected": false,
"text": "<T> <T> <T> <T> <T> <T>"
},
{
"answer_id": 2361060,
"author": "Dax70",
"author_id": 182227,
"author_profile": "https://Stackoverflow.com/users/182227",
"pm_score": 2,
"selected": false,
"text": "[DllImport (\"gdi32.dll\")] \n[return : MarshalAs(UnmanagedType.I4)]\n[StructLayout(LayoutKind.Sequential)]\n"
},
{
"answer_id": 2405367,
"author": "Anthony Mastrean",
"author_id": 3619,
"author_profile": "https://Stackoverflow.com/users/3619",
"pm_score": 3,
"selected": false,
"text": "{\n service.DoTonsOfWork(args);\n}\n using try... finally //using(var scope = new TransactionScope)\n{\n service.DoTonsOfWork(args);\n}\n"
},
{
"answer_id": 2455744,
"author": "Edison Chuang",
"author_id": 83946,
"author_profile": "https://Stackoverflow.com/users/83946",
"pm_score": 4,
"selected": false,
"text": " [Flags]\n public enum Colors\n {\n None = 0,\n Red = 1,\n Blue = 2,\n White = 4,\n Black = 8,\n Green = 16,\n All = 31 //It seems pretty bad...\n }\n [Flags]\n public enum Colors\n {\n None = 0,\n Red = 1,\n Blue = 2,\n White = 4,\n Black = 8,\n Green = 16,\n All = ~0 //much better now. that mean 0xffffffff in default.\n }\n"
},
{
"answer_id": 2484117,
"author": "user287107",
"author_id": 287107,
"author_profile": "https://Stackoverflow.com/users/287107",
"pm_score": 3,
"selected": false,
"text": " public Func<int> RandomGenerator\n {\n get\n {\n var r = new Random();\n return () => { return r.Next(); };\n }\n }\n\n void SomeFunction()\n {\n var result1 = RandomGenerator();\n\n var x = RandomGenerator;\n var result2 = x();\n }\n"
},
{
"answer_id": 2495330,
"author": "John K",
"author_id": 179972,
"author_profile": "https://Stackoverflow.com/users/179972",
"pm_score": 5,
"selected": false,
"text": "void MyWritingMethod() {\n\n int sameAge = 35;\n\n\n { // scope some work\n string name = \"Joe\";\n Log.Write(name + sameAge.ToString());\n }\n\n\n { // scope some other work\n string name = \"Susan\";\n Log.Write(name + sameAge.ToString());\n }\n\n // I'll never mix up Joe and Susan again\n}\n XmlWriter xw = new XmlWriter(..);\n\n//<root>\nxw.WriteStartElement(\"root\");\n{\n //<game>\n xw.WriteStartElement(\"game\");\n {\n //<score>#</score>\n for (int i = 0; i < scores.Length; ++i) // multiple scores\n xw.WriteElementString(\"score\", scores[i].ToString());\n\n }\n //</game>\n xw.WriteEndElement();\n}\n//</root>\nxw.WriteEndElement();\n var somePerson = this.GetPerson(); // whatever \n{ \n var p = somePerson; \n p.FirstName = \"John\"; \n p.LastName = \"Doe\"; \n //... \n p.City = \"Gotham\"; \n} \n"
},
{
"answer_id": 2531350,
"author": "Dariusz",
"author_id": 59528,
"author_profile": "https://Stackoverflow.com/users/59528",
"pm_score": 3,
"selected": false,
"text": "var value = -0.5;\nvar value2 = 0.5;\nvar value3 = 1.4;\n\nConsole.WriteLine( Math.Round(value, MidpointRounding.AwayFromZero) ); //out: -1\nConsole.WriteLine(Math.Round(value2, MidpointRounding.AwayFromZero)); //out: 1\nConsole.WriteLine(Math.Round(value3, MidpointRounding.ToEven)); //out: 1\n"
},
{
"answer_id": 2576855,
"author": "Joshua Rodgers",
"author_id": 308118,
"author_profile": "https://Stackoverflow.com/users/308118",
"pm_score": 2,
"selected": false,
"text": "class StaticDestructor\n{\n /// <summary>\n /// The delegate that is invoked when the destructor is called.\n /// </summary>\n public delegate void Handler();\n private Handler doDestroy;\n\n /// <summary>\n /// Creates a new static destructor with the specified delegate to handle the destruction.\n /// </summary>\n /// <param name=\"method\">The delegate that will handle destruction.</param>\n public StaticDestructor(Handler method)\n {\n doDestroy = method;\n }\n\n ~StaticDestructor()\n {\n doDestroy();\n }\n}\n private static readonly StaticDestructor destructor = new StaticDestructor\n(\n delegate()\n {\n //Cleanup here\n }\n);\n using System;\n\nnamespace TestStaticDestructor\n{\n class StaticDestructor\n {\n public delegate void Handler();\n private Handler doDestroy;\n\n public StaticDestructor(Handler method)\n {\n doDestroy = method;\n }\n\n ~StaticDestructor()\n {\n doDestroy();\n }\n }\n\n class SomeClass\n {\n static SomeClass()\n {\n Console.WriteLine(\"Statically constructed!\");\n }\n\n static readonly StaticDestructor destructor = new StaticDestructor(\n delegate()\n {\n Console.WriteLine(\"Statically destructed!\");\n }\n );\n }\n\n class Program\n {\n static void Main(string[] args)\n {\n SomeClass someClass = new SomeClass();\n someClass = null;\n System.Threading.Thread.Sleep(1000);\n }\n }\n}\n"
},
{
"answer_id": 2578334,
"author": "Nakul Chaudhary",
"author_id": 34588,
"author_profile": "https://Stackoverflow.com/users/34588",
"pm_score": 3,
"selected": false,
"text": "#if DEBUG\n //Code run in debugging mode\n\n#else\n //Code run in release mode\n\n#endif\n"
},
{
"answer_id": 2602813,
"author": "k25",
"author_id": 312219,
"author_profile": "https://Stackoverflow.com/users/312219",
"pm_score": 2,
"selected": false,
"text": "XmlWriterSettings xmlWriterSettings = new XmlWriterSettings();\nxmlWriterSettings.NewLineOnAttributes = true;\nxmlWriterSettings.Indent = true;\n\n\nXmlWriter xml = XmlWriter.Create(@\"C:\\file.xml\", xmlWriterSettings);\n\n// Start writing the data using xml.WriteStartElement(), xml.WriteElementString(...), xml.WriteEndElement() etc\n"
},
{
"answer_id": 2689007,
"author": "Jehof",
"author_id": 83039,
"author_profile": "https://Stackoverflow.com/users/83039",
"pm_score": 4,
"selected": false,
"text": "public class BoundObject : INotifyPropertyChanged {\n\n private int _value;\n private string _text;\n\n public event PropertyChangedEventHandler PropertyChanged;\n\n public int Value {\n get {\n return _value;\n }\n set {\n if (_value != value) {\n _value = value;\n OnPropertyChanged(\"Value\");\n }\n }\n }\n\n public string Text {\n get {\n return _text;\n }\n set {\n if (_text != value) {\n _text = value;\n OnPropertyChanged(\"Text\");\n }\n }\n }\n\n public void Init(){\n _text = \"InitialValue\";\n _value = 1;\n OnPropertyChanged(string.Empty);\n }\n\n public void Reset() {\n _text = \"DefaultValue\";\n _value = 0;\n OnPropertyChanged(string.Empty);\n }\n\n private void OnPropertyChanged(string propertyName) {\n PropertyChangedEventArgs e = new PropertyChangedEventArgs(propertyName);\n\n if (PropertyChanged != null) {\n PropertyChanged(this, e);\n }\n }\n}\n"
},
{
"answer_id": 2753564,
"author": "Navid Farhadi",
"author_id": 184756,
"author_profile": "https://Stackoverflow.com/users/184756",
"pm_score": 3,
"selected": false,
"text": " class MyClass<T> where T : new()\n {\n\n }\n"
},
{
"answer_id": 2836741,
"author": "Pretzel",
"author_id": 21244,
"author_profile": "https://Stackoverflow.com/users/21244",
"pm_score": 3,
"selected": false,
"text": "Dictionary<string, int> nameAgeDict = new Dictionary<string, int>();\nnameAgeDict[\"Joe\"] = 34; // no error. will just auto-add key/value\nnameAgeDict[\"Joe\"] = 41; // no error. key/value just get overwritten\nnameAgeDict.Add(\"Joe\", 30); // ERROR! key already exists\n"
},
{
"answer_id": 2843263,
"author": "Razor",
"author_id": 17211,
"author_profile": "https://Stackoverflow.com/users/17211",
"pm_score": 1,
"selected": false,
"text": " public class StaticConstrucEx2Outer<T> {\n\n // Will hold a different value depending on the specicified generic type\n public T SomeProperty { get; set; }\n\n static StaticConstrucEx2Outer() {\n Console.WriteLine(\"StaticConstrucEx2Outer \" + typeof(T).Name);\n }\n\n public class StaticConstrucEx2Inner<U, V> {\n\n static StaticConstrucEx2Inner() {\n\n Console.WriteLine(\"Outer <{0}> : Inner <{1}><{2}>\",\n typeof(T).Name,\n typeof(U).Name,\n typeof(V).Name);\n }\n\n public static void FooBar() {}\n }\n\n public class SCInner {\n\n static SCInner() {\n Console.WriteLine(\"SCInner init <{0}>\", typeof(T).Name);\n }\n\n public static void FooBar() {}\n }\n}\n\n\nStaticConstrucEx2Outer<int>.StaticConstrucEx2Inner<string, DateTime>.FooBar();\nStaticConstrucEx2Outer<int>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, DateTime>.FooBar();\nStaticConstrucEx2Outer<string>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, Int16>.FooBar();\nStaticConstrucEx2Outer<string>.SCInner.FooBar();\n\nStaticConstrucEx2Outer<string>.StaticConstrucEx2Inner<string, UInt32>.FooBar();\n\nStaticConstrucEx2Outer<long>.StaticConstrucEx2Inner<string, UInt32>.FooBar();\n Outer <Int32> : Inner <String><DateTime>\nSCInner init <Int32>\n\nOuter <String> : Inner <String><DateTime>\nSCInner init <String>\n\nOuter <String> : Inner <String><Int16>\n\nOuter <String> : Inner <String><UInt32>\n\nOuter <Int64> : Inner <String><UInt32>\n"
},
{
"answer_id": 2905415,
"author": "Thomas Levesque",
"author_id": 98713,
"author_profile": "https://Stackoverflow.com/users/98713",
"pm_score": 4,
"selected": false,
"text": "Object.Equals if ((x == y) || ((x != null && y != null) && x.Equals(y)))\n{\n ...\n}\n if (Object.Equals(x, y))\n{\n ...\n}\n Object.Equals"
},
{
"answer_id": 2918238,
"author": "Kim Tranjan",
"author_id": 340381,
"author_profile": "https://Stackoverflow.com/users/340381",
"pm_score": 5,
"selected": false,
"text": "string.Format() Console.WriteLine(\"Product: {0,-7} Price: {1,5}\", product1, price1);\nConsole.WriteLine(\"Product: {0,-7} Price: {1,5}\", product2, price2);\n"
},
{
"answer_id": 3031174,
"author": "Buildstarted",
"author_id": 365526,
"author_profile": "https://Stackoverflow.com/users/365526",
"pm_score": 5,
"selected": false,
"text": "using ListOfDictionary = System.Collections.Generic.List<System.Collections.Generic.Dictionary<string, string>>;\n ListOfDictionary list = new ListOfDictionary();\n"
},
{
"answer_id": 3090178,
"author": "jcruz",
"author_id": 358007,
"author_profile": "https://Stackoverflow.com/users/358007",
"pm_score": 6,
"selected": false,
"text": "String.IsNullOrWhiteSpace(String value)\n"
},
{
"answer_id": 3093285,
"author": "Steve Dunn",
"author_id": 28901,
"author_profile": "https://Stackoverflow.com/users/28901",
"pm_score": 4,
"selected": false,
"text": "enum flags [Flags]\npublic enum ErrorTypes {\n None = 0,\n MissingPassword = 1 << 0,\n MissingUsername = 1 << 1,\n PasswordIncorrect = 1 << 2 \n}\n"
},
{
"answer_id": 3094954,
"author": "Bill Barry",
"author_id": 108993,
"author_profile": "https://Stackoverflow.com/users/108993",
"pm_score": 4,
"selected": false,
"text": "public static class EventExtensions {\n public static void Raise<T>(this EventHandler<T> @event, \n object sender, T args) where T : EventArgs {\n if(@event!= null) {\n @event(sender, args);\n }\n }\n}\n public class MyImportantThing {\n public event EventHandler<MyImportantEventEventArgs> SomethingHappens;\n ...\n public void Bleh() {\n SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });\n }\n}\n EventHandler<> InlineAttribute"
},
{
"answer_id": 3096408,
"author": "Steve Dunn",
"author_id": 28901,
"author_profile": "https://Stackoverflow.com/users/28901",
"pm_score": 6,
"selected": false,
"text": "$exception"
},
{
"answer_id": 3138039,
"author": "Keith Bluestone",
"author_id": 378081,
"author_profile": "https://Stackoverflow.com/users/378081",
"pm_score": 5,
"selected": false,
"text": "IDAL<Foo>: IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T\n [Test, Category(\"ProfileEntity\")]\npublic void MyTest()\n{\n // this is the object that we want profiled.\n // we would normally pass this around and call\n // methods on this instance.\n DALToBeProfiled dal = new DALToBeProfiled();\n\n // To profile, instead we obtain our proxy\n // and pass it around instead.\n DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);\n\n // or...\n DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal);\n\n // Now use proxy wherever we would have used the original...\n // All methods' timings are automatically recorded\n // with a high-resolution timer\n DoStuffToThisObject(dalProxy);\n\n // Output profiling results\n ProfileManager.Instance.ToConsole();\n}\n [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]\n[SecurityPermission(SecurityAction.LinkDemand, \n Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop\npublic override IMessage Invoke(IMessage msg)\n{\n IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;\n Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28\n\n // The MethodCallMessageWrapper\n // provides read/write access to the method \n // call arguments. \n MethodCallMessageWrapper mc =\n new MethodCallMessageWrapper(msgMethodCall);\n\n // This is the reflected method base of the called method. \n MethodInfo mi = (MethodInfo)mc.MethodBase;\n\n IMessage retval = null;\n\n // Pass the call to the method and get our return value\n string profileName = ProfileClassName + \".\" + mi.Name;\n\n using (ProfileManager.Start(profileName))\n {\n IMessage myReturnMessage =\n RemotingServices.ExecuteMessage(_target, msgMethodCall);\n\n retval = myReturnMessage;\n }\n\n return retval;\n}\n"
},
{
"answer_id": 3146453,
"author": "Incognito",
"author_id": 303756,
"author_profile": "https://Stackoverflow.com/users/303756",
"pm_score": 5,
"selected": false,
"text": "AppDomain.UnhandledException"
},
{
"answer_id": 3147945,
"author": "Dan",
"author_id": 59532,
"author_profile": "https://Stackoverflow.com/users/59532",
"pm_score": 4,
"selected": false,
"text": "string.Empty\n"
},
{
"answer_id": 3172255,
"author": "Ozan",
"author_id": 137065,
"author_profile": "https://Stackoverflow.com/users/137065",
"pm_score": 4,
"selected": false,
"text": " [OperationContract, ServiceKnownType(typeof(Prism)), ServiceKnownType(typeof(Cuboid))]\n Shape GetShape();\n"
},
{
"answer_id": 3189640,
"author": "WedTM",
"author_id": 88770,
"author_profile": "https://Stackoverflow.com/users/88770",
"pm_score": 3,
"selected": false,
"text": "OptionalField"
},
{
"answer_id": 3189688,
"author": "AaronLS",
"author_id": 84206,
"author_profile": "https://Stackoverflow.com/users/84206",
"pm_score": 3,
"selected": false,
"text": "endOfLineChar"
},
{
"answer_id": 9413174,
"author": "Laradda",
"author_id": 820089,
"author_profile": "https://Stackoverflow.com/users/820089",
"pm_score": 2,
"selected": false,
"text": "protected internal"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9033",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/31505/"
] |
9,044 | <p>I have a base class that represents a database test in TestNG, and I want to specify that all classes extending from this class are of a group "db-test", however I have found that this doesn't seem possible. I have tried the @Test annotation:</p>
<pre><code>@Test(groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>However, this doesn't work because the @Test annotation will try to make a bunch of methods into tests, and warnings/errors pop up in eclipse when the tests are run.</p>
<p>So I tried disabling the test, so at least the groups are assigned:</p>
<pre><code>@Test(enabled = false, groups = { "db-test" })
public class DBTestBase {
}
</code></pre>
<p>but then any @BeforeTest (and other similar annotations) ALSO get disabled... which is of course not what I want.</p>
<p>I would like some way to annotate a class as being of a particular type of group, but it doesn't quite seem possible in TestNG. Does anyone have any other ideas?</p>
| [
{
"answer_id": 154080,
"author": "Jorge Ferreira",
"author_id": 6508,
"author_profile": "https://Stackoverflow.com/users/6508",
"pm_score": 0,
"selected": false,
"text": "public class DBTestBase {\n\n @BeforeTest(groups = \"db-test\")\n public void beforeTest() {\n System.out.println(\"Running before test\");\n }\n\n public void method1() {\n Assert.fail(); // this does not run. It does not belong to 'db-test' group.\n }\n\n @Test(groups = \"db-test\")\n public void testMethod1() {\n Assert.assertTrue(true);\n }\n}\n"
},
{
"answer_id": 275342,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 1,
"selected": false,
"text": "@Test(groups = { \"aGlobalGroup\" })\npublic class Base {\n\n /**\n * \n */\n @BeforeClass\n public final void setUp() {\n System.out.println(\"Base class: @BeforeClass\");\n }\n\n\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test(groups = { \"aLocalGroup\" })\n public final void aFastTest() {\n System.out.println(\"Base class: Fast test\");\n }\n\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test(groups = { \"aLocalGroup\" })\n public final void aSlowTest() {\n System.out.println(\"Base class: Slow test\");\n //throw new IllegalArgumentException(\"oups\");\n }\n\n /**\n * Should not be executed. <br />\n * Yet the global annotation Test on the class would include it in the TestNG methods...\n */\n public final void notATest() {\n System.out.println(\"Base class: NOT a test\");\n }\n\n /**\n * SubClass of a TestNG class. Some of its methods are TestNG methods, other are not. <br />\n * The goal is to check if a group specify in the super-class will include methods of this class. <br />\n * And to avoid including too much methods, such as public methods not intended to be TestNG methods.\n * @author <a href=\"http://stackoverflow.com/users/6309/vonc\">VonC</a>\n */\n public static class Extended extends Base\n {\n /**\n * Test not part a 'aGlobalGroup', but still included in that group due to the super-class annotation. <br />\n * Will be executed even if the TestNG class tested is a sub-class.\n */\n @Test\n public final void anExtendedTest() {\n System.out.println(\"Extended class: An Extended test\");\n }\n\n /**\n * Should not be executed. <br />\n * Yet the global annotation Test on the class would include it in the TestNG methods...\n */ \n public final void notAnExtendedTest() {\n System.out.println(\"Extended class: NOT an Extended test\");\n }\n }\n"
},
{
"answer_id": 275353,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "@Groups({ \"myGroup1\", \"myGroup2\"})\npublic class MyTestCase {\n @Test\n @Groups(\"aMethodLevelGroup\")\n public void myTest() {\n }\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/122/"
] |
9,052 | <p>I'm working on a spec for a piece of software for my company and as part of the auditing system I think it would be neat if there was a way to grab the current Active Directory user.</p>
<p>Hopefully something like:</p>
<pre><code>Dim strUser as String
strUser = ActiveDirectory.User()
MsgBox "Welcome back, " & strUser
</code></pre>
| [
{
"answer_id": 9054,
"author": "JamesSugrue",
"author_id": 1075,
"author_profile": "https://Stackoverflow.com/users/1075",
"pm_score": 4,
"selected": true,
"text": "Private Declare Function GetUserName Lib \"advapi32.dll\" Alias \"GetUserNameA\" _\n (ByVal IpBuffer As String, nSize As Long) As Long\nPrivate Declare Function GetComputerName Lib \"kernel32\" Alias \"GetComputerNameA\" _\n (ByVal lpBuffer As String, nSize As Long) As Long\n\nFunction ThisUserName() As String\n Dim LngBufLen As Long\n Dim strUser As String\n\n strUser = String$(15, \" \")\n LngBufLen = 15\n\n If GetUserName(strUser, LngBufLen) = 1 Then\n ThisUserName = Left(strUser, LngBufLen - 1)\n Else\n ThisUserName = \"Unknown\"\n End If\nEnd Function\n\nFunction ThisComputerID() As String\n Dim LngBufLen As Long\n Dim strUser As String\n\n strUser = String$(15, \" \")\n LngBufLen = 15\n\n If GetComputerName(strUser, LngBufLen) = 1 Then\n ThisComputerID = Left(strUser, LngBufLen)\n Else\n ThisComputerID = 0\n End If\nEnd Function\n"
},
{
"answer_id": 249759,
"author": "Yarik",
"author_id": 31415,
"author_profile": "https://Stackoverflow.com/users/31415",
"pm_score": 2,
"selected": false,
"text": "Public Function CurrentWorkbenchUser() As String\n\n ' 2004-01-05, YM: Using Application.CurrentUser for identification of \n ' current user is very problematic (more specifically, extremely \n ' cumbersome to set up and administer for all users). \n ' Therefore, as a quick fix, let's use the OS-level user's \n ' identity instead (NB: the environment variables used below must work fine\n ' on Windows NT/2000/2003 but may not work on Windows 98/ME)\n ' CurrentWorkbenchUser = Application.CurrentUser\n '\n ' 2005-06-13, YM: Environment variables do not work in Windows 2003. \n ' Use Windows Scripting Host (WSH) Networking object instead.\n ' CurrentWorkbenchUser = Environ(\"UserDomain\") & \"\\\" & Environ(\"UserName\")\n '\n ' 2007-01-23, YM: Somewhere between 2007-01-09 and 2007-01-20, \n ' the WshNetwork object stopped working on CONTROLLER3. \n ' We could not find any easy way to fix that.\n ' At the same time, it turns out that environment variables \n ' do work on Windows 2003.\n ' (Apparently, it was some weird configuration problem back in 2005: \n ' we had only one Windows 2003 computer at that time and it was \n ' Will's workstation).\n '\n ' In any case, at the time of this writing, \n ' returning to environment variables \n ' appears to be the simplest solution to the problem on CONTROLLER3.\n ' Dim wshn As New WshNetwork\n ' CurrentWorkbenchUser = wshn.UserDomain & \"\\\" & wshn.UserName\n\n CurrentWorkbenchUser = Environ(\"USERDOMAIN\") & \"\\\" & Environ(\"USERNAME\")\n\nEnd Function\n"
},
{
"answer_id": 31496094,
"author": "bgmCoder",
"author_id": 1038866,
"author_profile": "https://Stackoverflow.com/users/1038866",
"pm_score": 2,
"selected": false,
"text": "'gets firstname, lastname, fullname or username\nPublic Function GetUser(Optional whatpart = \"username\")\n Dim returnthis As String\n If whatpart = \"username\" Then GetUser = Environ(\"USERNAME\"): Exit Function\n Set objSysInfo = CreateObject(\"ADSystemInfo\")\n Set objUser = GetObject(\"LDAP://\" & objSysInfo.USERNAME)\n Select Case whatpart\n Case \"fullname\": returnthis = objUser.FullName\n Case \"firstname\", \"givenname\": returnthis = objUser.givenName\n Case \"lastname\": returnthis = objUser.LastName\n Case Else: returnthis = Environ(\"USERNAME\")\n End Select\n GetUser = returnthis\nEnd Function\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9052",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/428190/"
] |
9,081 | <p>How do I <code>grep</code> and show the preceding and following 5 lines surrounding each matched line?</p>
| [
{
"answer_id": 9083,
"author": "Pat Notz",
"author_id": 825,
"author_profile": "https://Stackoverflow.com/users/825",
"pm_score": 13,
"selected": true,
"text": "grep -B num -A num grep -B 3 -A 2 foo README.txt\n -C num grep -C 3 foo README.txt\n"
},
{
"answer_id": 9084,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 5,
"selected": false,
"text": "grep astring myfile -A 5 -B 5\n"
},
{
"answer_id": 9088,
"author": "Stu",
"author_id": 414,
"author_profile": "https://Stackoverflow.com/users/414",
"pm_score": 9,
"selected": false,
"text": "-A -B -C n n -n n"
},
{
"answer_id": 9120,
"author": "Sam Merrell",
"author_id": 782,
"author_profile": "https://Stackoverflow.com/users/782",
"pm_score": 4,
"selected": false,
"text": "grep searchstring file -C n # n for number of lines of context up and down\n man grep\n info grep\n"
},
{
"answer_id": 48325,
"author": "elmarco",
"author_id": 1277510,
"author_profile": "https://Stackoverflow.com/users/1277510",
"pm_score": 6,
"selected": false,
"text": "-C"
},
{
"answer_id": 19237071,
"author": "Malcolm Boekhoff",
"author_id": 1388639,
"author_profile": "https://Stackoverflow.com/users/1388639",
"pm_score": 4,
"selected": false,
"text": "/some/file.txt Awk grep -[ACB] awk '\n\n/17655/ {\n for (i = (b + 1) % 10; i != b; i = (i + 1) % 10) {\n print before[i]\n }\n print (NR \":\" ($0))\n a = 10\n}\n\na-- > 0 {\n print (NR \":\" ($0))\n}\n\n{\n before[b] = (NR \":\" ($0))\n b = (b + 1) % 10\n}' /some/file.txt;\n"
},
{
"answer_id": 48225316,
"author": "chtenb",
"author_id": 1546844,
"author_profile": "https://Stackoverflow.com/users/1546844",
"pm_score": 4,
"selected": false,
"text": "$ grep --help | grep -i context\nContext control:\n -B, --before-context=NUM print NUM lines of leading context\n -A, --after-context=NUM print NUM lines of trailing context\n -C, --context=NUM print NUM lines of output context\n -NUM same as --context=NUM\n"
},
{
"answer_id": 49772613,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 3,
"selected": false,
"text": "awk awk 'c-->0;$0~s{if(b)for(c=b+1;c>1;c--)print r[(NR-c+1)%b];print;c=a}b{r[NR%b]=$0}' b=3 a=3 s=\"pattern\" myfile\n a b -A -B -C"
},
{
"answer_id": 49772704,
"author": "kenorb",
"author_id": 55075,
"author_profile": "https://Stackoverflow.com/users/55075",
"pm_score": 4,
"selected": false,
"text": "ripgrep ripgrep grep rg -C5 \"pattern\" .\n -C --context NUM -A --after-context -B --before-context"
},
{
"answer_id": 54055064,
"author": "JBone",
"author_id": 4969849,
"author_profile": "https://Stackoverflow.com/users/4969849",
"pm_score": 2,
"selected": false,
"text": "$ grep thestring thefile -5\n -5 5 -C 5 -A 5 -B 5"
},
{
"answer_id": 55096777,
"author": "prime",
"author_id": 2523147,
"author_profile": "https://Stackoverflow.com/users/2523147",
"pm_score": 3,
"selected": false,
"text": "Context Line Control --context | grep -C 5\n | grep -5\n"
},
{
"answer_id": 59291057,
"author": "franzisk",
"author_id": 2716142,
"author_profile": "https://Stackoverflow.com/users/2716142",
"pm_score": 3,
"selected": false,
"text": "grep -5 string file\n grep -A 5 -B 5 string file\n"
},
{
"answer_id": 61486000,
"author": "Rose",
"author_id": 466884,
"author_profile": "https://Stackoverflow.com/users/466884",
"pm_score": 4,
"selected": false,
"text": "-C ag -C 3 \"foo\" myFile\n\nline 1\nline 2\nline 3\nline that has \"foo\"\nline 5\nline 6\nline 7\n"
},
{
"answer_id": 72938054,
"author": "Tushar",
"author_id": 9730403,
"author_profile": "https://Stackoverflow.com/users/9730403",
"pm_score": 3,
"selected": false,
"text": "-A 5 # this will give you 5 lines after searched string.\n-B 5 # this will give you 5 lines before searched string.\n-C 5 # this will give you 5 lines before & after searched string\n [abc@xyz]~/% cat file.txt # print all file data\nthis is first line\nthis is 2nd line\nthis is 3rd line\nthis is 4th line\nthis is 5th line\nthis is 6th line\n\n[abc@xyz]~% grep \"3rd\" file.txt # we are searching for keyword '3rd' in the file\nthis is 3rd line\n\n[abc@xyz]~% grep -A 2 \"3rd\" file.txt # print 2 lines after finding the searched string\nthis is 3rd line\nthis is 4th line\nthis is 5th line\n\n[abc@xyz]~% grep -B 2 \"3rd\" file.txt # Print 2 lines before the search string.\nthis is first line\nthis is 2nd line\nthis is 3rd line\n\n[abc@xyz]~% grep -C 2 \"3rd\" file.txt # print 2 line before and 2 line after the searched string \nthis is first line\nthis is 2nd line\nthis is 3rd line\nthis is 4th line\nthis is 5th line\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/116/"
] |
9,104 | <p>I'm thinking that the reason I can't do this is because it might be a huge security hole, but here goes...</p>
<p>I want to have a bookmark on my browser (FF3, preferably) that is only a snippet of javascript code. It would merely construct a URL based on the current date and then do a window.location = on that URL.</p>
<p>I know that I could make a page and keep it on my local machine and just refer to it that way, but I was just wondering if you could bypass that step and actually have the "location" of the bookmark really just be javascript. I could have sworn that this was possible years ago, but I can't find anything that tells me either way now.</p>
| [
{
"answer_id": 9109,
"author": "Dillie-O",
"author_id": 71,
"author_profile": "https://Stackoverflow.com/users/71",
"pm_score": 3,
"selected": false,
"text": "javascript:alert('Wacky%20test%20yo');\n"
},
{
"answer_id": 476592,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "javascript:(function(){var%20a=window,b=document,c=encodeURIComponent,d=a.open(\"http://www.google.com/bookmarks/mark?op=edit&output=popup&bkmk=\"+c(b.location)+\"&title=\"+c(b.title),\"bkmk_popup\",\"left=\"+((a.screenX||a.screenLeft)+10)+\",top=\"+((a.screenY||a.screenTop)+10)+\",height=420px,width=550px,resizable=1,alwaysRaised=1\");a.setTimeout(function(){d.focus()},300)})();\n"
},
{
"answer_id": 6764379,
"author": "Joseph Marikle",
"author_id": 854246,
"author_profile": "https://Stackoverflow.com/users/854246",
"pm_score": 5,
"selected": false,
"text": "javascript:(function(){\n location.href = location.href + \"#\";\n})();\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9104",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/232/"
] |
9,122 | <p>I'm trying to use a select statement to get all of the columns from a certain MySQL table except one. Is there a simple way to do this?</p>
<p>EDIT: There are 53 columns in this table (NOT MY DESIGN)</p>
| [
{
"answer_id": 9123,
"author": "Thomas Owens",
"author_id": 572,
"author_profile": "https://Stackoverflow.com/users/572",
"pm_score": 5,
"selected": false,
"text": "SELECT col1, col2, col3, col4 FROM tbl\n SELECT * FROM tbl \n SELECT * FROM tbl\n SELECT col3, col6, col45, col 52 FROM tbl\n"
},
{
"answer_id": 9124,
"author": "Mike Stone",
"author_id": 122,
"author_profile": "https://Stackoverflow.com/users/122",
"pm_score": 5,
"selected": false,
"text": "SELECT column1, column2, column4 FROM table WHERE whatever\n"
},
{
"answer_id": 9146,
"author": "Brian Childress",
"author_id": 721,
"author_profile": "https://Stackoverflow.com/users/721",
"pm_score": 6,
"selected": false,
"text": "CREATE VIEW vwTable\nas \nSELECT \n col1 \n , col2 \n , col3 \n , col.. \n , col53 \nFROM table\n"
},
{
"answer_id": 9147,
"author": "nlucaroni",
"author_id": 157,
"author_profile": "https://Stackoverflow.com/users/157",
"pm_score": 2,
"selected": false,
"text": "Select * Select *"
},
{
"answer_id": 9156,
"author": "mbillard",
"author_id": 810,
"author_profile": "https://Stackoverflow.com/users/810",
"pm_score": 2,
"selected": false,
"text": "SELECT\n col1\n , col2\n , col3\n , col..\n , col53\n\nFROM table\n"
},
{
"answer_id": 1375831,
"author": "rplevy",
"author_id": 163815,
"author_profile": "https://Stackoverflow.com/users/163815",
"pm_score": 2,
"selected": false,
"text": "echo $(echo 'select concat(\"select \", group_concat(column_name) , \" from TABLE\") from information_schema.columns where table_name=\"TABLE\" and column_name != \"EXCLUDEDFIELD\" group by \"t\"' | MYSQL | tail -n 1) | MYSQL\n column_list=$(echo 'select group_concat(column_name) from information_schema.columns where table_name=\"TABLE\" and column_name != \"EXCLUDEDFIELD\" group by \"t\"' | MYSQL | tail -n 1)\n $column_list"
},
{
"answer_id": 1495476,
"author": "Mahomedalid",
"author_id": 143393,
"author_profile": "https://Stackoverflow.com/users/143393",
"pm_score": 9,
"selected": true,
"text": "SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME), '<columns_to_omit>,', '') FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = '<table>' AND TABLE_SCHEMA = '<database>'), ' FROM <table>');\n\nPREPARE stmt1 FROM @sql;\nEXECUTE stmt1;\n <table>, <database> and <columns_to_omit>"
},
{
"answer_id": 2019450,
"author": "Soth",
"author_id": 182619,
"author_profile": "https://Stackoverflow.com/users/182619",
"pm_score": 2,
"selected": false,
"text": "SELECT * FROM table WHERE whatever\n while (($data = mysql_fetch_array($result, MYSQL_ASSOC)) !== FALSE) {\n unset($data[\"id\"]);\n foreach ($data as $k => $v) { \n echo\"$v,\";\n } \n}\n"
},
{
"answer_id": 2322117,
"author": "Nathan A",
"author_id": 279884,
"author_profile": "https://Stackoverflow.com/users/279884",
"pm_score": 3,
"selected": false,
"text": "SELECT *\nINTO #temp\nFROM table\n\nALTER TABLE #temp DROP COlUMN column_name\n\nSELECT *\nFROM #temp\n"
},
{
"answer_id": 4461117,
"author": "bortunac",
"author_id": 544803,
"author_profile": "https://Stackoverflow.com/users/544803",
"pm_score": 6,
"selected": false,
"text": "DROP TABLE IF EXISTS temp_tb;\nCREATE TEMPORARY TABLE ENGINE=MEMORY temp_tb SELECT * FROM orig_tb;\nALTER TABLE temp_tb DROP col_a, DROP col_f,DROP col_z; #// MySQL\nSELECT * FROM temp_tb;\n"
},
{
"answer_id": 4622233,
"author": "David Poor",
"author_id": 111796,
"author_profile": "https://Stackoverflow.com/users/111796",
"pm_score": 2,
"selected": false,
"text": "CREATE FUNCTION `getTableColumns`(tablename varchar(100)) \n RETURNS varchar(5000) CHARSET latin1\nBEGIN\n DECLARE done INT DEFAULT 0;\n DECLARE res VARCHAR(5000) DEFAULT \"\";\n\n DECLARE col VARCHAR(200);\n DECLARE cur1 CURSOR FOR \n select COLUMN_NAME from information_schema.columns \n where TABLE_NAME=@table AND TABLE_SCHEMA=\"yourdatabase\" ORDER BY ORDINAL_POSITION;\n DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;\n OPEN cur1;\n REPEAT\n FETCH cur1 INTO col;\n IF NOT done THEN \n set res = CONCAT(res,IF(LENGTH(res)>0,\",\",\"\"),col);\n END IF;\n UNTIL done END REPEAT;\n CLOSE cur1;\n RETURN res;\n"
},
{
"answer_id": 6624383,
"author": "cwd",
"author_id": 288032,
"author_profile": "https://Stackoverflow.com/users/288032",
"pm_score": 3,
"selected": false,
"text": "table. "
},
{
"answer_id": 8035440,
"author": "neurotico79",
"author_id": 1033534,
"author_profile": "https://Stackoverflow.com/users/1033534",
"pm_score": 2,
"selected": false,
"text": "<columns_to_delete>, SET @sql = CONCAT('SELECT ', (SELECT REPLACE(GROUP_CONCAT(COLUMN_NAME),\n '<columns_to_delete>', '\\'FIELD_REMOVED\\'')\n FROM INFORMATION_SCHEMA.COLUMNS\n WHERE TABLE_NAME = '<table>'\n AND TABLE_SCHEMA = '<database>'), ' FROM <table>');\n <table> <database>"
},
{
"answer_id": 10598274,
"author": "Junaid",
"author_id": 806440,
"author_profile": "https://Stackoverflow.com/users/806440",
"pm_score": 3,
"selected": false,
"text": "@Mahomedalid @Bill Karwin @Jan Koritak SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');\nPREPARE stmt1 FROM @SQL;\nEXECUTE stmt1;\n id company_id"
},
{
"answer_id": 11060861,
"author": "hahakubile",
"author_id": 709096,
"author_profile": "https://Stackoverflow.com/users/709096",
"pm_score": 2,
"selected": false,
"text": "SET @database = 'database_name';\nSET @tablename = 'table_name';\nSET @cols2delete = 'col1,col2,col3';\n\nSET @sql = CONCAT(\n'SELECT ', \n(\n SELECT GROUP_CONCAT( IF(FIND_IN_SET(COLUMN_NAME, @cols2delete), NULL, COLUMN_NAME ) )\n FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @tablename AND TABLE_SCHEMA = @database\n), \n' FROM ',\n@tablename);\n\nSELECT @sql;\n SET @@group_concat_max_len = 2048;\n"
},
{
"answer_id": 15012522,
"author": "Nick",
"author_id": 1953467,
"author_profile": "https://Stackoverflow.com/users/1953467",
"pm_score": -1,
"selected": false,
"text": " //create an array, we will call it here. \n $here = array();\n //create an SQL query in order to get all of the column names\n $SQL = \"SHOW COLUMNS FROM Table\";\n //put all of the column names in the array\n foreach($conn->query($SQL) as $row) {\n $here[] = $row[0];\n }\n //now search through the array containing the column names for the name of the column, in this case i used the common ID field as an example\n $key = array_search('ID', $here);\n //now delete the entry\n unset($here[$key]);\n"
},
{
"answer_id": 15571552,
"author": "Kilise",
"author_id": 1715913,
"author_profile": "https://Stackoverflow.com/users/1715913",
"pm_score": 2,
"selected": false,
"text": "public function getColsExcept($table,$remove){\n $res =mysql_query(\"SHOW COLUMNS FROM $table\");\n\n while($arr = mysql_fetch_assoc($res)){\n $cols[] = $arr['Field'];\n }\n if(is_array($remove)){\n $newCols = array_diff($cols,$remove);\n return \"`\".implode(\"`,`\",$newCols).\"`\";\n }else{\n $length = count($cols);\n for($i=0;$i<$length;$i++){\n if($cols[$i] == $remove)\n unset($cols[$i]);\n }\n return \"`\".implode(\"`,`\",$cols).\"`\";\n }\n}\n mysql_query(\"SELECT \".$db->getColsExcept('table',array('id','bigtextcolumn')).\" FROM table\");\n mysql_query(\"SELECT \".$db->getColsExcept('table','bigtextcolumn').\" FROM table\");\n"
},
{
"answer_id": 17093312,
"author": "Sean O",
"author_id": 5701,
"author_profile": "https://Stackoverflow.com/users/5701",
"pm_score": 5,
"selected": false,
"text": "SELECT *, NULL AS salary FROM users\n"
},
{
"answer_id": 17719025,
"author": "Suraj",
"author_id": 1065227,
"author_profile": "https://Stackoverflow.com/users/1065227",
"pm_score": 4,
"selected": false,
"text": "SET @SQL = CONCAT('SELECT ', (SELECT GROUP_CONCAT(CONCAT(\"`\", COLUMN_NAME, \"`\")) FROM\nINFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users' AND COLUMN_NAME NOT IN ('id')), ' FROM users');\nPREPARE stmt1 FROM @SQL;\nEXECUTE stmt1;\n"
},
{
"answer_id": 17747307,
"author": "Bhavik Shah",
"author_id": 1680256,
"author_profile": "https://Stackoverflow.com/users/1680256",
"pm_score": 2,
"selected": false,
"text": "SELECT CONCAT('SELECT ',\n( SELECT GROUP_CONCAT(t.col)\nFROM\n(\n SELECT CASE\n WHEN COLUMN_NAME = 'eid' THEN NULL\n ELSE COLUMN_NAME\n END AS col \n FROM INFORMATION_SCHEMA.COLUMNS \n WHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'\n) t\nWHERE t.col IS NOT NULL) ,\n' FROM employee' );\n SELECT table_name,column_name \nFROM INFORMATION_SCHEMA.COLUMNS \nWHERE TABLE_NAME = 'employee' AND TABLE_SCHEMA = 'test'\n table_name column_name\nemployee eid\nemployee name_eid\nemployee sal\n 'SELECT name_eid,sal FROM employee'\n"
},
{
"answer_id": 56431536,
"author": "Eaten by a Grue",
"author_id": 1767412,
"author_profile": "https://Stackoverflow.com/users/1767412",
"pm_score": 1,
"selected": false,
"text": "SEPARATOR GROUP_CONCAT WHERE REPLACE() ORDER BY GROUP_CONCAT() SELECT CONCAT(\n 'SELECT `',\n GROUP_CONCAT(COLUMN_NAME ORDER BY `ORDINAL_POSITION` SEPARATOR '`,`'),\n '` FROM `',\n `TABLE_SCHEMA`,\n '`.`',\n TABLE_NAME,\n '`;'\n)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE `TABLE_SCHEMA` = 'my_database'\n AND `TABLE_NAME` = 'my_table'\n AND `COLUMN_NAME` != 'column_to_omit';\n"
},
{
"answer_id": 57268792,
"author": "MR_AMDEV",
"author_id": 10114772,
"author_profile": "https://Stackoverflow.com/users/10114772",
"pm_score": 1,
"selected": false,
"text": "SELECT *, LEFT(col1, 0) AS col1, LEFT(col2, 0) as col2 FROM table\n"
},
{
"answer_id": 64573062,
"author": "Adam",
"author_id": 2311074,
"author_profile": "https://Stackoverflow.com/users/2311074",
"pm_score": 0,
"selected": false,
"text": "Send to sql editor Select All Statement SELECT `purchase_history`.`id`,\n `purchase_history`.`user_id`,\n `purchase_history`.`deleted_at`\nFROM `fs_normal_run_2`.`purchase_history`;\nSELECT * FROM fs_normal_run_2.purchase_history;\n"
},
{
"answer_id": 70622146,
"author": "Lukas Eder",
"author_id": 521799,
"author_profile": "https://Stackoverflow.com/users/521799",
"pm_score": 0,
"selected": false,
"text": "* EXCEPT SELECT * FROM actor\n |actor_id|first_name|last_name |last_update |\n|--------|----------|------------|-----------------------|\n|1 |PENELOPE |GUINESS |2006-02-15 04:34:33.000|\n|2 |NICK |WAHLBERG |2006-02-15 04:34:33.000|\n|3 |ED |CHASE |2006-02-15 04:34:33.000|\n SELECT * EXCEPT (last_update) FROM actor\n |actor_id|first_name|last_name |\n|--------|----------|------------|\n|1 |PENELOPE |GUINESS |\n|2 |NICK |WAHLBERG |\n|3 |ED |CHASE |\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9122",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/44/"
] |
9,173 | <p>My C# project - we'll call it the SuperUI - used to make use of a class from an external assembly. Now it doesn't, but the compiler won't let me build the project without the assembly reference in place. Let me elaborate.</p>
<p>This project used to throw and catch a custom exception class - the <code>SuperException</code> - which was derived from the standard System.Exception and lived in a separate, precompiled assembly, <code>SuperAssembly.DLL</code>, which I referenced.</p>
<p>Eventually, I decided this was a pointless exercise and replaced all <code>SuperExceptions</code> with a System.SuitableStandardException in each case. I removed the reference to <code>SuperException.DLL</code>, but am now met with the following on trying to compile the project:</p>
<blockquote>
<p>The type 'SuperException' is defined in an assembly that is not referenced. You must add a reference to assembly 'SuperException, Version=1.1.0.0 (...)'</p>
</blockquote>
<p>The source file referenced by the error doesn't seem relevant; it's the project namespace that gets highlighted in the IDE.</p>
<p>Now, here's the thing:</p>
<ol>
<li>All uses of <code>SuperException</code> have been eliminated from the project's code.</li>
<li>Compared to another project that compiles fine without a reference to <code>SuperException.DLL</code>, I only reference one more assembly - and <code>that</code> references nothing that my project doesn't reference itself. While it's possible that any of these dependencies could throw <code>SuperExceptions</code>, I'm only catching the base Exception class and in any case... the other project builds fine!</li>
<li>I've done Visual Studio's "Clean Solution" and cleared everything out by hand, many times.</li>
</ol>
<p>It's not the end of the world to include this reference, I just don't see why it's necessary any more. Nrrrgg. Any pointers welcome!</p>
| [
{
"answer_id": 9276,
"author": "Orion Edwards",
"author_id": 234,
"author_profile": "https://Stackoverflow.com/users/234",
"pm_score": 0,
"selected": false,
"text": "SuperException SpecializedSuperException SuperException SuperException"
},
{
"answer_id": 9350,
"author": "Bernard",
"author_id": 61,
"author_profile": "https://Stackoverflow.com/users/61",
"pm_score": -1,
"selected": false,
"text": "grep -R SuperException * grep"
},
{
"answer_id": 5760084,
"author": "dmihailescu",
"author_id": 376495,
"author_profile": "https://Stackoverflow.com/users/376495",
"pm_score": 0,
"selected": false,
"text": "SuitableStandardException SuperException SuperException.DLL SuperException SuitableStandardException SuperAssembly.DLL superException.dll SuperAssembly.DLL SuperException.DLL [assembly:InternalsVisibleTo(\"SuperException, PublicKey=0024000004800000....)]\n SuperAssembly.DLL SuperException.DLL"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9173",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1135/"
] |
9,191 | <p>I'd like to ask a question then follow it up with my own answer, but also see what answers other people have.</p>
<p>We have two large files which we'd like to read from two separate threads concurrently. One thread will sequentially read fileA while the other thread will sequentially read fileB. There is no locking or communication between the threads, both are sequentially reading as fast as they can, and both are immediately discarding the data they read.</p>
<p>Our experience with this setup on Windows is very poor. The combined throughput of the two threads is in the order of 2-3 MiB/sec. The drive seems to be spending most of its time seeking backwards and forwards between the two files, presumably reading very little after each seek.</p>
<p>If we disable one of the threads and temporarily look at the performance of a single thread then we get much better bandwidth (~45 MiB/sec for this machine). So clearly the bad two-thread performance is an artefact of the OS disk scheduler.</p>
<p><strong>Is there anything we can do to improve the concurrent thread read performance?</strong> Perhaps by using different APIs or by tweaking the OS disk scheduler parameters in some way.</p>
<p>Some details:</p>
<p>The files are in the order of 2 GiB each on a machine with 2GiB of RAM. For the purpose of this question we consider them not to be cached and perfectly defragmented. We have used defrag tools and rebooted to ensure this is the case.</p>
<p>We are using no special APIs to read these files. The behaviour is repeatable across various bog-standard APIs such as Win32's CreateFile, C's fopen, C++'s std::ifstream, Java's FileInputStream, etc.</p>
<p>Each thread spins in a loop making calls to the read function. We have varied the number of bytes requested from the API each iteration from values between 1KiB up to 128MiB. Varying this has had no effect, so clearly the amount the OS is physically reading after each disk seek is not dictated by this number. This is exactly what should be expected.</p>
<p>The dramatic difference between one-thread and two-thread performance is repeatable across Windows 2000, Windows XP (32-bit and 64-bit), Windows Server 2003, and also with and without hardware RAID5.</p>
| [
{
"answer_id": 9193,
"author": "pauldoo",
"author_id": 755,
"author_profile": "https://Stackoverflow.com/users/755",
"pm_score": 3,
"selected": false,
"text": "FILE_FLAG_NO_BUFFERING CreateFile ReadFile CreateFile FILE_FLAG_SEQUENTIAL_SCAN"
},
{
"answer_id": 9826,
"author": "Andrea Bertani",
"author_id": 1005,
"author_profile": "https://Stackoverflow.com/users/1005",
"pm_score": 5,
"selected": true,
"text": "if THREAD A is reading from disk then wait for THREAD A to stop reading or wait for X ms\nRead for X ms (or Y MB)\nStop reading and check status of thread A again \n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9191",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755/"
] |
9,204 | <p>Is there any IL level debugger in form of a VS plugin or standalone application?</p>
<p>Visual studio’s debugger is great, but it allows you to debug on either HLL code level or assembly language, you can’t debug IL.
It seems that in some situations it would be useful to have an opportunity to debug at IL level. </p>
<p>In particular it might be helpful when debugging a problem in the code that you don't have the source of.</p>
<p>It is arguable if it is actually useful to debug IL when you don't have the source, but anyway.</p>
| [
{
"answer_id": 9210,
"author": "Chris Smith",
"author_id": 322,
"author_profile": "https://Stackoverflow.com/users/322",
"pm_score": 5,
"selected": false,
"text": "ildasm foo.exe /OUT=foo.exe.il /SOURCE ilasm foo.exe.il /DEBUG"
},
{
"answer_id": 29853999,
"author": "BSalita",
"author_id": 317797,
"author_profile": "https://Stackoverflow.com/users/317797",
"pm_score": 2,
"selected": false,
"text": "for /f \"tokens=1 delims=.\" %%1 in (\"%1\") do set NAME_ONLY=%%1\n@erase/q %NAME_ONLY%.il.il\n@if not exist %NAME_ONLY%.dll goto quit\nildasm /out:%NAME_ONLY%.il.il /source /nobar %NAME_ONLY%.dll\n@if not exist %NAME_ONLY%.il.il goto quit\nilasm /dll /debug /out=%NAME_ONLY%.dll %NAME_ONLY%.il.il\n@if not exist %NAME_ONLY%.dll goto quit\npeverify %NAME_ONLY%.dll\n:quit\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9204",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/578/"
] |
9,240 | <p>Say you have an application divided into 3-tiers: GUI, business logic, and data access. In your business logic layer you have described your business objects: getters, setters, accessors, and so on... you get the idea. The interface to the business logic layer guarantees safe usage of the business logic, so all the methods and accessors you call will validate input. </p>
<p>This great when you first write the UI code, because you have a neatly defined interface that you can trust.</p>
<p>But here comes the tricky part, when you start writing the data access layer, the interface to the business logic does not accommodate your needs. You need to have more accessors and getters to set fields which are/used to be hidden. Now you are forced to erode the interface of your business logic; now it is possible set fields from the UI layer, which the UI layer has no business setting. </p>
<p>Because of the changes needed for the data access layer, the interface to the business logic has eroded to the point where it is possible to even set the business logic with invalid data. Thus, the interface does not guarantee safe usage anymore.</p>
<p>I hope I explained the problem clearly enough. How do you prevent interface eroding, maintain information hiding and encapsulation, and yet still accommodate different interface needs among different layers? </p>
| [
{
"answer_id": 9251,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "public class BusinessObjectRecord : BusinessObject\n{\n}\n"
},
{
"answer_id": 9257,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "namespace Data\n{\n public class BusinessObjectDataManager\n {\n public void SaveObject(BusinessObject object)\n {\n // Exec stored procedure\n {\n }\n}\n"
},
{
"answer_id": 9277,
"author": "Derek Park",
"author_id": 872,
"author_profile": "https://Stackoverflow.com/users/872",
"pm_score": 0,
"selected": false,
"text": "public class BusinessLayer : ISimpleBusiness\n{}\n\npublic class Some3LayerObject : ISimpleSome3LayerObject\n{}\n"
},
{
"answer_id": 9369,
"author": "Jon Limjap",
"author_id": 372,
"author_profile": "https://Stackoverflow.com/users/372",
"pm_score": 0,
"selected": false,
"text": "public class BusinessObject : IView, IData\n public class BusinessObject : DomainObject\n\npublic class ViewManager<T> where T : DomainObject\n\npublic class DataManager<T> where T : DomainObject\n"
},
{
"answer_id": 9502,
"author": "Wheelie",
"author_id": 1131,
"author_profile": "https://Stackoverflow.com/users/1131",
"pm_score": 4,
"selected": true,
"text": "public class User\n{\n private string name;\n private AccountStatus status;\n\n private User()\n {\n }\n\n public string Name\n {\n get { return name; }\n set { name = value; }\n }\n\n public AccountStatus Status\n {\n get { return status; }\n }\n\n public void Activate()\n {\n status = AccountStatus.Active;\n }\n\n public void Suspend()\n {\n status = AccountStatus.Suspended;\n }\n\n public static User GetById(int id)\n {\n User fetchedUser = new User();\n\n // Lots of database and error-checking code\n // omitted for clarity\n // ...\n\n fetchedUser.name = (string) reader[\"Name\"];\n fetchedUser.status = (int)reader[\"statusCode\"] == 0 ? AccountStatus.Suspended : AccountStatus.Active;\n\n return fetchedUser;\n }\n\n public static void Save(User user)\n {\n // Code to save User's internal structure to database\n // ...\n }\n}\n"
}
] | 2008/08/12 | [
"https://Stackoverflow.com/questions/9240",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |