qid
int64
4
22.2M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
90,313
<p>Despite my lack of coding knowledge I managed to write a small little app in VB net that a lot of people are now using. Since I made it for free I have no way of knowing how popular it really is and was thinking I could make it ping some sort of online stat counter so I could figure out if I should port it to other languages. Any idea of how I could ping a url via vb without actually opening a window or asking to receive any data? When I google a lot of terms for this I end up with examples with 50+ lines of code for what I would think should only take one line or so, similar to opening an IE window.</p> <p>Side Note: Would of course fully inform all users this was happening.</p>
[ { "answer_id": 90344, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 1, "selected": false, "text": "Sub PingServer(Server As String, Port As Integer)\n Dim Temp As New System.Net.Sockets();\n Temp.Connect(Server, Port)\n Temp.Close()\nEnd Sub\n" }, { "answer_id": 90352, "author": "JohnnyLambada", "author_id": 9648, "author_profile": "https://Stackoverflow.com/users/9648", "pm_score": 0, "selected": false, "text": "Imports System\nImports System.IO\nImports System.Net\nModule Module1 \n Sub Main()\n ' Address of URL\n Dim URL As String = http://www.c-sharpcorner.com/default.asp\n ' Get HTML data\n Dim client As WebClient = New WebClient()\n Dim data As Stream = client.OpenRead(URL)\n Dim reader As StreamReader = New StreamReader(data)\n Dim str As String = \"\"\n str = reader.ReadLine()\n Do While str.Length > 0\n Console.WriteLine(str)\n str = reader.ReadLine()\n Loop\n End Sub\nEnd Module\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,350
<p>I have 3 PDF documents that are generated on the fly by a legacy library that we use, and written to disk. What's the easiest way for my JAVA server code to grab these 3 documents and turn them into one long PDF document where it's just all the pages from document #1, followed by all the pages from document #2, etc.</p> <p>Ideally I would like this to happen in memory so I can return it as a stream to the client, but writing it to disk is also an option.</p>
[ { "answer_id": 90512, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 3, "selected": true, "text": "public class PdfMergeHelper {\n\n /**\n * Merges the passed in PDFs, in the order that they are listed in the java.util.List.\n * Writes the resulting PDF out to the OutputStream provided.\n * \n * Sample Usage:\n * List<InputStream> pdfs = new ArrayList<InputStream>();\n * pdfs.add(new FileInputStream(\"/location/of/pdf/OQS_FRSv1.5.pdf\"));\n * pdfs.add(new FileInputStream(\"/location/of/pdf/PPFP-Contract_Genericv0.5.pdf\"));\n * pdfs.add(new FileInputStream(\"/location/of/pdf/PPFP-Quotev0.6.pdf\"));\n * FileOutputStream output = new FileOutputStream(\"/location/to/write/to/merge.pdf\");\n * PdfMergeHelper.concatPDFs(pdfs, output, true);\n * \n * @param streamOfPDFFiles the list of files to merge, in the order that they should be merged\n * @param outputStream the output stream to write the merged PDF to\n * @param paginate true if you want page numbers to appear at the bottom of each page, false otherwise\n */\n public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {\n Document document = new Document();\n try {\n List<InputStream> pdfs = streamOfPDFFiles;\n List<PdfReader> readers = new ArrayList<PdfReader>();\n int totalPages = 0;\n Iterator<InputStream> iteratorPDFs = pdfs.iterator();\n\n // Create Readers for the pdfs.\n while (iteratorPDFs.hasNext()) {\n InputStream pdf = iteratorPDFs.next();\n PdfReader pdfReader = new PdfReader(pdf);\n readers.add(pdfReader);\n totalPages += pdfReader.getNumberOfPages();\n }\n // Create a writer for the outputstream\n PdfWriter writer = PdfWriter.getInstance(document, outputStream);\n\n document.open();\n BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);\n PdfContentByte cb = writer.getDirectContent(); // Holds the PDF\n // data\n\n PdfImportedPage page;\n int currentPageNumber = 0;\n int pageOfCurrentReaderPDF = 0;\n Iterator<PdfReader> iteratorPDFReader = readers.iterator();\n\n // Loop through the PDF files and add to the output.\n while (iteratorPDFReader.hasNext()) {\n PdfReader pdfReader = iteratorPDFReader.next();\n\n // Create a new page in the target for each source page.\n while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {\n document.newPage();\n pageOfCurrentReaderPDF++;\n currentPageNumber++;\n page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);\n cb.addTemplate(page, 0, 0);\n\n // Code for pagination.\n if (paginate) {\n cb.beginText();\n cb.setFontAndSize(bf, 9);\n cb.showTextAligned(PdfContentByte.ALIGN_CENTER, \"\" + currentPageNumber + \" of \" + totalPages,\n 520, 5, 0);\n cb.endText();\n }\n }\n pageOfCurrentReaderPDF = 0;\n }\n outputStream.flush();\n document.close();\n outputStream.close();\n } catch (Exception e) {\n e.printStackTrace();\n } finally {\n if (document.isOpen()) {\n document.close();\n }\n try {\n if (outputStream != null) {\n outputStream.close();\n }\n } catch (IOException ioe) {\n ioe.printStackTrace();\n }\n }\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6044/" ]
90,360
<p>I was investigating the rapid growth of a SQL Server 2005 transaction log when I found that transaction logs will only truncate correctly - if the sys.databases "log_reuse_wait" column is set to 0 - meaning that nothing is keeping the transaction log from reusing existing space. </p> <p>One day when I was intending to backup/truncate a log file, I found that this column had a 4, or ACTIVE_TRANSACTION going on in the tempdb. I then checked for any open transactions using DBCC OPENTRAN('tempdb'), and the open_tran column from sysprocesses. The result was that I could find no active transactions anywhere in the system.</p> <p>Are the settings in the log_reuse_wait column accurate? Are there transactions going on that are not detectable using the methods I described above? Am I just missing something obvious?</p>
[ { "answer_id": 93269, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 1, "selected": false, "text": "TRUNCATE_ONLY" }, { "answer_id": 335014, "author": "Clinemi", "author_id": 14947, "author_profile": "https://Stackoverflow.com/users/14947", "pm_score": 3, "selected": false, "text": "select * from sys.dm_tran_active_transactions\n\nselect * from sys.dm_tran_session_transactions \n\nselect * from sys.dm_tran_locks\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14947/" ]
90,363
<p>I'm trying to read a .doc file into a database so that I can index it's contents. Is there an easy way for PHP on Linux to read .doc files? Failing that is it possible to convert .doc files to rtf, pdf or some other 'open' format that is easy to read?</p> <p>Note, I am not interested in .docx files. </p>
[ { "answer_id": 93504, "author": "Ivan Krechetov", "author_id": 6430, "author_profile": "https://Stackoverflow.com/users/6430", "pm_score": 3, "selected": false, "text": "/usr/lib/ooo-2.0/program/soffice.bin -norestore -nofirststart -nologo -headless -invisible \"macro:///Standard.Module1.SaveAsPDF(demo.doc)\"\n" }, { "answer_id": 36132567, "author": "hugsbrugs", "author_id": 2295192, "author_profile": "https://Stackoverflow.com/users/2295192", "pm_score": 0, "selected": false, "text": "sudo apt-get install wv\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90363", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17265/" ]
90,367
<p>I recently started using Rake to build some of my (non-ruby) packages. Rake is nice, but what I found missing is a way to do hierarchical builds (aggregate Rakefiles in subdirectories). Since this is a common feature in most other build tools, I'm wondering if someone more familiar with Rake has a good solution.</p>
[ { "answer_id": 123520, "author": "davetron5000", "author_id": 3029, "author_profile": "https://Stackoverflow.com/users/3029", "pm_score": 1, "selected": false, "text": "SUBDIR = \"subdir\"\ntask :subtask => SRC_FILES do |t|\n chdir(SUBDIR) do \n system(\"rake\")\n end\nend\n\ntask :subtaskclean do |t|\n chdir(SUBDIR) do \n system(\"rake clean\")\n end\nend\n\ntask :subtaskclean do |t|\n chdir(SUBDIR) do \n system(\"rake clobber\")\n end\nend\n\ntask :default => [:maintask, :subtask]\ntask :clean => :subtaskclean\ntask :clobber => :subtaskclobber\n" }, { "answer_id": 29996297, "author": "Sander Mertens", "author_id": 1964905, "author_profile": "https://Stackoverflow.com/users/1964905", "pm_score": 0, "selected": false, "text": "Dir.chdir(File.dirname(Rake.application.rakefile))\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17276/" ]
90,401
<p>How to create new PCL file similar to existing MS doc. I have MS doc template and replacing it with actual data. I need to achieve same for PCL format (Create PCL file as template and replacing it with actual value from database and send it to fax).</p>
[ { "answer_id": 90653, "author": "CL.", "author_id": 11654, "author_profile": "https://Stackoverflow.com/users/11654", "pm_score": 4, "selected": true, "text": "c:\\temp\\print.pcl" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,411
<p>I want to extend an existing application I made to make it set mixer volume by wheel-scrolling over it's notification area icon.</p> <p>As far as I know, the notification area doesn't receive any WM_MOUSEWHEEL messages, but still I found an application that does exactly what I want to achieve (<a href="http://www.actualsolution.com/power_mixer/" rel="nofollow noreferrer">http://www.actualsolution.com/power_mixer</a>). Using WinspectorSpy I've noticed some strange messages the application's form receives: 0x000003d0 and 0x000003d1, but I found no references about them.</p> <p>Does anyone have any idea on how I could achieve the desired functionality?</p>
[ { "answer_id": 90793, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 1, "selected": false, "text": "var\n hwndTaskBar, hwndTrayWnd, hwndTrayToolBar : HWND;\n rTrayToolBar : tRect;\nbegin\n hwndTaskBar := FindWindowEx (0, 0, 'Shell_TrayWnd', nil);\n hwndTrayWnd := FindWindowEx (hwndTaskBar , 0, 'TrayNotifyWnd',nil);\n hwndTrayToolBar := FindWindowEx(hwndTrayWnd, 0, 'ToolbarWindow32',nil);\n\n Windows.GetClientRect(hwndTrayToolBar, rTrayToolBar);\nend\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2073/" ]
90,413
<p>I want to encrypt few files using python what is the best way I can use gpg/pgp using any standard/famous python libraries?</p>
[ { "answer_id": 90959, "author": "bortzmeyer", "author_id": 15625, "author_profile": "https://Stackoverflow.com/users/15625", "pm_score": 3, "selected": false, "text": "signed = core.Data(sys.stdin.read())\nplain = core.Data()\ncontext = core.Context()\n\ncontext.op_verify(signed, None, plain)\nresult = context.op_verify_result()\n\nsign = result.signatures\nwhile sign:\n if sign.status != 0:\n print \"BAD signature from:\"\n else:\n print \"Good signature from:\"\n print \" uid: \", context.get_key(sign.fpr, 0).uids.uid\n print \" timestamp: \", sign.timestamp\n print \" fingerprint:\", sign.fpr\n sign = sign.next\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6946/" ]
90,418
<p>I have a shell script that executes a number of commands. How do I make the shell script exit if any of the commands exit with a non-zero exit code?</p>
[ { "answer_id": 90434, "author": "Martin W", "author_id": 14199, "author_profile": "https://Stackoverflow.com/users/14199", "pm_score": 4, "selected": false, "text": "&&" }, { "answer_id": 90435, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 10, "selected": true, "text": "$?" }, { "answer_id": 90440, "author": "Allen", "author_id": 6043, "author_profile": "https://Stackoverflow.com/users/6043", "pm_score": 6, "selected": false, "text": "set -e" }, { "answer_id": 90441, "author": "Jeff Hill", "author_id": 14742, "author_profile": "https://Stackoverflow.com/users/14742", "pm_score": 8, "selected": false, "text": "$?" }, { "answer_id": 90447, "author": "Arvodan", "author_id": 5751, "author_profile": "https://Stackoverflow.com/users/5751", "pm_score": 5, "selected": false, "text": "OR" }, { "answer_id": 90475, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "# This will trap any errors or commands with non-zero exit status\n# by calling function catch_errors()\ntrap catch_errors ERR;\n\n#\n# ... the rest of the script goes here\n#\n\nfunction catch_errors() {\n # Do whatever on errors\n #\n #\n echo \"script aborted, because of errors\";\n exit 0;\n}\n" }, { "answer_id": 493676, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "cmd1" }, { "answer_id": 8045505, "author": "chemila", "author_id": 889064, "author_profile": "https://Stackoverflow.com/users/889064", "pm_score": 5, "selected": false, "text": "[ $? -eq 0 ] || exit $?; # Exit for nonzero return code\n" }, { "answer_id": 9353084, "author": "Yordan Georgiev", "author_id": 65706, "author_profile": "https://Stackoverflow.com/users/65706", "pm_score": 2, "selected": false, "text": "#\n#------------------------------------------------------------------------------\n# purpose: to run a command, log cmd output, exit on error\n# usage:\n# set -e; do_run_cmd_or_exit \"$cmd\" ; set +e\n#------------------------------------------------------------------------------\ndo_run_cmd_or_exit(){\n cmd=\"$@\" ;\n\n do_log \"DEBUG running cmd or exit: \\\"$cmd\\\"\"\n msg=$($cmd 2>&1)\n export exit_code=$?\n\n # If occurred during the execution, exit with error\n error_msg=\"Failed to run the command:\n \\\"$cmd\\\" with the output:\n \\\"$msg\\\" !!!\"\n\n if [ $exit_code -ne 0 ] ; then\n do_log \"ERROR $msg\"\n do_log \"FATAL $msg\"\n do_exit \"$exit_code\" \"$error_msg\"\n else\n # If no errors occurred, just log the message\n do_log \"DEBUG : cmdoutput : \\\"$msg\\\"\"\n fi\n\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
90,428
<p>I'm looking for an LDAP libracy in C or C++ that allows me to specify a list of LDAP hostnames instead of a single hostname. The library should then use the first one it can connect to in case one or more of the servers is/are down. I'm sure it'd be easy to wrap an existing library to create this, but why reinvent the wheel?</p>
[ { "answer_id": 288838, "author": "geocar", "author_id": 37507, "author_profile": "https://Stackoverflow.com/users/37507", "pm_score": 2, "selected": false, "text": "ldapserver.example.com. IN A 1.2.3.4\nldapserver.example.com. IN A 2.3.4.5\n" }, { "answer_id": 1329273, "author": "Stef", "author_id": 131414, "author_profile": "https://Stackoverflow.com/users/131414", "pm_score": 1, "selected": false, "text": "ldap_init()" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,462
<p>How do I obtain the serial number of the CPU in a PC?</p>
[ { "answer_id": 90505, "author": "Friedrich", "author_id": 15068, "author_profile": "https://Stackoverflow.com/users/15068", "pm_score": -1, "selected": false, "text": "#include <stdlib.h>\n#include <string.h>\n#include <intrinsics.h>\n\n_CPUID cpuinfo;\nint main(void) {\n_cpuid(&cpuinfo);\nprintf(\"Vendor: %s\\n\", cpuinfo.Vendor);\nreturn 0;\n}\n" }, { "answer_id": 10160408, "author": "BlackTalon", "author_id": 786897, "author_profile": "https://Stackoverflow.com/users/786897", "pm_score": 2, "selected": false, "text": "Win32_BIOS" }, { "answer_id": 35945180, "author": "Amir", "author_id": 5050750, "author_profile": "https://Stackoverflow.com/users/5050750", "pm_score": 1, "selected": false, "text": "__get_cpuid (unsigned int __level, unsigned int *__eax, unsigned int *__ebx, unsigned int *__ecx, unsigned int *__edx);" }, { "answer_id": 55945482, "author": "Anthony Bachler", "author_id": 6933234, "author_profile": "https://Stackoverflow.com/users/6933234", "pm_score": 2, "selected": false, "text": "\n#include <Windows.h>\n#include <stdio.h>\n#include <xmmintrin.h>\n#include <iphlpapi.h>\n#include <Rpc.h>\n\nstatic void GetMACaddress(void);\nstatic void uuidGetMACaddress(void);\n\nint main(){\n SYSTEM_INFO SysInfo;\n GetSystemInfo(&SysInfo);\n printf(\"Processors - %d\\n\" , SysInfo.dwNumberOfProcessors);\n DWORD a , b , c , d , e;\n DWORD BasicLeaves;\n char* VendorID = (char*)malloc(20);\n char* message = (char*)malloc(20);\n _asm {\n pusha\n pushfd\n pop eax\n push eax\n xor eax , 0x00200000\n push eax\n popfd\n pushfd\n pop ecx\n pop eax\n xor eax , ecx\n mov [a] , eax\n }\n if(a & 0x00200000){\n printf(\"CPUID opcode supported.\\n\");\n } else {\n printf(\"CPUID opcode not supported, exiting...\\n\");\n return 0;\n }\n\n //DWORD* pa = &a[0];\n //DWORD* pb = &a[1];\n //DWORD* pc = &a[2];\n //DWORD* pd = &a[3];\n //a[4] = 0;\n e = 0;\n __asm {\n mov eax , 0\n cpuid\n mov [BasicLeaves] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n }\n memcpy(&VendorID[0] , &b , 4);\n memcpy(&VendorID[4] , &d , 4);\n memcpy(&VendorID[8] , &c , 4);\n VendorID[12] = 0;\n\n printf(\"%d Basic Leaves\\nVendorID - %s\\n\" , BasicLeaves , VendorID);\n\n __asm {\n mov eax , 1\n cpuid\n mov [a] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n }\n if(d & 0x00000001) printf(\"FPU\\n\");\n if(d & 0x00000200) printf(\"APIC On-Chip\\n\");\n if(d & 0x00040000) printf(\"Processor Serial Number Present\\n\");\n if(d & 0x00800000) printf(\"MMX\\n\");\n if(d & 0x01000000) printf(\"SSE\\n\");\n if(d & 0x02000000) printf(\"SSE2\\n\");\n if(d & 0x08000000) printf(\"Hyperthreading (HTT)\\n\");\n\n if(c & 0x00000001) printf(\"SSE3\\n\");\n if(c & 0x00000200) printf(\"SSSE3\\n\");\n if(c & 0x00080000) printf(\"SSE4.1\\n\");\n if(c & 0x00100000) printf(\"SSE4.2\\n\");\n if(c & 0x02000000) printf(\"AES\\n\");\n\n\n __asm {\n mov eax , 0x80000000\n cpuid\n and eax , 0x7fffffff;\n mov [a] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n }\n\n printf(\"%d Extended Leaves\\n\" , a);\n\n printf(\"Processor Brand String - \");\n __asm {\n mov eax , 0x80000002\n cpuid\n mov [a] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n }\n memcpy(&message[0] , &a , 4);\n memcpy(&message[4] , &b , 4);\n memcpy(&message[8] , &c , 4);\n memcpy(&message[12] , &d , 4);\n message[16] = 0;\n printf(\"%s\" , message);\n\n __asm {\n mov eax , 0x80000003\n cpuid\n mov [a] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n }\n\n memcpy(&message[0] , &a , 4);\n memcpy(&message[4] , &b , 4);\n memcpy(&message[8] , &c , 4);\n memcpy(&message[12] , &d , 4);\n message[16] = 0;\n printf(\"%s\" , message);\n\n __asm {\n mov eax , 0x80000004\n cpuid\n mov [a] , eax;\n mov [b] , ebx;\n mov [c] , ecx;\n mov [d] , edx;\n popa\n }\n memcpy(&message[0] , &a , 4);\n memcpy(&message[4] , &b , 4);\n memcpy(&message[8] , &c , 4);\n memcpy(&message[12] , &d , 4);\n message[16] = 0;\n printf(\"%s\\n\" , message);\n\n char VolumeName[256]; DWORD VolumeSerialNumber; DWORD MaxComponentLength; DWORD FileSystemFlags; char FileSystemNameBuffer[256]; \n GetVolumeInformationA(\"c:\\\\\" , VolumeName , 256 , &VolumeSerialNumber , &MaxComponentLength , &FileSystemFlags , (LPSTR)&FileSystemNameBuffer , 256);\n printf(\"Serialnumber - %X\\n\" , VolumeSerialNumber);\n\n GetMACaddress();\n uuidGetMACaddress();\n\n return 0;\n }\n\n// Fetches the MAC address and prints it\nstatic void GetMACaddress(void){\n IP_ADAPTER_INFO AdapterInfo[16]; // Allocate information \n // for up to 16 NICs\n DWORD dwBufLen = sizeof(AdapterInfo); // Save memory size of buffer\n\n DWORD dwStatus = GetAdaptersInfo( // Call GetAdapterInfo\n AdapterInfo, // [out] buffer to receive data\n &dwBufLen); // [in] size of receive data buffer\n //assert(dwStatus == ERROR_SUCCESS); // Verify return value is \n // valid, no buffer overflow\n\n PIP_ADAPTER_INFO pAdapterInfo = AdapterInfo; // Contains pointer to\n // current adapter info\n do {\n printf(\"Adapter MAC Address - %X-%X-%X-%X-%X-%X\\n\" , pAdapterInfo->Address[0] , pAdapterInfo->Address[1] , pAdapterInfo->Address[2] , pAdapterInfo->Address[3] , pAdapterInfo->Address[4] , pAdapterInfo->Address[5]);\n printf(\"Adapter IP Address - %s\\n\" , pAdapterInfo->CurrentIpAddress);\n printf(\"Adapter Type - %d\\n\" , pAdapterInfo->Type);\n printf(\"Adapter Name - %s\\n\" , pAdapterInfo->AdapterName);\n printf(\"Adapter Description - %s\\n\" , pAdapterInfo->Description);\n uuidGetMACaddress();\n\n printf(\"\\n\");\n //PrintMACaddress(pAdapterInfo->Address); // Print MAC address\n pAdapterInfo = pAdapterInfo->Next; // Progress through \n // linked list\n } while(pAdapterInfo); // Terminate if last adapter\n }\n\n// Fetches the MAC address and prints it\n\nstatic void uuidGetMACaddress(void)\n{\n unsigned char MACData[6];\n\n UUID uuid;\n UuidCreateSequential( &uuid ); // Ask OS to create UUID\n\n for (int i=2; i<8; i++) // Bytes 2 through 7 inclusive \n // are MAC address\n MACData[i - 2] = uuid.Data4[i];\n\n printf(\"UUID MAC Address - %X-%X-%X-%X-%X-%X\\n\" , MACData[0] , MACData[1] , MACData[2] , MACData[3] , MACData[4] , MACData[5]);\n}//*/\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90462", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16314/" ]
90,493
<p>How can I cast long to HWND (C++ visual studio 8)?</p> <pre><code>Long lWindowHandler; HWND oHwnd = (HWND)lWindowHandler; </code></pre> <p>But I got the following warning:</p> <blockquote> <p>warning C4312: 'type cast' : conversion from 'LONG' to 'HWND' of greater size</p> </blockquote> <p>Thanks.</p>
[ { "answer_id": 90508, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": false, "text": "HWND hWnd = (HWND)(LONG_PTR)lParam;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,511
<p>Basically, I would like a brief explanation of how I can access a SQL database in C# code. I gather that a connection and a command is required, but what's going on? I guess what I'm asking is for someone to de-mystify the process a bit. Thanks.</p> <p>For clarity, in my case I'm doing web apps, e-commerce stuff. It's all ASP.NET, C#, and SQL databases.</p> <p>I'm going to go ahead and close this thread. It's a little to general and I am going to post some more pointed and tutorial-esque questions and answers on the subject.</p>
[ { "answer_id": 90514, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 3, "selected": false, "text": "private static void ReadOrderData(string connectionString)\n{\n string queryString = \n \"SELECT OrderID, CustomerID FROM dbo.Orders;\";\n using (SqlConnection connection = new SqlConnection(\n connectionString))\n {\n SqlCommand command = new SqlCommand(\n queryString, connection);\n connection.Open();\n SqlDataReader reader = command.ExecuteReader();\n try\n {\n while (reader.Read())\n {\n Console.WriteLine(String.Format(\"{0}, {1}\",\n reader[0], reader[1]));\n }\n }\n finally\n {\n // Always call Close when done reading.\n reader.Close();\n }\n }\n}\n" }, { "answer_id": 90539, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 1, "selected": false, "text": "using System.Data;\nusing System.Data.SqlClient;\n\nstring connString = \"Data Source=...\";\nSqlConnection conn = new SqlConnection(connString); // you can also use ConnectionStringBuilder\nconnection.Open();\n\nstring sql = \"...\"; // your SQL query\nSqlCommand command = new SqlCommand(sql, conn);\n\n// if you're interested in reading from a database use one of the following methods\n\n// method 1\nSqlDataReader reader = command.ExecuteReader();\n\nwhile (reader.Read()) {\n object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index\n}\n\n// make sure you close the reader when you're done\nreader.Close();\n\n// method 2\nDataTable table;\nSqlDataAdapter adapter = new SqlDataAdapter(command);\nadapter.Fill(table);\n\n// then work with the table as you would normally\n\n// when you're done\nconnection.Close();\n" }, { "answer_id": 91733, "author": "naspinski", "author_id": 14777, "author_profile": "https://Stackoverflow.com/users/14777", "pm_score": 2, "selected": false, "text": "exampleDataContext db = new exampleDataContext(); // initializes your linq-to-sql\nitem item_I_want = (from i in db.items where i.itemID == 3 select i).First(); // using the 'item' class your dbml made\n" }, { "answer_id": 91813, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "string connString = \"Data Source=...\";\nstring sql = \"...\"; // your SQL query\n\n//this using block\nusing( SqlConnection conn = new SqlConnection(connString) )\nusing( SqlCommand command = new SqlCommand(sql, conn) )\n{\n connection.Open();\n\n // if you're interested in reading from a database use one of the following methods\n\n // method 1\n SqlDataReader reader = command.ExecuteReader();\n\n while (reader.Read()) {\n object someValue = reader.GetValue(0); // GetValue takes one parameter -- the column index\n }\n\n // make sure you close the reader when you're done\n reader.Close();\n\n // method 2\n DataTable table;\n SqlDataAdapter adapter = new SqlDataAdapter(command);\n adapter.Fill(table);\n\n // then work with the table as you would normally\n\n // when you're done\n connection.Close();\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13578/" ]
90,517
<p>When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in. </p> <p>It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie?</p> <p>Should I add <code>mysql_real_escape_string</code> (or something else) to all my cookie calls or is there some kind of built in procedure that will not allow this to happen?</p>
[ { "answer_id": 90609, "author": "joelhardi", "author_id": 11438, "author_profile": "https://Stackoverflow.com/users/11438", "pm_score": 4, "selected": true, "text": "define('COOKIE_SALT', 'secretblahblahlkdsfklj');\n$cookie_value = sha1($username.$password.COOKIE_SALT);\n" }, { "answer_id": 90705, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 0, "selected": false, "text": "$usernameFromPostDbsafe = LimitToAlphaNumUnderscore($usernameFromPost);\n$result = Query(\"SELECT hash FROM userTable WHERE username='$usernameFromPostDbsafe' LIMIT 1;\");\n$hashFromDb = $result['hash'];\nif( (sha1($usernameFromPost.$passwordFromPost.SALT)) == $hashFromDb ){\n //Auth Success\n}else{\n //Auth Failure\n}\n" }, { "answer_id": 91090, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "$db = MDB2::factory( $dsn );\n\n$types = array( 'integer', 'text' );\n$sth = $db->prepare( \"INSERT INTO table (ID,Text) (?,?)\", $types );\nif( PEAR::isError( $sth ) ) die( $sth->getMessage() );\n\n$data = array( 5, 'some text' );\n$result = $sth->execute( $data );\n$sth->free();\nif( PEAR::isError( $result ) ) die( $result->getMessage() );\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,553
<p>I've kind of backed myself into a corner here.</p> <p>I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls.</p> <p>What I want to do is just have one event handler, in the parent UserControl, which goes and does stuff that only the parent control can do (that is, conditionally calling an event, as the event's defined in the parent). I'd then hook up this event handler to all my input boxes in my child controls, and the child controls would sort out the task of parsing the input and telling the parent control whether to throw that event. Nice and clean, no repetitive, copy-paste code (which for me <em>always</em> results in a bug).</p> <p>Here's my question. Visual Studio thinks I'm being too clever by half, and warns me that "the method 'CheckReadiness' [the event handler in the parent] cannot be the method for an event because a class this class derives from already defines the method." Yes, Visual Studio, <em>that's the point</em>. I <em>want</em> to have an event handler that only handles events thrown by child classes, and its only job is to enable me to hook up the children without having to write a single line of code. I don't need those extra handlers - all the functionality I need is naturally called as the children process the user input.</p> <p>I'm not sure why Visual Studio has started complaining about this now (as it let me do it before), and I'm not sure how to make it go away. Preferably, I'd like to do it without having to define a method that just calls CheckReadiness. What's causing this warning, what's causing it to come up now when it didn't an hour ago, and how can I make it go away without resorting to making little handlers in all the child classes?</p>
[ { "answer_id": 90606, "author": "TK.", "author_id": 1816, "author_profile": "https://Stackoverflow.com/users/1816", "pm_score": 4, "selected": true, "text": "base.checkReadyness(sender, e);\n" }, { "answer_id": 11704494, "author": "Bolek", "author_id": 1524524, "author_profile": "https://Stackoverflow.com/users/1524524", "pm_score": 0, "selected": false, "text": " protected override void OnLoad(EventArgs e)\n {\n try\n {\n this.SuspendLayout();\n base.OnLoad(e);\n\n foreach (Control ctrl in Controls)\n {\n Button btn = ctrl as Button;\n if (btn == null) continue;\n\n if (string.Equals(btn.Name, \"btnAdd\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnAdd_Click);\n else if (string.Equals(btn.Name, \"btnEdit\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnEdit_Click);\n else if (string.Equals(btn.Name, \"btnDelete\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnDelete_Click);\n else if (string.Equals(btn.Name, \"btnPrint\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnPrint_Click);\n else if (string.Equals(btn.Name, \"btnExport\", StringComparison.Ordinal))\n btn.Click += new EventHandler(btnExport_Click);\n }\n" }, { "answer_id": 37685569, "author": "user6436572", "author_id": 6436572, "author_profile": "https://Stackoverflow.com/users/6436572", "pm_score": 2, "selected": false, "text": " public MyForm()\n {\n InitializeComponent();\n btnOK.Click += Ok_Click;\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5133/" ]
90,565
<p>NHibernate is not really a good fit for our environment due to all the dependencies. (Castle, log4net etc.)</p> <p>Is there a good lightweight alternative?</p> <p>Support for simple file based databases such as Access/SQLite/VistaDB is essential.</p> <p>Ideally, something contained in a single assembly that only references .NET assemblies. If it only requires .NET framework 2.0 or 3.0 that is a bonus.</p>
[ { "answer_id": 23510631, "author": "Vitaliy Fedorchenko", "author_id": 2756471, "author_profile": "https://Stackoverflow.com/users/2756471", "pm_score": 0, "selected": false, "text": "var dalc = new DbDalc(new SqlClientDalcFactory(), connectionStr);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90565", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5776/" ]
90,578
<p>I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment. </p> <p>For instance, something that surprised me and wasted a lot of time is absence of real properties on a class object (something I assumed all OOP languages had). There are many gotchas. I've been to various places where they compare Java syntax vs C#, but there don't seem to be any sites that tell of things to look out for when moving to Java. </p> <p>The environment is a whole other issue all together. The Blackberry IDE is simply horrible. The look reminds me Borland C++ for Windows 3.1 - it's that outdated. Some of the other issues included spotty intellisense, weak debugging, etc... Blackberry does have a beta of the Eclipse plugin, but without debugging support, it's just an editor with fancy refactoring tools.</p> <p>So, any advice on how to blend in to Java-ME?</p>
[ { "answer_id": 90601, "author": "Noel Grandin", "author_id": 6591, "author_profile": "https://Stackoverflow.com/users/6591", "pm_score": 2, "selected": false, "text": "public class MyClass {\n public static int MY_CLASS_PROPERTY = 12;\n}\n" }, { "answer_id": 90655, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 7, "selected": true, "text": "System.out.println(\"Hello\");\n" }, { "answer_id": 91123, "author": "Tomer Gabel", "author_id": 11558, "author_profile": "https://Stackoverflow.com/users/11558", "pm_score": 5, "selected": false, "text": "java.lang.Exception" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
90,579
<p>How to center text over an image in a table cell using javascript, css, and/or html?</p> <p>I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.</p> <p>ADDENDUM: i did end up having to use javascript to center the text reliably using a fixed-size div with absolute positioning; i just could not get it to work any other way</p>
[ { "answer_id": 90596, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "<table>\n <tr>\n <td style=\"background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center\">\n Here is my text\n </td>\n </tr>\n</table>\n" }, { "answer_id": 90625, "author": "sdkpoly", "author_id": 15640, "author_profile": "https://Stackoverflow.com/users/15640", "pm_score": 0, "selected": false, "text": "<TABLE><TR valign=center>\n <TD align=center background=\"some image\"> image label </TD>\n</TR></TABLE>\n" }, { "answer_id": 99848, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 1, "selected": false, "text": "#image1, #image1-text, #image1-container {\n overflow: hidden;\n height: 100px;\n width: 100px;\n}\n\n#image1 {\n top: -100px;\n position: relative;\n z-index: -1;\n}\n\n#image1-text {\n text-align: center;\n vertical-align: middle;\n display: table-cell;\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
90,580
<p>Without getting a degree in information retrieval, I'd like to know if there exists any algorithms for counting the frequency that words occur in a given body of text. The goal is to get a "general feel" of what people are saying over a set of textual comments. Along the lines of <a href="http://wordle.net/" rel="noreferrer">Wordle</a>.</p> <p>What I'd like:</p> <ul> <li>ignore articles, pronouns, etc ('a', 'an', 'the', 'him', 'them' etc)</li> <li>preserve proper nouns</li> <li>ignore hyphenation, except for soft kind</li> </ul> <p>Reaching for the stars, these would be peachy:</p> <ul> <li>handling stemming &amp; plurals (e.g. like, likes, liked, liking match the same result)</li> <li>grouping of adjectives (adverbs, etc) with their subjects ("great service" as opposed to "great", "service")</li> </ul> <p>I've attempted some basic stuff using Wordnet but I'm just tweaking things blindly and hoping it works for my specific data. Something more generic would be great.</p>
[ { "answer_id": 90890, "author": "underspecified", "author_id": 8146, "author_profile": "https://Stackoverflow.com/users/8146", "pm_score": 4, "selected": false, "text": "$ echo \"Without getting a degree in information retrieval, I'd like to know if there exists any algorithms for counting the frequency that words occur in a given body of text.\" | tree-tagger-english \n# Word POS surface form\nWithout IN without\ngetting VVG get\na DT a\ndegree NN degree\nin IN in\ninformation NN information\nretrieval NN retrieval\n, , ,\nI PP I\n'd MD will\nlike VV like\nto TO to\nknow VV know\nif IN if\nthere EX there\nexists VVZ exist\nany DT any\nalgorithms NNS algorithm\nfor IN for\ncounting VVG count\nthe DT the\nfrequency NN frequency\nthat IN/that that\nwords NNS word\noccur VVP occur\nin IN in\na DT a\ngiven VVN give\nbody NN body\nof IN of\ntext NN text\n. SENT .\n" }, { "answer_id": 90939, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 2, "selected": false, "text": ">>> import urllib2, string\n>>> devilsdict = urllib2.urlopen('http://www.gutenberg.org/files/972/972.txt').read()\n>>> workinglist = devilsdict.split()\n>>> cleanlist = [item.strip(string.punctuation) for item in workinglist]\n>>> results = {}\n>>> skip = {'a':'', 'the':'', 'an':''}\n>>> for item in cleanlist:\n if item not in skip:\n try:\n results[item] += 1\n except KeyError:\n results[item] = 1\n\n>>> results\n{'': 17, 'writings': 3, 'foul': 1, 'Sugar': 1, 'four': 8, 'Does': 1, \"friend's\": 1, 'hanging': 4, 'Until': 1, 'marching': 2 ...\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17328/" ]
90,595
<p>How to implement a web page that scales when the browser window is resized?</p> <p>I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized</p> <p>i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize hook, but it is cumbersome. Is there a better way?</p> <ul> <li><p>thanks everyone for the answers so far, i intend to try them all (or at least most of them) and then choose the best solution as the answer to this thread</p></li> <li><p>using CSS and percentages seems to work best, which is what I did in the original solution; using a visibility:hidden div set to 100% by 100% gives a way to measure the client area of the window [difficult in IE otherwise], and an onwindowresize javascript function lets the AJAXPRO methods kick in when the window is resized to redraw the layout-cell contents at the new resolution</p></li> </ul> <p>EDIT: my apologies for not being completely clear; i needed a 'liquid layout' where the major elements ('panes') would scale as the browser window was resized. I found that i had to use an AJAX call to re-display the 'pane' contents after resizing, and keep overflow:auto turned on to avoid scrolling</p>
[ { "answer_id": 90603, "author": "Fire Lancer", "author_id": 6266, "author_profile": "https://Stackoverflow.com/users/6266", "pm_score": 5, "selected": true, "text": "<body>\n <div style=\"width:50%\">\n <!--some stuff-->\n </div>\n</body>\n" }, { "answer_id": 90696, "author": "Florian", "author_id": 12336, "author_profile": "https://Stackoverflow.com/users/12336", "pm_score": 1, "selected": false, "text": "<head><title>Centered</title>\n<style type=\"text/css\">\nbody { \n background-position: center center;\n border: thin solid #000000;\n height: 300px;\n width: 600px;\n position: absolute;\n left: 50%;\n top: 50%;\n margin-top: -150px;\n margin-right: auto;\n margin-bottom: auto;\n margin-left: -300px;\n }\n</style></head> \n" }, { "answer_id": 181215, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "<script type=\"text/javascript\">\nvar tmout = null;\nvar mustReload = false;\n\nfunction Resizing()\n{\n if (tmout != null)\n {\n clearTimeout(tmout);\n }\n tmout = setTimeout(RefreshAll,300);\n}\nfunction Reload()\n{\n document.location.href = document.location.href;\n}\n//IE fires the window's onresize event when the client area \n//expands or contracts, which causes an infinite loop.\n//the way around this is a hidden div set to 100% of \n//height and width, with a guard around the resize event \n//handler to see if the _window_ size really changed\nvar windowHeight;\nvar windowWidth;\nwindow.onresize = null;\nwindow.onresize = function()\n{\n var backdropDiv = document.getElementById(\"divBackdrop\");\n if (windowHeight != backdropDiv.offsetHeight ||\n windowWidth != backdropDiv.offsetWidth)\n {\n //if screen is shrinking, must reload to get correct sizes\n if (windowHeight != backdropDiv.offsetHeight ||\n windowWidth != backdropDiv.offsetWidth)\n {\n mustReload = true;\n }\n else\n {\n mustReload = mustReload || false;\n }\n windowHeight = backdropDiv.offsetHeight;\n windowWidth = backdropDiv.offsetWidth;\n Resizing();\n }\n}\n</script>\n" }, { "answer_id": 2160019, "author": "Sphvn", "author_id": 261564, "author_profile": "https://Stackoverflow.com/users/261564", "pm_score": 0, "selected": false, "text": " /**** Page Rescaling Function ****/\n\n function resizeWindow() \n {\n var windowHeight = getWindowHeight();\n var windowWidth = getWindowWidth();\n\n document.getElementById(\"content\").style.height = (windowHeight - 4) + \"px\";\n }\n\n function getWindowHeight() \n {\n var windowHeight=0;\n if (typeof(window.innerHeight)=='number') \n {\n windowHeight = window.innerHeight;\n }\n else {\n if (document.documentElement && document.documentElement.clientHeight) \n {\n windowHeight = document.documentElement.clientHeight;\n }\n else \n {\n if (document.body && document.body.clientHeight) \n {\n windowHeight = document.body.clientHeight;\n }\n }\n }\n return windowHeight;\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90595", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9345/" ]
90,657
<p>I'm trying to find a way to fake the result of a method called from within another method.</p> <p>I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result).</p> <p>So I have code like this:</p> <pre><code>public class MyClass(){ public void LoadData(){ SomeProperty = Helper.GetSomeData(); } public object SomeProperty {get;set;} } </code></pre> <p>I want to have a known result from the Helper.GetSomeData() method. Can I use a mocking framework (I've got fairly limited experience with Rhino Mocks but am open to anything) to force an expected result? If so, how?</p> <p>*Edit - yeah as expected I couldn't achieve the hack I wanted, I'll have to work out a better way to set up the data.</p>
[ { "answer_id": 90692, "author": "Fossmo", "author_id": 4093, "author_profile": "https://Stackoverflow.com/users/4093", "pm_score": 0, "selected": false, "text": "public class MyClass(){\n public void LoadData(IHelper helper){\n SomeProperty = helper.GetSomeData();\n }\n" }, { "answer_id": 90737, "author": "Justin Bozonier", "author_id": 9401, "author_profile": "https://Stackoverflow.com/users/9401", "pm_score": 3, "selected": false, "text": "public class MyClass()\n{\n private IHelper _helper;\n\n public MyClass()\n {\n //Default constructor normal code would use.\n this._helper = new Helper();\n }\n\n public MyClass(IHelper helper)\n {\n if(helper == null)\n {\n throw new NullException(); //I forget the exact name but you get my drift ;)\n }\n this._helper = helper;\n }\n\n public void LoadData()\n {\n SomeProperty = this._helper.GetSomeData();\n }\n public object SomeProperty {get;set;}\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11388/" ]
90,662
<p>I'm a CompSci student, and fairly new at C#, and I was doing a "Josephus Problem" program for a class, and I created an Exit button that calls Application.Exit() to exit at anytime, but if C# is still working on painting and the button is pressed it throws an ObjectDisposedExeception for the Graphics object. Is there any way to prevent this?. I was thinking of try{}catch or change a boolean to tell the painting process to stop before exiting, but I want to know if there's another solution.</p>
[ { "answer_id": 93204, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": true, "text": "WM_PAINT" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90662", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4182/" ]
90,674
<p>I am developing an application using vb.net. For performing some tasks the application needs administrator privileges in the machine. How to ask for the privileges during the execution of the program?</p> <p>What is the general method of switching user accounts for executing an application? In other words, is there some way for an application to run under an arbitrary user account?</p>
[ { "answer_id": 860277, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\" />" }, { "answer_id": 71724940, "author": "PsychoDev", "author_id": 18601544, "author_profile": "https://Stackoverflow.com/users/18601544", "pm_score": 1, "selected": false, "text": "<requestedExecutionLevel level=\"asInvoker\" uiAccess=\"false\" />" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
90,682
<p>Is it possible to get a thread dump of a Java Web Start application? And if so, how?</p> <p>It would be nice if there were a simple solution, which would enable a non-developer (customer) to create a thread dump. Alternatively, is it possible to create a thread dump programmatically?</p> <p>In the Java Web Start Console I can get a list of threads by pressing 't' but stacktraces are not included.</p> <p>If answers require certain java versions, please say so.</p>
[ { "answer_id": 90711, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 2, "selected": false, "text": "StackTraceElement[] stack = Thread.currentThread().getStackTrace();\n" }, { "answer_id": 90794, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 0, "selected": false, "text": "Thread.currentThread().dumpStack();\n" }, { "answer_id": 90796, "author": "ashirley", "author_id": 6950, "author_profile": "https://Stackoverflow.com/users/6950", "pm_score": 2, "selected": false, "text": "Thread.getAllStackTraces()" }, { "answer_id": 91097, "author": "scotty", "author_id": 15925, "author_profile": "https://Stackoverflow.com/users/15925", "pm_score": 4, "selected": true, "text": "t: dump thread list\nv: dump thread stack\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15646/" ]
90,693
<p>I have tree control object created using CTreeCtrl MFC class. The tree control needs to support rename. When I left click on any of item in Tree the TVN_SELCHANGED event is called from which I can get the selected item of the tree as below : HTREEITEM h = m_moveListTree.GetSelectedItem(); CString s = m_moveListTree.GetItemText(h);</p> <p>However when I rightclick on any item in tree I do not get any TVN_SELCHANGED event and hence my selected item still remains the same from left click event. This is causing following problem : 1)User leftclicks on item A 2)user right clicks on item B and says rename 3)Since the selected item is still A the rename is applying for item A.</p> <p>Please help in solving problem.</p> <p>-Praveen</p>
[ { "answer_id": 90773, "author": "jussij", "author_id": 14738, "author_profile": "https://Stackoverflow.com/users/14738", "pm_score": 1, "selected": true, "text": "LRESULT xTreeCtrl::onRightClick(NMHDR *)\n{\n xPoint pt;\n\n //-- get the cursor at the time the mesage was posted\n DWORD dwPos = ::GetMessagePos();\n\n pt.x = GET_X_LPARAM(dwPos);\n pt.y = GET_Y_LPARAM (dwPos);\n\n //-- now convert to window co-ordinates\n pt.toWindow(this);\n\n //-- check for a hit\n HTREEITEM hItem = this->hitTest(pt);\n\n //-- select any item that was hit\n if ((int)hItem != -1) this->select(hItem);\n\n //-- leave the rest to default processing\n return 0;\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90693", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,697
<p>How do I create a resource that I can reference and use in various parts of my program easily?</p> <p>My specific problem is that I have a NotifyIcon that I want to change the icon of depending on the state of the program. A common problem, but one I've been struggling with for a long time. </p>
[ { "answer_id": 90699, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 9, "selected": true, "text": "Properties.Resources" }, { "answer_id": 90735, "author": "Chuck Conway", "author_id": 17360, "author_profile": "https://Stackoverflow.com/users/17360", "pm_score": 3, "selected": false, "text": "GetLocalResourceObject([resource entry key/name])" }, { "answer_id": 67958544, "author": "Wojciech", "author_id": 4348120, "author_profile": "https://Stackoverflow.com/users/4348120", "pm_score": 2, "selected": false, "text": "paused = !paused;\nif (paused)\n notifyIcon.Icon = Properties.Resources.RedIcon;\nelse\n notifyIcon.Icon = Properties.Resources.GreenIcon;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90697", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15537/" ]
90,702
<p>I am working on a small application in VB.NET. The program needs administrator privilege for doing some tasks. Is there a way to ask for administrator privileges during the execution if the program?</p> <p>What is the general way of changing the user account under which the application is running?</p>
[ { "answer_id": 90718, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 3, "selected": true, "text": "CoCreateInstanceAsAdmin" }, { "answer_id": 3334114, "author": "AnOnYmOuS", "author_id": 402172, "author_profile": "https://Stackoverflow.com/users/402172", "pm_score": 1, "selected": false, "text": " Try\n Dim procInfo As New ProcessStartInfo()\n procInfo.UseShellExecute = True\n procInfo.FileName = 'Filename here\n procInfo.WorkingDirectory = \"\"\n procInfo.Verb = \"runas\"\n Process.Start(procInfo)\n Catch ex As Exception\n MsgBox(ex.Message.ToString(), vbCritical)\n End Try\n End If\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
90,704
<p>GNU/Linux text console, X11 not involved, indeed not even installed. Keyboard is US layout, keymap US default. Kernel version 2.20.x or later.</p> <p>An application written in C is getting keyboard input in translation mode, i.e. <code>XLATE</code> or <code>UNICODE</code>. When a key is pressed, the application receives the corresponding keystring. As an example, you press F1, the application reads <code>"\033[[A"</code>.</p> <p>Before the kernel sends the keystring to the application, it must know which key is pressed, i.e. it must know its scancode. In the F1 example above, the scancode for the key pressed is 59 or 0x3b.</p> <p>That's to say even when the keyboard is in translation mode, the scancodes are held somewhere in memory. How can the application access them without switching the keyboard to <code>RAW</code> or <code>MEDIUMRAW</code> mode? A code snippet would help.</p>
[ { "answer_id": 90837, "author": "Sqeaky", "author_id": 17315, "author_profile": "https://Stackoverflow.com/users/17315", "pm_score": 0, "selected": false, "text": "dumpkeys -f > test.txt\n" }, { "answer_id": 92228, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 0, "selected": false, "text": "kbdev" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90704", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,713
<p>i've created a Form Panel, and i'm rendering couple of Combo Boxes in the panel with a store which is populated via an response handler. the problem if i want to render the panel again it renders the combo boxes without the store, though i'm re-constructing the panel. i tried to debug to figure out the cause and surprisingly though for combo box the Store is null on calling - comboBox.setStore(store) it checks for the property (isRendered) and finds it to be true and hence doesn't add the store but just keep the existing store which is still null.</p> <p>i've seen this problem in another scenaio where i had created a collapsible field set containing the Combobox, On minimize and maximize of the fieldset the store vanishes for the same reasons.</p> <p>can someone please help me here, i'm completely struck here i tried various option but nothing works.</p>
[ { "answer_id": 91347, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "doLayout()" }, { "answer_id": 91589, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "view_plugin = {\n\n init: function(o) {\n\n o.setNewStore = function(newStore) {\n this.view.setStore(newStore);\n };\n }\n};\n" }, { "answer_id": 94093, "author": "Thevs", "author_id": 8559, "author_profile": "https://Stackoverflow.com/users/8559", "pm_score": 0, "selected": false, "text": "field = new ComboBox({plugins: view_plugin});" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90713", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,751
<p>Do C#/.NET floating point operations differ in precision between debug mode and release mode?</p>
[ { "answer_id": 90815, "author": "Dark Shikari", "author_id": 11206, "author_profile": "https://Stackoverflow.com/users/11206", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n float e = 0.000000001;\n float f[3] = {33810340466158.90625,276553805316035.1875,10413022032824338432.0};\n f[0] = pow(f[0],2-e); f[1] = pow(f[1],2+e); f[2] = pow(f[2],-2-e);\n printf(\"%s\\n\",f);\n return 0;\n}\n" }, { "answer_id": 90835, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 6, "selected": true, "text": "class Foo\n{\n double _v = ...;\n\n void Bar()\n {\n double v = _v;\n\n if( v == _v )\n {\n // Code may or may not execute here.\n // _v is 64-bit.\n // v could be either 64-bit (debug) or 80-bit (release) or something else (future?).\n }\n }\n}\n" }, { "answer_id": 91027, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 4, "selected": false, "text": "static void Main (string [] args)\n{\n float\n a = float.MaxValue / 3.0f,\n b = a * a;\n\n if (a * a < b)\n {\n Console.WriteLine (\"Less\");\n }\n else\n {\n Console.WriteLine (\"GreaterEqual\");\n }\n}\n" }, { "answer_id": 55383018, "author": "fuglede", "author_id": 5085211, "author_profile": "https://Stackoverflow.com/users/5085211", "pm_score": 2, "selected": false, "text": "Single f1 = 0.00000000002f;\nSingle f2 = 1 / f1;\nDouble d = f2;\nConsole.WriteLine(d);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ]
90,755
<p>How do I get a list of the active IP-addresses, MAC-addresses and <a href="http://en.wikipedia.org/wiki/NetBIOS" rel="nofollow noreferrer">NetBIOS</a> names on the LAN?</p> <p>I'd like to get NetBIOS name, IP and <a href="http://en.wikipedia.org/wiki/MAC_address" rel="nofollow noreferrer">MAC addresses</a> for every host on the LAN, preferably not having to walk to every single PC and take note of the stuff myself.</p> <p>How to do that with <a href="http://en.wikipedia.org/wiki/Windows_Script_Host" rel="nofollow noreferrer">Windows Script Host</a>/PowerShell/whatever?</p>
[ { "answer_id": 90854, "author": "mana", "author_id": 12016, "author_profile": "https://Stackoverflow.com/users/12016", "pm_score": 4, "selected": true, "text": " nmap -sP 192.168.1.1/24\n" }, { "answer_id": 90875, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 3, "selected": false, "text": "arp -a\n" }, { "answer_id": 5135520, "author": "mjsr", "author_id": 1169720, "author_profile": "https://Stackoverflow.com/users/1169720", "pm_score": 1, "selected": false, "text": "function Explore-Net($subnet, [int[]]$range){\n $range | % { test-connection \"$subnet.$_\" -count 1 -erroraction silentlycontinue} | select -Property address | % {[net.dns]::gethostbyaddress($_.address)}\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6069/" ]
90,758
<p>I'm currently using ImageMagick to determine the size of images uploaded to the website. By calling ImageMagick's "identify" on the command line it takes about 0.42 seconds to determine a 1MB JPEG's dimensions along with the fact that it's a JPEG. I find that a bit slow.</p> <p>Using the Imagick PHP library is even slower as it attemps to load the whole 1MB in memory before doing any treatment to the image (in this case, simply determining its size and type).</p> <p>Are there any solutions to speed up this process of determining which file type and which dimensions an arbitrary image file has? I can live with it only supporting JPEG and PNG. It's important to me that the file type is determined by looking at the file's headers and not simply the extension.</p> <p><strong>Edit: The solution can be a command-line tool UNIX called by PHP, much like the way I'm using ImageMagick at the moment</strong></p>
[ { "answer_id": 90784, "author": "Kasprzol", "author_id": 5957, "author_profile": "https://Stackoverflow.com/users/5957", "pm_score": 2, "selected": false, "text": "/tmp$ file stackoverflow-logo-250.png" }, { "answer_id": 90824, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "identify -ping filename.png\n" }, { "answer_id": 91034, "author": "Steven Noble", "author_id": 10393, "author_profile": "https://Stackoverflow.com/users/10393", "pm_score": 3, "selected": true, "text": "$files = array('2819547919_db7466149b_o_d.jpg', 'GP1-green2.jpg', 'aegeri-lake-switzerland.JPG');\nforeach($files as $file){\n $size2 = array();\n $size3 = array();\n $time1 = microtime();\n $size = getimagesize($file);\n $time1 = microtime() - $time1;\n print \"$time1 \\n\";\n $time2 = microtime();\n exec(\"identify -ping $file\", $size2);\n $time2 = microtime() - $time2;\n print $time2/$time1 . \"\\n\";\n $time2 = microtime();\n exec(\"identify $file\", $size3);\n $time2 = microtime() - $time2;\n print $time2/$time1 . \"\\n\";\n print_r($size);\n print_r($size2);\n print_r($size3);\n}\n" }, { "answer_id": 15657701, "author": "kralyk", "author_id": 786102, "author_profile": "https://Stackoverflow.com/users/786102", "pm_score": 0, "selected": false, "text": "exec()" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90758", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10024/" ]
90,775
<p>I have an exe file generated with py2exe. In the setup.py I specify an icon to be embedded in the exe:</p> <pre><code>windows=[{'script': 'my_script.py','icon_resources': [(0, 'my_icon.ico')], ... </code></pre> <p>I tried loading the icon using:</p> <pre><code>hinst = win32api.GetModuleHandle(None) hicon = win32gui.LoadImage(hinst, 0, win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>But this produces an (very unspecific) error:<br> <strong>pywintypes.error: (0, 'LoadImage', 'No error message is available')</strong><br> <br> If I try specifying 0 as a string</p> <pre><code>hicon = win32gui.LoadImage(hinst, '0', win32con.IMAGE_ICON, 0, 0, win32con.LR_DEFAULTSIZE) </code></pre> <p>then I get the error:<br> <strong>pywintypes.error: (1813, 'LoadImage', 'The specified resource type cannot be found in the image file.')</strong><br> <br>So, what's the correct method/syntax to load the icon?<br> <em>Also please notice that I don't use any GUI toolkit - just the Windows API via PyWin32.</em></p>
[ { "answer_id": 91245, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 0, "selected": false, "text": "'icon_resources': [(42, 'my_icon.ico')]\n" }, { "answer_id": 91670, "author": "elifiner", "author_id": 15109, "author_profile": "https://Stackoverflow.com/users/15109", "pm_score": 1, "selected": false, "text": "wx.Icon(sys.argv[0], wx.BITMAP_TYPE_ICO)\n" }, { "answer_id": 92710, "author": "efotinis", "author_id": 12320, "author_profile": "https://Stackoverflow.com/users/12320", "pm_score": 1, "selected": false, "text": "rt_icon_id" }, { "answer_id": 110777, "author": "Andreas Thomas", "author_id": 1531, "author_profile": "https://Stackoverflow.com/users/1531", "pm_score": 4, "selected": true, "text": "hicon = win32gui.CreateIconFromResource(win32api.LoadResource(None, win32con.RT_ICON, 1), True)\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90775", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1531/" ]
90,838
<p>In our application, we receive text files (<code>.txt</code>, <code>.csv</code>, etc.) from diverse sources. When reading, these files sometimes contain garbage, because the files where created in a different/unknown codepage.</p> <p>Is there a way to (automatically) detect the codepage of a text file? </p> <p>The <code>detectEncodingFromByteOrderMarks</code>, on the <code>StreamReader</code> constructor, works for <code>UTF8</code> and other unicode marked files, but I'm looking for a way to detect code pages, like <code>ibm850</code>, <code>windows1252</code>. </p> <hr> <p>Thanks for your answers, this is what I've done.</p> <p>The files we receive are from end-users, they do not have a clue about codepages. The receivers are also end-users, by now this is what they know about codepages: Codepages exist, and are annoying.</p> <p><strong>Solution:</strong> </p> <ul> <li>Open the received file in Notepad, look at a garbled piece of text. If somebody is called François or something, with your human intelligence you can guess this.</li> <li>I've created a small app that the user can use to open the file with, and enter a text that user knows it will appear in the file, when the correct codepage is used. </li> <li>Loop through all codepages, and display the ones that give a solution with the user provided text. </li> <li>If more as one codepage pops up, ask the user to specify more text.</li> </ul>
[ { "answer_id": 10861648, "author": "Thommy Johansson", "author_id": 1432278, "author_profile": "https://Stackoverflow.com/users/1432278", "pm_score": -1, "selected": false, "text": "'Works for Default and unicode (auto detect)\nDim mystreamreader As New StreamReader(LocalFileName, Encoding.Default) \nMyEditTextBox.Text = mystreamreader.ReadToEnd()\nDebug.Print(mystreamreader.CurrentEncoding.CodePage) 'Autodetected encoding\nmystreamreader.Close()\n" }, { "answer_id": 11611025, "author": "ITmeze", "author_id": 57728, "author_profile": "https://Stackoverflow.com/users/57728", "pm_score": 5, "selected": false, "text": "public static void Main(String[] args)\n{\n string filename = args[0];\n using (FileStream fs = File.OpenRead(filename)) {\n Ude.CharsetDetector cdet = new Ude.CharsetDetector();\n cdet.Feed(fs);\n cdet.DataEnd();\n if (cdet.Charset != null) {\n Console.WriteLine(\"Charset: {0}, confidence: {1}\", \n cdet.Charset, cdet.Confidence);\n } else {\n Console.WriteLine(\"Detection failed.\");\n }\n }\n} \n" }, { "answer_id": 15651402, "author": "Nick Matteo", "author_id": 2132213, "author_profile": "https://Stackoverflow.com/users/2132213", "pm_score": 1, "selected": false, "text": "libenca" }, { "answer_id": 19464728, "author": "TarmoPikaro", "author_id": 2338477, "author_profile": "https://Stackoverflow.com/users/2338477", "pm_score": 3, "selected": false, "text": " public static Encoding DetectEncoding(byte[] fileContent)\n {\n if (fileContent == null)\n throw new ArgumentNullException();\n\n if (fileContent.Length < 2)\n return Encoding.ASCII; // Default fallback\n\n if (fileContent[0] == 0xff\n && fileContent[1] == 0xfe\n && (fileContent.Length < 4\n || fileContent[2] != 0\n || fileContent[3] != 0\n )\n )\n return Encoding.Unicode;\n\n if (fileContent[0] == 0xfe\n && fileContent[1] == 0xff\n )\n return Encoding.BigEndianUnicode;\n\n if (fileContent.Length < 3)\n return null;\n\n if (fileContent[0] == 0xef && fileContent[1] == 0xbb && fileContent[2] == 0xbf)\n return Encoding.UTF8;\n\n if (fileContent[0] == 0x2b && fileContent[1] == 0x2f && fileContent[2] == 0x76)\n return Encoding.UTF7;\n\n if (fileContent.Length < 4)\n return null;\n\n if (fileContent[0] == 0xff && fileContent[1] == 0xfe && fileContent[2] == 0 && fileContent[3] == 0)\n return Encoding.UTF32;\n\n if (fileContent[0] == 0 && fileContent[1] == 0 && fileContent[2] == 0xfe && fileContent[3] == 0xff)\n return Encoding.GetEncoding(12001);\n\n String probe;\n int len = fileContent.Length;\n\n if( fileContent.Length >= 128 ) len = 128;\n probe = Encoding.ASCII.GetString(fileContent, 0, len);\n\n MatchCollection mc = Regex.Matches(probe, \"^<\\\\?xml[^<>]*encoding[ \\\\t\\\\n\\\\r]?=[\\\\t\\\\n\\\\r]?['\\\"]([A-Za-z]([A-Za-z0-9._]|-)*)\", RegexOptions.Singleline);\n // Add '[0].Groups[1].Value' to the end to test regex\n\n if( mc.Count == 1 && mc[0].Groups.Count >= 2 )\n {\n // Typically picks up 'UTF-8' string\n Encoding enc = null;\n\n try {\n enc = Encoding.GetEncoding( mc[0].Groups[1].Value );\n }catch (Exception ) { }\n\n if( enc != null )\n return enc;\n }\n\n return Encoding.ASCII; // Default fallback\n }\n" }, { "answer_id": 20353639, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 2, "selected": false, "text": "apt-get install uchardet" }, { "answer_id": 32372048, "author": "PrivatePyle", "author_id": 4199351, "author_profile": "https://Stackoverflow.com/users/4199351", "pm_score": 0, "selected": false, "text": " private Encoding GetEncodingFromString(string codePageName)\n {\n try\n {\n return Encoding.GetEncoding(codePageName);\n }\n catch\n {\n return Encoding.ASCII;\n }\n }\n" }, { "answer_id": 35294619, "author": "Markus", "author_id": 4516689, "author_profile": "https://Stackoverflow.com/users/4516689", "pm_score": 3, "selected": false, "text": "public static class StreamExtension\n{\n /// <summary>\n /// Convert the content to a string.\n /// </summary>\n /// <param name=\"stream\">The stream.</param>\n /// <returns></returns>\n public static string ReadAsString(this Stream stream)\n {\n var startPosition = stream.Position;\n try\n {\n // 1. Check for a BOM\n // 2. or try with UTF-8. The most (86.3%) used encoding. Visit: http://w3techs.com/technologies/overview/character_encoding/all/\n var streamReader = new StreamReader(stream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: true);\n return streamReader.ReadToEnd();\n }\n catch (DecoderFallbackException ex)\n {\n stream.Position = startPosition;\n\n // 3. The second most (6.7%) used encoding is ISO-8859-1. So use Windows-1252 (0.9%, also know as ANSI), which is a superset of ISO-8859-1.\n var streamReader = new StreamReader(stream, Encoding.GetEncoding(1252));\n return streamReader.ReadToEnd();\n }\n }\n}\n" }, { "answer_id": 50214214, "author": "Schlacki", "author_id": 4448353, "author_profile": "https://Stackoverflow.com/users/4448353", "pm_score": 0, "selected": false, "text": "uchardet" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90838", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11492/" ]
90,855
<p>I'd like to offer my users correct links to an upgraded version of my program based on what platform they're running on, so I need to know whether I'm currently running on an x86 OS or an x64 OS.</p> <p>The best I've found is using <code>Environment.GetEnvironmentVariable("PROCESSOR_ARCHITECTURE")</code>, but I would think there would be some built-in facility for this?</p>
[ { "answer_id": 90945, "author": "Jakub Kotrla", "author_id": 16943, "author_profile": "https://Stackoverflow.com/users/16943", "pm_score": -1, "selected": false, "text": "IntPtr.Size" }, { "answer_id": 93074, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "IsWow64Process" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3191/" ]
90,871
<p>Continuing from my <a href="https://stackoverflow.com/questions/90751/double-and-floats-in-c">previous question</a>, is there a comprehensive document that lists all available differences between debug and release modes in a C# application, and particularly in a web application?</p> <p>What differences are there?</p>
[ { "answer_id": 579456, "author": "andleer", "author_id": 64262, "author_profile": "https://Stackoverflow.com/users/64262", "pm_score": 3, "selected": false, "text": "web.config" }, { "answer_id": 17891796, "author": "Samuel Poirier", "author_id": 1310590, "author_profile": "https://Stackoverflow.com/users/1310590", "pm_score": 3, "selected": false, "text": " #if DEBUG\n // Some code running only in debug\n #endif\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/288629/" ]
90,885
<p>I want to make an entity that has an autogenerated primary key, but also a unique compound key made up of two other fields. How do I do this in JPA?<br> I want to do this because the primary key should be used as foreign key in another table and making it compound would not be good.</p> <p>In the following snippet, I need the command and model to be unique. pk is of course the primary key.</p> <pre><code>@Entity @Table(name = "dm_action_plan") public class ActionPlan { @Id private int pk; @Column(name = "command", nullable = false) private String command; @Column(name = "model", nullable = false) String model; } </code></pre>
[ { "answer_id": 90960, "author": "Michel", "author_id": 7198, "author_profile": "https://Stackoverflow.com/users/7198", "pm_score": 5, "selected": true, "text": "@UniqueConstraint" }, { "answer_id": 90968, "author": "Nicolas", "author_id": 1730, "author_profile": "https://Stackoverflow.com/users/1730", "pm_score": 0, "selected": false, "text": "@Entity\n@Table(name = \"dm_action_plan\"\n uniqueConstraint = @UniqueConstraint({\"command\", \"model\"})\n)\npublic class ActionPlan {\n @Id\n @GeneratedValue\n private int pk;\n @Column(name = \"command\", nullable = false)\n private String command;\n @Column(name = \"model\", nullable = false)\n String model;\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
90,891
<p>Is there a way to control the Fujitsu Softune debugger with an other application(e.g. Eclipse)? I think about sending the command mentioned in the documentation of Softune and parse the output, but also other approaches are welcome.</p>
[ { "answer_id": 998989, "author": "guzelo", "author_id": 118732, "author_profile": "https://Stackoverflow.com/users/118732", "pm_score": 1, "selected": false, "text": "debug:" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,899
<p>How can I get all items from a specific calendar (for a specific date). Lets say for instance that I have a calendar with a recurring item every Monday evening. When I request all items like this:</p> <pre><code>CalendarItems = CalendarFolder.Items; CalendarItems.IncludeRecurrences = true; </code></pre> <p>I only get 1 item...</p> <p>Is there an easy way to get <strong>all</strong> items (main item + derived items) from a calendar? In my specific situation it can be possible to set a date limit but it would be cool just to get all items (my recurring items are time limited themselves).</p> <p><strong>I'm using the Microsoft Outlook 12 Object library (Microsoft.Office.Interop.Outlook)</strong>.</p>
[ { "answer_id": 92184, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "public void GetAllCalendarItems()\n{\n Microsoft.Office.Interop.Outlook.Application oApp = null;\n Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\n Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\n Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\n oApp = new Microsoft.Office.Interop.Outlook.Application();\n mapiNamespace = oApp.GetNamespace(\"MAPI\"); ;\n CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = CalendarFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n if (item.IsRecurring)\n {\n Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();\n DateTime first = new DateTime(2008, 8, 31, item.Start.Hour, item.Start.Minute, 0);\n DateTime last = new DateTime(2008, 10, 1);\n Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;\n\n\n\n for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))\n {\n try\n {\n recur = rp.GetOccurrence(cur);\n MessageBox.Show(recur.Subject + \" -> \" + cur.ToLongDateString());\n }\n catch\n { }\n }\n }\n else\n {\n MessageBox.Show(item.Subject + \" -> \" + item.Start.ToLongDateString());\n }\n }\n\n}\n" }, { "answer_id": 2869463, "author": "uygar", "author_id": 345515, "author_profile": "https://Stackoverflow.com/users/345515", "pm_score": -1, "selected": false, "text": "calendarFolder = \n mapiNamespace.GetDefaultFolder(\n Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n" }, { "answer_id": 7106351, "author": "sdyutjan", "author_id": 900453, "author_profile": "https://Stackoverflow.com/users/900453", "pm_score": 2, "selected": false, "text": "// Set recepient\nOutlook.Recipient oRecip = (Outlook.Recipient)oNS.CreateRecipient(\"abc@yourmail.com\");\n\n// Get calendar folder \nOutlook.MAPIFolder oCalendar = oNS.GetSharedDefaultFolder(oRecip, Outlook.OlDefaultFolders.olFolderCalendar);\n" }, { "answer_id": 8366973, "author": "Eliot", "author_id": 1078856, "author_profile": "https://Stackoverflow.com/users/1078856", "pm_score": 3, "selected": false, "text": "Application outlook;\nNameSpace OutlookNS;\n\noutlook = new ApplicationClass();\nOutlookNS = outlook.GetNamespace(\"MAPI\");\n\nMAPIFolder f = OutlookNS.GetDefaultFolder(OlDefaultFolders.olFolderCalendar);\n\nCalendarSharing cs = f.GetCalendarExporter();\ncs.CalendarDetail = OlCalendarDetail.olFullDetails;\ncs.StartDate = new DateTime(2011, 11, 1);\ncs.EndDate = new DateTime(2011, 12, 31);\ncs.SaveAsICal(\"c:\\\\temp\\\\cal.ics\");\n" }, { "answer_id": 15669633, "author": "Vladimir Sitnikov", "author_id": 1261287, "author_profile": "https://Stackoverflow.com/users/1261287", "pm_score": 2, "selected": false, "text": "tdystart = VBA.Format(#8/1/2012#, \"Short Date\")\ntdyend = VBA.Format(#8/31/2012#, \"Short Date\")\n\nDim folder As MAPIFolder\nSet appointments = folder.Items\n\nappointments.Sort \"[Start]\" ' <-- !!! Sort is a MUST\nappointments.IncludeRecurrences = True ' <-- This will expand reccurent items\n\nSet app = appointments.Find(\"[Start] >= \"\"\" & tdystart & \"\"\" and [Start] <= \"\"\" & tdyend & \"\"\"\")\n\nWhile TypeName(app) <> \"Nothing\"\n MsgBox app.Start & \" \" & app.Subject\n Set app = appointments.FindNext\nWend\n" }, { "answer_id": 19149688, "author": "Roy Ashbrook", "author_id": 2074040, "author_profile": "https://Stackoverflow.com/users/2074040", "pm_score": 3, "selected": false, "text": "//using Microsoft.Office.Interop.Outlook\nApplication a = new Application();\nItems i = a.Session.GetDefaultFolder(OlDefaultFolders.olFolderCalendar).Items;\ni.IncludeRecurrences = true;\ni.Sort(\"[Start]\");\ni = i.Restrict(\n \"[Start] >= '10/1/2013 12:00 AM' AND [End] < '10/3/2013 12:00 AM'\");\n\n\nvar r =\n from ai in i.Cast<AppointmentItem>()\n select new {\n ai.Categories,\n ai.Start,\n ai.Duration\n };\nr.Dump();\n" }, { "answer_id": 21669956, "author": "RameezAli", "author_id": 3098077, "author_profile": "https://Stackoverflow.com/users/3098077", "pm_score": 2, "selected": false, "text": "public void GetAllCalendarItems()\n {\n DataTable sample = new DataTable(); //Sample Data\n sample.Columns.Add(\"Subject\", typeof(string));\n sample.Columns.Add(\"Location\", typeof(string));\n sample.Columns.Add(\"StartTime\", typeof(DateTime));\n sample.Columns.Add(\"EndTime\", typeof(DateTime));\n sample.Columns.Add(\"StartDate\", typeof(DateTime));\n sample.Columns.Add(\"EndDate\", typeof(DateTime));\n sample.Columns.Add(\"AllDayEvent\", typeof(bool));\n sample.Columns.Add(\"Body\", typeof(string));\n\n\n listViewContacts.Items.Clear();\n oApp = new Outlook.Application();\n oNS = oApp.GetNamespace(\"MAPI\");\n oCalenderFolder = oNS.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = oCalenderFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n // DataTable sample = new DataTable();\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n DataRow row = sample.NewRow();\n row[\"Subject\"] = item.Subject;\n row[\"Location\"] = item.Location;\n row[\"StartTime\"] = item.Start.TimeOfDay.ToString();\n row[\"EndTime\"] = item.End.TimeOfDay.ToString();\n row[\"StartDate\"] = item.Start.Date;\n row[\"EndDate\"] = item.End.Date;\n row[\"AllDayEvent\"] = item.AllDayEvent;\n row[\"Body\"] = item.Body;\n sample.Rows.Add(row);\n }\n sample.AcceptChanges();\n foreach (DataRow dr in sample.Rows)\n {\n ListViewItem lvi = new ListViewItem(dr[\"Subject\"].ToString());\n\n lvi.SubItems.Add(dr[\"Location\"].ToString());\n lvi.SubItems.Add(dr[\"StartTime\"].ToString());\n lvi.SubItems.Add(dr[\"EndTime\"].ToString());\n lvi.SubItems.Add(dr[\"StartDate\"].ToString());\n lvi.SubItems.Add(dr[\"EndDate\"].ToString());\n lvi.SubItems.Add(dr[\"AllDayEvent\"].ToString());\n lvi.SubItems.Add(dr[\"Body\"].ToString());\n\n\n\n this.listViewContacts.Items.Add(lvi);\n }\n oApp = null;\n oNS = null;\n\n }\n" }, { "answer_id": 28295179, "author": "Dobry", "author_id": 1045115, "author_profile": "https://Stackoverflow.com/users/1045115", "pm_score": 0, "selected": false, "text": " public List<AdxCalendarItem> GetAllCalendarItems()\n {\n Outlook.Application OutlookApp = new Outlook.Application();\n List<AdxCalendarItem> result = new List<AdxCalendarItem>();\n Outlook._NameSpace session = OutlookApp.Session;\n if (session != null)\n try\n {\n object stores = session.GetType().InvokeMember(\"Stores\", BindingFlags.GetProperty, null, session, null);\n if (stores != null)\n try\n {\n int count = (int)stores.GetType().InvokeMember(\"Count\", BindingFlags.GetProperty, null, stores, null);\n for (int i = 1; i <= count; i++)\n {\n object store = stores.GetType().InvokeMember(\"Item\", BindingFlags.GetProperty, null, stores, new object[] { i });\n if (store != null)\n try\n {\n Outlook.MAPIFolder calendar = null;\n try\n {\n calendar = (Outlook.MAPIFolder)store.GetType().InvokeMember(\"GetDefaultFolder\", BindingFlags.GetProperty, null, store, new object[] { Outlook.OlDefaultFolders.olFolderCalendar });\n }\n catch\n {\n continue;\n }\n if (calendar != null)\n try\n {\n Outlook.Folders folders = calendar.Folders;\n try\n {\n Outlook.MAPIFolder subfolder = null;\n for (int j = 1; j < folders.Count + 1; j++)\n {\n subfolder = folders[j];\n try\n {\n // add subfolder items\n result.AddRange(GetAppointmentItems(subfolder));\n }\n finally\n { if (subfolder != null) Marshal.ReleaseComObject(subfolder); }\n }\n }\n finally\n { if (folders != null) Marshal.ReleaseComObject(folders); }\n // add root items\n result.AddRange(GetAppointmentItems(calendar));\n }\n finally { Marshal.ReleaseComObject(calendar); }\n }\n finally { Marshal.ReleaseComObject(store); }\n }\n }\n finally { Marshal.ReleaseComObject(stores); }\n }\n finally { Marshal.ReleaseComObject(session); }\n return result;\n }\n\n List<AdxCalendarItem> GetAppointmentItems(Outlook.MAPIFolder calendarFolder)\n {\n List<AdxCalendarItem> result = new List<AdxCalendarItem>();\n Outlook.Items calendarItems = calendarFolder.Items;\n try\n {\n calendarItems.IncludeRecurrences = true;\n Outlook.AppointmentItem appointment = null;\n for (int j = 1; j < calendarItems.Count + 1; j++)\n {\n appointment = calendarItems[j] as Outlook.AppointmentItem;\n try\n {\n AdxCalendarItem item = new AdxCalendarItem(\n calendarFolder.Name,\n appointment.Subject,\n appointment.Location,\n appointment.Start,\n appointment.End,\n appointment.Start.Date,\n appointment.End.Date,\n appointment.AllDayEvent,\n appointment.Body);\n result.Add(item);\n }\n finally\n {\n { Marshal.ReleaseComObject(appointment); }\n }\n }\n }\n finally { Marshal.ReleaseComObject(calendarItems); }\n return result;\n }\n}\n\npublic class AdxCalendarItem\n{\n public string CalendarName;\n public string Subject;\n public string Location;\n public DateTime StartTime;\n public DateTime EndTime;\n public DateTime StartDate;\n public DateTime EndDate;\n public bool AllDayEvent;\n public string Body;\n\n public AdxCalendarItem(string CalendarName, string Subject, string Location, DateTime StartTime, DateTime EndTime,\n DateTime StartDate, DateTime EndDate, bool AllDayEvent, string Body)\n {\n this.CalendarName = CalendarName;\n this.Subject = Subject;\n this.Location = Location;\n this.StartTime = StartTime;\n this.EndTime = EndTime;\n this.StartDate = StartDate;\n this.EndDate = EndDate;\n this.AllDayEvent = AllDayEvent;\n this.Body = Body;\n\n }\n\n}\n" }, { "answer_id": 53943350, "author": "TC Anıl Aydınalp", "author_id": 9359745, "author_profile": "https://Stackoverflow.com/users/9359745", "pm_score": 0, "selected": false, "text": " Microsoft.Office.Interop.Outlook.Application oApp = null;\n Microsoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\n Microsoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\n Microsoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\n oApp = new Microsoft.Office.Interop.Outlook.Application();\n mapiNamespace = oApp.GetNamespace(\"MAPI\"); ;\n CalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\n outlookCalendarItems = CalendarFolder.Items;\n outlookCalendarItems.IncludeRecurrences = true;\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems)\n {\n if (item.IsRecurring)\n {\n Microsoft.Office.Interop.Outlook.RecurrencePattern rp = item.GetRecurrencePattern();\n\n // get all date \n DateTime first = new DateTime( item.Start.Hour, item.Start.Minute, 0);\n DateTime last = new DateTime();\n Microsoft.Office.Interop.Outlook.AppointmentItem recur = null;\n\n\n\n for (DateTime cur = first; cur <= last; cur = cur.AddDays(1))\n {\n try\n {\n recur = rp.GetOccurrence(cur);\n MessageBox.Show(recur.Subject + \" -> \" + cur.ToLongDateString());\n }\n catch\n { }\n }\n }\n else\n {\n MessageBox.Show(item.Subject + \" -> \" + item.Start.ToLongDateString());\n }\n }\n\n}\n" }, { "answer_id": 57530946, "author": "anhoppe", "author_id": 1178267, "author_profile": "https://Stackoverflow.com/users/1178267", "pm_score": 1, "selected": false, "text": "using Outlook = Microsoft.Office.Interop.Outlook;\n\nprivate void DemoAppointmentsInRange()\n{\n Outlook.Folder calFolder = Application.Session.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar)\n as Outlook.Folder;\n DateTime start = DateTime.Now;\n DateTime end = start.AddDays(5);\n Outlook.Items rangeAppts = GetAppointmentsInRange(calFolder, start, end);\n if (rangeAppts != null)\n {\n foreach (Outlook.AppointmentItem appt in rangeAppts)\n {\n Debug.WriteLine(\"Subject: \" + appt.Subject \n + \" Start: \" + appt.Start.ToString(\"g\"));\n }\n }\n}\n\n/// <summary>\n/// Get recurring appointments in date range.\n/// </summary>\n/// <param name=\"folder\"></param>\n/// <param name=\"startTime\"></param>\n/// <param name=\"endTime\"></param>\n/// <returns>Outlook.Items</returns>\nprivate Outlook.Items GetAppointmentsInRange(\n Outlook.Folder folder, DateTime startTime, DateTime endTime)\n{\n string filter = \"[Start] >= '\"\n + startTime.ToString(\"g\")\n + \"' AND [End] <= '\"\n + endTime.ToString(\"g\") + \"'\";\n Debug.WriteLine(filter);\n try\n {\n Outlook.Items calItems = folder.Items;\n calItems.IncludeRecurrences = true;\n calItems.Sort(\"[Start]\", Type.Missing);\n Outlook.Items restrictItems = calItems.Restrict(filter);\n if (restrictItems.Count > 0)\n {\n return restrictItems;\n }\n else\n {\n return null;\n }\n }\n catch { return null; }\n }\n" }, { "answer_id": 73280470, "author": "Binxalot", "author_id": 1086549, "author_profile": "https://Stackoverflow.com/users/1086549", "pm_score": 0, "selected": false, "text": "using Microsoft.Office.Interop.Outlook;\n\nvoid GetAllCalendarItems()\n{\n\nMicrosoft.Office.Interop.Outlook.Application oApp = null;\nMicrosoft.Office.Interop.Outlook.NameSpace mapiNamespace = null;\nMicrosoft.Office.Interop.Outlook.MAPIFolder CalendarFolder = null;\nMicrosoft.Office.Interop.Outlook.Items outlookCalendarItems = null;\n\noApp = new Microsoft.Office.Interop.Outlook.Application();\nmapiNamespace = oApp.GetNamespace(\"MAPI\"); ;\nCalendarFolder = mapiNamespace.GetDefaultFolder(Microsoft.Office.Interop.Outlook.OlDefaultFolders.olFolderCalendar);\noutlookCalendarItems = CalendarFolder.Items;\noutlookCalendarItems.IncludeRecurrences = false;\n\nConsole.WriteLine(\"Showing Calendar Items From the last 30 days\");\n\n//Set your dates here...\nDateTime startTime = DateTime.Now.AddDays(-31);\nDateTime endTime = DateTime.Now;\n\nstring filter = \"[Start] >= '\"\n + startTime.ToString(\"g\")\n + \"' AND [End] <= '\"\n + endTime.ToString(\"g\") + \"'\";\n\ntry\n{\n\n outlookCalendarItems.Sort(\"[Start]\", Type.Missing);\n\n\n foreach (Microsoft.Office.Interop.Outlook.AppointmentItem item in outlookCalendarItems.Restrict(filter))\n {\n\n Console.WriteLine(item.Subject + \" -> \" + item.Start.ToLongDateString());\n\n }\n\n\n}\ncatch { }\n\n\nConsole.WriteLine(\"Finished\");\n}\n\n\nGetAllCalendarItems();\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90899", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,907
<p>I would like to know what would be the best way to do unit testing of a servlet. </p> <p>Testing internal methods is not a problem as long as they don't refer to the servlet context, but what about testing the doGet/doPost methods as well as the internal method that refer to the context or make use of session parameters?</p> <p>Is there a way to do this simply using classical tools such as JUnit, or preferrably TestNG? Did I need to embed a tomcat server or something like that?</p>
[ { "answer_id": 90993, "author": "Marcio Aguiar", "author_id": 4213, "author_profile": "https://Stackoverflow.com/users/4213", "pm_score": 3, "selected": false, "text": "myServlet.doGet(new HttpServletRequestWrapper() {\n public HttpSession getSession() {\n return mockSession;\n }\n\n ...\n}\n" }, { "answer_id": 91109, "author": "Garth Gilmour", "author_id": 2635682, "author_profile": "https://Stackoverflow.com/users/2635682", "pm_score": 6, "selected": false, "text": "public class OrdersPageTest {\n private static final String WEBSITE_URL = \"http://localhost:8080/demo1\";\n\n @Before\n public void start() {\n webTester = new WebTester();\n webTester.setTestingEngineKey(TestingEngineRegistry.TESTING_ENGINE_HTMLUNIT);\n webTester.getTestContext().setBaseUrl(WEBSITE_URL);\n }\n @Test\n public void sanity() throws Exception {\n webTester.beginAt(\"/orderEntry.html\");\n webTester.assertTitleEquals(\"Order Entry Form\");\n }\n @Test\n public void idIsRequired() throws Exception {\n webTester.beginAt(\"/orderEntry.html\");\n webTester.submit();\n webTester.assertTextPresent(\"ID Missing!\");\n }\n @Test\n public void nameIsRequired() throws Exception {\n webTester.beginAt(\"/orderEntry.html\");\n webTester.setTextField(\"id\",\"AB12\");\n webTester.submit();\n webTester.assertTextPresent(\"Name Missing!\");\n }\n @Test\n public void validOrderSucceeds() throws Exception {\n webTester.beginAt(\"/orderEntry.html\");\n webTester.setTextField(\"id\",\"AB12\");\n webTester.setTextField(\"name\",\"Joe Bloggs\");\n\n //fill in order line one\n webTester.setTextField(\"lineOneItemNumber\", \"AA\");\n webTester.setTextField(\"lineOneQuantity\", \"12\");\n webTester.setTextField(\"lineOneUnitPrice\", \"3.4\");\n\n //fill in order line two\n webTester.setTextField(\"lineTwoItemNumber\", \"BB\");\n webTester.setTextField(\"lineTwoQuantity\", \"14\");\n webTester.setTextField(\"lineTwoUnitPrice\", \"5.6\");\n\n webTester.submit();\n webTester.assertTextPresent(\"Total: 119.20\");\n }\n private WebTester webTester;\n}\n" }, { "answer_id": 14178508, "author": "John Yeary", "author_id": 160361, "author_profile": "https://Stackoverflow.com/users/160361", "pm_score": 4, "selected": false, "text": "test" }, { "answer_id": 38589678, "author": "Bob", "author_id": 6524449, "author_profile": "https://Stackoverflow.com/users/6524449", "pm_score": 2, "selected": false, "text": "HttpRequest" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9396/" ]
90,920
<p>Could somebody please name a few. I could given time, but this is for somebody else, and I'd also like some community input.</p>
[ { "answer_id": 117106, "author": "JohnIdol", "author_id": 1311500, "author_profile": "https://Stackoverflow.com/users/1311500", "pm_score": 1, "selected": false, "text": "BEGIN TRY\n -- Generate divide-by-zero error.\n SELECT 1/0;\nEND TRY\nBEGIN CATCH\n -- Execute custom error retrieval routine.\nEND CATCH;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
90,940
<p>I'm writing the memory manager for an application, as part of a team of twenty-odd coders. We're running out of memory quota and we need to be able to see what's going on, since we only appear to be using about 700Mb. I need to be able to report where it's all going - fragmentation etc. Any ideas?</p>
[ { "answer_id": 91054, "author": "Suma", "author_id": 16673, "author_profile": "https://Stackoverflow.com/users/16673", "pm_score": 3, "selected": true, "text": "void PrintVMMap()\n{\n size_t start = 0;\n // TODO: make portable - not compatible with /3GB, 64b OS or 64b app\n size_t end = 1U<<31; // map 32b user space only - kernel space not accessible\n SYSTEM_INFO si;\n GetSystemInfo(&si);\n size_t pageSize = si.dwPageSize;\n size_t longestFreeApp = 0;\n\n int index=0;\n for (size_t addr = start; addr<end; )\n {\n MEMORY_BASIC_INFORMATION buffer;\n SIZE_T retSize = VirtualQuery((void *)addr,&buffer,sizeof(buffer));\n if (retSize==sizeof(buffer) && buffer.RegionSize>0)\n {\n // dump information about this region\n printf(.... some buffer information here ....);\n // track longest feee region - usefull fragmentation indicator\n if (buffer.State&MEM_FREE)\n {\n if (buffer.RegionSize>longestFreeApp) longestFreeApp = buffer.RegionSize;\n }\n addr += buffer.RegionSize;\n index+= buffer.RegionSize/pageSize;\n }\n else\n {\n // always proceed\n addr += pageSize;\n index++;\n }\n }\n printf(\"Longest free VM region: %d\",longestFreeApp);\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11483/" ]
90,949
<p>There is no documentation on cakephp.org and I am unable to find one on google. Please link me some documentation or supply one!</p>
[ { "answer_id": 100658, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 5, "selected": true, "text": "__('string')" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90949", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4013/" ]
90,971
<p>Let's say I have a class:</p> <pre><code>class Foo { public string Bar { get { ... } } public string this[int index] { get { ... } } } </code></pre> <p>I can bind to these two properties using "{Binding Path=Bar}" and "{Binding Path=[x]}". Fine.</p> <p>Now let's say I want to implement INotifyPropertyChanged:</p> <pre><code>class Foo : INotifyPropertyChanged { public string Bar { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "Bar" ) ); } } } public string this[int index] { get { ... } set { ... if( PropertyChanged != null ) { PropertyChanged( this, new PropertyChangedEventArgs( "????" ) ); } } } public event PropertyChangedEventHandler PropertyChanged; } </code></pre> <p>What goes in the part marked ????? (I've tried string.Format("[{0}]", index) and it doesn't work). Is this a bug in WPF, is there an alternative syntax, or is it simply that INotifyPropertyChanged isn't as powerful as normal binding?</p>
[ { "answer_id": 91083, "author": "stusmith", "author_id": 6604, "author_profile": "https://Stackoverflow.com/users/6604", "pm_score": 5, "selected": true, "text": "Item[]\n" }, { "answer_id": 798762, "author": "jEROD", "author_id": 97207, "author_profile": "https://Stackoverflow.com/users/97207", "pm_score": 3, "selected": false, "text": "PropertyChanged( this, new PropertyChangedEventArgs( \"Item[]\" ) )\n" }, { "answer_id": 10500334, "author": "Adi Lester", "author_id": 389966, "author_profile": "https://Stackoverflow.com/users/389966", "pm_score": 3, "selected": false, "text": "Binding.IndexerName" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6604/" ]
90,977
<p>Emacs Lisp has <code>replace-string</code> but has no <code>replace-char</code>. I want to replace "typographic" curly quotes (Emacs code for this character is hexadecimal 53979) with regular ASCII quotes, and I can do so with:</p> <pre><code>(replace-string (make-string 1 ?\x53979) "'") </code></pre> <p>I think it would be better with <code>replace-char</code>. </p> <p>What is the best way to do this?</p>
[ { "answer_id": 91043, "author": "0124816", "author_id": 11521, "author_profile": "https://Stackoverflow.com/users/11521", "pm_score": 2, "selected": false, "text": "This function is usually the wrong thing to use in a Lisp program.\nWhat you probably want is a loop like this:\n (while (search-forward \"’\" nil t)\n (replace-match \"'\" nil t))\n" }, { "answer_id": 97261, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 4, "selected": true, "text": "(replace-string \"\\x53979\" \"'\")\n" }, { "answer_id": 1052892, "author": "Yoo", "author_id": 37664, "author_profile": "https://Stackoverflow.com/users/37664", "pm_score": 2, "selected": false, "text": "(defun my-replace-smart-quotes (beg end)\n \"replaces ’ (the curly typographical quote, unicode hexa 2019) to ' (ordinary ascii quote).\"\n (interactive \"r\")\n (save-excursion\n (format-replace-strings '((\"\\x2019\" . \"'\")) nil beg end)))\n" }, { "answer_id": 44957530, "author": "notetiene", "author_id": 7879170, "author_profile": "https://Stackoverflow.com/users/7879170", "pm_score": 3, "selected": false, "text": "(subst-char-in-string ?' ?’ \"John's\")\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15625/" ]
90,982
<p>I'm looking for a good, clean way to go around the fact that PHP5 still doesn't support multiple inheritance. Here's the class hierarchy:</p> <p>Message<br> -- TextMessage<br> -------- InvitationTextMessage<br> -- EmailMessage<br> -------- InvitationEmailMessage </p> <p>The two types of Invitation* classes have a lot in common; i'd love to have a common parent class, Invitation, that they both would inherit from. Unfortunately, they also have a lot in common with their current ancestors... TextMessage and EmailMessage. Classical desire for multiple inheritance here. </p> <p>What's the most light-weight approach to solve the issue? </p> <p>Thanks!</p>
[ { "answer_id": 91303, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 8, "selected": true, "text": "$m = new Message();\n$m->type = 'text/html';\n$m->from = 'John Doe <jdoe@yahoo.com>';\n$m->to = 'Random Hacker <rh@gmail.com>';\n$m->subject = 'Invitation email';\n$m->importBody('invitation.html');\n\n$d = new MessageDispatcher();\n$d->dispatch($m);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16668/" ]
90,988
<p>Using eclipse 3.3.2 with MyEclipse installed. For some reason if a file isn't called build.xml then it isnt' recognised as an ant file. The file association for *.xml includes ant and says "locked by 'Ant Buildfile' content type.</p> <p>The run-as menu is broken. Even if the editor association works run-as doesn't.</p> <p>The ant buildfiles in question are correctly formatted. They work fine if you call them build.xml or if you use them anywhere else. Eclipse just won't recognise and thus wont allow you to run them.</p>
[ { "answer_id": 91557, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n<project name=\"myproject\" default=\"t1\">\n <target name=\"t1\"></target>\n</project>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
90,996
<p>I have an IList that contains items ( parent first ), they need to be added to a Diagram Document in the reverse order so that the parent is added last, drawn on top so that it is the first thing to be selected by the user.</p> <p>What's the best way to do it? Something better/more elegant than what I am doing currently which I post below..</p>
[ { "answer_id": 90998, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "for(int iLooper = obEvtArgs.NewItems.Count-1; iLooper >= 0; iLooper--)\n {\n GoViewBoy.Document.Add(CreateNodeFor(obEvtArgs.NewItems[iLooper] as IMySpecificObject, obNextPos));\n }\n" }, { "answer_id": 91044, "author": "Davy Landman", "author_id": 11098, "author_profile": "https://Stackoverflow.com/users/11098", "pm_score": 4, "selected": true, "text": "foreach(var item in obEvtArgs.NewItems.Reverse())\n{\n ...\n}\n" }, { "answer_id": 146294, "author": "Emperor XLII", "author_id": 2495, "author_profile": "https://Stackoverflow.com/users/2495", "pm_score": 2, "selected": false, "text": "System.Collections.IList" }, { "answer_id": 17299868, "author": "Rok Strniša", "author_id": 974531, "author_profile": "https://Stackoverflow.com/users/974531", "pm_score": 0, "selected": false, "text": "var reversed = new List<T>(original); // assuming original has type IList<T>\nreversed.Reverse();\nforeach (T e in reversed) {\n ...\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/90996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
91,007
<p>What is the best way of doing this? tmpnam() returns a path to a file in the root of the drive, which requires administrator privileges on Windows Vista, so this is not an option.</p>
[ { "answer_id": 91141, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 0, "selected": false, "text": "BUGS\n Never use this function. Use mkstemp(3) instead.\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17424/" ]
91,038
<p>I would like to redirect/rewrite this two kinds of URLs:</p> <ul> <li>mydomain.com -> newdomain.com</li> <li>mydomain.com/specificPage -> newdomain.com/newSpecificPage</li> <li>mydomain.com/anyOtherPage -> mydomain.com/anyOtherPage (no redirect here)</li> </ul> <p>So I just want to redirect the root domain to a new domain, and <em>some</em> pages from my domain to some pages on a new domain...</p> <p>How can I do that on a JBoss server ?</p>
[ { "answer_id": 91167, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "RewriteCond %{REQUEST_URI} ^URI_TO_REDIRECT\nRewriteRule redirect=301 NEW_SITE [L]\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17426/" ]
91,071
<p>In Emacs, <kbd>C-x o</kbd> takes me to the next window.</p> <p>What keyboard macro takes me to the previous window in Emacs?</p>
[ { "answer_id": 96540, "author": "Nate", "author_id": 17009, "author_profile": "https://Stackoverflow.com/users/17009", "pm_score": 7, "selected": false, "text": "(global-set-key (kbd \"C-x <up>\") 'windmove-up)\n(global-set-key (kbd \"C-x <down>\") 'windmove-down)\n(global-set-key (kbd \"C-x <right>\") 'windmove-right)\n(global-set-key (kbd \"C-x <left>\") 'windmove-left)\n" }, { "answer_id": 6081258, "author": "Troydm", "author_id": 513227, "author_profile": "https://Stackoverflow.com/users/513227", "pm_score": 2, "selected": false, "text": ";; Windows Cycling\n(defun windmove-up-cycle()\n (interactive)\n (condition-case nil (windmove-up)\n (error (condition-case nil (windmove-down)\n (error (condition-case nil (windmove-right) (error (condition-case nil (windmove-left) (error (windmove-up))))))))))\n\n(defun windmove-down-cycle()\n (interactive)\n (condition-case nil (windmove-down)\n (error (condition-case nil (windmove-up)\n (error (condition-case nil (windmove-left) (error (condition-case nil (windmove-right) (error (windmove-down))))))))))\n\n(defun windmove-right-cycle()\n (interactive)\n (condition-case nil (windmove-right)\n (error (condition-case nil (windmove-left)\n (error (condition-case nil (windmove-up) (error (condition-case nil (windmove-down) (error (windmove-right))))))))))\n\n(defun windmove-left-cycle()\n (interactive)\n (condition-case nil (windmove-left)\n (error (condition-case nil (windmove-right)\n (error (condition-case nil (windmove-down) (error (condition-case nil (windmove-up) (error (windmove-left))))))))))\n\n(global-set-key (kbd \"C-x <up>\") 'windmove-up-cycle)\n(global-set-key (kbd \"C-x <down>\") 'windmove-down-cycle)\n(global-set-key (kbd \"C-x <right>\") 'windmove-right-cycle)\n(global-set-key (kbd \"C-x <left>\") 'windmove-left-cycle)\n" }, { "answer_id": 9305758, "author": "octi", "author_id": 752726, "author_profile": "https://Stackoverflow.com/users/752726", "pm_score": 4, "selected": false, "text": "(defun frame-bck()\n (interactive)\n (other-window-or-frame -1)\n)\n(define-key (current-global-map) (kbd \"M-o\") 'other-window-or-frame)\n(define-key (current-global-map) (kbd \"M-O\") 'frame-bck)\n" }, { "answer_id": 11184101, "author": "ocodo", "author_id": 311660, "author_profile": "https://Stackoverflow.com/users/311660", "pm_score": 5, "selected": false, "text": "window-number.el" }, { "answer_id": 11730954, "author": "aspirin", "author_id": 1550119, "author_profile": "https://Stackoverflow.com/users/1550119", "pm_score": 1, "selected": false, "text": "(require 'windmove)\n(windmove-default-keybindings 'meta) ;; or use 'super to use windows key instead alt\n" }, { "answer_id": 12667392, "author": "Hal", "author_id": 935470, "author_profile": "https://Stackoverflow.com/users/935470", "pm_score": 2, "selected": false, "text": "(setq windmove-wrap-around t)\n" }, { "answer_id": 17984479, "author": "bnzmnzhnz", "author_id": 2321928, "author_profile": "https://Stackoverflow.com/users/2321928", "pm_score": 4, "selected": false, "text": " (defun prev-window ()\n (interactive)\n (other-window -1))\n\n (define-key global-map (kbd \"C-x p\") 'prev-window)\n" }, { "answer_id": 20263424, "author": "tshepang", "author_id": 321731, "author_profile": "https://Stackoverflow.com/users/321731", "pm_score": 2, "selected": false, "text": "M-n" }, { "answer_id": 24142223, "author": "Indradhanush Gupta", "author_id": 1773961, "author_profile": "https://Stackoverflow.com/users/1773961", "pm_score": 2, "selected": false, "text": "arrow keys" }, { "answer_id": 28267273, "author": "sjas", "author_id": 805284, "author_profile": "https://Stackoverflow.com/users/805284", "pm_score": 2, "selected": false, "text": "(global-unset-key (kbd \"M-j\"))\n(global-unset-key (kbd \"M-k\"))\n(global-set-key (kbd \"M-j\") (lambda () (interactive) (other-window 1)))\n(global-set-key (kbd \"M-k\") (lambda () (interactive) (other-window -1)))\n" }, { "answer_id": 49732076, "author": "user9618991", "author_id": 9618991, "author_profile": "https://Stackoverflow.com/users/9618991", "pm_score": 0, "selected": false, "text": "(global-set-key (kbd \"C-x a\") 'ace-swap-window) \n(global-set-key (kbd \"C-x q\") 'ace-select-window)\n\ndownload ace-window from the melpa repo if you don't know how to do that\nput this in your .emacs file if you don't have one create it \n\n(package-initialize) \n\n(require 'package) \n(add-to-list 'package-archives '(\"melpa\" , \"http://melpa.org/packages/\")) \n\n(package-initialize) \n\nthen \"m-x list-packages\"\n" }, { "answer_id": 64249501, "author": "Micah Elliott", "author_id": 326516, "author_profile": "https://Stackoverflow.com/users/326516", "pm_score": 0, "selected": false, "text": "(key-chord-define-global \"qw\" 'prev-window)\n(key-chord-define-global \"'y\" 'other-window) ; bonus for my colemak, adjust otherwise\n(key-chord-define-global \";'\" 'other-window) ; probably normal\n\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17239/" ]
91,108
<p>How do I get my C# program to sleep (pause execution) for 50 milliseconds?</p>
[ { "answer_id": 91119, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 10, "selected": true, "text": "System.Threading.Thread.Sleep(50);\n" }, { "answer_id": 91120, "author": "Alexander Prokofyev", "author_id": 11256, "author_profile": "https://Stackoverflow.com/users/11256", "pm_score": 5, "selected": false, "text": "using System.Threading;\n// ...\nThread.Sleep(50);\n" }, { "answer_id": 91441, "author": "SelvirK", "author_id": 17465, "author_profile": "https://Stackoverflow.com/users/17465", "pm_score": 4, "selected": false, "text": "Thread.Sleep(50);\n" }, { "answer_id": 92512, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 6, "selected": false, "text": ".Sleep()" }, { "answer_id": 5743843, "author": "Marcel Toth", "author_id": 702199, "author_profile": "https://Stackoverflow.com/users/702199", "pm_score": 7, "selected": false, "text": "Thread.Sleep(numberOfMilliseconds);\n" }, { "answer_id": 13684964, "author": "Toni Petrina", "author_id": 671469, "author_profile": "https://Stackoverflow.com/users/671469", "pm_score": 6, "selected": false, "text": "async void foo()\n{\n // something\n await Task.Delay(50);\n}\n" }, { "answer_id": 15650225, "author": "Colonel Panic", "author_id": 284795, "author_profile": "https://Stackoverflow.com/users/284795", "pm_score": 3, "selected": false, "text": "using System.Threading;\nThread.Sleep(TimeSpan.FromMilliseconds(50));\n" }, { "answer_id": 40311525, "author": "Akumaburn", "author_id": 4104551, "author_profile": "https://Stackoverflow.com/users/4104551", "pm_score": -1, "selected": false, "text": "using System.Runtime.InteropServices;\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeBeginPeriod\", SetLastError = true)]\n private static extern uint TimeBeginPeriod(uint uMilliseconds);\n\n [DllImport(\"winmm.dll\", EntryPoint = \"timeEndPeriod\", SetLastError = true)]\n private static extern uint TimeEndPeriod(uint uMilliseconds);\n /**\n * Extremely accurate sleep is needed here to maintain performance so system resolution time is increased\n */\n private void accurateSleep(int milliseconds)\n {\n //Increase timer resolution from 20 miliseconds to 1 milisecond\n TimeBeginPeriod(1);\n Stopwatch stopwatch = new Stopwatch();//Makes use of QueryPerformanceCounter WIN32 API\n stopwatch.Start();\n\n while (stopwatch.ElapsedMilliseconds < milliseconds)\n {\n //So we don't burn cpu cycles\n if ((milliseconds - stopwatch.ElapsedMilliseconds) > 20)\n {\n Thread.Sleep(5);\n }\n else\n {\n Thread.Sleep(1);\n }\n }\n\n stopwatch.Stop();\n //Set it back to normal.\n TimeEndPeriod(1);\n }\n" }, { "answer_id": 57364499, "author": "timmebee", "author_id": 11772622, "author_profile": "https://Stackoverflow.com/users/11772622", "pm_score": 2, "selected": false, "text": "using System.Threading.Tasks;\n\nTask.Delay(50).Wait(); // wait 50ms\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91108", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
91,110
<p>How to match a single quote in sed if the expression is enclosed in single quotes:</p> <pre><code>sed -e '...' </code></pre> <p>For example need to match this text:</p> <pre><code>'foo' </code></pre>
[ { "answer_id": 91176, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 7, "selected": true, "text": "\"texta'textb\" (APOSTROPHE inside QUOTATION MARKs)\n" }, { "answer_id": 206963, "author": "TimB", "author_id": 4193, "author_profile": "https://Stackoverflow.com/users/4193", "pm_score": 6, "selected": false, "text": "sed -e '...'\\''foo'\\''...'\n" }, { "answer_id": 63193353, "author": "dragon788", "author_id": 3794873, "author_profile": "https://Stackoverflow.com/users/3794873", "pm_score": -1, "selected": false, "text": "[']" }, { "answer_id": 65133170, "author": "Rachel", "author_id": 7938150, "author_profile": "https://Stackoverflow.com/users/7938150", "pm_score": 1, "selected": false, "text": "var=\"I'm a string with a single quote\"\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
91,116
<p>I'm using this formula to calculate the distance between entries in my (My)SQL database which have latitude and longitude fields in decimal format:</p> <pre><code>6371 * ACOS(SIN(RADIANS( %lat1% )) * SIN(RADIANS( %lat2% )) + COS(RADIANS( %lat1% )) * COS(RADIANS( %lat2% )) * COS(RADIANS( %lon2% ) - RADIANS( %lon1% ))) </code></pre> <p>Substituting %lat1% and %lat2% appropriately it can be used in the WHERE clause to find entries within a certain radius of another entry, using it in the ORDER BY clause together with LIMIT will find the nearest x entries etc.</p> <p>I'm writing this mostly as a note for myself, but improvements are always welcome. :)</p> <p>Note: As mentioned by Valerion below, this calculates in kilometers. Substitute 6371 by an <a href="http://en.wikipedia.org/wiki/Earth_radius" rel="nofollow noreferrer">appropriate alternative number</a> to use meters, miles etc.</p>
[ { "answer_id": 123413, "author": "David", "author_id": 21328, "author_profile": "https://Stackoverflow.com/users/21328", "pm_score": 3, "selected": false, "text": "class User < ActiveRecord::Base\n ...\n # has integer x & y coordinates\n ...\n\n # Returns array of {:user => <User>, :distance => <distance>}, sorted by distance (in metres).\n # Distance is rounded to nearest integer.\n # point is a Geo::LatLng.\n # radius is in metres.\n # limit specifies the maximum number of records to return (default 100).\n def self.find_within_radius(point, radius, limit = 100)\n\n sql = <<-SQL\n select id, lat, lng, (#{point.x} - x) * (#{point.x} - x) + (#{point.y} - y) * (#{point.y} - y) d \n from users where #{(radius ** 2)} >= d \n order by d limit #{limit}\n SQL\n \n users = User.find_by_sql(sql)\n users.each {|user| user.d = Math.sqrt(user.d.to_f).round}\n return users\n end\n" }, { "answer_id": 11621817, "author": "2pha", "author_id": 1547127, "author_profile": "https://Stackoverflow.com/users/1547127", "pm_score": 1, "selected": false, "text": "SELECT n, SQRT(POW((69.1 * (n.field_geofield_lat - :lat)) , 2 ) + POW((53 * (n.field_geofield_lon - :lon)), 2)) AS distance FROM field_revision_field_geofield n ORDER BY distance ASC\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
91,127
<p>I want to verify a drag &amp; drop operation is allowed. A valid item can come from another one of our "controls", or internally from within the custom treeview. Currently I have this:</p> <pre><code>bool CanDrop(DragEventArgs e) { bool allow = false; Point point = tree.PointToClient(new Point(e.X, e.Y)); TreeNode target = tree.GetNodeAt(point); if (target != null) { if (CanWrite(target)) //user permissions { if (e.Data.GetData(typeof(DataInfoObject)) != null) //from internal application { DataInfoObject info = (DataInfoObject)e.Data.GetData(typeof(DataInfoObject)); DragDataCollection data = info.GetData(typeof(DragDataCollection)) as DragDataCollection; if (data != null) { allow = true; } } else if (tree.SelectedNode.Tag.GetType() != typeof(TreeRow)) //node belongs to this &amp; not a root node { if (TargetExistsInNode(tree.SelectedNode, target) == false) { if (e.Effect == DragDropEffects.Copy) { allow = true; } else if (e.Effect == DragDropEffects.Move) { allow = true; } } } } } return allow; } </code></pre> <p>I've moved all the checking code to this method to try to improve things, but to me this is still horrible!</p> <p>So much logic, and so much of it to do things that I'd expect the treeview would do itself (eg. "TargetExistsInNode" checks whether the dragged node is being dragged to one of its children).</p> <p>What is the best way to validate input to a control?</p>
[ { "answer_id": 91995, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": true, "text": "class TreeNodeController {\n Entity data; \n\n virtual bool IsReadOnly { get; }\n virtual bool CanDrop(TreeNodeController source, DragDropEffects effect);\n virtual bool CanDrop(DataInfoObject info, DragDropEffects effect);\n virtual bool CanRename();\n}\n\nclass ParentNodeController : TreeNodeController {\n override bool IsReadOnly { get { return data.IsReadOnly; } } \n override bool CanDrop(TreeNodeController source, DragDropEffect effect) {\n return !IsReadOnly && !data.IsChildOf(source.data) && effect == DragDropEffect.Move;\n }\n virtual bool CanDrop(DataInfoObject info, DragDropEffects effect) {\n return info.DragDataCollection != null;\n }\n override bool CanRename() { \n return !data.IsReadOnly && data.HasName;\n }\n}\n\nclass LeafNodeController : TreeNodeController {\n override bool CanDrop(TreeNodeController source, DragDropEffect effect) {\n return false;\n }\n}\n" }, { "answer_id": 126146, "author": "Nigel Hawkins", "author_id": 1389021, "author_profile": "https://Stackoverflow.com/users/1389021", "pm_score": 1, "selected": false, "text": "DragDropEffects" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91127", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15608/" ]
91,137
<p>I've been thinking about this object oriented design question for a while now and have unable to come up with a satisfactory solution, so thought I'd throw it open to the crowds here for some opinions.</p> <p>I have a <em>Game</em> class that represents a turn based board game, we can assume it's similar to Monopoly for the purposes of this question. In my design I have a <em>Player</em> class containing a method <em>TakeTurn</em>.</p> <p>The <em>Game</em> loops through all <em>Player</em>s and calls the TakeTurn method to do all the necessary things to complete the turn. I want to be able to have n number of players, and be able to set an arbitrary number of them to be computer players. So, my thought was to have a HumanPlayer class and a <em>ComputerPlayer</em> class, both of which derive from Player.</p> <p>The <em>Game</em> knows only the <em>Player</em> class and simply calls the <em>TakeTurn</em> method on each <em>Player</em> in turn. My problem comes in the fact that <em>ComputerPlayer</em> objects can be completely automated, i.e. keeping with the Monopoly example, can decide to buy a property using some piece of logic. Now, with the <em>HumanPlayer</em> object, it needs to get an input from the actual user to be able to buy a property for instance, which seems to imply a different interface and potentially mean they shouldn't derive</p> <p>I haven't been able to come up with a good solution to the problem without having the <em>Game</em> class know the actual implementations of the various <em>Player</em> classes explicitly. I could always make the assumption in the <em>Game</em> class that there will only ever be human and computer players and effectively close it for extension, but it doesn't seem like good OO programming.</p> <p>Any opinions on this would be appreciated.</p>
[ { "answer_id": 91172, "author": "Grad van Horck", "author_id": 12569, "author_profile": "https://Stackoverflow.com/users/12569", "pm_score": 0, "selected": false, "text": "Game" }, { "answer_id": 91247, "author": "RhysC", "author_id": 17466, "author_profile": "https://Stackoverflow.com/users/17466", "pm_score": 0, "selected": false, "text": "public abstract class Player \n{\n int position;\n DecisionMaker decisionDependency;\n\n ...\n\n public void TakeTurn()\n {\n position += RollDice();\n GameOption option GetOptions(position);\n MakeDescion(option);\n }\n\n protected int RollDice()\n {\n //do something to get the movement\n }\n\n protected abstract void MakeDecision(GameOption option);\n\n}\n\nPublic class ComputerPlayer : Player\n{\n public ComputerPlayer()\n {\n decisionDependency = new AIDecisionMaker();\n }\n\n protected override void void MakeDecision(GameOption option)\n {\n decisionDependency.MakeDecision(option);\n //do stuff, probably delgate toan AI based dependency\n }\n}\n\nPublic class HumanPlayer : Player\n{\n public HumanPlayer()\n {\n decisionDependency = new UIDecisionMaker();\n }\n\n protected override void void MakeDecision(GameOption option)\n {\n decisionDependency.MakeDecision(option);\n //do stuff, probably interacting with the a UI or delgate to a dependency\n }\n}\n" }, { "answer_id": 109278, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "Observable" }, { "answer_id": 1422625, "author": "Rogério", "author_id": 2326914, "author_profile": "https://Stackoverflow.com/users/2326914", "pm_score": 2, "selected": false, "text": "HumanPlayer" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91137", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16752/" ]
91,150
<p>How do I create an optional parameter in a mysql stored procedure?</p>
[ { "answer_id": 18519386, "author": "Anthony Geoghegan", "author_id": 1640661, "author_profile": "https://Stackoverflow.com/users/1640661", "pm_score": 2, "selected": false, "text": "CREATE PROCEDURE add_product(product_name VARCHAR(100), product_price FLOAT,\n cat1 INT, cat2 INT, cat3 INT)\n-- The cat? parameters are optional; provide a NULL value if not required\nBEGIN\n\n ...\n\n -- Add product to relevant categories \n IF cat1 IS NOT NULL THEN\n INSERT INTO products_to_categories (products_id, categories_id) VALUES (product_id, cat1);\n END IF;\n IF cat2 IS NOT NULL THEN\n INSERT INTO products_to_categories (products_id, categories_id) VALUES (product_id, cat2);\n END IF;\n IF cat3 IS NOT NULL THEN\n INSERT INTO products_to_categories (products_id, categories_id) VALUES (product_id, cat3);\n END IF;\n\nEND\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,160
<p>How do I best convert a System.Data.DbType enumeration value to the corresponding (or at least one of the possible corresponding) System.Type values?</p> <p>For example:</p> <pre><code>DbType.StringFixedLength -&gt; System.String DbType.String -&gt; System.String DbType.Int32 -&gt; System.Int32 </code></pre> <p>I've only seen very "dirty" solutions but nothing really clean.</p> <p>(yes, it's a follow up to a different question of mine, but it made more sense as two seperate questions)</p>
[ { "answer_id": 18621961, "author": "Jon Banta", "author_id": 2748177, "author_profile": "https://Stackoverflow.com/users/2748177", "pm_score": 2, "selected": false, "text": "var dbType = DbType.Currency;\n\nType metaClrType = Type.GetType(\n \"System.Data.SqlClient.MetaType, System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\",\n true,\n true\n );\n\nobject metaType = metaClrType.InvokeMember(\n \"GetMetaTypeFromDbType\",\n BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic,\n null,\n null,\n new object[] { dbType }\n);\n\nvar classType = (Type)metaClrType.InvokeMember(\n \"ClassType\",\n BindingFlags.GetField | BindingFlags.Instance | BindingFlags.NonPublic,\n null,\n metaType,\n null\n);\n\nstring cSharpDataType = classType.FullName;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5790/" ]
91,169
<p>So I log into a Solaris box, try to start Apache, and find that there is already a process listening on port 80, and it's not Apache. Our boxes don't have lsof installed, so I can't query with that. I guess I could do:</p> <pre><code>pfiles `ls /proc` | less </code></pre> <p>and look for "port: 80", but if anyone has a better solution, I'm all ears! Even better if I can look for the listening process without being root. I'm open to both shell and C solutions; I wouldn't mind having a little custom executable to carry with me for the next time this comes up.</p> <p>Updated: I'm talking about generic installs of solaris for which I am not the administrator (although I do have superuser access), so installing things from the freeware disk isn't an option. Obviously neither are using Linux-specific extensions to fuser, netstat, or other tools. So far running pfiles on <strong>all</strong> processes seems to be the best solution, unfortunately. If that remains the case, I'll probably post an answer with some slightly more efficient code that the clip above.</p>
[ { "answer_id": 91188, "author": "Christoffer", "author_id": 15514, "author_profile": "https://Stackoverflow.com/users/15514", "pm_score": -1, "selected": false, "text": "netstat" }, { "answer_id": 825155, "author": "mavroprovato", "author_id": 89435, "author_profile": "https://Stackoverflow.com/users/89435", "pm_score": 5, "selected": false, "text": "#!/bin/ksh\n\nline='---------------------------------------------'\npids=$(/usr/bin/ps -ef | sed 1d | awk '{print $2}')\n\nif [ $# -eq 0 ]; then\n read ans?\"Enter port you would like to know pid for: \"\nelse\n ans=$1\nfi\n\nfor f in $pids\ndo\n /usr/proc/bin/pfiles $f 2>/dev/null | /usr/xpg4/bin/grep -q \"port: $ans\"\n if [ $? -eq 0 ]; then\n echo $line\n echo \"Port: $ans is being used by PID:\\c\"\n /usr/bin/ps -ef -o pid -o args | egrep -v \"grep|pfiles\" | grep $f\n fi\ndone\nexit 0\n" }, { "answer_id": 9703830, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 2, "selected": false, "text": "#! /usr/bin/env perl\n##\n## Search the processes which are listening on the given port.\n##\n## For SunOS 5.10.\n##\n\nuse strict;\nuse warnings;\n\ndie \"Port missing\" unless $#ARGV >= 0;\nmy $port = int($ARGV[0]);\ndie \"Invalid port\" unless $port > 0;\n\nmy @pids;\nmap { push @pids, $_ if $_ > 0; } map { int($_) } `ls /proc`;\n\nforeach my $pid (@pids) {\n open (PF, \"pfiles $pid 2>/dev/null |\") \n || warn \"Can not read pfiles $pid\";\n $_ = <PF>;\n my $fd;\n my $type;\n my $sockname;\n my $peername;\n my $report = sub {\n if (defined $fd) {\n if (defined $sockname && ! defined $peername) {\n print \"$pid $type $sockname\\n\"; } } };\n while (<PF>) {\n if (/^\\s*(\\d+):.*$/) {\n &$report();\n $fd = int ($1);\n undef $type;\n undef $sockname;\n undef $peername; }\n elsif (/(SOCK_DGRAM|SOCK_STREAM)/) { $type = $1; }\n elsif (/sockname: AF_INET[6]? (.*) port: $port/) {\n $sockname = $1; }\n elsif (/peername: AF_INET/) { $peername = 1; } }\n &$report();\n close (PF); }\n" }, { "answer_id": 16201498, "author": "Mauricio Morales", "author_id": 1830021, "author_profile": "https://Stackoverflow.com/users/1830021", "pm_score": 3, "selected": false, "text": "ps -ef| awk '{print $2}'| xargs -I '{}' sh -c 'echo examining process {}; pfiles {}| grep 80'\n" }, { "answer_id": 18597375, "author": "RomAndNonES", "author_id": 2743777, "author_profile": "https://Stackoverflow.com/users/2743777", "pm_score": 1, "selected": false, "text": "#!/bin/sh\nif [ $# -ne 1 ]\nthen\n echo \"Sintaxis:\\n\\t\"\n echo \" $0 {port to search in process }\"\n exit\nelse\n MYPORT=$1\n for i in `ls /proc`\n do\n\n pfiles $i | grep port | grep \"port: $MYPORT\" > /dev/null\n if [ $? -eq 0 ]\n then\n echo \" Port $MYPORT founded in $i proccess !!!\\n\\n\"\n echo \"Details\\n\\t\"\n pfiles $i | grep port | grep \"port: $MYPORT\"\n echo \"\\n\\t\"\n echo \"Process detail: \\n\\t\"\n ps -ef | grep $i | grep -v grep\n fi\n done\nfi\n" }, { "answer_id": 19218132, "author": "Malcolm Boekhoff", "author_id": 1388639, "author_profile": "https://Stackoverflow.com/users/1388639", "pm_score": 2, "selected": false, "text": "#!/usr/bin/bash\n# This is a little script based on the \"pfiles\" solution that prints the PID and PORT.\n\npfiles `ls /proc` 2>/dev/null | awk \"/^[^ \\\\t]/{smatch=\\$0;next}/port:[ \\\\t]*${1}/{print smatch, \\$0}{next}\"\n" }, { "answer_id": 24312175, "author": "JohnGH", "author_id": 224625, "author_profile": "https://Stackoverflow.com/users/224625", "pm_score": 2, "selected": false, "text": "$ lsof -v\nlsof version information:\n revision: 4.85\n latest revision: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/\n latest FAQ: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/FAQ\n latest man page: ftp://lsof.itap.purdue.edu/pub/tools/unix/lsof/lsof_man\n configuration info: 64 bit kernel\n constructed: Fri Mar 7 10:32:54 GMT 2014\n constructed by and on: user@hostname\n compiler: gcc\n compiler version: 3.4.3 (csl-sol210-3_4-branch+sol_rpath)\n 8<- - - - ***SNIP*** - - -\n" }, { "answer_id": 24488977, "author": "peterh", "author_id": 1504556, "author_profile": "https://Stackoverflow.com/users/1504556", "pm_score": 2, "selected": false, "text": "netstat" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,179
<p>What options are there for building automated tests for GUIs written in Java Swing?</p> <p>I'd like to test some GUIs which have been written using the <a href="http://www.netbeans.org/features/java/swing.html" rel="noreferrer">NetBeans Swing GUI Builder</a>, so something that works without requiring special tampering of the code under test would be ideal.</p>
[ { "answer_id": 92459, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 3, "selected": false, "text": "java.awt.Robot" }, { "answer_id": 1001028, "author": "Dema", "author_id": 407003, "author_profile": "https://Stackoverflow.com/users/407003", "pm_score": 4, "selected": false, "text": " Scenario: Dialog manipulation\n Given the frame \"SwingSet\" is visible\n And the frame \"SwingSet\" is the container\n When I click the menu \"File/About\"\n Then I should see the dialog \"About Swing!\"\n Given the dialog \"About Swing!\" is the container\n When I click the button \"OK\"\n Then I should not see the dialog \"About Swing!\"\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91179", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]
91,181
<p>this is my first question to stackoverflow so here it goes...</p> <p>I use cruise control for my continuous integration scheme, i want to use obfuscation in order to add another protection layer to my assemblies. The thing is that i don't know how to go about it since i couldn't find articles describing about this. Suggestions that include other CI tools such as NAnt are also accepted. </p> <p>Commercial tools are also an option so don't hesitate to include them in your answer. The applications that i am building and want to obfuscate are mostly written in Compact Framework 2.0, Dot Net 2.0-3.5.</p> <p>At the moment cruise control checks for changes in the repository, then based on the script for the specific solution downloads and builds the project by using devenv, after the setup project has been run it copies the setup file into a different folder and thats more or less it. So i need obfuscate somewhere in this process..</p>
[ { "answer_id": 91197, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "<exec>\n <executable>make</executable>\n <baseDirectory>D:\\dev\\MyProject</baseDirectory>\n <buildArgs>all</buildArgs>\n <buildTimeoutSeconds>10</buildTimeoutSeconds>\n <successExitCodes>0,1,3,5</successExitCodes>\n <environment>\n <variable>\n <name>MyVar1</name>\n <value>Var1Value</value>\n </variable>\n <variable name=\"MyVar2\" value=\"Var2Value\"/>\n ...\n </environment>\n</exec>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17443/" ]
91,183
<p>I need to write code in python language for comparing the text of document using fingerprint techniques. I do not know to take fingerprint of a document or to generate fingerprint of a document. I'm asking if anyone knows the method or has source code for generating fingerprints of documents which is stored in bits form.</p>
[ { "answer_id": 91197, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 0, "selected": false, "text": "<exec>\n <executable>make</executable>\n <baseDirectory>D:\\dev\\MyProject</baseDirectory>\n <buildArgs>all</buildArgs>\n <buildTimeoutSeconds>10</buildTimeoutSeconds>\n <successExitCodes>0,1,3,5</successExitCodes>\n <environment>\n <variable>\n <name>MyVar1</name>\n <value>Var1Value</value>\n </variable>\n <variable name=\"MyVar2\" value=\"Var2Value\"/>\n ...\n </environment>\n</exec>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91183", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
91,202
<p>I'm trying to draw a polygon using c# and directx</p> <p>All I get is an ordered list of points from a file and I need to draw the flat polygon in a 3d world.</p> <p>I can load the points and draw a convex shape using a trianglefan and drawuserprimitives.</p> <p>This obviously leads to incorrect results when the polygon is very concave (which it may be).</p> <p>I can't imagine I'm the only person to grapple with this problem (tho I'm a gfx/directx neophyte - my background is in gui\windows application development). </p> <p>Can anyone point me towards a simple to follow resource\tutorial\algorithm which may assist me?</p>
[ { "answer_id": 347033, "author": "Walt D", "author_id": 44003, "author_profile": "https://Stackoverflow.com/users/44003", "pm_score": 2, "selected": false, "text": "Clear the stencil buffer to 1.\nPick an arbitrary vertex v0, probably somewhere near the polygon to reduce floating-point errors.\nFor each vertex v[i] of the polygon in clockwise order:\n let s be the segment v[i]->v[i+1] (where i+1 will wrap to 0 when the last vertex is reached)\n if v0 is to the \"right\" of s:\n draw a triangle defined by v0, v[i], v[i+1] that adds 1 to the stencil buffer\n else\n draw a triangle defined by v0, v[i], v[i+1] that subtracts 1 from the stencil buffer\nend for\nfill the screen with the desired color/texture, testing for stencil buffer values >= 2.\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16268/" ]
91,205
<p>I'm a little confused about how the standard library will behave now that Python (from 3.0) is unicode-based. Will modules such as CGI and urllib use unicode strings or will they use the new 'bytes' type and just provide encoded data?</p>
[ { "answer_id": 91301, "author": "pdc", "author_id": 8925, "author_profile": "https://Stackoverflow.com/users/8925", "pm_score": 5, "selected": true, "text": "bytes" }, { "answer_id": 91325, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 3, "selected": false, "text": ">>> import urllib.request\n>>> fh = urllib.request.urlopen('http://www.python.org/')\n>>> print(type(fh.read(100)))\n<class 'bytes'>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91205", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17457/" ]
91,216
<p><code>mysql_real_escape_string</code> and <code>addslashes</code> are both used to escape data before the database query, so what's the difference? (This question is not about parametrized queries/PDO/mysqli)</p>
[ { "answer_id": 91250, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "mysql_real_escape_string" }, { "answer_id": 91255, "author": "Mark Embling", "author_id": 6844, "author_profile": "https://Stackoverflow.com/users/6844", "pm_score": 5, "selected": true, "text": "string mysql_real_escape_string ( string $unescaped_string [, resource $link_identifier ] )" }, { "answer_id": 91271, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "mysql_real_escape_string" }, { "answer_id": 91695, "author": "Jon Cram", "author_id": 5343, "author_profile": "https://Stackoverflow.com/users/5343", "pm_score": 3, "selected": false, "text": "mysql_real_escape_string()" }, { "answer_id": 15290368, "author": "Mansab Khan", "author_id": 2147790, "author_profile": "https://Stackoverflow.com/users/2147790", "pm_score": 1, "selected": false, "text": "$str = \"input's data\";\n\nprint mysql_real_escape_string($str); input\\'s data\n\nprint addslashes($str); input\\'s data;\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7506/" ]
91,223
<p>I'm using Microsoft.XMLHTTP to get some information from another server from an old ASP/VBScript site. But that other server is restarted fairly often, so I want to check that it's up and running before trying to pull information from it (or avoid my page from giving an HTTP 500 by detecting the problem some other way).</p> <p>How can I do this with ASP?</p>
[ { "answer_id": 91488, "author": "bastos.sergio", "author_id": 12772, "author_profile": "https://Stackoverflow.com/users/12772", "pm_score": 2, "selected": true, "text": "PostURL = homelink & \"CustID.aspx?SearchFlag=PO\"\nset xmlhttp = CreateObject(\"MSXML2.ServerXMLHTTP.3.0\")\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91223", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1367/" ]
91,263
<p>Part of the install for an app I am responsible for, compiles some C code libraries. This is done in a console using GNU Make.</p> <p>So, as part of the install, a console window pops open, you see the make file output wiz by as it compiles and links, when finished the console window closes and the installer continues.</p> <p>All good, unless there is a compilation error. Then the make file bugs out and the console window closes before you have a chance to figure out what is happening.</p> <p>So, what I'd like to happen is have the console window pause with a 'press a key to continue' type functionality, if there is an error from the makefile so that the console stays open. Otherwise, just exit as normal and close the console.</p> <p>I can't work out how to do this in a GNU Makefile or from a batch file that could run the Make. </p>
[ { "answer_id": 91273, "author": "Amir Arad", "author_id": 11813, "author_profile": "https://Stackoverflow.com/users/11813", "pm_score": 4, "selected": true, "text": "if not ERRORLEVEL 0 pause\n" }, { "answer_id": 91346, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "@echo off\necho hello world\npause\n" }, { "answer_id": 7850322, "author": "Benja", "author_id": 178576, "author_profile": "https://Stackoverflow.com/users/178576", "pm_score": 2, "selected": false, "text": "if ERRORLEVEL 1 pause\n" }, { "answer_id": 41080486, "author": "bryc", "author_id": 815680, "author_profile": "https://Stackoverflow.com/users/815680", "pm_score": 1, "selected": false, "text": "#include <stdio.h>\nmain(int argc, char *argv[]) {\n if (argc == 2) {\n // return integer of argument 1\n return strtol(argv[1], NULL, 10);\n }\n else {\n return 0;\n }\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6063/" ]
91,275
<p>I'm writing a small tool in C# which will need to send and receive data to/from a website using POST and json formatting. I've never done anything like this before in C# (or any language really) so I'm struggling to find some useful information to get me started.</p> <p>I've found some information on the WebRequest class in C# (specifically from <a href="http://msdn.microsoft.com/en-us/library/debx8sh9.aspx" rel="noreferrer">here</a>) but before I start diving into it, I wondered if this was the right tool for the job.</p> <p>I've found plenty of tools to convert data into the json format but not much else, so any information would be really helpful here in case I end up down a dead end.</p>
[ { "answer_id": 91317, "author": "Eric Schoonover", "author_id": 3957, "author_profile": "https://Stackoverflow.com/users/3957", "pm_score": 4, "selected": false, "text": "using (WebClient client = new WebClient ())\n{\n //manipulate request headers (optional)\n client.Headers.Add (HttpRequestHeader.UserAgent, \"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)\");\n\n //execute request and read response as string to console\n using (StreamReader reader = new StreamReader(client.OpenRead(targetUri)))\n {\n string s = reader.ReadToEnd ();\n Console.WriteLine (s);\n }\n}\n" }, { "answer_id": 91322, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 1, "selected": false, "text": "Nothing" }, { "answer_id": 91326, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 6, "selected": true, "text": "HttpWebRequest req = (HttpWebRequest)\nWebRequest.Create(\"http://mysite.com/index.php\");\nreq.Method = \"POST\";\nreq.ContentType = \"application/x-www-form-urlencoded\";\nstring postData = \"var=value1&var2=value2\";\nreq.ContentLength = postData.Length;\n\nStreamWriter stOut = new\nStreamWriter(req.GetRequestStream(),\nSystem.Text.Encoding.ASCII);\nstOut.Write(postData);\nstOut.Close();\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,289
<p>I have a migration that runs an SQL script to create a new Postgres schema. When creating a new database in Postgres by default it creates a schema called 'public', which is the main schema we use. The migration to create the new database schema seems to be working fine, however the problem occurs after the migration has run, when rails tries to update the 'schema_info' table that it relies on it says that it does not exist, as if it is looking for it in the new database schema and not the default 'public' schema where the table actually is.</p> <p>Does anybody know how I can tell rails to look at the 'public' schema for this table?</p> <p>Example of SQL being executed: ~</p> <pre><code>CREATE SCHEMA new_schema; COMMENT ON SCHEMA new_schema IS 'this is the new Postgres database schema to sit along side the "public" schema'; -- various tables, triggers and functions created in new_schema </code></pre> <p>Error being thrown: ~</p> <pre><code>RuntimeError: ERROR C42P01 Mrelation "schema_info" does not exist L221 RRangeVarGetRelid: UPDATE schema_info SET version = ?? </code></pre> <p>Thanks for your help</p> <p>Chris Knight</p>
[ { "answer_id": 91603, "author": "Jean", "author_id": 7898, "author_profile": "https://Stackoverflow.com/users/7898", "pm_score": 4, "selected": true, "text": " # Drops a PostgreSQL database\n #\n # Example:\n # drop_database 'matt_development'\n def drop_database(name) #:nodoc:\n execute \"DROP DATABASE IF EXISTS #{name}\"\n end\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91289", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11557/" ]
91,305
<p>Is there a easy way to do this? Or do I have to parse the file and do some search/replacing on my own?</p> <p>The ideal would be something like:</p> <pre><code>var myXML: XML = ???; // ... load xml data into the XML object myXML.someAttribute = newValue; </code></pre>
[ { "answer_id": 91952, "author": "Swaroop C H", "author_id": 4869, "author_profile": "https://Stackoverflow.com/users/4869", "pm_score": 5, "selected": true, "text": "@" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91305", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,307
<p>When I use quick documentaion lookup (Ctrl+Q) on j2ee classes or annotations in IDEA I only get an empty javadoc. It only contains the basics like class name.</p> <p>How do I add the javadoc to the libs IDEA provides itself?</p>
[ { "answer_id": 91514, "author": "Hugo Palma", "author_id": 17515, "author_profile": "https://Stackoverflow.com/users/17515", "pm_score": 8, "selected": true, "text": "(File -> Project Structure)" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91307", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16152/" ]
91,350
<p>Coming from a Classic ASP background, I'm used to multiple forms on a page, but this clearly limited in a ASP.NET page.</p> <p>However, I have a situation where I have a form that gathers input from the user, saves the data to a DB, and afterwards I want to render (and tweak the values of) a special form that posts to the PayPal website.</p> <p>If the PayPal form's field values were static, there would be no problem, but since I want to manipulate the form server-side (to tweak the qty, desc, price fields etc) this <em>will</em> be a problem.</p> <p>I was considering redirecting to a different page after writing to the DB, and I suspect this would work fairly well, but it's a bit of extra effort that may be unneccessary.</p> <p>It has also been suggested to me that I could programmatically render a different form, depending on where in the cycle I am. That is, use a placeholder, and on Page_Load I would add a DB Form (complete with child controls) initially, and the PayPal form after a Postback.</p> <p>This scenario has got to be a common one for you guys, so I'm looking for opinions advice and any relevant code samples if you have preferred approach.</p> <p>I know I can get by, but this project is a learning vehicle so I want to adopt what passes for best practice.</p>
[ { "answer_id": 91374, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 4, "selected": true, "text": "runat=\"server\"" }, { "answer_id": 91378, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 1, "selected": false, "text": "<form id=\"Form1\" method=\"post\" runat=\"server\">\n <div id=\"getUserInput\" visible=\"true\">\n <asp:button id=\"btnSubmitFirst\" />\n </div>\n <div id=\"doSubmissionToPaypal\" visible=\"false\">\n <asp:button id=\"btnSubmitSecond\" />\n </div>\n</form>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6898/" ]
91,355
<p>Environment: HP laptop with Windows XP SP2</p> <p>I had created some encrypted files using GnuPG (gpg) for Windows. Yesterday, my hard disk failed so I had reimage the hard disk. I have now reinstalled gpg and regenerated my keys using the same passphrase as earlier. But, I am now unable to decrypt the files. I get the following error:</p> <pre> C:\sureshr>gpg -a c:\sureshr\work\passwords.gpg gpg: encrypted with 1024-bit ELG-E key, ID 279AB302, created 2008-07-21 "Suresh Ramaswamy (AAA) BBB" gpg: decryption failed: secret key not available C:\sureshr>gpg --list-keys C:/Documents and Settings/sureshr/Application Data/gnupg\pubring.gpg -------------------------------------------------------------------- pub 1024D/80059241 2008-07-21 uid Suresh Ramaswamy (AAA) BBB sub 1024g/279AB302 2008-07-21 </pre> <p>AAA = gpg comment <br> BBB = my email address</p> <p>I am sure that I am using the correct passphrase. What exactly does this error mean? How do I tell gpg where to find my secret key?</p> <p>Thanks,</p> <p>Suresh</p>
[ { "answer_id": 91457, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "gpg --allow-secret-key-import --import <keyring>\n" }, { "answer_id": 1482670, "author": "Randy Fay", "author_id": 179638, "author_profile": "https://Stackoverflow.com/users/179638", "pm_score": 3, "selected": false, "text": "--allow-secret-key-import" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,357
<p>I want to log in to Stack Overflow with Techorati OpenID hosted at my site.</p> <p><a href="https://stackoverflow.com/users/login">https://stackoverflow.com/users/login</a> has some basic information.</p> <p>I understood that I should change</p> <pre><code>&lt;link rel="openid.delegate" href="http://yourname.x.com" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.delegate" href="http://technorati.com/people/technorati/USERNAME/" /&gt; </code></pre> <p>but if I change</p> <pre><code>&lt;link rel="openid.server" href="http://x.com/server" /&gt; </code></pre> <p>to</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/server" /&gt; </code></pre> <p>or</p> <pre><code>&lt;link rel="openid.server" href="http://technorati.com/" /&gt; </code></pre> <p>it does not work.</p>
[ { "answer_id": 91457, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 5, "selected": false, "text": "gpg --allow-secret-key-import --import <keyring>\n" }, { "answer_id": 1482670, "author": "Randy Fay", "author_id": 179638, "author_profile": "https://Stackoverflow.com/users/179638", "pm_score": 3, "selected": false, "text": "--allow-secret-key-import" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17469/" ]
91,360
<p>I need to sum points on each level earned by a tree of users. Level 1 is the sum of users' points of the users 1 level below the user. Level 2 is the Level 1 points of the users 2 levels below the user, etc...</p> <p>The calculation happens once a month on a non production server, no worries about performance.</p> <p>What would the SQL look like to do it?</p> <p>If you're confused, don't worry, I am as well!</p> <p>User table:</p> <pre><code>ID ParentID Points 1 0 230 2 1 150 3 0 80 4 1 110 5 4 54 6 4 342 Tree: 0 |---\ 1 3 | \ 2 4--- \ \ 5 6 </code></pre> <p>Output should be:</p> <pre><code>ID Points Level1 Level2 1 230 150+110 150+110+54+342 2 150 3 80 4 110 54+342 5 54 6 342 </code></pre> <p>SQL Server Syntax and functions preferably...</p>
[ { "answer_id": 91400, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 2, "selected": false, "text": "SELECT SUM(points) \nFROM users \nwhere left > x and right < y \n" }, { "answer_id": 91418, "author": "Matthias Kestenholz", "author_id": 317346, "author_profile": "https://Stackoverflow.com/users/317346", "pm_score": 1, "selected": false, "text": "SELECT id, \n SUM(value) AS value \nFROM table \nWHERE left>left\\_value\\_of\\_your\\_node \n AND right<$right\\_value\\_of\\_your\\_node;\n" }, { "answer_id": 91464, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION CALC\n(\n@node integer,\n)\nreturns \n(\n@total integer\n)\nas\nbegin\n select @total = (select node_value from yourtable where node_id = @node);\n\n declare @children table (value integer);\n insert into @children \n select calc(node_id) from yourtable where parent_id = @node;\n\n @current = @current + select sum(value) from @children;\n return\nend\n" }, { "answer_id": 91903, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "INSERT INTO relations (id, parent_id) VALUES ([current_id], [current_id]);" }, { "answer_id": 93202, "author": "Darrel Miller", "author_id": 6819, "author_profile": "https://Stackoverflow.com/users/6819", "pm_score": 1, "selected": false, "text": "WITH Parent (id, GrandParentId, parentId, Points, Level1Points, Level2Points)\nAS\n(\n -- Find root\n SELECT id, \n 0 AS GrandParentId,\n ParentId,\n Points,\n 0 AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints ptr\n WHERE ptr.ParentId = 0\n\n UNION ALL (\n -- Level2 Points\n SELECT pa.GrandParentId AS Id,\n NULL AS GrandParentId,\n NULL AS ParentId,\n 0 AS Points, \n 0 AS Level1Points,\n pa.Points AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.GrandParentId = pt.Id \n UNION ALL\n -- Level1 Points\n SELECT pt.ParentId AS Id,\n NULL AS GrandParentId,\n NULL AS ParentId,\n 0 AS Points, \n pt.Points AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL \n UNION ALL\n -- Points\n SELECT pt.id,\n pa.ParentId AS GrandParentId,\n pt.ParentId,\n pt.Points, \n 0 AS Level1Points,\n 0 AS Level2Points\n FROM tblPoints pt\n JOIN Parent pa ON pa.Id = pt.ParentId AND pa.ParentId IS NOT NULL )\n)\nSELECT id, \n SUM(Points) AS Points, \n SUM(Level1Points) AS Level1Points,\n CASE WHEN SUM(Level2Points) > 0 THEN SUM(Level1Points) + SUM(Level2Points) ELSE 0 END AS Level2Points\nFROM Parent\nGROUP BY id \nORDER by id\n" }, { "answer_id": 4429139, "author": "Stef Heyenrath", "author_id": 255966, "author_profile": "https://Stackoverflow.com/users/255966", "pm_score": 0, "selected": false, "text": "Id ParentId\n1 NULL\n11 1\n12 1\n110 11\n111 11\n112 11\n120 12\n121 12\n122 12\n123 12\n124 12\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6681/" ]
91,362
<p>How can brackets be escaped in using <code>string.Format</code>?</p> <p>For example:</p> <pre><code>String val = &quot;1,2,3&quot; String.Format(&quot; foo {{0}}&quot;, val); </code></pre> <p>This example doesn't throw an exception, but it outputs the string <code>foo {0}</code>.</p> <p>Is there a way to escape the brackets?</p>
[ { "answer_id": 91375, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 11, "selected": true, "text": " foo {1, 2, 3}" }, { "answer_id": 91385, "author": "Wolfwyrd", "author_id": 15570, "author_profile": "https://Stackoverflow.com/users/15570", "pm_score": 6, "selected": false, "text": "{{" }, { "answer_id": 15085178, "author": "Guru Kara", "author_id": 386161, "author_profile": "https://Stackoverflow.com/users/386161", "pm_score": 8, "selected": false, "text": "{" }, { "answer_id": 37077594, "author": "pomber", "author_id": 1325646, "author_profile": "https://Stackoverflow.com/users/1325646", "pm_score": 3, "selected": false, "text": "[TestMethod]\npublic void BraceEscapingTest()\n{\n var result = String.Format(\"Foo {{0}}\", \"1,2,3\"); //\"1,2,3\" is not parsed\n Assert.AreEqual(\"Foo {0}\", result);\n\n result = String.Format(\"Foo {{{0}}}\", \"1,2,3\");\n Assert.AreEqual(\"Foo {1,2,3}\", result);\n\n result = String.Format(\"Foo {0} {{bar}}\", \"1,2,3\");\n Assert.AreEqual(\"Foo 1,2,3 {bar}\", result);\n\n result = String.Format(\"{{{0:N}}}\", 24); //24 is not parsed, see @Guru Kara answer\n Assert.AreEqual(\"{N}\", result);\n\n result = String.Format(\"{0}{1:N}{2}\", \"{\", 24, \"}\");\n Assert.AreEqual(\"{24.00}\", result);\n\n result = String.Format(\"{{{0}}}\", 24.ToString(\"N\"));\n Assert.AreEqual(\"{24.00}\", result);\n}\n" }, { "answer_id": 43474880, "author": "Adam Cox", "author_id": 2250792, "author_profile": "https://Stackoverflow.com/users/2250792", "pm_score": 4, "selected": false, "text": "var json = $@\"{{\"\"name\"\":\"\"{name}\"\"}}\";\n" }, { "answer_id": 44661558, "author": "SliverNinja - MSFT", "author_id": 175679, "author_profile": "https://Stackoverflow.com/users/175679", "pm_score": 4, "selected": false, "text": "string.format" }, { "answer_id": 48081666, "author": "Aarif", "author_id": 6027876, "author_profile": "https://Stackoverflow.com/users/6027876", "pm_score": 2, "selected": false, "text": "var value = \"1, 2, 3\";\nvar output = $\" foo {{{value}}}\";\n" }, { "answer_id": 55636923, "author": "Goldfish", "author_id": 3355999, "author_profile": "https://Stackoverflow.com/users/3355999", "pm_score": 2, "selected": false, "text": "\"{CR}{LF}\"" }, { "answer_id": 58342909, "author": "Manish Kumar Gurjar", "author_id": 6265595, "author_profile": "https://Stackoverflow.com/users/6265595", "pm_score": 0, "selected": false, "text": "var inVal = \"1, 2, 3\";\nvar outVal = $\" foo {{{inVal}}}\";\n// The output will be: foo {1, 2, 3}\n" }, { "answer_id": 71252214, "author": "Mohamed Anas", "author_id": 12511391, "author_profile": "https://Stackoverflow.com/users/12511391", "pm_score": 2, "selected": false, "text": "var outVal = $\" foo {\"{\"}{inVal}{\"}\"} --- {\"{\"}Also Like This{\"}\"}\"" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4685/" ]
91,364
<p>I have a virtual machine (VMware) with Mercury Quick Test Professional 9.2 installed. I have a script to test an application, written in VB.NET using the Infragistics library.</p> <p>If I access this virtual machine using my laptop (using Remote Desktop), everything works fine, the script completes without a problem. My laptop runs XP, with Windows Classic theme.</p> <p>If I access this virtual machine using another machine (using Remote Desktop), the script starts fine, but stops halfway through, without no error message from QTP, nothing. This machine runs XP, with Windows Classic theme.</p> <p>One difference between the two setups is the size of the screen, the laptop is 1920x1280, other machine 1280x1024.</p> <p>The step where the script stops involves checking a checkbox within an UltraWinGrid. The checkbox itself is displayed, is on the screen in both cases.</p> <p>Has anyone had this problem before, or have any idea why the behaviour is different between the two machines?</p> <p>Thanks.</p>
[ { "answer_id": 125734, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 0, "selected": false, "text": "SwfTable" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91364", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1836/" ]
91,367
<p>Is there a way to debug or trace every JavaScript event in Internet&nbsp;Explorer&nbsp;7?</p> <p>I have a bug that prevents scrolling after text-selecting, and I have no idea which event or action creates the bug. I really want to see which events are being triggered when I move the mouse for example. </p> <p>It's too much work to rewire the source and I kind of hoped there was something like a sniffer which shows me all the events that are triggered.</p>
[ { "answer_id": 91410, "author": "Michiel Borkent", "author_id": 6264, "author_profile": "https://Stackoverflow.com/users/6264", "pm_score": 2, "selected": false, "text": "console.log" }, { "answer_id": 91453, "author": "Glenn", "author_id": 11814, "author_profile": "https://Stackoverflow.com/users/11814", "pm_score": 0, "selected": false, "text": "document.write" }, { "answer_id": 92331, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 4, "selected": false, "text": "var allElements = document.all; // Is this right? Anyway, you get the idea.\n\nfor (var i in allElements) {\n if (typeof allElements[i].onblur == \"function\") {\n var oldFunc = allElements[i].onblur;\n allElements[i].onblur = function() {\n alert(\"onblur called\");\n oldFunc();\n };\n }\n}\n" }, { "answer_id": 92355, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 2, "selected": false, "text": "document.all" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15981/" ]
91,368
<p>From a shell script, how do I check if a directory contains files?</p> <p>Something similar to this</p> <pre class="lang-sh prettyprint-override"><code>if [ -e /some/dir/* ]; then echo "huzzah"; fi; </code></pre> <p>but which works if the directory contains one or several files (the above one only works with exactly 0 or 1 files).</p>
[ { "answer_id": 91387, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 5, "selected": false, "text": "if [ ! -z `ls /some/dir/*` ]; then echo \"huzzah\"; fi\n" }, { "answer_id": 91394, "author": "Andrew Taylor", "author_id": 1776, "author_profile": "https://Stackoverflow.com/users/1776", "pm_score": 3, "selected": false, "text": "DIR=\"/some/dir\"\nif [ \"$(ls -A $DIR)\" ]; then\n echo 'There is something alive in here'\nfi\n" }, { "answer_id": 91403, "author": "DGM", "author_id": 14253, "author_profile": "https://Stackoverflow.com/users/14253", "pm_score": 3, "selected": false, "text": " ls -A /some/dir | wc -l\n" }, { "answer_id": 91419, "author": "Toby", "author_id": 14265, "author_profile": "https://Stackoverflow.com/users/14265", "pm_score": -1, "selected": false, "text": "if ls /some/dir/* >/dev/null 2>&1 ; then echo \"huzzah\"; fi;\n" }, { "answer_id": 91558, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 7, "selected": true, "text": "ls" }, { "answer_id": 91639, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 6, "selected": false, "text": "if find /some/dir/ -maxdepth 0 -empty | read v; then echo \"Empty dir\"; fi\n" }, { "answer_id": 91769, "author": "Gravstar", "author_id": 17381, "author_profile": "https://Stackoverflow.com/users/17381", "pm_score": 4, "selected": false, "text": "ls" }, { "answer_id": 410190, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "if find /path/to/check/* -maxdepth 0 -type f | read\n then echo \"Files Exist\"\nfi\n" }, { "answer_id": 2403078, "author": "Roland Illig", "author_id": 225757, "author_profile": "https://Stackoverflow.com/users/225757", "pm_score": 2, "selected": false, "text": "for" }, { "answer_id": 4778234, "author": "gr8can8dian", "author_id": 586929, "author_profile": "https://Stackoverflow.com/users/586929", "pm_score": 4, "selected": false, "text": "# Works on hidden files, directories and regular files\n### isEmpty()\n# This function takes one parameter:\n# $1 is the directory to check\n# Echoes \"huzzah\" if the directory has files\nfunction isEmpty(){\n if [ \"$(ls -A $1)\" ]; then\n echo \"huzzah\"\n else \n echo \"has no files\"\n fi\n}\n" }, { "answer_id": 8954828, "author": "thejartender", "author_id": 835806, "author_profile": "https://Stackoverflow.com/users/835806", "pm_score": -1, "selected": false, "text": "ls - A" }, { "answer_id": 16307494, "author": "N D", "author_id": 780180, "author_profile": "https://Stackoverflow.com/users/780180", "pm_score": -1, "selected": false, "text": "if [ -d $target_dir ]; then\n ls_contents=$(ls -1 $target_dir | xargs); \n if [ ! -z \"$ls_contents\" -a \"$ls_contents\" != \"\" ]; then\n echo \"is not empty\";\n else\n echo \"is empty\";\n fi;\nelse\n echo \"directory does not exist\";\nfi;\n" }, { "answer_id": 17902999, "author": "oHo", "author_id": 938111, "author_profile": "https://Stackoverflow.com/users/938111", "pm_score": 7, "selected": false, "text": "shopt -s nullglob dotglob; f=your/dir/*; ((${#f}))" }, { "answer_id": 25085215, "author": "bishop", "author_id": 2908724, "author_profile": "https://Stackoverflow.com/users/2908724", "pm_score": 1, "selected": false, "text": " # Bourne\n find \"$somedir\" -type f -exec echo Found unexpected file {} \\;\n find \"$somedir\" -maxdepth 0 -empty -exec echo {} is empty. \\; # GNU/BSD\n find \"$somedir\" -type d -empty -exec cp /my/configfile {} \\; # GNU/BSD\n" }, { "answer_id": 25146519, "author": "Jecht Tyre", "author_id": 3542839, "author_profile": "https://Stackoverflow.com/users/3542839", "pm_score": 0, "selected": false, "text": "ls -l <directory> | egrep -c \"^-\"\n" }, { "answer_id": 25818893, "author": "Alex", "author_id": 2498790, "author_profile": "https://Stackoverflow.com/users/2498790", "pm_score": 2, "selected": false, "text": "dir_is_empty() {\n [ \"${1##*/}\" = \"*\" ]\n}\n\nif dir_is_empty /some/dir/* ; then\n echo \"huzzah\"\nfi\n" }, { "answer_id": 28332702, "author": "jerzyjerzy", "author_id": 3459193, "author_profile": "https://Stackoverflow.com/users/3459193", "pm_score": -1, "selected": false, "text": "some_dir=\"/some/dir with whitespace & other characters/\"\nif find \"`echo \"$some_dir\"`\" -maxdepth 0 -empty | read v; then echo \"Empty dir\"; fi\n" }, { "answer_id": 29841389, "author": "Daishi", "author_id": 2003537, "author_profile": "https://Stackoverflow.com/users/2003537", "pm_score": 2, "selected": false, "text": "directory=\"/some/dir\"\nnumber_of_files=$(ls -A $directory | wc -l)\n\nif [ \"$number_of_files\" == \"0\" ]; then\n echo \"directory $directory is empty\"\nelse\n echo \"directory $directory contains $number_of_files files\"\nfi\n" }, { "answer_id": 32603647, "author": "loockass", "author_id": 4450526, "author_profile": "https://Stackoverflow.com/users/4450526", "pm_score": 1, "selected": false, "text": "files=$(ls -1 /some/dir| wc -l)\nif [ $files -gt 0 ] \nthen\n echo \"Contains files\"\nelse\n echo \"Empty\"\nfi\n" }, { "answer_id": 36041465, "author": "Laurent G", "author_id": 4693472, "author_profile": "https://Stackoverflow.com/users/4693472", "pm_score": 0, "selected": false, "text": "find \"$some_dir\" -prune -empty -type d | read && echo empty || echo \"not empty\"\n" }, { "answer_id": 36903410, "author": "Thomas Steinbach", "author_id": 1768273, "author_profile": "https://Stackoverflow.com/users/1768273", "pm_score": 0, "selected": false, "text": "if [[ $(ls /some/dir/) ]]; then echo \"huzzah\"; fi;\n" }, { "answer_id": 37342326, "author": "fedorqui", "author_id": 1983854, "author_profile": "https://Stackoverflow.com/users/1983854", "pm_score": 0, "selected": false, "text": "find" }, { "answer_id": 42857176, "author": "igiannak", "author_id": 2538200, "author_profile": "https://Stackoverflow.com/users/2538200", "pm_score": -1, "selected": false, "text": "#!/bin/bash\n\n_DIR=\"/home/user/test/\"\n#_DIR=$1\n_FIND=$(find $_DIR -type f )\nif [ -n \"$_FIND\" ]\nthen\n echo -e \"$_DIR contains files or subdirs with files \\n\\n \"\n echo \"$_FIND\"\nelse\necho \"empty (or does not exist)\"\nfi\n" }, { "answer_id": 50751686, "author": "Zorawar", "author_id": 498730, "author_profile": "https://Stackoverflow.com/users/498730", "pm_score": 2, "selected": false, "text": "foo" }, { "answer_id": 51402122, "author": "chanaka777", "author_id": 1190837, "author_profile": "https://Stackoverflow.com/users/1190837", "pm_score": 1, "selected": false, "text": "ls /some/dir | grep xml | wc -l | grep -w \"0\"" }, { "answer_id": 57086669, "author": "ForDummies", "author_id": 1422472, "author_profile": "https://Stackoverflow.com/users/1422472", "pm_score": 2, "selected": false, "text": "function isEmptyDir {\n [ -d $1 -a -n \"$( find $1 -prune -empty 2>/dev/null )\" ]\n}\n" }, { "answer_id": 66515306, "author": "Phi", "author_id": 4423190, "author_profile": "https://Stackoverflow.com/users/4423190", "pm_score": 0, "selected": false, "text": "[ \"$(cd $dir;echo *)\" = \"*\" ] && echo empty || echo non-empty\n" }, { "answer_id": 67232142, "author": "Zenexer", "author_id": 1188377, "author_profile": "https://Stackoverflow.com/users/1188377", "pm_score": 1, "selected": false, "text": "if [[ -s somedir ]]; then\n echo \"Files present\"\nfi\n" }, { "answer_id": 69463817, "author": "hh skladby", "author_id": 15979256, "author_profile": "https://Stackoverflow.com/users/15979256", "pm_score": 0, "selected": false, "text": "dir=\"/some/dir\"\n[ \"$(echo $dir/*)x\" != \"$dir/*x\" ] || [ \"$(echo $dir/.[^.]*)x\" != \"$dir/.[^.]*x\" ] || echo \"empty dir\"\n" }, { "answer_id": 72997050, "author": "Chris K", "author_id": 5128431, "author_profile": "https://Stackoverflow.com/users/5128431", "pm_score": 1, "selected": false, "text": "test" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17491/" ]
91,384
<p>I'm working on a large c++ system that is has been in development for a few years now. As part of an effort to improve the quality of the existing code we engaged on a large long-term refactoring project.</p> <p>Do you know a good tool that can help me write unit tests in C++? Maybe something similar to Junit or Nunit?</p> <p>Can anyone give some good advice on the methodology of writing unit tests for modules that were written without unit testing in mind?</p>
[ { "answer_id": 4212585, "author": "icecrime", "author_id": 451980, "author_profile": "https://Stackoverflow.com/users/451980", "pm_score": 4, "selected": false, "text": "calculator" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91384", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12818/" ]
91,413
<p>JSON text (<a href="http://www.ietf.org/rfc/rfc4627.txt?number=4627" rel="noreferrer">RFC 4627</a>) has unambigious representation of objects, arrays, strings, numbers, Boolean values (literally <code>true</code> or <code>false</code>) and <code>null</code>. However, it has nothing defined for representing time information like date and time of day, which is very common in applications. What are the current methods in use to represent time in JSON given the constraints and grammar laid out in <a href="http://www.ietf.org/rfc/rfc4627.txt?number=4627" rel="noreferrer">RFC 4627</a>?</p> <p>Note to respondents: The purpose of this question is to document the various methods known to be in circulation along with examples and relative pros and cons (ideally from field experience).</p>
[ { "answer_id": 10900081, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 3, "selected": false, "text": "Date" }, { "answer_id": 44058166, "author": "Jim DeLaHunt", "author_id": 1099571, "author_profile": "https://Stackoverflow.com/users/1099571", "pm_score": 0, "selected": false, "text": "{ \"$date\": \"2017-05-17T23:09:14.000000Z\" }" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6682/" ]
91,420
<p>I have a static library written in C++ and I have a structure describing data format, i.e.<br></p> <pre><code>struct Format{ long fmtId; long dataChunkSize; long headerSize; Format(long, long, long); bool operator==(Format const &amp; other) const; }; </code></pre> <p>Some of data formats are widely used, like <code>{fmtId=0, dataChunkSize=128, headerSize=0}</code> and <code>{fmtId=0, dataChunkSize=256, headerSize=0}</code><br><br> Some data structure classes receive format in constructor. I'd like to have some sort of shortcuts for those widely used formats, like a couple of global <code>Format</code> members <code>gFmt128, gFmt256</code> that I can pass by reference. I instantiate them in a .cpp file like </p> <p><code>Format gFmt128(0, 128, 0);</code></p> <p>and in .h there is</p> <p><code>extern Format gFmt128;</code></p> <p>also, I declare <code>Format const &amp; Format::Fmt128(){return gFmt128;}</code> and try to use it in the main module.</p> <p>But if I try and do it in the main module that uses the lib, the linker complains about unresolved external <code>gFmt128</code>.</p> <p>How can I make my library 'export' those global vars, so I can use them from other modules?</p>
[ { "answer_id": 91433, "author": "yrp", "author_id": 7228, "author_profile": "https://Stackoverflow.com/users/7228", "pm_score": 2, "selected": false, "text": "struct Format\n{\n [...]\n static Format gFmt128;\n};\n// Format.cpp\nFormat Format::gFmt128 = { 0, 128, 0 }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17481/" ]
91,443
<p>I seem to recall reading about an Amazon S3-compatible test server that you could run on your own server for unit tests or whatever. However, I've just exhausted my patience looking for this with both Google and AWS. Does such a thing exist? If not, I think I'll write one.</p> <p>Note: I'm asking about Amazon S3 (the storage system) rather than Amazon EC2 (cloud computing).</p>
[ { "answer_id": 16627235, "author": "andres.riancho", "author_id": 1347554, "author_profile": "https://Stackoverflow.com/users/1347554", "pm_score": 2, "selected": false, "text": "import boto\nfrom boto.s3.key import Key\n\nclass MyModel(object):\n def __init__(self, name, value):\n self.name = name\n self.value = value\n\n def save(self):\n conn = boto.connect_s3()\n bucket = conn.get_bucket('mybucket')\n k = Key(bucket)\n k.key = self.name\n k.set_contents_from_string(self.value)\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/893/" ]
91,479
<p>By default data extracted by the <code>GROUP BY</code> clause is ordered as ascending. How to change it to descending.</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "DESC" }, { "answer_id": 91491, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "ORDER BY foo DESC" }, { "answer_id": 97096, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 3, "selected": false, "text": "SELECT * FROM foo GROUP BY bar\n" }, { "answer_id": 3915087, "author": "Giancarlo Frison", "author_id": 473384, "author_profile": "https://Stackoverflow.com/users/473384", "pm_score": 4, "selected": false, "text": "select * \nfrom activities \ngroup by id_customer \norder by creation_date\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
91,480
<p>I would like to know where can I find the code which eclipse uses to display the forms in the plugin.xml file. In particular I am looking for the form layout used in the extension tab in the plugin.xml</p>
[ { "answer_id": 91485, "author": "RB.", "author_id": 15393, "author_profile": "https://Stackoverflow.com/users/15393", "pm_score": 3, "selected": false, "text": "DESC" }, { "answer_id": 91491, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 1, "selected": false, "text": "ORDER BY foo DESC" }, { "answer_id": 97096, "author": "Shinhan", "author_id": 18219, "author_profile": "https://Stackoverflow.com/users/18219", "pm_score": 3, "selected": false, "text": "SELECT * FROM foo GROUP BY bar\n" }, { "answer_id": 3915087, "author": "Giancarlo Frison", "author_id": 473384, "author_profile": "https://Stackoverflow.com/users/473384", "pm_score": 4, "selected": false, "text": "select * \nfrom activities \ngroup by id_customer \norder by creation_date\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17512/" ]
91,487
<p>I keep running into this problem when debugging JSP pages in OpenNMS. The Jetty wiki talks about keepGenerated (<a href="http://docs.codehaus.org/display/JETTY/KeepGenerated" rel="nofollow noreferrer">http://docs.codehaus.org/display/JETTY/KeepGenerated</a>) in webdefault.xml but it seems unclear how this works in embedded setups.</p>
[ { "answer_id": 92213, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 0, "selected": false, "text": "index.jsp" }, { "answer_id": 92233, "author": "Roel Spilker", "author_id": 12634, "author_profile": "https://Stackoverflow.com/users/12634", "pm_score": 2, "selected": false, "text": "String webApp = \"./web/myapp\"; // Location of the jsp files\nString contextPath = \"/myapp\";\nWebAppContext webAppContext = new WebAppContext(webApp, contextPath); \nServletHandler servletHandler = webAppContext.getServletHandler();\nServletHolder holder = new ServletHolder(JspServlet.class);\nservletHandler.addServletWithMapping(holder, \"*.jsp\");\nholder.setInitOrder(0);\nholder.setInitParameter(\"compiler\", \"modern\");\nholder.setInitParameter(\"fork\", \"false\");\n\nFile dir = new File(\"./web/compiled/\" + webApp);\ndir.mkdirs();\nholder.setInitParameter(\"scratchdir\", dir.getAbsolutePath());\n" }, { "answer_id": 8297734, "author": "James B", "author_id": 217850, "author_profile": "https://Stackoverflow.com/users/217850", "pm_score": 2, "selected": false, "text": "<servlet id=\"jsp\">\n ....\n <init-param>\n <param-name>keepgenerated</param-name>\n <param-value>true</param-value>\n </init-param>\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91487", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17507/" ]
91,511
<p>I have a memory buffer corresponding to my screen resolution (1280x800 at 24-bits-per-pixel) that contains my screen contents at 24bpp. I want to convert this to 8-bpp (ie. Halftone color palette in Windows). I currently do this: 1. Use CreateDIBSection to allocate a new 1280x800 24-bpp buffer and access it as a DC, as well as a plain memory buffer 2. Use memcpy to copy from my original buffer to this new buffer from step 1 3. Use BitBlt to let GDI perform the color conversion</p> <p>I want to avoid the extra memcpy of step 2. To do this, I can think of two approaches:</p> <p>a. Wrap my original mem buf in a DC to perform BitBlt directly from it</p> <p>b. Write my own 24-bpp to 8-bpp color conversion. I can't find any info on how Windows implements this halftone color conversion. Besides even if I find out, I won't be using the accelerated features of GDI that BitBlt has access to.</p> <p>So how do I do either (a) or (b)?</p> <p>thanks!</p>
[ { "answer_id": 91575, "author": "Ray Hayes", "author_id": 7093, "author_profile": "https://Stackoverflow.com/users/7093", "pm_score": 3, "selected": true, "text": "private void LockUnlockBitsExample(PaintEventArgs e)\n{\n\n // Create a new bitmap.\n Bitmap bmp = new Bitmap(\"c:\\\\fakePhoto.jpg\");\n\n // Lock the bitmap's bits. \n Rectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\n System.Drawing.Imaging.BitmapData bmpData =\n bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadWrite,\n bmp.PixelFormat);\n\n // Get the address of the first line.\n IntPtr ptr = bmpData.Scan0;\n\n // Declare an array to hold the bytes of the bitmap.\n int bytes = bmpData.Stride * bmp.Height;\n byte[] rgbValues = new byte[bytes];\n\n // Copy the RGB values into the array.\n System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);\n\n // Set every third value to 255. A 24bpp bitmap will look red. \n for (int counter = 2; counter < rgbValues.Length; counter += 3)\n rgbValues[counter] = 255;\n\n // Copy the RGB values back to the bitmap\n System.Runtime.InteropServices.Marshal.Copy(rgbValues, 0, ptr, bytes);\n\n // Unlock the bits.\n bmp.UnlockBits(bmpData);\n\n // Draw the modified image.\n e.Graphics.DrawImage(bmp, 0, 150);\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91511", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
91,518
<p>Suppose I have a simple XHTML document that uses a custom namespace for attributes:</p> <pre><code>&lt;html xmlns="..." xmlns:custom="http://www.example.com/ns"&gt; ... &lt;div class="foo" custom:attr="bla"/&gt; ... &lt;/html&gt; </code></pre> <p>How do I match each element that has a certain custom attribute using jQuery? Using</p> <pre><code>$("div[custom:attr]") </code></pre> <p>does not work. (Tried with Firefox only, so far.)</p>
[ { "answer_id": 91607, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 2, "selected": false, "text": "$('div').attr('custom:attr')" }, { "answer_id": 91807, "author": "Devon", "author_id": 13850, "author_profile": "https://Stackoverflow.com/users/13850", "pm_score": 6, "selected": true, "text": "// find all divs that have custom:attr\n$('div').filter(function() { return $(this).attr('custom:attr'); }).each(function() {\n // matched a div with custom::attr\n $(this).html('I was found.');\n});\n" }, { "answer_id": 2184474, "author": "Fyrd", "author_id": 193099, "author_profile": "https://Stackoverflow.com/users/193099", "pm_score": 4, "selected": false, "text": "$(\"div[custom\\\\:attr]\")" }, { "answer_id": 2927811, "author": "Suphi Basdemir", "author_id": 352737, "author_profile": "https://Stackoverflow.com/users/352737", "pm_score": 3, "selected": false, "text": "$(\"div[customattr=bla]\")" }, { "answer_id": 10015279, "author": "Katie Kilian", "author_id": 645511, "author_profile": "https://Stackoverflow.com/users/645511", "pm_score": 2, "selected": false, "text": "// Custom jQuery selector to select on custom namespaced attributes\n$.expr[':'].nsAttr = function(obj, index, meta, stack) {\n\n // if the parameter isn't a string, the selector is invalid, \n // so always return false.\n if ( typeof meta[3] != 'string' )\n return false;\n\n // if the parameter doesn't have an '=' character in it, \n // assume it is an attribute name with no value, \n // and match all elements that have only that attribute name.\n if ( meta[3].indexOf('=') == -1 )\n {\n var val = $(obj).attr(meta[3]);\n return (typeof val !== 'undefined' && val !== false);\n }\n // if the parameter does contain an '=' character, \n // we should only match elements that have an attribute \n // with a matching name and value.\n else\n {\n // split the parameter into name/value pairs\n var arr = meta[3].split('=', 2);\n var attrName = arr[0];\n var attrValue = arr[1];\n\n // if the current object has an attribute matching the specified \n // name & value, include it in our selection.\n return ( $(obj).attr(attrName) == attrValue );\n }\n};\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7779/" ]
91,521
<p>I am using c# 2005 i want to write string diagonally on image. But by default c# provides the option to write horizontally or vertically.</p> <p>how we write diagonally?</p> <p>Thanks</p>
[ { "answer_id": 91542, "author": "Phil Wright", "author_id": 6276, "author_profile": "https://Stackoverflow.com/users/6276", "pm_score": 3, "selected": false, "text": "g.RotateTransform(45f);\ng.DrawString(\"My String\"...);\ng.RotateTransform(-45f);\n" }, { "answer_id": 16771661, "author": "a d", "author_id": 1661105, "author_profile": "https://Stackoverflow.com/users/1661105", "pm_score": 1, "selected": false, "text": " void DrawDigonalString(Graphics G, string S, Font F, Brush B, PointF P, int Angle)\n {\n SizeF MySize = G.MeasureString(S, F);\n G.TranslateTransform(P.X + MySize.Width / 2, P.Y + MySize.Height / 2);\n G.RotateTransform(Angle);\n G.DrawString(S, F, B, new PointF(-MySize.Width / 2, -MySize.Height / 2));\n G.RotateTransform(-Angle);\n G.TranslateTransform(-P.X - MySize.Width / 2, -P.Y- MySize.Height / 2);\n }\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91521", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
91,563
<p>How can I make this work?</p> <pre><code>switch(property.PropertyType){ case typeof(Boolean): //doStuff break; case typeof(String): //doOtherStuff break; default: break; } </code></pre> <p>I don't want to use the name since string comparing for types is just awfull and can be subject to change.</p>
[ { "answer_id": 91591, "author": "Sam Meldrum", "author_id": 16005, "author_profile": "https://Stackoverflow.com/users/16005", "pm_score": 0, "selected": false, "text": "if(property.PropertyType == typeof(bool)) {\n //dostuff;\n}\nelse if (property.PropertyType == typeof(string)) {\n //do other stuff;\n}\n" }, { "answer_id": 91594, "author": "user17527", "author_id": 17527, "author_profile": "https://Stackoverflow.com/users/17527", "pm_score": -1, "selected": false, "text": "if (property.PropertyType == typeof(Boolean))\n{\n} \nelse if (property.PropertyType == typeof(String))\n{\n}\nelse if (...)\n{\n}\n" }, { "answer_id": 91597, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 7, "selected": true, "text": " System.Type propertyType = typeof(Boolean);\n System.TypeCode typeCode = Type.GetTypeCode(propertyType);\n switch (typeCode)\n {\n case TypeCode.Boolean:\n //doStuff\n break;\n case TypeCode.String:\n //doOtherStuff\n break;\n default: break;\n }\n" }, { "answer_id": 91609, "author": "Paul van Brenk", "author_id": 1837197, "author_profile": "https://Stackoverflow.com/users/1837197", "pm_score": 2, "selected": false, "text": "var TypeMapping = new Dictionary<Type, Action<string>>(){\n {typeof(string), (x)=>Console.WriteLine(\"string\")},\n {typeof(bool), (x)=>Console.WriteLine(\"bool\")}\n};\n\n\n\nstring s = \"my string\";\n\nTypeMapping[s.GetType()](\"foo\");\nTypeMapping[true.GetType()](\"true\");\n" }, { "answer_id": 91614, "author": "xan", "author_id": 15667, "author_profile": "https://Stackoverflow.com/users/15667", "pm_score": 0, "selected": false, "text": "if(property.PropertyType is bool){\n //dostuff;\n}\nelse if (property.PropertyType is string){\n //do other stuff;\n}\n" }, { "answer_id": 91615, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "private delegate object MyDelegate();\n\nprivate IDictionary<Type, MyDelegate> functionMap = new IDictionary<Type, MyDelegate>();\n\npublic Init()\n{\n functionMap.Add(typeof(String), someFunction);\n functionMap.Add(tyepof(Boolean), someOtherFunction);\n}\n\npublic T doStuff<T>(Type someType)\n{\n return (T)functionMap[someType]();\n}\n" }, { "answer_id": 91711, "author": "timvw", "author_id": 15267, "author_profile": "https://Stackoverflow.com/users/15267", "pm_score": -1, "selected": false, "text": "Dictionary<Type, other>" }, { "answer_id": 41089461, "author": "Krzysztof Branicki", "author_id": 5297231, "author_profile": "https://Stackoverflow.com/users/5297231", "pm_score": 2, "selected": false, "text": "switch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"<unknown shape>\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
91,576
<p>I'm building a project using a GNU tool chain and everything works fine until I get to linking it, where the linker complains that it is missing/can't find <code>crti.o</code>. This is not one of my object files, it seems to be related to libc but I can't understand why it would need this <code>crti.o</code>, wouldn't it use a library file, e.g. <code>libc.a</code>?</p> <p>I'm cross compiling for the arm platform. I have the file in the toolchain, but how do I get the linker to include it? </p> <p><code>crti.o</code> is on one of the 'libraries' search path, but should it look for <code>.o</code> file on the library path? </p> <p>Is the search path the same for <code>gcc</code> and <code>ld</code>?</p>
[ { "answer_id": 91595, "author": "stsquad", "author_id": 17507, "author_profile": "https://Stackoverflow.com/users/17507", "pm_score": 6, "selected": true, "text": "crti.o" }, { "answer_id": 7837638, "author": "Rob Fisher", "author_id": 991411, "author_profile": "https://Stackoverflow.com/users/991411", "pm_score": 1, "selected": false, "text": "/home/rob/compiler/usr/bin/arm-linux-gcc --sysroot=/home/rob/compiler hello.c\n" }, { "answer_id": 25900752, "author": "FractalSpace", "author_id": 175169, "author_profile": "https://Stackoverflow.com/users/175169", "pm_score": 0, "selected": false, "text": "export LDFLAGS='--sysroot=/home/me/<path-to-my-sysroot-parent>/sysroot'\n" }, { "answer_id": 40129998, "author": "Eugen Konkov", "author_id": 4632019, "author_profile": "https://Stackoverflow.com/users/4632019", "pm_score": 3, "selected": false, "text": "Linux Mint 18.0/Ubuntu 16.04" }, { "answer_id": 59244724, "author": "Surajit Sinha", "author_id": 5521476, "author_profile": "https://Stackoverflow.com/users/5521476", "pm_score": 1, "selected": false, "text": "export LDFLAGS=\"\"--sysroot=${SDKTARGETSYSROOT}\" -L${SDKTARGETSYSROOT}/lib -L${SDKTARGETSYSROOT}/usr/lib -L${SDKTARGETSYSROOT}/usr/lib/arm-poky-linux-gnueabi/5.3.0\"\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91576", "https://Stackoverflow.com", "https://Stackoverflow.com/users/76121/" ]
91,585
<p>I'm one of the people involved in the <a href="http://testanything.org/wiki/index.php/TAP_at_IETF:_Notes" rel="noreferrer">Test Anything Protocol (TAP) IETF group</a> (if interested, feel free to join the mailing list). Many programming languages are starting to adopt TAP as their primary testing protocol and they want more from it than what we currently offer. As a result, we'd like to get feedback from people who have a background in xUnit, TestNG or any other testing framework/methodology.</p> <p>Basically, aside from a simple pass/fail, what information do you need from a test harness? Just to give you some examples:</p> <ul> <li>Filename and line number (if applicable) </li> <li>Start and end time</li> <li>Diagnostic output such as the difference between what you got and what you expected.</li> </ul> <p>And so on ...</p>
[ { "answer_id": 27824043, "author": "Erik Aronesty", "author_id": 627042, "author_profile": "https://Stackoverflow.com/users/627042", "pm_score": 0, "selected": false, "text": "1..4\nok 1 - yay\nnot ok 2 - boo\nok 3 - yay #json:{...}\nok 4 - see my json\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8003/" ]
91,617
<p>I am looking for a tool that can take a unit test, like </p> <pre><code>IPerson p = new Person(); p.Name = "Sklivvz"; Assert.AreEqual("Sklivvz", p.Name); </code></pre> <p>and generate, automatically, the corresponding stub class and interface</p> <pre><code>interface IPerson // inferred from IPerson p = new Person(); { string Name { get; // inferred from Assert.AreEqual("Sklivvz", p.Name); set; // inferred from p.Name = "Sklivvz"; } } class Person: IPerson // inferred from IPerson p = new Person(); { private string name; // inferred from p.Name = "Sklivvz"; public string Name // inferred from p.Name = "Sklivvz"; { get { return name; // inferred from Assert.AreEqual("Sklivvz", p.Name); } set { name = value; // inferred from p.Name = "Sklivvz"; } } public Person() // inferred from IPerson p = new Person(); { } } </code></pre> <p>I know ReSharper and Visual Studio do some of these, but I need a complete tool -- command line or whatnot -- that automatically infers what needs to be done. If there is no such tool, how would you write it (e.g. extending ReSharper, from scratch, using which libraries)?</p>
[ { "answer_id": 93321, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": -1, "selected": false, "text": "public string Name { get; set; }\n" }, { "answer_id": 9969981, "author": "Ira Baxter", "author_id": 120163, "author_profile": "https://Stackoverflow.com/users/120163", "pm_score": 3, "selected": true, "text": " IPerson p = new Person();\n" }, { "answer_id": 10064880, "author": "Jordão", "author_id": 31158, "author_profile": "https://Stackoverflow.com/users/31158", "pm_score": 1, "selected": false, "text": "dynamic p = someFactory.Create(\"MyNamespace.Person\");\np.Name = \"Sklivvz\";\nAssert.AreEqual(\"Sklivvz\", p.Name);\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91617", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7028/" ]
91,618
<p>In static languages like Java you need interfaces because otherwise the type system just won't let you do certain things. But in dynamic languages like PHP and Python you just take advantage of <em>duck-typing</em>.</p> <p>PHP supports interfaces. Ruby and Python don't have them. So you can clearly live happily without them.</p> <p>I've been mostly doing my work in PHP and have never really made use of the ability to define interfaces. When I need a set of classes to implement certain common interface, then I just describe it in documentation.</p> <p>So, what do you think? Aren't you better off without using interfaces in dynamic languages at all?</p>
[ { "answer_id": 91687, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 2, "selected": false, "text": "pass" }, { "answer_id": 92183, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 1, "selected": false, "text": "class InterfaceLikeThing( object ):\n def __init__( self, arg ):\n self.attr= None\n self.otherAttr= arg\n def aMethod( self ):\n raise NotImplementedError\n def anotherMethod( self ):\n return NotImplemented\n" }, { "answer_id": 92420, "author": "Robert Sanders", "author_id": 16952, "author_profile": "https://Stackoverflow.com/users/16952", "pm_score": 3, "selected": false, "text": "object.respond_to? :sync\n" }, { "answer_id": 101437, "author": "wbg", "author_id": 18763, "author_profile": "https://Stackoverflow.com/users/18763", "pm_score": 0, "selected": false, "text": "file_interface = ('read', 'readline', 'seek')\n\nclass InterfaceException(Exception): pass\n\ndef implements_interface(obj, interface):\n d = dir(obj)\n for item in interface:\n if item not in d: raise InterfaceException(\"%s not implemented.\" % item)\n return True\n\n>>> import StringIO\n>>> s = StringIO.StringIO()\n>>> implements_interface(s, file_interface)\nTrue\n>>> \n>>> fp = open('/tmp/123456.temp', 'a') \n>>> implements_interface(fp, file_interface)\nTrue\n>>> fp.close()\n>>> \n>>> d = {}\n>>> implements_interface(d, file_interface)\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"<stdin>\", line 4, in implements_interface\n__main__.InterfaceException: read not implemented.\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91618", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15982/" ]
91,628
<p>I would like to automatically increment a field named `incrementID' anytime any field in any row within the table named 'tb_users' is updated. Currently I am doing it via the sql update statement. i.e "UPDATE tb_users SET name = @name, incrementID = incrementID + 1 .....WHERE id = @id;</p> <p>I'm wondering how I can do this automatically. for example, by changing the way sql server treats the field - kind of like the increment setting of 'Identity'. Before I update a row, I wish to check whether the incrementID of the object to be updated is different to the incrementID of the row of the db.</p>
[ { "answer_id": 92442, "author": "Mike Dimmick", "author_id": 6970, "author_profile": "https://Stackoverflow.com/users/6970", "pm_score": 2, "selected": false, "text": "rowversion" }, { "answer_id": 92505, "author": "TrevorD", "author_id": 12492, "author_profile": "https://Stackoverflow.com/users/12492", "pm_score": 3, "selected": true, "text": "create trigger update_increment for update as\nif not update(incrementID) \n UPDATE tb_users SET incrementID = incrementID + 1 \n from inserted WHERE tb_users.id = inserted.id\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17510/" ]
91,629
<p>I'm trying to match elements with a name that is <code>'container1$container2$chkChecked'</code>, using a regex of <code>'.+\$chkChecked'</code>, but I'm not getting the matches I expect when the element name is as described. What am I doing wrong?</p>
[ { "answer_id": 91647, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 2, "selected": false, "text": "string.match( /[$]chkChecked$/ ) \n" }, { "answer_id": 91724, "author": "Steven Noble", "author_id": 10393, "author_profile": "https://Stackoverflow.com/users/10393", "pm_score": 3, "selected": true, "text": "re = new RegExp('.+\\$chkChecked');\n" }, { "answer_id": 91811, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 2, "selected": false, "text": "'" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
91,635
<p>I am considering using Postsharp framework to ease the burden of application method logging. It basically allows me to adorn methods with logging attribute and at compile time injects the logging code needed into the il. I like this solution as it keeps the noise out of the deign time code environment. Any thoughts, experiences or better alternatives?</p>
[ { "answer_id": 91659, "author": "Chris Canal", "author_id": 5802, "author_profile": "https://Stackoverflow.com/users/5802", "pm_score": 4, "selected": true, "text": "namespace Tools.CastleWindsor.Interceptors\n{\nusing System;\nusing System.Text;\nusing Castle.Core.Interceptor;\nusing Castle.Core.Logging;\n\npublic abstract class AbstractLoggingInterceptor : IInterceptor\n{\n protected readonly ILoggerFactory logFactory;\n\n protected AbstractLoggingInterceptor(ILoggerFactory logFactory)\n {\n this.logFactory = logFactory;\n }\n\n public virtual void Intercept(IInvocation invocation)\n {\n ILogger logger = logFactory.Create(invocation.TargetType);\n\n try\n {\n StringBuilder sb = null;\n\n if (logger.IsDebugEnabled)\n {\n sb = new StringBuilder(invocation.TargetType.FullName).AppendFormat(\".{0}(\", invocation.Method);\n\n for (int i = 0; i < invocation.Arguments.Length; i++)\n {\n if (i > 0)\n sb.Append(\", \");\n\n sb.Append(invocation.Arguments[i]);\n }\n\n sb.Append(\")\");\n\n logger.Debug(sb.ToString());\n }\n\n invocation.Proceed();\n\n if (logger.IsDebugEnabled && invocation.ReturnValue != null)\n {\n logger.Debug(\"Result of \" + sb + \" is: \" + invocation.ReturnValue);\n }\n }\n catch (Exception e)\n {\n logger.Error(string.Empty, e);\n throw;\n }\n }\n}\n}\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91635", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6440/" ]
91,672
<p>In an application where users can belong to multiple groups, I'm currently storing their groups in a column called <code>groups</code> as a binary. Every four bytes is a 32 bit integer which is the <code>GroupID</code>. However, this means that to enumerate all the users in a group I have to programatically select all users, and manually find out if they contain that group.</p> <p>Another method was to use a unicode string, where each character is the integer denoting a group, and this makes searching easy, but is a bit of a fudge.</p> <p>Another method is to create a separate table, linking users to groups. One column called <code>UserID</code> and another called <code>GroupID</code>.</p> <p>Which of these ways would be the best to do it? Or is there a better way?</p>
[ { "answer_id": 91702, "author": "JacquesB", "author_id": 7488, "author_profile": "https://Stackoverflow.com/users/7488", "pm_score": 4, "selected": true, "text": "User: (UserId[PrimaryKey], UserName etc.)\nGroup: (GroupId[PrimaryKey], GroupName etc.)\nUserInGroup: (UserId[ForeignKey], GroupId[ForeignKey])\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16299/" ]
91,678
<p>My Tomcat instance is listening to multiple IP addresses, but I want to control which source IP address is used when opening a <code>URLConnection</code>. </p> <p>How can I specify this?</p>
[ { "answer_id": 92124, "author": "Javaxpert", "author_id": 15241, "author_profile": "https://Stackoverflow.com/users/15241", "pm_score": 4, "selected": true, "text": "URL url = new URL(yourUrlHere);\nProxy proxy = new Proxy(Proxy.Type.DIRECT, \n new InetSocketAddress( \n InetAddress.getByAddress(\n new byte[]{your, ip, interface, here}), yourTcpPortHere));\nURLConnection conn = url.openConnection(proxy);\n" }, { "answer_id": 93213, "author": "stian", "author_id": 17542, "author_profile": "https://Stackoverflow.com/users/17542", "pm_score": 2, "selected": false, "text": "HostConfiguration hostConfiguration = new HostConfiguration();\nbyte b[] = new byte[4];\nb[0] = new Integer(192).byteValue();\nb[1] = new Integer(168).byteValue();\nb[2] = new Integer(1).byteValue();\nb[3] = new Integer(11).byteValue();\n\nhostConfiguration.setLocalAddress(InetAddress.getByAddress(b));\n\nHttpClient client = new HttpClient();\nclient.setHostConfiguration(hostConfiguration);\nGetMethod method = new GetMethod(\"http://remoteserver/\");\nmethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,\n new DefaultHttpMethodRetryHandler(3, false));\nint statusCode = client.executeMethod(method);\n\nif (statusCode != HttpStatus.SC_OK) {\n System.err.println(\"Method failed: \" + method.getStatusLine());\n}\n\nbyte[] responseBody = method.getResponseBody();\nSystem.out.println(new String(responseBody));\");\n" }, { "answer_id": 17530095, "author": "Enzo", "author_id": 2561264, "author_profile": "https://Stackoverflow.com/users/2561264", "pm_score": 0, "selected": false, "text": "private HttpsURLConnection openConnection(URL src, URL dest, SSLContext sslContext)\n throws IOException, ProtocolException {\n HttpsURLConnection connection = (HttpsURLConnection) dest.openConnection();\n HttpsHostNameVerifier httpsHostNameVerifier = new HttpsHostNameVerifier();\n connection.setHostnameVerifier(httpsHostNameVerifier);\n connection.setConnectTimeout(CONNECT_TIMEOUT);\n connection.setReadTimeout(READ_TIMEOUT);\n connection.setRequestMethod(POST_METHOD);\n connection.setRequestProperty(CONTENT_TYPE, SoapConstants.CONTENT_TYPE_HEADER);\n connection.setDoOutput(true);\n connection.setDoInput(true);\n connection.setSSLSocketFactory(sslContext.getSocketFactory());\n if ( src!=null ) {\n InetAddress inetAddress = InetAddress.getByName(src.getHost());\n int destPort = dest.getPort();\n if ( destPort <=0 ) \n destPort=SERVER_HTTPS_PORT;\n int srcPort = src.getPort();\n if ( srcPort <=0 ) \n srcPort=CLIENT_HTTPS_PORT;\n connectionSocket = connection.getSSLSocketFactory().createSocket(dest.getHost(), destPort, inetAddress, srcPort);\n }\n connection.connect();\n return connection;\n} \n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17542/" ]
91,692
<p>Can anyone recommend a framework for templating/formatting messages in a standalone application along the lines of the JSP EL (Expression Language)?</p> <p>I would expect to be able to instantiate a an object of some sort, give it a template along the lines of</p> <pre><code>Dear ${customer.firstName}. You order will be dispatched on ${order.estimatedDispatchDate} </code></pre> <p>provide it with a context which would include a value dictionary of parameter objects (in this case an object of type Customer with a name 'customer', say, and an object of type Order with a name 'order').</p> <p>I know there are many template frameworks out there - many of which work outside the web application context, but I do not see this as a big heavyweight templating framework. Just a better version of the basic Message Format functionality Java already provides </p> <p>For example, I can accomplish the above with java.text.MessageFormat by using a template (or a 'pattern' as they call it) such as</p> <pre><code>Dear {0}. You order will be dispatched on {1,date,EEE dd MMM yyyy} </code></pre> <p>and I can pass it an Object array, in my calling Java program</p> <pre><code>new Object[] { customer.getFirstName(), order.getEstimatedDispatchDate() }; </code></pre> <p>However, in this usage, the code and the pattern are intimately linked. While I could put the pattern in a resource properties file, the code and the pattern need to know intimate details about each other. With an EL-like system, the contract between the code and the pattern would be at a much higher level (e.g. customer and order, rather then customer.firstName and order.estimatedDispatchDate), making it easier to change the structure, order and contents of the message without changing any code.</p>
[ { "answer_id": 133028, "author": "Vihung", "author_id": 15452, "author_profile": "https://Stackoverflow.com/users/15452", "pm_score": 0, "selected": false, "text": "Dear {0}. Your order will be dispatched on {1,date,EEE dd MMM yyyy}\n" }, { "answer_id": 28663050, "author": "yglodt", "author_id": 272180, "author_profile": "https://Stackoverflow.com/users/272180", "pm_score": 2, "selected": false, "text": "int year = (Integer) parser.parseExpression(\"Birthdate.Year + 1900\").getValue(context);\n\nString city = (String) parser.parseExpression(\"placeOfBirth.City\").getValue(context);\n\n// weekday is a String, e.g. \"Mon\", time is an int, e.g. 1400 or 900\n{\"Thu\", \"Fri\"}.contains(weekday) and time matches '\\d{4}'\n" } ]
2008/09/18
[ "https://Stackoverflow.com/questions/91692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15452/" ]