qid
int64
question
string
answers
list
date
string
metadata
list
24,528
<p>I'm curious to hear the experiences of those who are currently running their SVN server on Windows. </p> <p>Jeff Atwood has a post on <a href="https://blog.codinghorror.com/setting-up-subversion-on-windows/" rel="nofollow noreferrer">how to setup SVN as a Windows service</a>. It's a great first step, but it doesn't touch on other topics, such as:</p> <ul> <li>What to use for a web-based repository browser? <a href="http://websvn.tigris.org/" rel="nofollow noreferrer">WebSVN</a> <em>can</em> work on Windows, but it ain't pretty.</li> <li>How to manage the passwd file?</li> <li>Is it possible to integrate with Active Directory without running Apache?</li> <li>Strategies for backing up the repository.</li> <li>Useful global ignore patterns for Visual Studio development (suggestions <a href="http://blog.jasonhoekstra.com/2008/07/useful-net-subversion-global-ignore.html" rel="nofollow noreferrer">here</a>, <a href="http://www.thushanfernando.com/?p=12" rel="nofollow noreferrer">here</a>, and <a href="http://blog.donnfelker.com/2007/08/10/SubVersionTortoiseSVNGlobalIgnorePattern.aspx" rel="nofollow noreferrer">here</a> for example).</li> </ul> <p>Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world.</p>
[ { "answer_id": 24564, "author": "Portman", "author_id": 1690, "author_profile": "https://Stackoverflow.com/users/1690", "pm_score": 2, "selected": false, "text": "Repo 1: 652 files, 273 directories, 60.1MB\n 23 seconds for VisualSVN over http:// \n 16 seconds for SVN over svn://\n\nRepo 2: 4623 files, 964 directories, 127.9MB\n 2 minutes, 18 seconds for VisualSVN over http://\n 1 minute, 30 seconds for SVN over svn://\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24528", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1690/" ]
24,542
<p>Is there any reason not to use the bitwise operators &amp;, |, and ^ for "bool" values in C++? </p> <p>I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use &amp; and |. I also need to accumulate Boolean values sometimes, and &amp;= and |= can be quite useful.</p> <p>I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?</p>
[ { "answer_id": 24560, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 7, "selected": true, "text": "|| && true false | & ^ BOOL two = 2;\nBOOL one = 1;\nBOOL and = two & one; //and = 0\nBOOL cand = two && one; //cand = 1\n bool true false 1 0 b = b && x" }, { "answer_id": 25220, "author": "genix", "author_id": 2714, "author_profile": "https://Stackoverflow.com/users/2714", "pm_score": 2, "selected": false, "text": "bool onlyAIsTrue = (a && !b); // you could use bitwise XOR here\nbool onlyBIsTrue = (b && !a); // and not need this second line\nif (onlyAIsTrue || onlyBIsTrue)\n{\n .. stuff ..\n}\n" }, { "answer_id": 33801, "author": "Mark Borgerding", "author_id": 3343, "author_profile": "https://Stackoverflow.com/users/3343", "pm_score": 4, "selected": false, "text": "a != b\n" }, { "answer_id": 33995, "author": "Patrick Johnmeyer", "author_id": 363, "author_profile": "https://Stackoverflow.com/users/363", "pm_score": 5, "selected": false, "text": "false true 0 1 ^ int one = 1;\nint two = 2;\n\n// bitwise xor\nif (one ^ two)\n{\n // executes because expression = 3 and any non-zero integer evaluates to true\n}\n\n// logical xor; more correctly would be coded as\n// if (bool(one) != bool(two))\n// but spelled out to be explicit in the context of the problem\nif ((one && !two) || (!one && two))\n{\n // does not execute b/c expression = ((true && false) || (false && true))\n // which evaluates to false\n}\n | & ^ bool result = true;\nresult = result && a() && b();\n// will not call a() if result false, will not call b() if result or a() false\n bool result = true;\nresult &= (a() & b());\n// a() and b() both will be called, but not necessarily in that order in an\n// optimizing compiler\n a() b()" }, { "answer_id": 69680, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 2, "selected": false, "text": "^^ ^^ bool 1 & 2 1 && 2 GetMessage() BOOL 0 -1 & && | ||" }, { "answer_id": 13986306, "author": "Cheers and hth. - Alf", "author_id": 464581, "author_profile": "https://Stackoverflow.com/users/464581", "pm_score": 3, "selected": false, "text": "& | ^ ! && || bool 0 1 not and or bitand bitor xor compl and or not 1 & 2 0 1 && 2 true ^ true a && b ^ c\n a && (b ^ c) (a && b) != c\n a ^ b ^ c a b c a b c a b c bool (a + b + c) == 1\n bool bool (!!a + !!b + !!c) == 1\n &= &= |=? *= &&= struct Bool\n{\n bool value;\n\n void operator&=( bool const v ) { value = value && v; }\n operator bool() const { return value; }\n};\n\n#include <iostream>\n\nint main()\n{\n using namespace std;\n\n Bool a = {true};\n a &= true || false;\n a &= 1234;\n cout << boolalpha << a << endl;\n\n bool b = {true};\n b &= true || false;\n b &= 1234;\n cout << boolalpha << b << endl;\n}\n &= bool &= true" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891/" ]
24,546
<p>I'm trying to fetch Wikipedia pages using <a href="http://search.cpan.org/dist/libwww-perl" rel="noreferrer">LWP::Simple</a>, but they're not coming back. This code:</p> <pre><code>#!/usr/bin/perl use strict; use LWP::Simple; print get("http://en.wikipedia.org/wiki/Stack_overflow"); </code></pre> <p>doesn't print anything. But if I use some other webpage, say <code><a href="http://www.google.com" rel="noreferrer">http://www.google.com</a></code>, it works fine. </p> <p>Is there some other name that I should be using to refer to Wikipedia pages? </p> <p>What could be going on here?</p>
[ { "answer_id": 24574, "author": "Jesse Beder", "author_id": 112, "author_profile": "https://Stackoverflow.com/users/112", "pm_score": 5, "selected": true, "text": "#!/usr/bin/perl\nuse strict;\nuse LWP::UserAgent;\n\nmy $url = \"http://en.wikipedia.org/wiki/Stack_overflow\";\n\nmy $ua = LWP::UserAgent->new();\nmy $res = $ua->get($url);\n\nprint $res->content;\n" }, { "answer_id": 73107, "author": "zigdon", "author_id": 4913, "author_profile": "https://Stackoverflow.com/users/4913", "pm_score": 4, "selected": false, "text": "use LWP::Simple qw/get $ua/;\n$ua->agent(\"WikiBot/0.1\");\nprint get(\"http://en.wikipedia.org/wiki/Stack_overflow\");\n" }, { "answer_id": 13192749, "author": "Samed Konak", "author_id": 1792543, "author_profile": "https://Stackoverflow.com/users/1792543", "pm_score": 3, "selected": false, "text": "LWP:RobotUA LWP::UserAgent" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/112/" ]
24,551
<p>I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields.</p> <p>Should I do it at declaration?:</p> <pre><code>public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() { // ...... } } </code></pre> <p>or in a constructor?:</p> <pre><code>public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { // ..... } } </code></pre> <p>I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.</p>
[ { "answer_id": 24558, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 9, "selected": true, "text": "null false 0 0.0" }, { "answer_id": 32011236, "author": "Miroslav Holec", "author_id": 794117, "author_profile": "https://Stackoverflow.com/users/794117", "pm_score": 3, "selected": false, "text": "public class CsvFile\n{\n private List<CsvRow> lines = new List<CsvRow>();\n\n public CsvFile()\n {\n }\n}\n public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = new List<string>() {\"usernameA\", \"usernameB\"};\n }\n}\n public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = GetDefaultUsers(2);\n }\n}\n public class AdminTeam\n{\n private List<string> usernames = new List<string>();\n\n public AdminTeam()\n {\n }\n\n public AdminTeam(List<string> admins)\n {\n admins.ForEach(x => usernames.Add(x));\n }\n}\n" }, { "answer_id": 51232030, "author": "user1451111", "author_id": 1451111, "author_profile": "https://Stackoverflow.com/users/1451111", "pm_score": 0, "selected": false, "text": "class MyGeneric<T>\n{\n T data;\n //T data = \"\"; // <-- ERROR\n //T data = 0; // <-- ERROR\n //T data = null; // <-- ERROR \n\n public MyGeneric()\n {\n // All of the above errors would be errors here in constructor as well\n }\n}\n class MyGeneric<T>\n{\n T data = default(T);\n\n public MyGeneric()\n { \n // The same method can be used here in constructor\n }\n}\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24551", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2635/" ]
24,556
<p>In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it?</p> <p>A little context if it helps...</p> <p>I have this code in my <code>global.asax</code> as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the <code>Member</code> object in the same unit of work where it was created.</p> <pre><code>private void CheckCurrentUser() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember != null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation); } </code></pre>
[ { "answer_id": 24558, "author": "kokos", "author_id": 1065, "author_profile": "https://Stackoverflow.com/users/1065", "pm_score": 9, "selected": true, "text": "null false 0 0.0" }, { "answer_id": 32011236, "author": "Miroslav Holec", "author_id": 794117, "author_profile": "https://Stackoverflow.com/users/794117", "pm_score": 3, "selected": false, "text": "public class CsvFile\n{\n private List<CsvRow> lines = new List<CsvRow>();\n\n public CsvFile()\n {\n }\n}\n public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = new List<string>() {\"usernameA\", \"usernameB\"};\n }\n}\n public class AdminTeam\n{\n private List<string> usernames;\n\n public AdminTeam()\n {\n usernames = GetDefaultUsers(2);\n }\n}\n public class AdminTeam\n{\n private List<string> usernames = new List<string>();\n\n public AdminTeam()\n {\n }\n\n public AdminTeam(List<string> admins)\n {\n admins.ForEach(x => usernames.Add(x));\n }\n}\n" }, { "answer_id": 51232030, "author": "user1451111", "author_id": 1451111, "author_profile": "https://Stackoverflow.com/users/1451111", "pm_score": 0, "selected": false, "text": "class MyGeneric<T>\n{\n T data;\n //T data = \"\"; // <-- ERROR\n //T data = 0; // <-- ERROR\n //T data = null; // <-- ERROR \n\n public MyGeneric()\n {\n // All of the above errors would be errors here in constructor as well\n }\n}\n class MyGeneric<T>\n{\n T data = default(T);\n\n public MyGeneric()\n { \n // The same method can be used here in constructor\n }\n}\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24556", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2595/" ]
24,579
<p>Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app?</p>
[ { "answer_id": 348596, "author": "Tim Knight", "author_id": 43043, "author_profile": "https://Stackoverflow.com/users/43043", "pm_score": 3, "selected": false, "text": "before_save details details_html before_save :convert_details\n\ndef convert_details\n return if self.details.nil?\n self.details_html = RedCloth.new(self.details).to_html\nend\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24579", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
24,580
<p>How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?</p>
[ { "answer_id": 24583, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "msbuild" }, { "answer_id": 24584, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 5, "selected": false, "text": "\\Windows\\Microsoft.NET\\Framework\\[YOUR .NET VERSION]\\msbuild.exe\n msbuild.exe yoursln.sln\n" }, { "answer_id": 24601, "author": "Sam Hasler", "author_id": 2541, "author_profile": "https://Stackoverflow.com/users/2541", "pm_score": 1, "selected": false, "text": "BuildLog.htm Creating temporary file \"c:\\some\\path\\RSP00003C.rsp\" with contents\n[\n/D \"WIN32\" /D \"_WINDOWS\" /D \"STRICT\" /D \"NDEBUG\" ..... (lots of other switches)\n.\\Project.cpp\n.\\Another.cpp\n.\\AndAnother.cpp\n\".\\And Yet Another.cpp\"\n]\nCreating command line \"cl.exe @c:\\some\\path\\RSP00003C.rsp /nologo\"\n BuildLog.htm cl.exe @autobuild01.rsp /nologo\n" }, { "answer_id": 34063, "author": "Agnel Kurian", "author_id": 45603, "author_profile": "https://Stackoverflow.com/users/45603", "pm_score": 6, "selected": true, "text": "devenv solution.sln /build configuration\n" }, { "answer_id": 16248370, "author": "GSoft Consulting", "author_id": 305197, "author_profile": "https://Stackoverflow.com/users/305197", "pm_score": 2, "selected": false, "text": "\"C:\\Windows\\Microsoft.NET\\Framework\\v4.0.30319\\msbuild.exe\" \niTegra.Web.sln /p:Configuration=Debug /clp:Summary /nologo\n" }, { "answer_id": 27001741, "author": "rboy", "author_id": 2280961, "author_profile": "https://Stackoverflow.com/users/2280961", "pm_score": 2, "selected": false, "text": "D:\ncd \"D:\\MySoln\"\n\nif \"%1\" == \"\" goto all\nif %1 == x86 goto x86\nif %1 == x64 goto x64\n\n:x86\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86 < crosscompilex86.bat\ngoto eof\n\n:x64\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86_amd64 < crosscompilex64.bat\ngoto eof\n\n:all\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86 < crosscompilex86.bat\nif %ERRORLEVEL% NEQ 0 goto eof\n%comspec% /k \"\"C:\\Program Files\\Microsoft Visual Studio 10.0\\VC\\vcvarsall.bat\"\" x86_amd64 < crosscompilex64.bat\ngoto eof\n\n:eof\npause\n devenv MySoln.sln /clean \"Release|x86\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\ndevenv MySoln.sln /rebuild \"Release|x86\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\n devenv MySoln.sln /clean \"Release|x64\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\ndevenv MySoln.sln /rebuild \"Release|x64\"\nIF %ERRORLEVEL% NEQ 0 EXIT /B %ERRORLEVEL%\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2541/" ]
24,620
<p>What can be reasons to prevent a class from being inherited? (e.g. using sealed on a c# class) Right now I can't think of any.</p>
[ { "answer_id": 24665, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 0, "selected": false, "text": "sealed" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2374/" ]
24,622
<p>I can set the PHP include path in the <code>php.ini</code>:</p> <pre><code>include_path = /path/to/site/includes/ </code></pre> <p>But then other websites are affected so that is no good.</p> <p>I can set the PHP include in the start of every file:</p> <pre><code>$path = '/path/to/site/includes/'; set_include_path(get_include_path() . PATH_SEPARATOR . $path); </code></pre> <p>But that seems like bad practice and clutters things up. </p> <p>So I can make an include of that and then include it into every file:</p> <pre><code>include 'includes/config.php'; </code></pre> <p>or</p> <pre><code>include '../includes/config.php'; </code></pre> <p>This is what I'm doing right now, but the include path of <code>config.php</code> will change depending on what is including it. </p> <p>Is there a better way? Does it matter?</p>
[ { "answer_id": 24631, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 5, "selected": true, "text": "ini PHP_INI_ALL PHP_INI_PERDIR PHP_INI_ALL" }, { "answer_id": 24695, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 0, "selected": false, "text": "include_path include include_path require_once \"ClassName.php\";\n CustomRequire function CustomRequire ($file) {\n if(defined('MYINCLUDEPATH')) {\n require_once MYINCLUDEPATH . \"/$file\";\n } else {\n require_once $file;\n }\n}\n" }, { "answer_id": 25100, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 1, "selected": false, "text": "php.ini" }, { "answer_id": 66774, "author": "djn", "author_id": 9673, "author_profile": "https://Stackoverflow.com/users/9673", "pm_score": 3, "selected": false, "text": ".htaccess phpinfo() php_value include_path \"wherever\"\n php.ini does" }, { "answer_id": 3619057, "author": "Gras Double", "author_id": 289317, "author_profile": "https://Stackoverflow.com/users/289317", "pm_score": 2, "selected": false, "text": "$path = '/path/to/site/includes/';\nset_include_path($path . PATH_SEPARATOR . get_include_path());\n" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118/" ]
24,626
<p>Can you tell me what is the difference between <strong>abstraction</strong> and <strong>information hiding</strong> in software development?</p> <p>I am confused. Abstraction hides detail implementation and information hiding abstracts whole details of something.</p> <p><strong>Update:</strong> I found a good answer for these three concepts. <a href="https://stackoverflow.com/a/8694874/240733">See the separate answer below</a> for several citations taken from <a href="http://web.archive.org/web/20080906224409/http://www.itmweb.com/essay550.htm" rel="noreferrer">there</a>.</p>
[ { "answer_id": 24728, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 1, "selected": false, "text": "private protected" }, { "answer_id": 24748, "author": "rp.", "author_id": 2536, "author_profile": "https://Stackoverflow.com/users/2536", "pm_score": 8, "selected": true, "text": "System.Text.StringBuilder StringBuilder" }, { "answer_id": 12673174, "author": "Shashwat", "author_id": 1213885, "author_profile": "https://Stackoverflow.com/users/1213885", "pm_score": 6, "selected": false, "text": "Abstraction Information Hiding private public Encapsulation Class Packet Abstraction Information Hiding Encapsulation" }, { "answer_id": 48746900, "author": "Ammar Samater", "author_id": 5280933, "author_profile": "https://Stackoverflow.com/users/5280933", "pm_score": 0, "selected": false, "text": "MyList add remove removeAll" }, { "answer_id": 51695321, "author": "Rohan Sharma", "author_id": 7805375, "author_profile": "https://Stackoverflow.com/users/7805375", "pm_score": 0, "selected": false, "text": "class Rectangle\n{\nprivate int length;\nprivate int breadth;// see the word private that means they cant be accesed from \noutside world.\n //now to make them accessed indirectly define getters and setters methods\nvoid setLength(int length)\n{ \n// we are adding this condition to prevent users to make any irrelevent changes \n that is why we have made length private so that they should be set according to \n certain restrictions\nif(length!=0)\n{\n this.length=length\n }\nvoid getLength()\n{\n return length;\n }\n // same do for breadth\n}\n public int area()\n {\n return length*breadth;\n }\n" }, { "answer_id": 56767315, "author": "Rahul Sharma", "author_id": 6700342, "author_profile": "https://Stackoverflow.com/users/6700342", "pm_score": 2, "selected": false, "text": "Abstraction what the object does how an object works" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1556/" ]
24,644
<p>Is there any way, in any language, to hook my program when a user renames a file?</p> <p>For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?".</p> <p>I'm thinking/hoping this is possible with C++, C# or .NET.. But I don't have any clue where to look for.</p>
[ { "answer_id": 24781, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "IFileOperationProgressSink.PreRenameItem IFileOperation ConfirmRename SHFileOperation IFileOperation" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
24,675
<p>Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques.</p> <hr> <p>I'm developing a tool in <strong>PHP</strong> that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well).</p> <h2>Databases</h2> <p>At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually <em>need</em> multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server?</p> <h2>Caching</h2> <p>I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called it's cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load.</p> <p>My question on this:</p> <p>Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached.</p> <h2>Finally</h2> <p>Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for?</p>
[ { "answer_id": 31191, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "ob_start() ob_start ob_start() ob_end() ob_start/ob_end" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24675", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
24,680
<p>My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions:</p> <ul> <li>What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...)</li> <li>Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.)</li> </ul>
[ { "answer_id": 1530193, "author": "awe", "author_id": 109392, "author_profile": "https://Stackoverflow.com/users/109392", "pm_score": 3, "selected": false, "text": "*.vbw MSSCCPRJ.SCC *.log MyForm.frm MyForm.log" } ]
2008/08/23
[ "https://Stackoverflow.com/questions/24680", "https://Stackoverflow.com", "https://Stackoverflow.com/users/217/" ]
24,715
<p>I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag.</p> <p>I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format)</p> <pre><code>apple -&gt; fruit red food banana -&gt; fruit yellow food cheese -&gt; yellow food firetruck -&gt; vehicle red </code></pre> <p>If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana).</p> <p>How do I write a SQL query do do what I want?</p> <p>@Jeremy Ruten,</p> <p>Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record.</p> <p>Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so:</p> <pre><code>SELECT object WHERE tag = 'fruit' AND tag = 'food'; </code></pre> <p>Yields no results when run.</p>
[ { "answer_id": 24720, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": -1, "selected": false, "text": " apple -> fruit\n apple -> red\n apple -> food\n banana -> fruit\n banana -> yellow\n banana -> food\n SELECT object WHERE tag = 'fruit' OR tag = 'food';\n SELECT object WHERE tag LIKE 'red' OR tag LIKE '% red' OR tag LIKE 'red %' OR tag LIKE '% red %';\n" }, { "answer_id": 24754, "author": "DevelopingChris", "author_id": 1220, "author_profile": "https://Stackoverflow.com/users/1220", "pm_score": 3, "selected": true, "text": "SELECT distinct o.*\n from object o join objecttags ot on o.Id = ot.objectid\n join tags t on ot.tagid = t.id\n where t.Name = 'fruit' or t.name = 'food';\n group by having count = <number of ors> SELECT distinct o.name, count(*) as count\n from object o join objecttags ot on o.Id = ot.objectid\n join tags t on ot.tagid = t.id\n where t.Name = 'fruit' or t.name = 'food'\ngroup by o.name\n having count = 2;\n" }, { "answer_id": 24758, "author": "Matt Rogish", "author_id": 2590, "author_profile": "https://Stackoverflow.com/users/2590", "pm_score": 2, "selected": false, "text": "1) Tags ( tag_id, name )\n2) Objects (whatever that is)\n3) Object_Tag( tag_id, object_id )\n SELECT obj \n FROM object\n WHERE EXISTS( SELECT * \n FROM tags \n WHERE tag = 'fruit' \n AND oid = object_id ) \n AND EXISTS( SELECT * \n FROM tags \n WHERE tag = 'Apple'\n AND oid = object_id )\n SELECT oid\n FROM tags\n WHERE tag = 'Apple'\nINTERSECT\nSELECT oid\n FROM tags\n WHERE tag = 'Fruit'\n" }, { "answer_id": 24759, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 0, "selected": false, "text": "select object\nfrom tblTags\nwhere tag = @firstMatch\nand (\n @secondMatch is null \n or \n (object in (select object from tblTags where tag = @secondMatch)\n )\n" }, { "answer_id": 24761, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 0, "selected": false, "text": "Objects: objectID, objectName\nTags: tagID, tagName\nObjectTag: objectID,tagID\n select distinct\n objectName\nfrom\n ObjectTab ot\n join object o\n on o.objectID = ot.objectID\n join tabs t\n on t.tagID = ot.tagID\nwhere\n tagName in ('red','fruit')\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/658/" ]
24,723
<p>Jeff actually posted about this in <a href="http://refactormycode.com/codes/333-sanitize-html" rel="noreferrer">Sanitize HTML</a>. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java?</p> <p>[Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is!</p> <p>(*) In fact, I think it was still in closed beta</p>
[ { "answer_id": 535022, "author": "Chase Seibert", "author_id": 7679, "author_profile": "https://Stackoverflow.com/users/7679", "pm_score": 7, "selected": true, "text": "<HTML><BODY>\n<?xml:namespace prefix=\"t\" ns=\"urn:schemas-microsoft-com:time\">\n<?import namespace=\"t\" implementation=\"#default#time2\">\n<t:set attributeName=\"innerHTML\" to=\"XSS&lt;SCRIPT DEFER&gt;alert(&quot;XSS&quot;)&lt;/SCRIPT&gt;\">\n</BODY></HTML>\n <TABLE BACKGROUND=\"javascript:alert('XSS')\">\n public String toSafeHtml(String html) throws ScanException, PolicyException {\n\n Policy policy = Policy.getInstance(POLICY_FILE);\n AntiSamy antiSamy = new AntiSamy();\n CleanResults cleanResults = antiSamy.scan(html, policy);\n return cleanResults.getCleanHTML().trim();\n}\n" }, { "answer_id": 538379, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 0, "selected": false, "text": "[\\s\\w\\.]* &amp;" }, { "answer_id": 937158, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "^(\\s|\\w|\\d|<br>)*?$ \n <br> ^(\\s|\\w|\\d|<br>|<ul>|<\\ul>)*?$\n" }, { "answer_id": 24094764, "author": "user3709489", "author_id": 3709489, "author_profile": "https://Stackoverflow.com/users/3709489", "pm_score": 3, "selected": false, "text": "<[^\\w<>]*(?:[^<>\"'\\s]*:)?[^\\w<>]*(?:\\W*s\\W*c\\W*r\\W*i\\W*p\\W*t|\\W*f\\W*o\\W*r\\W*m|\\W*s\\W*t\\W*y\\W*l\\W*e|\\W*s\\W*v\\W*g|\\W*m\\W*a\\W*r\\W*q\\W*u\\W*e\\W*e|(?:\\W*l\\W*i\\W*n\\W*k|\\W*o\\W*b\\W*j\\W*e\\W*c\\W*t|\\W*e\\W*m\\W*b\\W*e\\W*d|\\W*a\\W*p\\W*p\\W*l\\W*e\\W*t|\\W*p\\W*a\\W*r\\W*a\\W*m|\\W*i?\\W*f\\W*r\\W*a\\W*m\\W*e|\\W*b\\W*a\\W*s\\W*e|\\W*b\\W*o\\W*d\\W*y|\\W*m\\W*e\\W*t\\W*a|\\W*i\\W*m\\W*a?\\W*g\\W*e?|\\W*v\\W*i\\W*d\\W*e\\W*o|\\W*a\\W*u\\W*d\\W*i\\W*o|\\W*b\\W*i\\W*n\\W*d\\W*i\\W*n\\W*g\\W*s|\\W*s\\W*e\\W*t|\\W*i\\W*s\\W*i\\W*n\\W*d\\W*e\\W*x|\\W*a\\W*n\\W*i\\W*m\\W*a\\W*t\\W*e)[^>\\w])|(?:<\\w[\\s\\S]*[\\s\\0\\/]|['\"])(?:formaction|style|background|src|lowsrc|ping|on(?:d(?:e(?:vice(?:(?:orienta|mo)tion|proximity|found|light)|livery(?:success|error)|activate)|r(?:ag(?:e(?:n(?:ter|d)|xit)|(?:gestur|leav)e|start|drop|over)?|op)|i(?:s(?:c(?:hargingtimechange|onnect(?:ing|ed))|abled)|aling)|ata(?:setc(?:omplete|hanged)|(?:availabl|chang)e|error)|urationchange|ownloading|blclick)|Moz(?:M(?:agnifyGesture(?:Update|Start)?|ouse(?:PixelScroll|Hittest))|S(?:wipeGesture(?:Update|Start|End)?|crolledAreaChanged)|(?:(?:Press)?TapGestur|BeforeResiz)e|EdgeUI(?:C(?:omplet|ancel)|Start)ed|RotateGesture(?:Update|Start)?|A(?:udioAvailable|fterPaint))|c(?:o(?:m(?:p(?:osition(?:update|start|end)|lete)|mand(?:update)?)|n(?:t(?:rolselect|extmenu)|nect(?:ing|ed))|py)|a(?:(?:llschang|ch)ed|nplay(?:through)?|rdstatechange)|h(?:(?:arging(?:time)?ch)?ange|ecking)|(?:fstate|ell)change|u(?:echange|t)|l(?:ick|ose))|m(?:o(?:z(?:pointerlock(?:change|error)|(?:orientation|time)change|fullscreen(?:change|error)|network(?:down|up)load)|use(?:(?:lea|mo)ve|o(?:ver|ut)|enter|wheel|down|up)|ve(?:start|end)?)|essage|ark)|s(?:t(?:a(?:t(?:uschanged|echange)|lled|rt)|k(?:sessione|comma)nd|op)|e(?:ek(?:complete|ing|ed)|(?:lec(?:tstar)?)?t|n(?:ding|t))|u(?:ccess|spend|bmit)|peech(?:start|end)|ound(?:start|end)|croll|how)|b(?:e(?:for(?:e(?:(?:scriptexecu|activa)te|u(?:nload|pdate)|p(?:aste|rint)|c(?:opy|ut)|editfocus)|deactivate)|gin(?:Event)?)|oun(?:dary|ce)|l(?:ocked|ur)|roadcast|usy)|a(?:n(?:imation(?:iteration|start|end)|tennastatechange)|fter(?:(?:scriptexecu|upda)te|print)|udio(?:process|start|end)|d(?:apteradded|dtrack)|ctivate|lerting|bort)|DOM(?:Node(?:Inserted(?:IntoDocument)?|Removed(?:FromDocument)?)|(?:CharacterData|Subtree)Modified|A(?:ttrModified|ctivate)|Focus(?:Out|In)|MouseScroll)|r(?:e(?:s(?:u(?:m(?:ing|e)|lt)|ize|et)|adystatechange|pea(?:tEven)?t|movetrack|trieving|ceived)|ow(?:s(?:inserted|delete)|e(?:nter|xit))|atechange)|p(?:op(?:up(?:hid(?:den|ing)|show(?:ing|n))|state)|a(?:ge(?:hide|show)|(?:st|us)e|int)|ro(?:pertychange|gress)|lay(?:ing)?)|t(?:ouch(?:(?:lea|mo)ve|en(?:ter|d)|cancel|start)|ime(?:update|out)|ransitionend|ext)|u(?:s(?:erproximity|sdreceived)|p(?:gradeneeded|dateready)|n(?:derflow|load))|f(?:o(?:rm(?:change|input)|cus(?:out|in)?)|i(?:lterchange|nish)|ailed)|l(?:o(?:ad(?:e(?:d(?:meta)?data|nd)|start)?|secapture)|evelchange|y)|g(?:amepad(?:(?:dis)?connected|button(?:down|up)|axismove)|et)|e(?:n(?:d(?:Event|ed)?|abled|ter)|rror(?:update)?|mptied|xit)|i(?:cc(?:cardlockerror|infochange)|n(?:coming|valid|put))|o(?:(?:(?:ff|n)lin|bsolet)e|verflow(?:changed)?|pen)|SVG(?:(?:Unl|L)oad|Resize|Scroll|Abort|Error|Zoom)|h(?:e(?:adphoneschange|l[dp])|ashchange|olding)|v(?:o(?:lum|ic)e|ersion)change|w(?:a(?:it|rn)ing|heel)|key(?:press|down|up)|(?:AppComman|Loa)d|no(?:update|match)|Request|zoom))[\\s\\0]*=\n" }, { "answer_id": 63775847, "author": "NoNaMe", "author_id": 1410342, "author_profile": "https://Stackoverflow.com/users/1410342", "pm_score": 0, "selected": false, "text": "value.replaceAll(\"(?i)(\\\\b)(on\\\\S+)(\\\\s*)=|javascript:|(<\\\\s*)(\\\\/*)script|style(\\\\s*)=|(<\\\\s*)meta\", \"\");\n" }, { "answer_id": 74359104, "author": "Ashhh", "author_id": 15397385, "author_profile": "https://Stackoverflow.com/users/15397385", "pm_score": 0, "selected": false, "text": "public String validate(String value) {\n\n\n // Avoid anything between script tags\n Pattern scriptPattern = Pattern.compile(\"<script>(.*?)</script>\", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything in a src='...' type of expression\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\'(.*?)\\\\\\'\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything in a src=\"...\" type of expression\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*\\\\\\\"(.*?)\\\\\\\"\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything in a src=... type of expression added because quotes are not necessary\n scriptPattern = Pattern.compile(\"src[\\r\\n]*=[\\r\\n]*(.*?)\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Remove any lonesome </script> tag\n scriptPattern = Pattern.compile(\"</script>\", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Remove any lonesome <script ...> tag\n scriptPattern = Pattern.compile(\"<script(.*?)>\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid eval(...) expressions\n scriptPattern = Pattern.compile(\"eval\\\\((.*?)\\\\)\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid expression(...) expressions\n scriptPattern = Pattern.compile(\"expression\\\\((.*?)\\\\)\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid javascript:... expressions\n scriptPattern = Pattern.compile(\"javascript:\", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid vbscript:... expressions\n scriptPattern = Pattern.compile(\"vbscript:\", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid onload= expressions\n scriptPattern = Pattern.compile(\"onload(.*?)=\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything between script tags added - paranoid regex. note: if testing local PREP this must be commented\n scriptPattern = Pattern.compile(\"<(.*?)[\\r\\n]*(.*?)>\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything between script tags added - paranoid regex\n scriptPattern = Pattern.compile(\"<script(.*?)[\\r\\n]*(.*?)/script>\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Avoid anything between * tags like *(alert)* added\n scriptPattern = Pattern.compile(\"\\\\*(.*?)[\\r\\n]*(.*?)\\\\*\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n \n // Avoid anything between + tags like +(alert)+ added\n scriptPattern = Pattern.compile(\"\\\\+(.*?)[\\r\\n]*(.*?)\\\\+\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n // Prohibit lines containing = (...) added\n scriptPattern = Pattern.compile(\"=(.*?)\\\\((.*?)\\\\)\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n \n // removing href link \n scriptPattern = Pattern.compile(\"(?i)<[\\\\s]*[/]?[\\\\s]*a[^>]*>\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n //Avoid alert\n scriptPattern = Pattern.compile(\"alert\", Pattern.CASE_INSENSITIVE);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n\n\n scriptPattern = Pattern.compile(\"[^\\\\dA-Za-z ]\", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);\n value = scriptPattern.matcher(value).replaceAll(\"\");\n \n \n return value;\n \n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1406/" ]
24,730
<p>I'm doing a little bit of work on a horrid piece of software built by Bangalores best.</p> <p>It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages :(</p> <p>I'm getting this message when it tries to connect to my local database:</p> <p><strong>Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done.</strong></p> <pre><code>Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) </code></pre> <p>Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string:</p> <pre><code>PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true </code></pre> <p>Which is the connection string that it was initially using, I just repointed it at my database.</p> <p><strong>UPDATE:</strong></p> <p>The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.</p>
[ { "answer_id": 24744, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 3, "selected": true, "text": "DRIVER={SQL Server};\n Provider=SQLOLEDB;\n" }, { "answer_id": 887833, "author": "Amadiere", "author_id": 7828, "author_profile": "https://Stackoverflow.com/users/7828", "pm_score": 0, "selected": false, "text": "Driver={MySQL ODBC 5.1 Driver};\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
24,734
<p>I'm trying to add support for stackoverflow feeds in my rss reader but <strong>SelectNodes</strong> and <strong>SelectSingleNode</strong> have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet.</p> <p>I have gotten it to work by removing all attributes from the <strong>feed</strong> tag, but that's a hack and I would like to do it properly. So, how do you use <strong>SelectNodes</strong> with atom feeds?</p> <p>Here's a snippet of the feed.</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;feed xmlns="http://www.w3.org/2005/Atom" xmlns:creativeCommons="http://backend.userland.com/creativeCommonsRssModule" xmlns:thr="http://purl.org/syndication/thread/1.0"&gt; &lt;title type="html"&gt;StackOverflow.com - Questions tagged: c&lt;/title&gt; &lt;link rel="self" href="http://stackoverflow.com/feeds/tag/c" type="application/atom+xml" /&gt; &lt;subtitle&gt;Check out the latest from StackOverflow.com&lt;/subtitle&gt; &lt;updated&gt;2008-08-24T12:25:30Z&lt;/updated&gt; &lt;id&gt;http://stackoverflow.com/feeds/tag/c&lt;/id&gt; &lt;creativeCommons:license&gt;http://www.creativecommons.org/licenses/by-nc/2.5/rdf&lt;/creativeCommons:license&gt; &lt;entry&gt; &lt;id&gt;http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server&lt;/id&gt; &lt;title type="html"&gt;What is the best way to communicate with a SQL server?&lt;/title&gt; &lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="c++" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="sql" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="mysql" /&gt;&lt;category scheme="http://stackoverflow.com/feeds/tag/c/tags" term="database" /&gt; &lt;author&gt;&lt;name&gt;Ed&lt;/name&gt;&lt;/author&gt; &lt;link rel="alternate" href="http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server" /&gt; &lt;published&gt;2008-08-22T05:09:04Z&lt;/published&gt; &lt;updated&gt;2008-08-23T04:52:39Z&lt;/updated&gt; &lt;summary type="html"&gt;&amp;lt;p&amp;gt;I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?&amp;lt;/p&amp;gt;&lt;/summary&gt; &lt;link rel="replies" type="application/atom+xml" href="http://stackoverflow.com/feeds/question/22901/answers" thr:count="2"/&gt; &lt;thr:total&gt;2&lt;/thr:total&gt; &lt;/entry&gt; &lt;/feed&gt; </code></pre> <p><br/></p> <h2>The Solution</h2> <pre><code>XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr); </code></pre>
[ { "answer_id": 24740, "author": "Julio César", "author_id": 2148, "author_profile": "https://Stackoverflow.com/users/2148", "pm_score": 3, "selected": false, "text": "XmlDocument document = new XmlDocument();\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);\nnsmgr.AddNamespace(\"creativeCommons\", \"http://backend.userland.com/creativeCommonsRssModule\");\n// AddNamespace for other namespaces too.\ndocument.Load(feed);\n" }, { "answer_id": 24753, "author": "sieben", "author_id": 1147, "author_profile": "https://Stackoverflow.com/users/1147", "pm_score": 0, "selected": false, "text": "XmlNodeList itemList = xmlDoc.DocumentElement.SelectNodes(\"entry\");\n XmlDocument document = new XmlDocument();\nXmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);\nnsmgr.AddNamespace(\"\", \"http://www.w3.org/2005/Atom\");\ndocument.Load(feed);\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1147/" ]
24,797
<p>What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is.</p> <p>CLR integration isn't an option for me either.</p> <p>The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)</p>
[ { "answer_id": 25073, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 6, "selected": true, "text": "TimeZones e.g.\n--------- ----\nTimeZoneId 19\nName Eastern (GMT -5)\nOffset -5\n DaylightSavings\n---------------\nTimeZoneId 19\nBeginDst 3/9/2008 2:00 AM\nEndDst 11/2/2008 2:00 AM\n inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId\nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert between ds.BeginDst and ds.EndDst\n dateadd(hh, tz.Offset + \n case when ds.LocalTimeZone is not null \n then 1 else 0 end, TheDateToConvert)\n" }, { "answer_id": 838184, "author": "Bob Albright", "author_id": 15050, "author_profile": "https://Stackoverflow.com/users/15050", "pm_score": 4, "selected": false, "text": "ALTER TABLE myTable ADD date_edt AS \n dateadd(hh, \n -- The schedule through 2006 in the United States was that DST began on the first Sunday in April \n -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). \n -- The time is adjusted at 02:00 local time.\n CASE WHEN YEAR(date) <= 2006 THEN \n CASE WHEN \n date >= '4/' + CAST(abs(8-DATEPART(dw,'4/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n AND \n date < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date) as varchar)) as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n THEN -4 ELSE -5 END\n ELSE\n -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years.[35] In 2008 \n -- daylight saving time ended at 02:00 on Sunday, November 2, and in 2009 it began at 02:00 on Sunday, March 8.[36]\n CASE WHEN \n date >= '3/' + CAST(abs(8-DATEPART(dw,'3/1/' + CAST(YEAR(date) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n AND \n date < \n '11/' + CAST(abs(8-DATEPART(dw,'11/1/' + CAST(YEAR(date) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date) as varchar) + ' 2:00' \n THEN -4 ELSE -5 END\n END\n ,date)\n" }, { "answer_id": 4035662, "author": "Larry", "author_id": 489129, "author_profile": "https://Stackoverflow.com/users/489129", "pm_score": 3, "selected": false, "text": "inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId \nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert between ds.BeginDst and ds.EndDst \n inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId \nleft join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone \n and x.TheDateToConvert >= ds.BeginDst and x.TheDateToConvert < ds.EndDst \n" }, { "answer_id": 16994483, "author": "WillDeStijl", "author_id": 1241580, "author_profile": "https://Stackoverflow.com/users/1241580", "pm_score": 3, "selected": false, "text": "SELECT\n date1, \n dateadd(hh,\n -- The schedule through 2006 in the United States was that DST began on the first Sunday in April \n -- (April 2, 2006), and changed back to standard time on the last Sunday in October (October 29, 2006). \n -- The time is adjusted at 02:00 local time (which, for edt, is 07:00 UTC at the start, and 06:00 GMT at the end).\n CASE WHEN YEAR(date1) <= 2006 THEN\n CASE WHEN \n date1 >= '4/' + CAST((8-DATEPART(dw,'4/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' \n AND \n date1 < '10/' + CAST(32-DATEPART(dw,'10/31/' + CAST(YEAR(date1) as varchar)) as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' \n THEN -4 ELSE -5 END\n ELSE\n -- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 \n -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8\n CASE WHEN \n date1 >= '3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(date1) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 7:00' \n AND \n date1 < '11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(date1) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(date1) as varchar) + ' 6:00' \n THEN -4 ELSE -5 END\n END\n , date1) as date1Edt\n from MyTbl\n" }, { "answer_id": 17820648, "author": "Daniel", "author_id": 2612179, "author_profile": "https://Stackoverflow.com/users/2612179", "pm_score": 3, "selected": false, "text": "--Use Minutes (\"MI\") here instead of hours because sometimes\n-- the UTC offset may be half an hour (e.g. 9.5 hours).\nSELECT DATEADD(MI,\n DATEDIFF(MI, SYSUTCDATETIME(),SYSDATETIME()),\n YourUtcDateHere)[LocalDateTime]\n" }, { "answer_id": 22842711, "author": "MattC", "author_id": 195198, "author_profile": "https://Stackoverflow.com/users/195198", "pm_score": 0, "selected": false, "text": "TimeZoneOffsets\n---------------\nTimeZoneId 19\nBegin 1/4/2008 2:00 AM\nEnd 1/9/2008 2:00 AM\nOffset -5\nTimeZoneId 19\nBegin 1/9/2008 2:00 AM\nEnd 1/4/2009 2:00 AM\nOffset -6\nTimeZoneId 20 --Hong Kong for example - no DST\nBegin 1/1/1900\nEnd 31/12/9999\nOffset +8\n Declare @offset INT = (Select IsNull(tz.Offset,0) from YourTable ds\n join TimeZoneOffsets tz on tz.TimeZoneId=ds.LocalTimeZoneId \n and x.TheDateToConvert >= ds.Begin and x.TheDateToConvert < ds.End)\n dateadd(hh, @offset, TheDateToConvert)\n" }, { "answer_id": 36869547, "author": "Milan", "author_id": 1438675, "author_profile": "https://Stackoverflow.com/users/1438675", "pm_score": 0, "selected": false, "text": "CREATE FUNCTION dbo.GetPst()\nRETURNS DATETIME\nAS \nBEGIN\n\n RETURN SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time'\n\nEND\n\nSELECT dbo.GetPst()\n CREATE FUNCTION dbo.ConvertUtcToPst(@utcTime DATETIME)\nRETURNS DATETIME\nAS\nBEGIN\n\n RETURN DATEADD(HOUR, 0 - DATEDIFF(HOUR, CAST(SYSDATETIMEOFFSET() AT TIME ZONE 'Pacific Standard Time' AS DATETIME), SYSDATETIME()), @utcTime)\n\nEND\n\n\nSELECT dbo.ConvertUtcToPst('2016-04-25 22:50:01.900')\n" }, { "answer_id": 38960682, "author": "Jody Wood", "author_id": 6718940, "author_profile": "https://Stackoverflow.com/users/6718940", "pm_score": 0, "selected": false, "text": "DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, GETDATE())\n DATEADD(HH,(DATEPART(HOUR, GETUTCDATE())-DATEPART(HOUR, GETDATE()))*-1, [MySourceColumn])\n" }, { "answer_id": 41905349, "author": "mattmc3", "author_id": 83144, "author_profile": "https://Stackoverflow.com/users/83144", "pm_score": 0, "selected": false, "text": "-- make a table (#dst) of years 1970-2101. Note that DST could change in the future and\n-- everything was all custom and jacked before 1970 in the US.\ndeclare @first_year varchar(4) = '1970'\ndeclare @last_year varchar(4) = '2101'\n\n-- make a table of all the years desired\nif object_id('tempdb..#years') is not null drop table #years\n;with cte as (\n select cast(@first_year as int) as int_year\n ,@first_year as str_year\n ,cast(@first_year + '-01-01' as datetime) as start_of_year\n union all\n select int_year + 1\n ,cast(int_year + 1 as varchar(4))\n ,dateadd(year, 1, start_of_year)\n from cte\n where int_year + 1 <= @last_year\n)\nselect *\ninto #years\nfrom cte\noption (maxrecursion 500);\n\n-- make a staging table of all the important DST dates each year\nif object_id('tempdb..#dst_stage') is not null drop table #dst_stage\nselect dst_date\n ,time_period\n ,int_year\n ,row_number() over (order by dst_date) as ordinal\ninto #dst_stage\nfrom (\n -- start of year\n select y.start_of_year as dst_date\n ,'start of year' as time_period\n ,int_year\n from #years y\n\n union all\n select dateadd(year, 1, y.start_of_year)\n ,'start of year' as time_period\n ,int_year\n from #years y\n where y.str_year = @last_year\n\n -- start of dst\n union all\n select\n case\n when y.int_year >= 2007 then\n -- second sunday in march\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-03-08')) + 1) % 7, y.str_year + '-03-08')\n when y.int_year between 1987 and 2006 then\n -- first sunday in april\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-01')) + 1) % 7, y.str_year + '-04-01')\n when y.int_year = 1974 then\n -- special case\n cast('1974-01-06' as datetime)\n when y.int_year = 1975 then\n -- special case\n cast('1975-02-23' as datetime)\n else\n -- last sunday in april\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-04-24')) + 1) % 7, y.str_year + '-04-24')\n end\n ,'start of dst' as time_period\n ,int_year\n from #years y\n\n -- end of dst\n union all\n select\n case\n when y.int_year >= 2007 then\n -- first sunday in november\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-11-01')) + 1) % 7, y.str_year + '-11-01')\n else\n -- last sunday in october\n dateadd(day, ((7 - datepart(weekday, y.str_year + '-10-25')) + 1) % 7, y.str_year + '-10-25')\n end\n ,'end of dst' as time_period\n ,int_year\n from #years y\n) y\norder by 1\n\n-- assemble a final table\nif object_id('tempdb..#dst') is not null drop table #dst\nselect a.dst_date +\n case\n when a.time_period = 'start of dst' then ' 03:00'\n when a.time_period = 'end of dst' then ' 02:00'\n else ' 00:00'\n end as start_date\n ,b.dst_date +\n case\n when b.time_period = 'start of dst' then ' 02:00'\n when b.time_period = 'end of dst' then ' 01:00'\n else ' 00:00'\n end as end_date\n ,cast(case when a.time_period = 'start of dst' then 1 else 0 end as bit) as is_dst\n ,cast(0 as bit) as is_ambiguous\n ,cast(0 as bit) as is_invalid\ninto #dst\nfrom #dst_stage a\njoin #dst_stage b on a.ordinal + 1 = b.ordinal\nunion all\nselect a.dst_date + ' 02:00' as start_date\n ,a.dst_date + ' 03:00' as end_date\n ,cast(1 as bit) as is_dst\n ,cast(0 as bit) as is_ambiguous\n ,cast(1 as bit) as is_invalid\nfrom #dst_stage a\nwhere a.time_period = 'start of dst'\nunion all\nselect a.dst_date + ' 01:00' as start_date\n ,a.dst_date + ' 02:00' as end_date\n ,cast(0 as bit) as is_dst\n ,cast(1 as bit) as is_ambiguous\n ,cast(0 as bit) as is_invalid\nfrom #dst_stage a\nwhere a.time_period = 'end of dst'\norder by 1\n\n-------------------------------------------------------------------------------\n\n-- Test Eastern\nselect\n the_date as eastern_local\n ,todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end) as eastern_local_tz\n ,switchoffset(todatetimeoffset(the_date, case when b.is_dst = 1 then '-04:00' else '-05:00' end), '+00:00') as utc_tz\n --,b.*\nfrom (\n select cast('2015-03-08' as datetime) as the_date\n union all select cast('2015-03-08 02:30' as datetime) as the_date\n union all select cast('2015-03-08 13:00' as datetime) as the_date\n union all select cast('2015-11-01 01:30' as datetime) as the_date\n union all select cast('2015-11-01 03:00' as datetime) as the_date\n) a left join\n#dst b on b.start_date <= a.the_date and a.the_date < b.end_date\n" }, { "answer_id": 55822437, "author": "Shakespeare101", "author_id": 11403003, "author_profile": "https://Stackoverflow.com/users/11403003", "pm_score": 0, "selected": false, "text": "--Adapted Bob Albright and WillDeStijl suggestions for SQL server 2014\n--\n--In this instance I had no dates prior to 2006, therefore I simplified the case example\n--I had to add the variables for the assignment to allow trimming the timestamp from my resultset \n\nDECLARE @MARCH_DST as DATETIME\nSET @MARCH_DST='3/' + CAST((8-DATEPART(dw,'3/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 8 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 7:00'\n\nDECLARE @NOV_DST as DATETIME\nSET @NOV_DST='11/' + CAST((8-DATEPART(dw,'11/1/' + CAST(YEAR(getdate()) as varchar)))%7 + 1 as varchar) + '/' + CAST(YEAR(getdate()) as varchar) + ' 6:00'\n\nselect cast(dateadd(HOUR,\n-- By the Energy Policy Act of 2005, daylight saving time (DST) was extended in the United States in 2007. \n -- DST starts on the second Sunday of March, which is three weeks earlier than in the past, and it ends on \n -- the first Sunday of November, one week later than in years past. This change resulted in a new DST period \n -- that is four weeks (five in years when March has five Sundays) longer than in previous years. In 2008 \n -- daylight saving time ended at 02:00 edt (06:00 UTC) on Sunday, November 2, and in 2009 it began at 02:00 edt (07:00 UTC) on Sunday, March 8\n CASE WHEN\n date1 >=@MARCH_DST\n AND\n date1< @NOV_DST\n THEN -4 ELSE -5 END\n , date1) as DATE) as date1_edited\n\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1950/" ]
24,816
<p>Does anyone know of an easy way to escape HTML from strings in <a href="http://jquery.com/" rel="noreferrer">jQuery</a>? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.</p>
[ { "answer_id": 24870, "author": "tghw", "author_id": 2363, "author_profile": "https://Stackoverflow.com/users/2363", "pm_score": 6, "selected": false, "text": "html.replace(/&/g, \"&amp;\").replace(/</g, \"&lt;\").replace(/>/g, \"&gt;\");\n \" &quot; var escaped = html;\nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g, \"&gt;\"], [/\"/g, \"&quot;\"]]\nfor(var item in findReplace)\n escaped = escaped.replace(findReplace[item][0], findReplace[item][1]);\n encodeURIComponent()" }, { "answer_id": 25207, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 10, "selected": true, "text": "text // before:\n// <div class=\"someClass\">text</div>\nvar someHtmlString = \"<script>alert('hi!');</script>\";\n\n// set a DIV's text:\n$(\"div.someClass\").text(someHtmlString);\n// after: \n// <div class=\"someClass\">&lt;script&gt;alert('hi!');&lt;/script&gt;</div>\n\n// get the text in a string:\nvar escaped = $(\"<div>\").text(someHtmlString).html();\n// value: \n// &lt;script&gt;alert('hi!');&lt;/script&gt;\n" }, { "answer_id": 374176, "author": "Henrik N", "author_id": 6962, "author_profile": "https://Stackoverflow.com/users/6962", "pm_score": 8, "selected": false, "text": "$('<div/>').text('This is fun & stuff').html(); // \"This is fun &amp; stuff\"\n" }, { "answer_id": 6084508, "author": "Wayne", "author_id": 404535, "author_profile": "https://Stackoverflow.com/users/404535", "pm_score": 3, "selected": false, "text": "<!-- WON'T WORK - item[0] is an index, not an item -->\n\nvar escaped = html; \nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g,\"&gt;\"], [/\"/g,\n\"&quot;\"]]\n\nfor(var item in findReplace) {\n escaped = escaped.replace(item[0], item[1]); \n}\n\n\n<!-- WORKS - findReplace[item[]] correctly references contents -->\n\nvar escaped = html;\nvar findReplace = [[/&/g, \"&amp;\"], [/</g, \"&lt;\"], [/>/g, \"&gt;\"], [/\"/g, \"&quot;\"]]\n\nfor(var item in findReplace) {\n escaped = escaped.replace(findReplace[item[0]], findReplace[item[1]]);\n}\n" }, { "answer_id": 10754604, "author": "NicolasBernier", "author_id": 1213445, "author_profile": "https://Stackoverflow.com/users/1213445", "pm_score": 4, "selected": false, "text": "escape() unescape() var escapedHtml = html.replace(/&/g, '&amp;')\n .replace(/>/g, '&gt;')\n .replace(/</g, '&lt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n" }, { "answer_id": 10825766, "author": "intrepidis", "author_id": 847235, "author_profile": "https://Stackoverflow.com/users/847235", "pm_score": 5, "selected": false, "text": "function escapeHtmlEntities (str) {\n if (typeof jQuery !== 'undefined') {\n // Create an empty div to use as a container,\n // then put the raw text in and get the HTML\n // equivalent out.\n return jQuery('<div/>').text(str).html();\n }\n\n // No jQuery, so use string replace.\n return str\n .replace(/&/g, '&amp;')\n .replace(/>/g, '&gt;')\n .replace(/</g, '&lt;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&apos;');\n}\n" }, { "answer_id": 11229519, "author": "Katharapu Ramana", "author_id": 1486081, "author_profile": "https://Stackoverflow.com/users/1486081", "pm_score": 0, "selected": false, "text": "function htmlEscape(str) {\n var stringval=\"\";\n $.each(str, function (i, element) {\n alert(element);\n stringval += element\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(' ', '-')\n .replace('?', '-')\n .replace(':', '-')\n .replace('|', '-')\n .replace('.', '-');\n });\n alert(stringval);\n return String(stringval);\n}\n" }, { "answer_id": 12033826, "author": "Nikita Koksharov", "author_id": 764206, "author_profile": "https://Stackoverflow.com/users/764206", "pm_score": 5, "selected": false, "text": "_.str.escapeHTML('<div>Blah blah blah</div>')\n '&lt;div&gt;Blah blah blah&lt;/div&gt;'\n" }, { "answer_id": 12034334, "author": "Tom Gruner", "author_id": 420688, "author_profile": "https://Stackoverflow.com/users/420688", "pm_score": 9, "selected": false, "text": "var entityMap = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;',\n '\"': '&quot;',\n \"'\": '&#39;',\n '/': '&#x2F;',\n '`': '&#x60;',\n '=': '&#x3D;'\n};\n\nfunction escapeHtml (string) {\n return String(string).replace(/[&<>\"'`=\\/]/g, function (s) {\n return entityMap[s];\n });\n}\n" }, { "answer_id": 12473399, "author": "Cees Timmerman", "author_id": 819417, "author_profile": "https://Stackoverflow.com/users/819417", "pm_score": -1, "selected": false, "text": "unescape(escape(\"It's > 20% less complicated this way.\"))\n It%27s%20%3E%2020%25%20less%20complicated%20this%20way. unescape(escape(\"It's > 20% less complicated this way.\").replace(/%20/g, \" \"))\n It%27s %3E 20%25 less complicated this way. escape() encodeURI() encodeURIComponent() ' decodeURI(encodeURI(\"It's > 20% less complicated this way.\").replace(/%20/g, \" \").replace(\"'\", '%27'))\n" }, { "answer_id": 13149865, "author": "amrp", "author_id": 1787210, "author_profile": "https://Stackoverflow.com/users/1787210", "pm_score": 3, "selected": false, "text": "function escapeHtml(str) {\n if (typeof(str) == \"string\"){\n try{\n var newStr = \"\";\n var nextCode = 0;\n for (var i = 0;i < str.length;i++){\n nextCode = str.charCodeAt(i);\n if (nextCode > 0 && nextCode < 128){\n newStr += \"&#\"+nextCode+\";\";\n }\n else{\n newStr += \"?\";\n }\n }\n return newStr;\n }\n catch(err){\n }\n }\n else{\n return str;\n }\n}\n" }, { "answer_id": 13371349, "author": "zrajm", "author_id": 351162, "author_profile": "https://Stackoverflow.com/users/351162", "pm_score": 5, "selected": false, "text": "\" & < > .replace() function escapeHtml(text) {\n 'use strict';\n return text.replace(/[\\\"&<>]/g, function (a) {\n return { '\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' }[a];\n });\n}\n / ' /[...]/g chr function escapeHtml(text) {\n 'use strict';\n return text.replace(/[\\\"&'\\/<>]/g, function (a) {\n return {\n '\"': '&quot;', '&': '&amp;', \"'\": '&#39;',\n '/': '&#47;', '<': '&lt;', '>': '&gt;'\n }[a];\n });\n}\n &#39; &apos; / ' escapeHtml chr .replace() var escapeHtml = (function () {\n 'use strict';\n var chr = { '\"': '&quot;', '&': '&amp;', '<': '&lt;', '>': '&gt;' };\n return function (text) {\n return text.replace(/[\\\"&<>]/g, function (a) { return chr[a]; });\n };\n}());\n" }, { "answer_id": 13510502, "author": "Jeena", "author_id": 63779, "author_profile": "https://Stackoverflow.com/users/63779", "pm_score": 4, "selected": false, "text": "escapeHTML() var __entityMap = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': '&quot;',\n \"'\": '&#39;',\n \"/\": '&#x2F;'\n};\n\nString.prototype.escapeHTML = function() {\n return String(this).replace(/[&<>\"'\\/]/g, function (s) {\n return __entityMap[s];\n });\n}\n \"Some <text>, more Text&Text\".escapeHTML()" }, { "answer_id": 16520846, "author": "Gheljenor", "author_id": 2377530, "author_profile": "https://Stackoverflow.com/users/2377530", "pm_score": 2, "selected": false, "text": "(function(undefined){\n var charsToReplace = {\n '&': '&amp;',\n '<': '&lt;',\n '>': '&gt;'\n };\n\n var replaceReg = new RegExp(\"[\" + Object.keys(charsToReplace).join(\"\") + \"]\", \"g\");\n var replaceFn = function(tag){ return charsToReplace[tag] || tag; };\n\n var replaceRegF = function(replaceMap) {\n return (new RegExp(\"[\" + Object.keys(charsToReplace).concat(Object.keys(replaceMap)).join(\"\") + \"]\", \"gi\"));\n };\n var replaceFnF = function(replaceMap) {\n return function(tag){ return replaceMap[tag] || charsToReplace[tag] || tag; };\n };\n\n String.prototype.htmlEscape = function(replaceMap) {\n if (replaceMap === undefined) return this.replace(replaceReg, replaceFn);\n return this.replace(replaceRegF(replaceMap), replaceFnF(replaceMap));\n };\n})();\n \"some<tag>and&symbol©\".htmlEscape({'©': '&copy;'})\n \"some&lt;tag&gt;and&amp;symbol&copy;\"\n" }, { "answer_id": 16889423, "author": "d-_-b", "author_id": 1166285, "author_profile": "https://Stackoverflow.com/users/1166285", "pm_score": 0, "selected": false, "text": "function htmlDecode(t){\n if (t) return $('<div />').html(t).text();\n}\n" }, { "answer_id": 17546215, "author": "Saram", "author_id": 1828986, "author_profile": "https://Stackoverflow.com/users/1828986", "pm_score": 5, "selected": false, "text": "function HTMLescape(html){\n return document.createElement('div')\n .appendChild(document.createTextNode(html))\n .parentNode\n .innerHTML\n}\n //prepare variables\nvar DOMtext = document.createTextNode(\"test\");\nvar DOMnative = document.createElement(\"span\");\nDOMnative.appendChild(DOMtext);\n\n//main work for each case\nfunction HTMLescape(html){\n DOMtext.nodeValue = html;\n return DOMnative.innerHTML\n}\n" }, { "answer_id": 18756038, "author": "chovy", "author_id": 33522, "author_profile": "https://Stackoverflow.com/users/33522", "pm_score": 5, "selected": false, "text": "_.escape(string) \n" }, { "answer_id": 25671389, "author": "ronnbot", "author_id": 1712950, "author_profile": "https://Stackoverflow.com/users/1712950", "pm_score": 4, "selected": false, "text": "_.escape _.escape('Curly, Larry & Moe'); // returns: Curly, Larry &amp; Moe\n" }, { "answer_id": 28219824, "author": "raam86", "author_id": 1143013, "author_profile": "https://Stackoverflow.com/users/1143013", "pm_score": 2, "selected": false, "text": "var escaped = document.createTextNode(\"<HTML TO/ESCAPE/>\")\ndocument.getElementById(\"[PARENT_NODE]\").appendChild(escaped)\n" }, { "answer_id": 28905718, "author": "Kauê Gimenes", "author_id": 1055711, "author_profile": "https://Stackoverflow.com/users/1055711", "pm_score": -1, "selected": false, "text": "var entityMap = {\n \"&\": \"&amp;\",\n \"<\": \"&lt;\",\n \">\": \"&gt;\",\n '\"': '&quot;',\n \"'\": '&#39;',\n \"/\": '&#x2F;'\n };\n\n function escapeHtml(string) {\n return String(string).replace(/[&<>\"'\\/]/g, function (s) {\n return entityMap[s];\n });\n }\n function escapeHtml(string){\n return string\n}\n" }, { "answer_id": 30467671, "author": "C Nimmanant", "author_id": 4761711, "author_profile": "https://Stackoverflow.com/users/4761711", "pm_score": -1, "selected": false, "text": "& &amp; escapeHtml = function (s) {\n return s ? s.replace(\n /[&<>'\"]/g,\n function (c, offset, str) {\n if (c === \"&\") {\n var substr = str.substring(offset, offset + 6);\n if (/&(amp|lt|gt|apos|quot);/.test(substr)) {\n // already escaped, do not re-escape\n return c;\n }\n }\n return \"&\" + {\n \"&\": \"amp\",\n \"<\": \"lt\",\n \">\": \"gt\",\n \"'\": \"apos\",\n '\"': \"quot\"\n }[c] + \";\";\n }\n ) : \"\";\n};\n" }, { "answer_id": 31637833, "author": "Dave Brown", "author_id": 5010517, "author_profile": "https://Stackoverflow.com/users/5010517", "pm_score": 2, "selected": false, "text": "function encode(e){return e.replace(/[^]/g,function(e){return\"&#\"+e.charCodeAt(0)+\";\"})}\n & < > \" ' function encode(r){\nreturn r.replace(/[\\x26\\x0A\\<>'\"]/g,function(r){return\"&#\"+r.charCodeAt(0)+\";\"})\n}\n\nvar myString='Encode HTML entities!\\n\"Safe\" escape <script></'+'script> & other tags!';\n\ntest.value=encode(myString);\n\ntesting.innerHTML=encode(myString);\n\n/*************\n* \\x26 is &ampersand (it has to be first),\n* \\x0A is newline,\n*************/ <p><b>What JavaScript Generated:</b></p>\n\n<textarea id=test rows=\"3\" cols=\"55\"></textarea>\n\n<p><b>What It Renders Too In HTML:</b></p>\n\n<div id=\"testing\">www.WHAK.com</div>" }, { "answer_id": 35735254, "author": "Adam Leggett", "author_id": 4735342, "author_profile": "https://Stackoverflow.com/users/4735342", "pm_score": 5, "selected": false, "text": "escaped = new Option(unescaped).innerHTML;\n" }, { "answer_id": 46685127, "author": "iamandrewluca", "author_id": 4671932, "author_profile": "https://Stackoverflow.com/users/4671932", "pm_score": 2, "selected": false, "text": "function escapeHtml(text) {\n var div = document.createElement('div');\n div.innerText = text;\n return div.innerHTML;\n}\n\nescapeHtml(\"<script>alert('hi!');</script>\")\n// \"&lt;script&gt;alert('hi!');&lt;/script&gt;\"\n" }, { "answer_id": 57956081, "author": "chickens", "author_id": 1602301, "author_profile": "https://Stackoverflow.com/users/1602301", "pm_score": 2, "selected": false, "text": "const escapeHTML = str => (str+'').replace(/[&<>\"'`=\\/]/g, s => ({'&': '&amp;','<': '&lt;','>': '&gt;','\"': '&quot;',\"'\": '&#39;','/': '&#x2F;','`': '&#x60;','=': '&#x3D;'})[s]);\n" }, { "answer_id": 65462577, "author": "Christian d'Heureuse", "author_id": 337221, "author_profile": "https://Stackoverflow.com/users/337221", "pm_score": 0, "selected": false, "text": "function escapeHtml(s) {\n let out = \"\";\n let p2 = 0;\n for (let p = 0; p < s.length; p++) {\n let r;\n switch (s.charCodeAt(p)) {\n case 34: r = \"&quot;\"; break; // \"\n case 38: r = \"&amp;\" ; break; // &\n case 39: r = \"&#39;\" ; break; // '\n case 60: r = '&lt;' ; break; // <\n case 62: r = '&gt;' ; break; // >\n default: continue;\n }\n if (p2 < p) {\n out += s.substring(p2, p);\n }\n out += r;\n p2 = p + 1;\n }\n if (p2 == 0) {\n return s;\n }\n if (p2 < s.length) {\n out += s.substring(p2);\n }\n return out;\n}\n\nconst s = \"Hello <World>!\";\ndocument.write(escapeHtml(s));\nconsole.log(escapeHtml(s));" }, { "answer_id": 70677639, "author": "oscar castellon", "author_id": 1283517, "author_profile": "https://Stackoverflow.com/users/1283517", "pm_score": 0, "selected": false, "text": "function htmlEscape(str) {\n return str\n .replace(/&/g, '&amp;')\n .replace(/\"/g, '&quot;')\n .replace(/'/g, '&#39;')\n .replace(/</g, '&lt;')\n .replace(/>/g, '&gt;')\n .replace(/\\//g, '&#x2F;')\n .replace(/=/g, '&#x3D;')\n .replace(/`/g, '&#x60;');\n}\n function htmlUnescape(str) {\n return str\n .replace(/&amp;/g, '&')\n .replace(/&quot;/g, '\"')\n .replace(/&#39;/g, \"'\")\n .replace(/&lt;/g, '<')\n .replace(/&gt;/g, '>')\n .replace(/&#x2F/g, '/')\n .replace(/&#x3D;/g, '=')\n .replace(/&#x60;/g, '`');\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2657/" ]
24,821
<p>This problem started <a href="http://forums.asp.net/t/1304033.aspx" rel="nofollow noreferrer">on a different board</a>, but <a href="https://stackoverflow.com/users/60/dave-ward">Dave Ward</a>, who was very prompt and helpful there is also here, so I'd like to pick up here for hopefully the last remaining piece of the puzzle.­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p> <p>Basically, I was looking for a way to do constant updates to a web page from a long process. I thought AJAX was the way to go, but Dave has <a href="http://encosia.com/2007/10/03/easy-incremental-status-updates-for-long-requests/" rel="nofollow noreferrer">a nice article about using JavaScript</a>. I integrated it into my application and it worked great on my client, but NOT my server WebHost4Life. I have another server @ Brinkster and decided to try it there and it DOES work. All the code is the same on my client, WebHost4Life, and Brinkster, so there's obviously something going on with WebHost4Life.</p> <p>I'm planning to write an email to them or request technical support, but I'd like to be proactive and try to figure out what could be going on with their end to cause this difference. I did everything I could with my code to turn off Buffering like <code>Page.Response.BufferOutput = False</code>. What server settings could they have implemented to cause this difference? Is there any way I could circumvent it on my own without their help? If not, what would they need to do?</p> <p>For reference, a link to the working version of a simpler version of my application is located @ <a href="http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx" rel="nofollow noreferrer">http://www.jasoncomedy.com/javascriptfun/javascriptfun.aspx</a> and the same version that isn't working is located @ <a href="http://www.tabroom.org/Ajaxfun/Default.aspx" rel="nofollow noreferrer">http://www.tabroom.org/Ajaxfun/Default.aspx</a>. You'll notice in the working version, you get updates with each step, but in the one that doesn't, it sits there for a long time until everything is done and then does all the updates to the client at once ... and that makes me sad.</p>
[ { "answer_id": 26483, "author": "Dave Ward", "author_id": 60, "author_profile": "https://Stackoverflow.com/users/60", "pm_score": 3, "selected": false, "text": "protected void Page_Load(object sender, EventArgs e)\n{\n for (int i = 0; i < 10; i++) \n {\n Response.Write(i + \"<br />\"); \n Response.Flush();\n\n Thread.Sleep(1000);\n }\n}\n" }, { "answer_id": 46425529, "author": "Duncan Smart", "author_id": 1278, "author_profile": "https://Stackoverflow.com/users/1278", "pm_score": 2, "selected": false, "text": "Request.Headers[\"Accept-Encoding\"] Response.BufferOutput = false;\nRequest.Headers[\"Accept-Encoding\"] = \"\"; // suppresses gzip compression on output\n Accept-Encoding: gzip ..." } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24821", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1953/" ]
24,829
<pre><code>public class MyClass { public int Age; public int ID; } public void MyMethod() { MyClass m = new MyClass(); int newID; } </code></pre> <p>To my understanding, the following is true:</p> <ol> <li>The reference m lives on the stack and goes out of scope when MyMethod() exits.</li> <li>The value type newID lives on the stack and goes out of scope when MyMethod() exits.</li> <li>The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. </li> </ol> <p>Here is my question:</p> <ol> <li>Do value types within objects live on the stack or the heap?</li> <li>Is boxing/unboxing value types in an object a concern?</li> <li>Are there any detailed, yet understandable, resources on this topic?</li> </ol> <p>Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there.</p> <p>Edit:</p> <p>Suggested reading for this topic:</p> <ol> <li><a href="http://www.microsoft.com/MSPress/books/6522.aspx" rel="nofollow noreferrer">CLR Via C# by Jeffrey Richter</a></li> <li><a href="http://books.google.com/books?id=Kl1DVZ8wTqcC&amp;dq=essential+.net&amp;pg=PP1&amp;ots=5a-UEHSLVJ&amp;sig=D2_xn2kzMnP8zLXDVIV6AJtfbCY&amp;hl=en&amp;sa=X&amp;oi=book_result&amp;resnum=1&amp;ct=result#PPP1,M1" rel="nofollow noreferrer">Essential .NET by Don Box</a></li> </ol>
[ { "answer_id": 24876, "author": "icelava", "author_id": 2663, "author_profile": "https://Stackoverflow.com/users/2663", "pm_score": 4, "selected": true, "text": "public class EmbeddedValues\n{\n public int NumberField;\n}\n public class EmbeddedTest\n{\n public void TestEmbeddedValues()\n {\n EmbeddedValues valueContainer = new EmbeddedValues();\n\n valueContainer.NumberField = 20;\n int publicField = valueContainer.NumberField;\n }\n}\n .method public hidebysig instance void TestEmbeddedValues() cil managed\n{\n // Code size 23 (0x17)\n .maxstack 2\n .locals init ([0] class soapextensions.EmbeddedValues valueContainer,\n [1] int32 publicField)\n IL_0000: nop\n IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor()\n IL_0006: stloc.0\n IL_0007: ldloc.0\n IL_0008: ldc.i4.s 20\n IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField\n IL_000f: ldloc.0\n IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField\n IL_0015: stloc.1\n IL_0016: ret\n} // end of method EmbeddedTest::TestEmbeddedValues\n" }, { "answer_id": 21390848, "author": "supercat", "author_id": 363751, "author_profile": "https://Stackoverflow.com/users/363751", "pm_score": 0, "selected": false, "text": "struct Foo {public int x,y; int z;}\n Foo bar; bar.x bar.y bar.z bar bar int bar bar bar_x bar_y bar_cantaccessthis_z bar" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1880/" ]
24,849
<p>Is there any JavaScript method similar to the jQuery <code>delay()</code> or <code>wait()</code> (to delay the execution of a script for a specific amount of time)?</p>
[ { "answer_id": 24852, "author": "Abhinav", "author_id": 2617, "author_profile": "https://Stackoverflow.com/users/2617", "pm_score": 9, "selected": true, "text": "setTimeout(function, milliseconds);\n setTimeout()" }, { "answer_id": 24934, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 5, "selected": false, "text": "setTimeout setTimeout(func, 4000);\nfunction func() {\n alert('Do stuff here');\n}\n" }, { "answer_id": 24953, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 8, "selected": false, "text": "setTimeout var a = \"world\";\nsetTimeout(alert(\"Hello \" + a), 2000);\n var a = \"world\";\nsetTimeout(function(){alert(\"Hello \" + a)}, 2000);\na = \"Stack Overflow\";\n function callback(a){\n return function(){\n alert(\"Hello \" + a);\n }\n}\nvar a = \"world\";\nsetTimeout(callback(a), 2000);\na = \"Stack Overflow\";\n" }, { "answer_id": 8783433, "author": "narasi", "author_id": 1137896, "author_profile": "https://Stackoverflow.com/users/1137896", "pm_score": 4, "selected": false, "text": "setTimeout() Date()" }, { "answer_id": 24488671, "author": "Mario Werner", "author_id": 2746541, "author_profile": "https://Stackoverflow.com/users/2746541", "pm_score": 5, "selected": false, "text": "delay <script type=\"text/javascript\">\n function delay(ms) {\n var cur_d = new Date();\n var cur_ticks = cur_d.getTime();\n var ms_passed = 0;\n while(ms_passed < ms) {\n var d = new Date(); // Possible memory leak?\n var ticks = d.getTime();\n ms_passed = ticks - cur_ticks;\n // d = null; // Prevent memory leak?\n }\n }\n\n alert(\"2 sec delay\")\n delay(2000);\n alert(\"done ... 500 ms delay\")\n delay(500);\n alert(\"done\");\n</script>\n" }, { "answer_id": 27576023, "author": "Christoffer", "author_id": 632182, "author_profile": "https://Stackoverflow.com/users/632182", "pm_score": 3, "selected": false, "text": "function delay(ms) {\n ms += new Date().getTime();\n while (new Date() < ms){}\n}\n delay(2000);\n" }, { "answer_id": 35230867, "author": "JohnnyIV", "author_id": 4133108, "author_profile": "https://Stackoverflow.com/users/4133108", "pm_score": 1, "selected": false, "text": "// Show current seconds and milliseconds\n// (I know there are other ways, I was aiming for minimal code\n// and fixed width.)\nfunction secs()\n{\n var s = Date.now() + \"\"; s = s.substr(s.length - 5);\n return s.substr(0, 2) + \".\" + s.substr(2);\n}\n\n// Log we're loading\nconsole.log(\"Loading: \" + secs());\n\n// Create a list of commands to execute\nvar cmds = \n[\n function() { console.log(\"A: \" + secs()); },\n function() { console.log(\"B: \" + secs()); },\n function() { console.log(\"C: \" + secs()); },\n function() { console.log(\"D: \" + secs()); },\n function() { console.log(\"E: \" + secs()); },\n function() { console.log(\"done: \" + secs()); }\n];\n\n// Run each command with a second delay in between\nvar ms = 1000;\ncmds.forEach(function(cmd, i)\n{\n setTimeout(cmd, ms * i);\n});\n\n// Log we've loaded (probably logged before first command)\nconsole.log(\"Loaded: \" + secs());\n Loading: 03.077\nLoaded: 03.078\nA: 03.079\nB: 04.075\nC: 05.075\nD: 06.075\nE: 07.076\ndone: 08.076\n" }, { "answer_id": 41667568, "author": "Al Joslin", "author_id": 2912739, "author_profile": "https://Stackoverflow.com/users/2912739", "pm_score": 3, "selected": false, "text": "new Promise(function(resolve, reject) {\n setTimeout(resolve, 2000);\n}).then(function() {\n console.log('do whatever you wanted to hold off on');\n});" }, { "answer_id": 41785515, "author": "Luca", "author_id": 410354, "author_profile": "https://Stackoverflow.com/users/410354", "pm_score": 3, "selected": false, "text": "setTimeout(\n function () {\n x = 1;\n }, 1000);\n" }, { "answer_id": 47213654, "author": "Doug", "author_id": 8027640, "author_profile": "https://Stackoverflow.com/users/8027640", "pm_score": 2, "selected": false, "text": "setTimeout setTimeout(window.history.back(), 3000);\n setTimeout(function() {window.history.back()}, 3000);\n alert() alert()" }, { "answer_id": 51450886, "author": "JavaSheriff", "author_id": 648026, "author_profile": "https://Stackoverflow.com/users/648026", "pm_score": 2, "selected": false, "text": "function delay(milisecondDelay) {\n milisecondDelay += Date.now();\n while(Date.now() < milisecondDelay){}\n}\n\nalert('Ill be back in 5 sec after you click OK....');\ndelay(5000);\nalert('# Im back # date:' +new Date());" }, { "answer_id": 54499594, "author": "Jackkobec", "author_id": 9477038, "author_profile": "https://Stackoverflow.com/users/9477038", "pm_score": 1, "selected": false, "text": "function executeWithDelay(anotherFunction) {\n setTimeout(anotherFunction, delayInMilliseconds);\n}\n" }, { "answer_id": 57497385, "author": "Zuhair Taha", "author_id": 1274894, "author_profile": "https://Stackoverflow.com/users/1274894", "pm_score": 2, "selected": false, "text": "/**\n * delay or pause for some time\n * @param {number} t - time (ms)\n * @return {Promise<*>}\n */\nconst delay = async t => new Promise(resolve => setTimeout(resolve, t));\n async await delay(1000);\n delay(1000).then(() => {\n // your code...\n});\n new Promise(r => setTimeout(r, 1000)).then(() => {\n // your code ...\n});\n// or\nawait new Promise(r => setTimeout(r, 1000));\n// your code...\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
24,853
<p>In C, what is the difference between using <code>++i</code> and <code>i++</code>, and which should be used in the incrementation block of a <code>for</code> loop?</p>
[ { "answer_id": 24856, "author": "Ryan Fox", "author_id": 55, "author_profile": "https://Stackoverflow.com/users/55", "pm_score": 6, "selected": false, "text": "++i i++ ++i i++" }, { "answer_id": 24858, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 11, "selected": true, "text": "++i i i = 1;\n j = ++i;\n (i is 2, j is 2)\n i++ i i i = 1;\n j = i++;\n (i is 2, j is 1)\n for ++i ++i i++ ++i i++ operator++()" }, { "answer_id": 24874, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 5, "selected": false, "text": "++i i++ i++ ++i ++i" }, { "answer_id": 6945779, "author": "Scott Urban", "author_id": 746993, "author_profile": "https://Stackoverflow.com/users/746993", "pm_score": 3, "selected": false, "text": "for (int i = 0; i != X; ++i) ...\n" }, { "answer_id": 9901848, "author": "Parag", "author_id": 1297267, "author_profile": "https://Stackoverflow.com/users/1297267", "pm_score": 8, "selected": false, "text": "i++ i++ i int i = 1, j;\nj = i++;\n j = 1 i = 2 i j i ++i ++i i j = i; i++ int i = 1, j;\nj = ++i;\n j = 2 i = 2 i j i i ++i j=i; for(i=0; i<5; i++)\n printf(\"%d \", i);\n for(i=0; i<5; ++i)\n printf(\"%d \", i);\n 0 1 2 3 4 for(i = 0; i<5;)\n printf(\"%d \", ++i);\n 1 2 3 4 5" }, { "answer_id": 17851935, "author": "Shivprasad Koirala", "author_id": 993672, "author_profile": "https://Stackoverflow.com/users/993672", "pm_score": 6, "selected": false, "text": "i++ ++i" }, { "answer_id": 18387007, "author": "GokhanAvci", "author_id": 2551464, "author_profile": "https://Stackoverflow.com/users/2551464", "pm_score": 3, "selected": false, "text": "++i i++ function(i++) function(++i) function(++i) i function(i++) i i int i=4;\nprintf(\"%d\\n\",pow(++i,2));//it prints 25 and i is 5 now\ni=4;\nprintf(\"%d\",pow(i++,2));//it prints 16 i is 5 now\n" }, { "answer_id": 18849765, "author": "Scitech", "author_id": 2611926, "author_profile": "https://Stackoverflow.com/users/2611926", "pm_score": 4, "selected": false, "text": "++i i++ ++i int i = 0;\nprintf(\"i: %d\\n\", i);\nprintf(\"i++: %d\\n\", i++);\nprintf(\"++i: %d\\n\", ++i);\n i: 0\ni++: 0\n++i: 2\n" }, { "answer_id": 37202119, "author": "Anands23", "author_id": 4643764, "author_profile": "https://Stackoverflow.com/users/4643764", "pm_score": 4, "selected": false, "text": "++i int i = 5 int b = ++i i++ int i = 5 int b = i++ i++ i" }, { "answer_id": 37202251, "author": "Gopinath Kaliappan", "author_id": 5444836, "author_profile": "https://Stackoverflow.com/users/5444836", "pm_score": 3, "selected": false, "text": "i =1 1,2,3,4,n i =1 2,3,4,5,n" }, { "answer_id": 46185399, "author": "IOstream", "author_id": 6820948, "author_profile": "https://Stackoverflow.com/users/6820948", "pm_score": 3, "selected": false, "text": "int i, j, k, l;\ni = 1; //initialize int i with 1\nj = i+1; //add 1 with i and set that as the value of j. i is still 1\nk = i++; //k gets the current value of i, after that i is incremented. So here i is 2, but k is 1\nl = ++i; // i is incremented first and then returned. So the value of i is 3 and so does l.\ncout << i << ' ' << j << ' ' << k << ' '<< l << endl;\nreturn 0;\n" }, { "answer_id": 46493511, "author": "Uddhav P. Gautam", "author_id": 7232295, "author_profile": "https://Stackoverflow.com/users/7232295", "pm_score": 3, "selected": false, "text": "int j = 0;\nSystem.out.println(j); // 0\nSystem.out.println(j++); // 0. post-increment. It means after this line executes j increments.\n\nint k = 0;\nSystem.out.println(k); // 0\nSystem.out.println(++k); // 1. pre increment. It means it increments first and then the line executes\n int m = 0;\nif((m == 0 || m++ == 0) && (m++ == 1)) { // False\n // In the OR condition, if the first line is already true\n // then the compiler doesn't check the rest. It is a\n // technique of compiler optimization\n System.out.println(\"post-increment \" + m);\n}\n\nint n = 0;\nif((n == 0 || n++ == 0) && (++n == 1)) { // True\n System.out.println(\"pre-increment \" + n); // 1\n}\n System.out.println(\"In Array\");\nint[] a = { 55, 11, 15, 20, 25 };\nint ii, jj, kk = 1, mm;\nii = ++a[1]; // ii = 12. a[1] = a[1] + 1\nSystem.out.println(a[1]); // 12\n\njj = a[1]++; // 12\nSystem.out.println(a[1]); // a[1] = 13\n\nmm = a[1]; // 13\nSystem.out.printf(\"\\n%d %d %d\\n\", ii, jj, mm); // 12, 12, 13\n\nfor (int val: a) {\n System.out.print(\" \" + val); // 55, 13, 15, 20, 25\n}\n #include <iostream>\nusing namespace std;\n\nint main() {\n\n int x = 10;\n int* p = &x;\n\n std::cout << \"address = \" << p <<\"\\n\"; // Prints the address of x\n std::cout << \"address = \" << p <<\"\\n\"; // Prints (the address of x) + sizeof(int)\n std::cout << \"address = \" << &x <<\"\\n\"; // Prints the address of x\n\n std::cout << \"address = \" << ++&x << \"\\n\"; // Error. The reference can't reassign, because it is fixed (immutable).\n}\n" }, { "answer_id": 46514153, "author": "Nihal Reddy", "author_id": 7091562, "author_profile": "https://Stackoverflow.com/users/7091562", "pm_score": 3, "selected": false, "text": "int i;\nint j;\n i = 1;\nj = ++i; // i is now 2, j is also 2\nj = i++; // i is now 3, j is 2\n" }, { "answer_id": 48873975, "author": "carloswm85", "author_id": 7389293, "author_profile": "https://Stackoverflow.com/users/7389293", "pm_score": 3, "selected": false, "text": "int i = 10, j = 10;\n \nprintf (\"i is %i \\n\", i);\nprintf (\"i++ is %i \\n\", i++);\nprintf (\"i is %i \\n\\n\", i);\n \nprintf (\"j is %i \\n\", j);\nprintf (\"++j is %i \\n\", ++j);\nprintf (\"j is %i \\n\", j);\n //Remember that the values are i = 10, and j = 10\n\ni is 10 \ni++ is 10 //Assigns (print out), then increments\ni is 11 \n\nj is 10 \n++j is 11 //Increments, then assigns (print out)\nj is 11 \n int i, j;\n\nfor (i = 0; i <= 3; i++)\n printf (\" > iteration #%i\", i);\n\nprintf (\"\\n\");\n\nfor (j = 0; j <= 3; ++j)\n printf (\" > iteration #%i\", j);\n > iteration #0 > iteration #1 > iteration #2 > iteration #3\n> iteration #0 > iteration #1 > iteration #2 > iteration #3 \n" }, { "answer_id": 51704394, "author": "Jeet Parikh", "author_id": 9906531, "author_profile": "https://Stackoverflow.com/users/9906531", "pm_score": 1, "selected": false, "text": "// case 1\n\ni++;\n\n/* you can think as,\n * i;\n * i= i+1;\n */\n\n\n\n// case 2\n\n++i;\n\n/* you can think as,\n * i = i+i;\n * i;\n */\n" }, { "answer_id": 54911582, "author": "Francesco Boi", "author_id": 1714692, "author_profile": "https://Stackoverflow.com/users/1714692", "pm_score": 5, "selected": false, "text": "#include<stdio.h>\n\nint main(int argc, char* argv[])\n{\n unsigned int i=0, a;\n printf(\"i initial value: %d; \", i);\n a = i++;\n printf(\"value returned by i++: %d, i after: %d\\n\", a, i);\n i=0;\n printf(\"i initial value: %d; \", i);\n a = ++i;\n printf(\" value returned by ++i: %d, i after: %d\\n\",a, i);\n}\n i initial value: 0; value returned by i++: 0, i after: 1\ni initial value: 0; value returned by ++i: 1, i after: 1\n ++i i++ i #include<stdio.h>\n\nint main ()\n int i=0;\n int a = i++*2;\n printf(\"i=0, i++*2=%d\\n\", a);\n i=0;\n a = ++i * 2;\n printf(\"i=0, ++i*2=%d\\n\", a);\n i=0;\n a = (++i) * 2;\n printf(\"i=0, (++i)*2=%d\\n\", a);\n i=0;\n a = (i++) * 2;\n printf(\"i=0, (i++)*2=%d\\n\", a);\n return 0;\n}\n i=0, i++*2=0\ni=0, ++i*2=2\ni=0, (++i)*2=2\ni=0, (i++)*2=0\n i++*2 ++i*2 (i++)*2 (++i)*2 for(int i=0; i<10; i++)\n for(int i=0; i<10; ++i)\n ++ i ++ ++ i ++ i" }, { "answer_id": 70671642, "author": "Talat El Beick", "author_id": 13562196, "author_profile": "https://Stackoverflow.com/users/13562196", "pm_score": 3, "selected": false, "text": "int i = 1;\nint j = i++;\n j 1 int i = 1;\nint j = ++i;\n j 2 i 2" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24853", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
24,866
<p>I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need.</p>
[ { "answer_id": 24897, "author": "Telcontar", "author_id": 518, "author_profile": "https://Stackoverflow.com/users/518", "pm_score": 0, "selected": false, "text": "public String DOM2String(Document doc)\n{\n TransformerFactory transformerFactory =TransformerFactory.newInstance();\n Transformer transformer = null;\n try{\n transformer = transformerFactory.newTransformer();\n }catch (javax.xml.transform.TransformerConfigurationException error){\n coderror=123;\n msgerror=error.getMessage();\n return null;\n }\n\n Source source = new DOMSource(doc);\n\n StringWriter writer = new StringWriter();\n Result result = new StreamResult(writer);\n try{\n transformer.transform(source,result);\n }catch (javax.xml.transform.TransformerException error){\n coderror=123;\n msgerror=error.getMessage();\n return null;\n }\n\n String s = writer.toString();\n return s;\n}\n\npublic Document string2DOM(String s)\n{\n Document tmpX=null;\n DocumentBuilder builder = null;\n try{\n builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();\n }catch(javax.xml.parsers.ParserConfigurationException error){\n coderror=10;\n msgerror=\"Error crando factory String2DOM \"+error.getMessage();\n return null;\n }\n try{\n tmpX=builder.parse(new ByteArrayInputStream(s.getBytes()));\n }catch(org.xml.sax.SAXException error){\n coderror=10;\n msgerror=\"Error parseo SAX String2DOM \"+error.getMessage();\n return null;\n }catch(IOException error){\n coderror=10;\n msgerror=\"Error generando Bytes String2DOM \"+error.getMessage();\n return null;\n }\n return tmpX;\n}\n" }, { "answer_id": 25187, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "document.write" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
24,881
<p>I'm trying to solve <a href="http://uva.onlinejudge.org/external/1/100.pdf" rel="noreferrer">the 3n+1 problem</a> and I have a <code>for</code> loop that looks like this: </p> <pre><code>for(int i = low; i &lt;= high; ++i) { res = runalg(i); if (res &gt; highestres) { highestres = res; } } </code></pre> <p>Unfortunately I'm getting this error when I try to compile with GCC:</p> <blockquote> <p>3np1.c:15: error: 'for' loop initial declaration used outside C99 mode</p> </blockquote> <p>I don't know what C99 mode is. Any ideas?</p>
[ { "answer_id": 24882, "author": "OysterD", "author_id": 2638, "author_profile": "https://Stackoverflow.com/users/2638", "pm_score": 8, "selected": true, "text": "i #include <stdio.h>\n\nint main() {\n\n int i;\n\n /* for loop execution */\n for (i = 10; i < 20; i++) {\n printf(\"i: %d\\n\", i);\n } \n\n return 0;\n}\n" }, { "answer_id": 24884, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 7, "selected": false, "text": "-std=c99" }, { "answer_id": 24888, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 4, "selected": false, "text": "for (int i=0;i<10;i++) { ..\n int i;\nfor (i=0;i<10;i++) { ..\n" }, { "answer_id": 15871843, "author": "Roberto Cuadros", "author_id": 2230871, "author_profile": "https://Stackoverflow.com/users/2230871", "pm_score": 3, "selected": false, "text": "for (int i=0;i<10;i++) { ..\n int i;\nfor (i=0;i<10;i++) { ..\n gcc -std=c99 foo.c -o foo\n" }, { "answer_id": 16816595, "author": "demiurg_spb", "author_id": 2119881, "author_profile": "https://Stackoverflow.com/users/2119881", "pm_score": 0, "selected": false, "text": "QMAKE_CFLAGS_DEBUG = \\\n -std=gnu99\n\nQMAKE_CFLAGS_RELEASE = \\\n -std=gnu99\n" }, { "answer_id": 18775636, "author": "Jihene Stambouli", "author_id": 2774528, "author_profile": "https://Stackoverflow.com/users/2774528", "pm_score": 1, "selected": false, "text": "i int i;\n\nfor(i = low; i <= high; ++i)\n\n{\n res = runalg(i);\n if (res > highestres)\n {\n highestres = res;\n }\n\n}\n" }, { "answer_id": 27225785, "author": "akelec", "author_id": 2857477, "author_profile": "https://Stackoverflow.com/users/2857477", "pm_score": 5, "selected": false, "text": "-std=c99" }, { "answer_id": 51066676, "author": "Mink", "author_id": 6557223, "author_profile": "https://Stackoverflow.com/users/6557223", "pm_score": 2, "selected": false, "text": "export CFLAGS=\"-std=c99\"\n export CXXFLAGS=\"-std=c++11\"\n" }, { "answer_id": 52686151, "author": "Dark Burrow", "author_id": 847192, "author_profile": "https://Stackoverflow.com/users/847192", "pm_score": 2, "selected": false, "text": "for(int i = low; i <= high; ++i)\n{\n res = runalg(i);\n if (res > highestres)\n {\n highestres = res;\n }\n}\n 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode\n for(int i = low...\n int i;\nfor (i=low...\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
24,886
<p>Is there a performance difference between <code>i++</code> and <code>++i</code> if the resulting value is not used?</p>
[ { "answer_id": 24887, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 10, "selected": true, "text": "i++ ++i i ++i i++ $ cat i++.c\nextern void g(int i);\nvoid f()\n{\n int i;\n\n for (i = 0; i < 100; i++)\n g(i);\n\n}\n ++i i++ $ diff i++.c ++i.c\n6c6\n< for (i = 0; i < 100; i++)\n---\n> for (i = 0; i < 100; ++i)\n $ gcc -c i++.c ++i.c\n$ gcc -S i++.c ++i.c\n $ md5 i++.s ++i.s\nMD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e\nMD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e\n\n$ md5 *.o\nMD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22\nMD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22\n" }, { "answer_id": 25077, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 0, "selected": false, "text": "myArray[i++] = \"hello\";\n myArray[++i] = \"hello\";\n" }, { "answer_id": 25657, "author": "JProgrammer", "author_id": 1675, "author_profile": "https://Stackoverflow.com/users/1675", "pm_score": 4, "selected": false, "text": "// Prefix\nInteger& Integer::operator++()\n{\n *this += 1;\n return *this;\n}\n\n// Postfix\nconst Integer Integer::operator++(int)\n{\n Integer oldValue = *this;\n ++(*this);\n return oldValue;\n}\n" }, { "answer_id": 25668, "author": "Andrew Grant", "author_id": 1043, "author_profile": "https://Stackoverflow.com/users/1043", "pm_score": 6, "selected": false, "text": "++i i int i i++ ++i Foo Foo::operator++()\n{\n Foo oldFoo = *this; // copy existing value - could be slow\n // yadda yadda, do increment\n return oldFoo;\n}\n ++i ++i i++" }, { "answer_id": 39286, "author": "tonylo", "author_id": 4071, "author_profile": "https://Stackoverflow.com/users/4071", "pm_score": 4, "selected": false, "text": "for (i = 0; i < 100; i++)\n 1 i i 100 i 100 for (i = 100; i != 0; i--)\n i Z==0" }, { "answer_id": 39306, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 7, "selected": false, "text": "++i i++ i++ ++i ++i" }, { "answer_id": 24044354, "author": "Shahbaz", "author_id": 912144, "author_profile": "https://Stackoverflow.com/users/912144", "pm_score": 2, "selected": false, "text": "A a = ++b + c;\n\n; increment b\nLD A, [&b]\nINC A\nST A, [&b]\n\n; add with c\nADD A, [&c]\n\n; store in a\nST A, [&a]\n a = b++ + c;\n\n; load b\nLD A, [&b]\n\n; add with c\nADD A, [&c]\n\n; store in a\nST A, [&a]\n\n; increment b\nLD A, [&b]\nINC A\nST A, [&b]\n b i++; b++ ++b - 1 b++ ++b ++b a = b++ + 1; a = ++b;" }, { "answer_id": 24045013, "author": "cmaster - reinstate monica", "author_id": 2445184, "author_profile": "https://Stackoverflow.com/users/2445184", "pm_score": 4, "selected": false, "text": "i++ ++i ++i ++i i ++i foo(i++) foo() foo() i i++ ++i i++ i++ ++i i++" }, { "answer_id": 26482954, "author": "Lundin", "author_id": 584518, "author_profile": "https://Stackoverflow.com/users/584518", "pm_score": 4, "selected": false, "text": "i++ ++i ++i i++ for(i=0; i<n; i++) i++ i++ i 1 ++ i 1 ++i i++ array[i++] = x; array[++i] = x; i array[i++] = x; i i i i i ++ ++ ++" }, { "answer_id": 57517045, "author": "daShier", "author_id": 11517179, "author_profile": "https://Stackoverflow.com/users/11517179", "pm_score": 3, "selected": false, "text": "i++ ++i --i i-- *(i++) *(++i)" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24886", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
24,891
<p>I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case.</p> <p>Can someone show me (with code examples) an example of when you would have to do some "memory management" ?</p>
[ { "answer_id": 24893, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 3, "selected": false, "text": " char *string = malloc(stringlength); // stringlength is the number of bytes to allocate\n\n // Do something with the string...\n\n free(string); // Free the allocated memory\n" }, { "answer_id": 24895, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": -1, "selected": false, "text": "class MyClass\n{\n SomeOtherClass *myObject;\n\n public MyClass()\n {\n //The object is created when the class is constructed\n myObject = (SomeOtherClass*)malloc(sizeof(myObject));\n }\n\n public ~MyClass()\n {\n //The class is destructed\n //If you don't free the object here, you leak memory\n free(myObject);\n }\n\n public void SomeMemberFunction()\n {\n //Some use of the object\n myObject->SomeOperation();\n }\n\n\n};\n" }, { "answer_id": 24908, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": false, "text": "char *strdup(char *src)\n{\n char * dest;\n dest = malloc(strlen(src) + 1);\n if (dest == NULL)\n abort();\n strcpy(dest, src);\n return dest;\n}\n main()\n{\n char *s;\n s = strdup(\"hello\");\n printf(\"%s\\n\", s);\n s = strdup(\"world\");\n printf(\"%s\\n\", s);\n}\n for (i = 0; i < 1000000000; ++i) /* billion times */\n s = strdup(\"hello world\"); /* 11 bytes */\n s = strdup(\"hello\");\nfree(s); /* now not leaking memory! */\ns = strdup(\"world\");\n...\n" }, { "answer_id": 24918, "author": "Chris B-C", "author_id": 1517, "author_profile": "https://Stackoverflow.com/users/1517", "pm_score": 3, "selected": false, "text": "int main() {\n char* myString = (char*)malloc(5*sizeof(char));\n myString = \"abcd\";\n}\n myString = \"abcde\";\n" }, { "answer_id": 24922, "author": "Euro Micelli", "author_id": 2230, "author_profile": "https://Stackoverflow.com/users/2230", "pm_score": 9, "selected": true, "text": "int a;\nchar c;\nchar d[16];\n int size;\n// ...\n// Set size to some value, based on information available at run-time. Then:\n// ...\nchar *p = (char *)malloc(size);\n free(p);\n" }, { "answer_id": 25068, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "typedef struct listelem { struct listelem *next; void *data;} listelem;\n\nlistelem * create(void * data)\n{\n listelem *p = calloc(1, sizeof(listelem));\n if(p) p->data = data;\n return p;\n}\n\nlistelem * delete(listelem * p)\n{\n listelem next = p->next;\n free(p);\n return next;\n}\n\nvoid deleteall(listelem * p)\n{\n while(p) p = delete(p);\n}\n\nvoid foreach(listelem * p, void (*fun)(void *data) )\n{\n for( ; p != NULL; p = p->next) fun(p->data);\n}\n\nlistelem * merge(listelem *p, listelem *q)\n{\n while(p != NULL && p->next != NULL) p = p->next;\n if(p) {\n p->next = q;\n return p;\n } else\n return q;\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2128/" ]
24,901
<p>We have the question <a href="/q/24886">is there a performance difference between <code>i++</code> and <code>++i</code> <strong>in C</strong>?</a></p> <p>What's the answer for C++?</p>
[ { "answer_id": 24904, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 10, "selected": true, "text": "++i i++ i i i++ ++i operator++ Foo& Foo::operator++() // called for ++i\n{\n this->data += 1;\n return *this;\n}\n\nFoo Foo::operator++(int ignored_dummy_value) // called for i++\n{\n Foo tmp(*this); // variable \"tmp\" cannot be optimized away by the compiler\n ++(*this);\n return tmp;\n}\n operator++ tmp" }, { "answer_id": 24910, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 6, "selected": false, "text": "struct C\n{\n C& operator++(); // prefix\n C operator++(int); // postfix\n\nprivate:\n\n int i_;\n};\n\nC& C::operator++()\n{\n ++i_;\n return *this; // self, no copy created\n}\n\nC C::operator++(int ignored_dummy_value)\n{\n C t(*this);\n ++(*this);\n return t; // return a copy\n}\n" }, { "answer_id": 25092, "author": "James Sutherland", "author_id": 1739, "author_profile": "https://Stackoverflow.com/users/1739", "pm_score": 5, "selected": false, "text": "#include <stdio.h>\n\nclass Foo\n{\npublic:\n\n Foo() { myData=0; }\n Foo(const Foo &rhs) { myData=rhs.myData; }\n\n const Foo& operator++()\n {\n this->myData++;\n return *this;\n }\n\n const Foo operator++(int)\n {\n Foo tmp(*this);\n this->myData++;\n return tmp;\n }\n\n int GetData() { return myData; }\n\nprivate:\n\n int myData;\n};\n\nint main(int argc, char* argv[])\n{\n Foo testFoo;\n\n int count;\n printf(\"Enter loop count: \");\n scanf(\"%d\", &count);\n\n for(int i=0; i<count; i++)\n {\n testFoo++;\n }\n\n printf(\"Value: %d\\n\", testFoo.GetData());\n}\n for(int i=0; i<10; i++)\n{\n testFoo++;\n}\n\nprintf(\"Value: %d\\n\", testFoo.GetData());\n 00401000 push 0Ah \n00401002 push offset string \"Value: %d\\n\" (402104h) \n00401007 call dword ptr [__imp__printf (4020A0h)] \n" }, { "answer_id": 42276, "author": "Motti", "author_id": 3848, "author_profile": "https://Stackoverflow.com/users/3848", "pm_score": 3, "selected": false, "text": "for ++i i++ ++C ++C" }, { "answer_id": 5616980, "author": "Geoffroy", "author_id": 610351, "author_profile": "https://Stackoverflow.com/users/610351", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nint main()\n{\n int a = 0;\n a++;\n int b = 0;\n ++b;\n return 0;\n}\n 0x0000000100000f24 <main+0>: push %rbp\n 0x0000000100000f25 <main+1>: mov %rsp,%rbp\n 0x0000000100000f28 <main+4>: movl $0x0,-0x4(%rbp)\n 0x0000000100000f2f <main+11>: incl -0x4(%rbp)\n 0x0000000100000f32 <main+14>: movl $0x0,-0x8(%rbp)\n 0x0000000100000f39 <main+21>: incl -0x8(%rbp)\n 0x0000000100000f3c <main+24>: mov $0x0,%eax\n 0x0000000100000f41 <main+29>: leaveq \n 0x0000000100000f42 <main+30>: retq\n" }, { "answer_id": 9519095, "author": "Sebastian Mach", "author_id": 76722, "author_profile": "https://Stackoverflow.com/users/76722", "pm_score": 6, "selected": false, "text": "// a.cc\n#include <ctime>\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\nint main () {\n Something s;\n\n for (int i=0; i<1024*1024*30; ++i) ++s; // warm up\n std::clock_t a = clock();\n for (int i=0; i<1024*1024*30; ++i) ++s;\n a = clock() - a;\n\n for (int i=0; i<1024*1024*30; ++i) s++; // warm up\n std::clock_t b = clock();\n for (int i=0; i<1024*1024*30; ++i) s++;\n b = clock() - b;\n\n std::cout << \"a=\" << (a/double(CLOCKS_PER_SEC))\n << \", b=\" << (b/double(CLOCKS_PER_SEC)) << '\\n';\n return 0;\n}\n // b.cc\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\n\nSomething& Something::operator++()\n{\n for (auto it=data.begin(), end=data.end(); it!=end; ++it)\n ++*it;\n return *this;\n}\n\nSomething Something::operator++(int)\n{\n Something ret = *this;\n ++*this;\n return ret;\n}\n Flags (--std=c++0x) ++i i++\n-DPACKET_SIZE=50 -O1 1.70 2.39\n-DPACKET_SIZE=50 -O3 0.59 1.00\n-DPACKET_SIZE=500 -O1 10.51 13.28\n-DPACKET_SIZE=500 -O3 4.28 6.82\n // c.cc\n#include <array>\nclass Something {\npublic:\n Something& operator++();\n Something operator++(int);\nprivate:\n std::array<int,PACKET_SIZE> data;\n};\n\n\nSomething& Something::operator++()\n{\n return *this;\n}\n\nSomething Something::operator++(int)\n{\n Something ret = *this;\n ++*this;\n return ret;\n}\n Flags (--std=c++0x) ++i i++\n-DPACKET_SIZE=50 -O1 0.05 0.74\n-DPACKET_SIZE=50 -O3 0.08 0.97\n-DPACKET_SIZE=500 -O1 0.05 2.79\n-DPACKET_SIZE=500 -O3 0.08 2.18\n-DPACKET_SIZE=5000 -O3 0.07 21.90\n i++ increment i, I am interested in the previous value, though ++i increment i, I am interested in the current value increment i, no interest in the previous value" }, { "answer_id": 13256938, "author": "bwDraco", "author_id": 681231, "author_profile": "https://Stackoverflow.com/users/681231", "pm_score": 2, "selected": false, "text": "++i i++ int struct ++i int& int::operator++() { \n return *this += 1;\n}\n i++ i++ int int::operator++(int& _Val) {\n int _Original = _Val;\n _Val += 1;\n return _Original;\n}\n struct class" }, { "answer_id": 22266658, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "++i i++ x = i++; // x contains the old value of i\ny = ++i; // y contains the new value of i \n #include <stdio.h>\n\nint main(){\n int a = 0;\n printf(\"%d\", a++);\n printf(\"%d\", ++a);\n return 0;\n}\n #include <iostream>\nusing namespace std;\n\nint main(){\n int a = 0;\n cout << a++;\n cout << ++a;\n return 0;\n}\n" }, { "answer_id": 49564789, "author": "Severin Pappadeux", "author_id": 4044696, "author_profile": "https://Stackoverflow.com/users/4044696", "pm_score": -1, "selected": false, "text": "#include <iostream>\n\nclass Data {\n private: class DataIncrementer {\n private: Data& _dref;\n\n public: DataIncrementer(Data& d) : _dref(d) {}\n\n public: ~DataIncrementer() {\n ++_dref;\n }\n };\n\n private: int _data;\n\n public: Data() : _data{0} {}\n\n public: Data(int d) : _data{d} {}\n\n public: Data(const Data& d) : _data{ d._data } {}\n\n public: Data& operator=(const Data& d) {\n _data = d._data;\n return *this;\n }\n\n public: ~Data() {}\n\n public: Data& operator++() { // prefix\n ++_data;\n return *this;\n }\n\n public: Data operator++(int) { // postfix\n DataIncrementer t(*this);\n return *this;\n }\n\n public: operator int() {\n return _data;\n }\n};\n\nint\nmain() {\n Data d(1);\n\n std::cout << d << '\\n';\n std::cout << ++d << '\\n';\n std::cout << d++ << '\\n';\n std::cout << d << '\\n';\n\n return 0;\n}\n" }, { "answer_id": 65016498, "author": "Siddhant Jain", "author_id": 13828587, "author_profile": "https://Stackoverflow.com/users/13828587", "pm_score": -1, "selected": false, "text": "++i i = i +1 i = i + 1 i++" }, { "answer_id": 71049628, "author": "Tristan", "author_id": 668455, "author_profile": "https://Stackoverflow.com/users/668455", "pm_score": 0, "selected": false, "text": "private static final int LIMIT = 100000;\n\n@Benchmark\npublic void postIncrement() {\n long a = 0;\n long b = 0;\n for (int i = 0; i < LIMIT; i++) {\n b = 3;\n a += i * (b++);\n }\n doNothing(a, b);\n}\n\n@Benchmark\npublic void preIncrement() {\n long a = 0;\n long b = 0;\n for (int i = 0; i < LIMIT; i++) {\n b = 3;\n a += i * (++b);\n }\n doNothing(a, b);\n} \n Benchmark Mode Cnt Score Error Units\nIncrementBenchmark.postIncrement avgt 10 0,039 0,001 ms/op\nIncrementBenchmark.preIncrement avgt 10 0,039 0,001 ms/op\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24901", "https://Stackoverflow.com", "https://Stackoverflow.com/users/116/" ]
24,929
<p>What is the difference between the <code>EXISTS</code> and <code>IN</code> clause in SQL?</p> <p>When should we use <code>EXISTS</code>, and when should we use <code>IN</code>?</p>
[ { "answer_id": 24930, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 6, "selected": false, "text": "SELECT *\nFROM Customers\nWHERE EXISTS (\n SELECT *\n FROM Orders\n WHERE Orders.CustomerID = Customers.ID\n)\n SELECT *\nFROM Customers\nWHERE ID IN (\n SELECT CustomerID\n FROM Orders\n)\n SELECT Customers.*\nFROM Customers\n INNER JOIN Orders ON Customers.ID = Orders.CustomerID\n" }, { "answer_id": 24932, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 7, "selected": false, "text": "EXISTS SELECT * \nFROM Orders o \nWHERE EXISTS (\n SELECT * \n FROM Products p \n WHERE p.ProductNumber = o.ProductNumber)\n IN SELECT * \nFROM Orders \nWHERE ProductNumber IN (1, 10, 100)\n IN SELECT * \nFROM Orders \nWHERE ProductNumber IN (\n SELECT ProductNumber \n FROM Products \n WHERE ProductInventoryQuantity > 0)\n" }, { "answer_id": 24933, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "EXISTS IN" }, { "answer_id": 24948, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 8, "selected": false, "text": "exists --this statement needs to check the entire table\nselect count(*) from [table] where ...\n\n--this statement is true as soon as one match is found\nexists ( select * from [table] where ... )\n if exists count in select * from [table]\n where [field] in (1, 2, 3)\n in join in join in" }, { "answer_id": 3964770, "author": "jackson", "author_id": 479956, "author_profile": "https://Stackoverflow.com/users/479956", "pm_score": 6, "selected": false, "text": "EXISTS IN IN EXISTS" }, { "answer_id": 9797674, "author": "ram", "author_id": 1282333, "author_profile": "https://Stackoverflow.com/users/1282333", "pm_score": 2, "selected": false, "text": "NULL NULL EXITS IN" }, { "answer_id": 10748678, "author": "Arulraj.M", "author_id": 1416571, "author_profile": "https://Stackoverflow.com/users/1416571", "pm_score": 3, "selected": false, "text": "Exists IN Select 1 Exists SELECT * FROM Temp1 where exists(select 1 from Temp2 where conditions...)\n IN Exists" }, { "answer_id": 11329321, "author": "Alireza Masali", "author_id": 1450585, "author_profile": "https://Stackoverflow.com/users/1450585", "pm_score": 5, "selected": false, "text": "EXISTS IN IN EXISTS CREATE TABLE t1 (id INT, title VARCHAR(20), someIntCol INT)\nGO\nCREATE TABLE t2 (id INT, t1Id INT, someData VARCHAR(20))\nGO\n\nINSERT INTO t1\nSELECT 1, 'title 1', 5 UNION ALL\nSELECT 2, 'title 2', 5 UNION ALL\nSELECT 3, 'title 3', 5 UNION ALL\nSELECT 4, 'title 4', 5 UNION ALL\nSELECT null, 'title 5', 5 UNION ALL\nSELECT null, 'title 6', 5\n\nINSERT INTO t2\nSELECT 1, 1, 'data 1' UNION ALL\nSELECT 2, 1, 'data 2' UNION ALL\nSELECT 3, 2, 'data 3' UNION ALL\nSELECT 4, 3, 'data 4' UNION ALL\nSELECT 5, 3, 'data 5' UNION ALL\nSELECT 6, 3, 'data 6' UNION ALL\nSELECT 7, 4, 'data 7' UNION ALL\nSELECT 8, null, 'data 8' UNION ALL\nSELECT 9, 6, 'data 9' UNION ALL\nSELECT 10, 6, 'data 10' UNION ALL\nSELECT 11, 8, 'data 11'\n SELECT\nFROM t1 \nWHERE not EXISTS (SELECT * FROM t2 WHERE t1.id = t2.t1id)\n SELECT t1.* \nFROM t1 \nWHERE t1.id not in (SELECT t2.t1id FROM t2 )\n t1 IN EXISTS" }, { "answer_id": 13701788, "author": "djohn", "author_id": 1875484, "author_profile": "https://Stackoverflow.com/users/1875484", "pm_score": 0, "selected": false, "text": "in exists exists" }, { "answer_id": 17671111, "author": "If you are using the IN operat", "author_id": 2586350, "author_profile": "https://Stackoverflow.com/users/2586350", "pm_score": 4, "selected": false, "text": "IN EXISTS" }, { "answer_id": 30325975, "author": "rogue lad", "author_id": 1400737, "author_profile": "https://Stackoverflow.com/users/1400737", "pm_score": 2, "selected": false, "text": "select * \nfrom abcTable\nwhere exists (select null)\n select *\nfrom abcTable\nwhere abcTable_ID in (select null)\n" }, { "answer_id": 39918818, "author": "David דודו Markovitz", "author_id": 6336479, "author_profile": "https://Stackoverflow.com/users/6336479", "pm_score": 4, "selected": false, "text": "select * \nfrom t1 \nwhere x in (select x from t2)\n;\n select * \nfrom t1 \nwhere exists (select null \n from t2 \n where t2.x=t1.x \n and t2.y>t1.y \n and t2.z like '℅' || t1.z || '℅'\n )\n;\n" }, { "answer_id": 42991746, "author": "FatalError", "author_id": 1795136, "author_profile": "https://Stackoverflow.com/users/1795136", "pm_score": 0, "selected": false, "text": "IN EXISTS" }, { "answer_id": 45737479, "author": "TOUZENE Mohamed Wassim", "author_id": 6056511, "author_profile": "https://Stackoverflow.com/users/6056511", "pm_score": 2, "selected": false, "text": "In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS." }, { "answer_id": 69865209, "author": "Adam", "author_id": 2311074, "author_profile": "https://Stackoverflow.com/users/2311074", "pm_score": 0, "selected": false, "text": "where in where exists where in where in where exists where exists where in were exists select * from `users` \nwhere `first_name` ='gates' \nor exists \n(\n select * from `companies` \n where `users`.`company_id` = `companies`.`id`\n and `name` = 'gates'\n)\n select * from `users` \nwhere `first_name` ='gates' \nor users.company_id in \n(\n select id from `companies` \n where `name` = 'gates'\n)\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2528/" ]
24,931
<ol> <li>Is it possible to capture Python interpreter's output from a Python script?</li> <li>Is it possible to capture Windows CMD's output from a Python script?</li> </ol> <p>If so, which librar(y|ies) should I look into?</p>
[ { "answer_id": 24939, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "somescript.py | your-capture-program-here\n" }, { "answer_id": 24949, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 4, "selected": true, "text": "python script_a.py | python script_b.py\n import subprocess\n# Of course you can open things other than python here :)\nprocess = subprocess.Popen([\"python\", \"main.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nx = process.stderr.readline()\ny = process.stdout.readline()\nprocess.wait()\n import sys\nx = sys.stderr.readline()\ny = sys.stdin.readline()\n" }, { "answer_id": 29169, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 2, "selected": false, "text": "import sys\nimport StringIO\n\ns = StringIO.StringIO()\n\nsys.stdout = s\n\nprint \"hey, this isn't going to stdout at all!\"\nprint \"where is it ?\"\n\nsys.stderr.write('It actually went to a StringIO object, I will show you now:\\n')\nsys.stderr.write(s.getvalue())\n" }, { "answer_id": 3378965, "author": "martineau", "author_id": 355230, "author_profile": "https://Stackoverflow.com/users/355230", "pm_score": 3, "selected": false, "text": "from contextlib import contextmanager\nimport sys\n\n@contextmanager\ndef stdout_redirected(new_stdout):\n saved_stdout = sys.stdout\n sys.stdout = new_stdout\n try:\n yield None\n finally:\n sys.stdout.close()\n sys.stdout = saved_stdout\n with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n\nprint \"screen only output again\"\n\nwith stdout_redirected(open(\"filename.txt\", \"a\")):\n print \"Hello world2\"\n sys.stderr" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1670/" ]
24,941
<p>I am using <a href="http://www.simpletest.org/" rel="nofollow noreferrer">Simpletest</a> as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.</p> <p>I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.</p> <p>Are there any good extended HTML reporters or GUI's out there for Simpletest?</p> <p>Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried <a href="http://cool.sourceforge.net/" rel="nofollow noreferrer">Cool PHPUnit Test Runner</a>, but was not convinced.</p>
[ { "answer_id": 24939, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 0, "selected": false, "text": "somescript.py | your-capture-program-here\n" }, { "answer_id": 24949, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 4, "selected": true, "text": "python script_a.py | python script_b.py\n import subprocess\n# Of course you can open things other than python here :)\nprocess = subprocess.Popen([\"python\", \"main.py\"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)\nx = process.stderr.readline()\ny = process.stdout.readline()\nprocess.wait()\n import sys\nx = sys.stderr.readline()\ny = sys.stdin.readline()\n" }, { "answer_id": 29169, "author": "Thomas Vander Stichele", "author_id": 2900, "author_profile": "https://Stackoverflow.com/users/2900", "pm_score": 2, "selected": false, "text": "import sys\nimport StringIO\n\ns = StringIO.StringIO()\n\nsys.stdout = s\n\nprint \"hey, this isn't going to stdout at all!\"\nprint \"where is it ?\"\n\nsys.stderr.write('It actually went to a StringIO object, I will show you now:\\n')\nsys.stderr.write(s.getvalue())\n" }, { "answer_id": 3378965, "author": "martineau", "author_id": 355230, "author_profile": "https://Stackoverflow.com/users/355230", "pm_score": 3, "selected": false, "text": "from contextlib import contextmanager\nimport sys\n\n@contextmanager\ndef stdout_redirected(new_stdout):\n saved_stdout = sys.stdout\n sys.stdout = new_stdout\n try:\n yield None\n finally:\n sys.stdout.close()\n sys.stdout = saved_stdout\n with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n with stdout_redirected(open(\"filename.txt\", \"w\")):\n print \"Hello world\"\n\nprint \"screen only output again\"\n\nwith stdout_redirected(open(\"filename.txt\", \"a\")):\n print \"Hello world2\"\n sys.stderr" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/276/" ]
24,954
<p>How to determine the applications associated with a particular extension (e.g. .JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...).</p> <p>I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.</p>
[ { "answer_id": 24974, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "using System;\nusing Microsoft.Win32;\n\nnamespace GetAssociatedApp\n{\n class Program\n {\n static void Main(string[] args)\n {\n const string extPathTemplate = @\"HKEY_CLASSES_ROOT\\{0}\";\n const string cmdPathTemplate = @\"HKEY_CLASSES_ROOT\\{0}\\shell\\open\\command\";\n\n // 1. Find out document type name for .jpeg files\n const string ext = \".jpeg\";\n\n var extPath = string.Format(extPathTemplate, ext);\n\n var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string;\n if (!string.IsNullOrEmpty(docName))\n {\n // 2. Find out which command is associated with our extension\n var associatedCmdPath = string.Format(cmdPathTemplate, docName);\n var associatedCmd = \n Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string;\n\n if (!string.IsNullOrEmpty(associatedCmd))\n {\n Console.WriteLine(\"\\\"{0}\\\" command is associated with {1} extension\", associatedCmd, ext);\n }\n }\n }\n }\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669/" ]
24,991
<p>I have defined a Java function:</p> <pre><code>static &lt;T&gt; List&lt;T&gt; createEmptyList() { return new ArrayList&lt;T&gt;(); } </code></pre> <p>One way to call it is like so:</p> <pre><code>List&lt;Integer&gt; myList = createEmptyList(); // Compiles </code></pre> <p>Why can't I call it by explicitly passing the generic type argument? :</p> <pre><code>Object myObject = createEmtpyList&lt;Integer&gt;(); // Doesn't compile. Why? </code></pre> <p>I get the error <code>Illegal start of expression</code> from the compiler.</p>
[ { "answer_id": 24997, "author": "Cheekysoft", "author_id": 1820, "author_profile": "https://Stackoverflow.com/users/1820", "pm_score": 5, "selected": false, "text": "static <T> List<T> createEmptyList( Class<T> type ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void createStringList() {\n List<String> stringList = createEmptyList( String.class );\n}\n Collection.toArray( T[] ) static <T> List<T> createEmptyList( T[] array ) {\n return new ArrayList<T>();\n}\n\n@Test\npublic void testThing() {\n List<Integer> integerList = createEmptyList( new Integer[ 1 ] );\n}\n" }, { "answer_id": 25010, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 0, "selected": false, "text": "static <T> List<T> createEmptyList( List<T> a ) {\n return new ArrayList<T>();\n}\n" }, { "answer_id": 25877, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": true, "text": "Object list = Collections.<String> emptyList();\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24991", "https://Stackoverflow.com", "https://Stackoverflow.com/users/755/" ]
24,993
<p>I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message:</p> <blockquote> <p>Could not find default endpoint element that references contract 'MyServiceReference.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element.</p> </blockquote> <p>The code I am using to create the instance is:</p> <pre><code>myServiceClient = new MyServiceClient(); </code></pre> <p>where MyServiceClient inherits from</p> <p>System.ServiceModel.ClientBase</p> <p>How do I solve this?</p> <p>Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.</p>
[ { "answer_id": 25004, "author": "Richard Morgan", "author_id": 2258, "author_profile": "https://Stackoverflow.com/users/2258", "pm_score": 0, "selected": false, "text": "<endpoint>" }, { "answer_id": 1711550, "author": "NealWalters", "author_id": 160245, "author_profile": "https://Stackoverflow.com/users/160245", "pm_score": 1, "selected": false, "text": "[System.ServiceModel.ServiceContractAttribute(Namespace = \"http://TFBIC.RCT.BizTalk.Orchestrations\", ConfigurationName = \" RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\")] [System.ServiceModel.ServiceContractAttribute(Namespace = \"http://TFBIC.RCT.BizTalk.Orchestrations\", ConfigurationName = \"TFBIC.RCT.HIP.Components.RCTWebService.WcfService_TFBIC_RCT_BizTalk_Orchestrations\")] namespace RCTHipComponents\n" }, { "answer_id": 2423898, "author": "Trond", "author_id": 287647, "author_profile": "https://Stackoverflow.com/users/287647", "pm_score": 3, "selected": false, "text": "BasicHttpBinding binding = new BasicHttpBinding();\nEndpointAddress address = new EndpointAddress(\"http://url-to-service/\");\n\n// Create a client that is configured with this address and binding.\nMyServiceClient client = new MyServiceClient(binding, address);\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/24993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
25,007
<p>What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%?</p> <p>I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much.</p> <p>Based on Marius and Andy's answers I'm using the following solution:</p> <pre><code>double red = (percent &lt; 50) ? 255 : 256 - (percent - 50) * 5.12; double green = (percent &gt; 50) ? 255 : percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); </code></pre> <p>Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow ...</p>
[ { "answer_id": 25012, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "#F00 #FF0 #0F0 for (int i = 0; i < 100; i++) {\n var red = i < 50\n ? 255\n : 255 - (256.0 / 100 * ((i - 50) * 2));\n var green = i < 50\n ? 256.0 / 100 * (i * 2)\n : 255;\n var col = Color.FromArgb((int) red, (int) green, 0);\n}\n" }, { "answer_id": 25014, "author": "Cade", "author_id": 565, "author_profile": "https://Stackoverflow.com/users/565", "pm_score": 3, "selected": false, "text": "XX = ( Percentage / 50 ) * 255 converted into hex.\n XX = ((100-Percentage) / 50) * 255 converted into hex. \n" }, { "answer_id": 25024, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 5, "selected": true, "text": "function setColor(p){\n var red = p<50 ? 255 : Math.round(256 - (p-50)*5.12);\n var green = p>50 ? 255 : Math.round((p)*5.12);\n return \"rgb(\" + red + \",\" + green + \",0)\";\n}\n" }, { "answer_id": 25065, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 3, "selected": false, "text": "#e7241d for v <= 12%\n#ef832c for v > 12% and v <= 36%\n#fffd46 for v > 36% and v <= 60%\n#9cfa40 for v > 60% and v <= 84%\n#60f83d for v > 84%\n" }, { "answer_id": 43215, "author": "Tom", "author_id": 3715, "author_profile": "https://Stackoverflow.com/users/3715", "pm_score": 0, "selected": false, "text": "def blendRGBHex(hex1, hex2, fraction):\n return RGBDecToHex(blendRGB(RGBHexToDec(hex1), \n RGBHexToDec(hex2), fraction))\n\ndef blendRGB(dec1, dec2, fraction):\n return [int(v1 + (v2-v1)*fraction) \n for (v1, v2) in zip(dec1, dec2)]\n\ndef RGBHexToDec(hex):\n return [int(hex[n:n+2],16) for n in range(0,len(hex),2)]\n\ndef RGBDecToHex(dec):\n return \"\".join([\"%02x\"%d for d in dec])\n >>> blendRGBHex(\"FF8080\", \"80FF80\", 0.5)\n\"BFBF80\"\n def colourRange(minV, minC, avgV, avgC, maxV, maxC, v):\n if v < minV: return minC\n if v > maxV: return maxC\n if v < avgV:\n return blendRGBHex(minC, avgC, (v - minV)/(avgV-minV))\n elif v > avgV:\n return blendRGBHex(avgC, maxC, (v - avgV)/(maxV-avgV))\n else:\n return avgC\n >>> colourRange(0, \"FF0000\", 50, \"FFFF00\", 100, \"00FF00\", 25)\n\"FF7F00\"\n" }, { "answer_id": 685216, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "def getBarColour(value):\n red = int( (1 - (value*value) ) * 180 )\n green = int( (value * value )* 180 )\n\n red = \"%02X\" % red\n green = \"%02X\" % green\n\n return '#' + red + green +'00'\n" }, { "answer_id": 3660287, "author": "Simon", "author_id": 212903, "author_profile": "https://Stackoverflow.com/users/212903", "pm_score": 0, "selected": false, "text": "var red:Number = (percentage <= 50) ? 255 : 256 - (percentage - 50) * 5.12;\nvar green:Number = (percentage >= 50) ? 255 : percentage * 5.12;\n\nvar redHex:Number = Math.round(red) * 0x10000;\nvar greenHex:Number = Math.round(green) * 0x100;\n\nvar colorToReturn:uint = redHex + greenHex;\n" }, { "answer_id": 27901262, "author": "Mark Whitaker", "author_id": 440921, "author_profile": "https://Stackoverflow.com/users/440921", "pm_score": 2, "selected": false, "text": "private const int RGB_MAX = 255; // Reduce this for a darker range\nprivate const int RGB_MIN = 0; // Increase this for a lighter range\n\nprivate Color getColorFromPercentage(int percentage)\n{\n // Work out the percentage of red and green to use (i.e. a percentage\n // of the range from RGB_MIN to RGB_MAX)\n var redPercent = Math.Min(200 - (percentage * 2), 100) / 100f;\n var greenPercent = Math.Min(percentage * 2, 100) / 100f;\n\n // Now convert those percentages to actual RGB values in the range\n // RGB_MIN - RGB_MAX\n var red = RGB_MIN + ((RGB_MAX - RGB_MIN) * redPercent);\n var green = RGB_MIN + ((RGB_MAX - RGB_MIN) * greenPercent);\n\n return Color.FromArgb(red, green, RGB_MIN);\n}\n VALUE GREEN RED RESULTING COLOUR\n 100% 100% 0% green\n 75% 100% 50% yellowy green\n 50% 100% 100% yellow\n 25% 50% 100% orange\n 0% 0% 100% red\n VALUE GREEN RED\n 100% 200% 0%\n 75% 150% 50%\n 50% 100% 100%\n 25% 50% 150%\n 0% 0% 200%\n Math.Min()" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1199387/" ]
25,033
<p>I am using the code snippet below, however it's not working quite as I understand it should. </p> <pre><code>public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line != null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } </code></pre> <p>From reading the Javadoc about <code>readLine()</code> it says: </p> <p>Reads a line of text. A line is considered to be terminated by any one of a line feed (<code>\n</code>), a carriage return (<code>\r</code>), or a carriage return followed immediately by a linefeed. </p> <p><strong>Returns</strong>: A <code>String</code> containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached </p> <p><strong>Throws</strong>: <code>IOException</code> - If an I/O error occurs</p> <p>From my understanding of this, <code>readLine</code> should return null the first time no input is entered other than a line termination, like <code>\r</code>. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?</p>
[ { "answer_id": 25043, "author": "Tom Lokhorst", "author_id": 2597, "author_profile": "https://Stackoverflow.com/users/2597", "pm_score": 4, "selected": true, "text": "readLine null \\n \\r\\n while (line != null && !line.equals(\"\"))\n java -cp . Echo < test.txt\n" }, { "answer_id": 36438, "author": "Bartosz Bierkowski", "author_id": 3666, "author_profile": "https://Stackoverflow.com/users/3666", "pm_score": 1, "selected": false, "text": "while(isNotEmpty(line)) {\n System.out.println(line);\n line = br.readLine();\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25033", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2628/" ]
25,041
<p>Using CSS,</p> <p>I'm trying to specify the height of a <code>span</code> tag in Firefox, but it's just not accepting it (IE does).</p> <p>Firefox accepts the <code>height</code> if I use a <code>div</code>, but the problem with using a <code>div</code> is the annoying line break after it, which I can't have in this particular instance. </p> <p>I tried setting the CSS style attribute of: <pre>display: inline</pre> for the <code>div</code>, but Firefox seems to revert that to <code>span</code> behavior anyway and ignores the <code>height</code> attribute once again.</p>
[ { "answer_id": 25047, "author": "ceejayoz", "author_id": 1902010, "author_profile": "https://Stackoverflow.com/users/1902010", "pm_score": 4, "selected": false, "text": "display: inline" }, { "answer_id": 25049, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 1, "selected": false, "text": "display: block; div display: block; <div style=\"background: #f00;\">\n Text <span style=\"padding: 14px 0 14px 0; background: #ff0;\">wooo</span> text.\n</div>\n" }, { "answer_id": 25051, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "/* makes the whole box higher by inserting a space between the border and the content */\npadding: 0.5em 0;\n" }, { "answer_id": 25053, "author": "Cade", "author_id": 565, "author_profile": "https://Stackoverflow.com/users/565", "pm_score": 5, "selected": true, "text": "<style>\n#div1 { float:left; height:20px; width:20px; }\n#div2 { float:left; height:30px; width:30px }\n</style>\n\n<div id=\"div1\">FirstDiv</div>\n<div id=\"div2\">SecondDiv</div>\n div's" }, { "answer_id": 25110, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 5, "selected": false, "text": "display: inline-block inline-block -moz-inline-stack inline-block inline-block" }, { "answer_id": 719266, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "height em relative line-height height:1.1em line-height:1.1" }, { "answer_id": 909584, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "span {\n display: block;\n height: 50px;\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25041", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
25,046
<p>I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable.</p> <p>I'm using <code>clisp</code> and <code>clisp -c</code> produces two files:</p> <ul> <li>.fas</li> <li>.lib</li> </ul> <p>What do I do next to get an executable?</p>
[ { "answer_id": 25435, "author": "thekidder", "author_id": 1631, "author_profile": "https://Stackoverflow.com/users/1631", "pm_score": 7, "selected": true, "text": "(EXT:SAVEINITMEM \"executable.exe\"\n :QUIET t\n :INIT-FUNCTION 'main\n :EXECUTABLE t\n :NORC t)\n :QUIET t :EXECUTABLE t (EXT:EXIT)\n :NORC t ~/.clisprc.lisp" }, { "answer_id": 34195243, "author": "Thayne", "author_id": 2543666, "author_profile": "https://Stackoverflow.com/users/2543666", "pm_score": 2, "selected": false, "text": "ros ros dump executable" }, { "answer_id": 45891272, "author": "Paul McCarthy", "author_id": 2158599, "author_profile": "https://Stackoverflow.com/users/2158599", "pm_score": -1, "selected": false, "text": "gcl -compile jugs2.lisp\n gcl\n (load \"jugs2.o\")\n (si:save-system \"jugs2\")\n oncrpc.dll <gcl install folder>\\lib\\gcl-2.6.1\\unixport" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2450/" ]
25,116
<p>In Python you can use <a href="https://docs.python.org/library/struct.html" rel="noreferrer">StringIO</a> for a file-like buffer for character data. <a href="https://docs.python.org/library/mmap.html" rel="noreferrer">Memory-mapped file</a> basically does similar thing for binary data, but it requires a file that is used as the basis. Does Python have a file object that is intended for binary data and is memory only, equivalent to Java's <a href="http://java.sun.com/javase/6/docs/api/java/io/ByteArrayOutputStream.html" rel="noreferrer">ByteArrayOutputStream</a>?</p> <p>The use-case I have is I want to create a ZIP file in memory, and <a href="https://docs.python.org/library/zipfile.html" rel="noreferrer">ZipFile</a> requires a file-like object.</p>
[ { "answer_id": 25123, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 2, "selected": false, "text": "\nimport struct\nf = open(filename, \"rb\")\ns = f.read(8)\nx, y = struct.unpack(\">hl\", s)\n" }, { "answer_id": 25180, "author": "Henrik Gustafsson", "author_id": 2010, "author_profile": "https://Stackoverflow.com/users/2010", "pm_score": 5, "selected": false, "text": "StringIO cStringIO StringIO f.write(u\"asdf\") import zipfile\nimport StringIO\n\ns = StringIO.StringIO()\nz = zipfile.ZipFile(s, \"w\")\nz.write(\"test.txt\")\nz.close()\nf = file(\"x.zip\", \"w\")\nf.write(s.getvalue())\ns.close()\nf.close()\n" }, { "answer_id": 7357938, "author": "akhan", "author_id": 828885, "author_profile": "https://Stackoverflow.com/users/828885", "pm_score": 8, "selected": true, "text": "from io import BytesIO\nbio = BytesIO(b\"some initial binary data: \\x00\\x01\")\n from io import StringIO\nsio = StringIO(b\"some initial binary data: \\x00\\x01\")\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679/" ]
25,128
<p>Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?</p>
[ { "answer_id": 25139, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 5, "selected": true, "text": "<?php\nheader (\"Content-type: image/png\");\n$im = @imagecreatetruecolor(120, 20)\n or die(\"Cannot Initialize new GD image stream\");\n$text_color = imagecolorallocate($im, 233, 14, 91);\nimagestring($im, 1, 5, 5, \"A Simple Text String\", $text_color);\nimagepng($im);\nimagedestroy($im);\n?>\n" }, { "answer_id": 871350, "author": "Chris Henry", "author_id": 103315, "author_profile": "https://Stackoverflow.com/users/103315", "pm_score": 0, "selected": false, "text": "$drawing_wand=NewDrawingWand();\nDrawSetFont($drawing_wand,\"/usr/share/fonts/bitstream-vera/Vera.ttf\");\nDrawSetFontSize($drawing_wand,20);\nDrawSetGravity($drawing_wand,MW_CenterGravity);\n$pixel_wand=NewPixelWand();\nPixelSetColor($pixel_wand,\"white\");\nDrawSetFillColor($drawing_wand,$pixel_wand);\nif (MagickAnnotateImage($magick_wand,$drawing_wand,0,0,0,\"Rose\") != 0) {\n header(\"Content-type: image/jpeg\");\nMagickEchoImageBlob( $magick_wand );\n} else {\necho MagickGetExceptionString($magick_wand);\n}\n" }, { "answer_id": 32886714, "author": "shekh danishuesn", "author_id": 5291660, "author_profile": "https://Stackoverflow.com/users/5291660", "pm_score": 0, "selected": false, "text": "header(\"Content-Type: image/png\");\n\n//try to create an image\n$im = @imagecreate(800, 600)\nor die(\"Cannot Initialize new GD image stream\");\n\n//set the background color of the image\n$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);\n\n//set the color for the text \n$text_color = imagecolorallocate($im, 133, 14, 91);\n\n//adf the string to the image\nimagestring($im, 5, 300, 300, \"I'm a pretty picture:))\", $text_color);\n\n//outputs the image as png\nimagepng($im);\n\n//frees any memory associated with the image \nimagedestroy($im);\n if(!file_exists('dw-negative.png')) {\n $img = imagecreatefrompng('dw-manipulate-me.png');\n imagefilter($img,IMG_FILTER_NEGATE);\n imagepng($img,'db-negative.png');\n imagedestroy($img);\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
25,132
<p>I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, &quot;htmlentities&quot; seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up.</p> <p>I would just <i>love</i> to just dump this kind of functions, they seem totally superfluous. <b>Is it still necessary these days to write '&amp;auml;' instead of 'ä'?</b> At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding.</p> <p><b>Update:</b> To be more precise: Are named entities necessary for <i>anything else than displaying HTML tags</i> (as in &quot;&amp;lt;&quot; for &quot;&lt;&quot;)</p> <h3>Update 2:</h3> <p>@Konrad: Are you saying that, no, named entities are not needed?</p> <p>@Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)</p>
[ { "answer_id": 25173, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": true, "text": "application/xhtml+xml text/html &lt; &gt; &amp; &quot; &apos;" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2077/" ]
25,147
<p>I have two arrays of animals (for example).</p> <pre><code>$array = array( array( 'id' =&gt; 1, 'name' =&gt; 'Cat', ), array( 'id' =&gt; 2, 'name' =&gt; 'Mouse', ) ); $array2 = array( array( 'id' =&gt; 2, 'age' =&gt; 321, ), array( 'id' =&gt; 1, 'age' =&gt; 123, ) ); </code></pre> <p>How can I merge the two arrays into one by the ID?</p>
[ { "answer_id": 25155, "author": "Erik van Brakel", "author_id": 909, "author_profile": "https://Stackoverflow.com/users/909", "pm_score": 2, "selected": false, "text": "$array = array(\n 1 => array(\n 'name' => 'Cat',\n ),\n 2 => array(\n 'name' => 'Mouse',\n )\n);\n foreach($array2 as $key=>$value) {\n if(!is_array($array[$key])) $array[$key] = $value;\n else $array[$key] = array_merge($array[key], $value); \n}\n" }, { "answer_id": 25166, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": true, "text": "$array2 $results $results = array();\n\nforeach($array as $subarray)\n{\n $results[$subarray['id']] = array('name' => $subarray['name']);\n}\n\nforeach($array2 as $subarray)\n{\n if(array_key_exists($subarray['id'], $results))\n {\n // Loop through $subarray would go here if you have extra \n $results[$subarray['id']]['age'] = $subarray['age'];\n }\n}\n" }, { "answer_id": 25215, "author": "Andy", "author_id": 1993, "author_profile": "https://Stackoverflow.com/users/1993", "pm_score": -1, "selected": false, "text": "$new = array();\nforeach ($array as $arr) {\n $match = false;\n foreach ($array2 as $arr2) {\n if ($arr['id'] == $arr2['id']) {\n $match = true;\n $new[] = array_merge($arr, $arr2);\n break;\n }\n }\n if ( !$match ) $new[] = $arr;\n}\n" }, { "answer_id": 25237, "author": "AnnanFay", "author_id": 2118, "author_profile": "https://Stackoverflow.com/users/2118", "pm_score": 1, "selected": false, "text": "foreach($array as &$animal)\n{\n foreach($array2 as $animal2)\n {\n if($animal['id'] === $animal2['id'])\n {\n $animal = array_merge($animal, $animal2);\n break;\n }\n }\n}\n" }, { "answer_id": 25347, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": false, "text": "<?php\n $a = array('a' => '1', 'b' => array('t' => '4', 'g' => array('e' => '8')));\n $b = array('c' => '3', 'b' => array('0' => '4', 'g' => array('h' => '5', 'v' => '9')));\n $c = array_merge_recursive($a, $b);\n print_r($c);\n?>\n Array\n(\n [a] => 1\n [b] => Array\n (\n [t] => 4\n [g] => Array\n (\n [e] => 8\n [h] => 5\n [v] => 9\n )\n\n [0] => 4\n )\n\n [c] => 3\n)\n" }, { "answer_id": 14685647, "author": "Uzair Bin Nisar", "author_id": 1276847, "author_profile": "https://Stackoverflow.com/users/1276847", "pm_score": 1, "selected": false, "text": "array_splice array_merge <?php \narray_splice($array1,count($array1),0,$array2);\n?>\n" }, { "answer_id": 14685886, "author": "Marcin Majchrzak", "author_id": 546081, "author_profile": "https://Stackoverflow.com/users/546081", "pm_score": 1, "selected": false, "text": "foreach ($array as $a)\n $new_array[$a['id']]['name'] = $a['name'];\n\nforeach ($array2 as $a)\n $new_array[$a['id']]['age'] = $a['age'];\n [1] => Array\n (\n [name] => Cat\n [age] => 123\n )\n\n [2] => Array\n (\n [name] => Mouse\n [age] => 321\n )\n" }, { "answer_id": 16175388, "author": "Hamed J.I", "author_id": 2294072, "author_profile": "https://Stackoverflow.com/users/2294072", "pm_score": 1, "selected": false, "text": "<?php\n$array1 = array(\"color\" => \"red\", 2, 4);\n$array2 = array(\"a\", \"b\", \"color\" => \"green\", \"shape\" => \"trapezoid\", 4);\n$result = array_merge($array1, $array2);\nprint_r($result);\n?>\n" }, { "answer_id": 17268429, "author": "jb510", "author_id": 554469, "author_profile": "https://Stackoverflow.com/users/554469", "pm_score": 1, "selected": false, "text": "Array (\n [0] => Array\n (\n [id] => 2\n [name] => Cat\n [age] => 321\n )\n\n [1] => Array\n (\n [id] => 1\n [name] => Mouse\n [age] => 123\n )\n)\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2118/" ]
25,158
<p>I'm rewriting an old application and use this as a good opportunity to try out C# and .NET development (I usually do a lot of plug-in stuff in C).</p> <p>The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see.</p> <p>What is the best practice to switch between the views? From start to running? Between the running views?</p> <p>Ideas:</p> <ul> <li>Use one form and hide and show controls</li> <li>Use one start form and then a form with a TabControl</li> <li>Use six separate forms</li> </ul>
[ { "answer_id": 25512, "author": "Chris Karcher", "author_id": 2773, "author_profile": "https://Stackoverflow.com/users/2773", "pm_score": 4, "selected": true, "text": "tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height;\ntabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height;\ntabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));\n" }, { "answer_id": 122186, "author": "Hath", "author_id": 5186, "author_profile": "https://Stackoverflow.com/users/5186", "pm_score": 3, "selected": false, "text": "public partial class MainForm : Form\n{\n public enum FormViews\n {\n A, B\n }\n private MyViewA viewA; //user control with view a on it \n private MyViewB viewB; //user control with view b on it\n\n private FormViews _formView;\n public FormViews FormView\n {\n get\n {\n return _formView;\n }\n set\n {\n _formView = value;\n OnFormViewChanged(_formView);\n }\n }\n protected virtual void OnFormViewChanged(FormViews view)\n {\n //contentPanel is just a System.Windows.Forms.Panel docked to fill the form\n switch (view)\n {\n case FormViews.A:\n if (viewA != null) viewA = new MyViewA();\n //extension method, you could use a static function.\n this.contentPanel.DockControl(viewA); \n break;\n case FormViews.B:\n if (viewB != null) viewB = new MyViewB();\n this.contentPanel.DockControl(viewB);\n break;\n }\n }\n\n public MainForm()\n {\n\n InitializeComponent();\n FormView = FormViews.A; //simply change views like this\n }\n}\n\npublic static class PanelExtensions\n{\n public static void DockControl(this Panel thisControl, Control controlToDock)\n {\n thisControl.Controls.Clear();\n thisControl.Controls.Add(controlToDock);\n controlToDock.Dock = DockStyle.Fill;\n }\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25158", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2703/" ]
25,161
<p>I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo.</p> <p>Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?</p>
[ { "answer_id": 25165, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "title" }, { "answer_id": 25211, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 3, "selected": false, "text": "title" }, { "answer_id": 25262, "author": "Peter Hilton", "author_id": 2670, "author_profile": "https://Stackoverflow.com/users/2670", "pm_score": 4, "selected": true, "text": "<img usemap=\"#logo\" src=\"http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png\">\n<map name=\"logo\">\n<area shape=\"rect\" href=\"\" coords=\"52,42,121,65\" title=\"Stack\">\n<area shape=\"rect\" href=\"\" coords=\"122,42,245,65\" title=\"Overflow\">\n</map>\n area area title shape" }, { "answer_id": 32331929, "author": "Ajay Gupta", "author_id": 2663073, "author_profile": "https://Stackoverflow.com/users/2663073", "pm_score": 1, "selected": false, "text": "title" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384652/" ]
25,174
<p>I've used the PHP MVC framework Symfony to build an on-demand web app.</p> <p>It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as <a href="http://robrosenbaum.com/php/howto-disable-session-timeout-in-symfony/" rel="nofollow noreferrer">this one</a> did not help me.</p> <p>I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future.</p> <p>Has anyone been there and solved it? I would be most grateful for a hint or two!</p>
[ { "answer_id": 483374, "author": "deresh", "author_id": 11851, "author_profile": "https://Stackoverflow.com/users/11851", "pm_score": 0, "selected": false, "text": "all:\n .settings:\n timeout: 864000\n" }, { "answer_id": 1438989, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "all:\n .settings:\n timeout: false\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25174", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2706/" ]
25,200
<p>I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a <code>AutoSize = false</code> in my constructor, however, when I place it in design mode, the property always is True. </p> <p>I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"?</p> <p>Here's the full source code of my Label in case anyone is interested.</p> <pre><code>using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel : UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width &gt; 0 ? width : 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth &gt; 0 ? heigth : 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth &gt; (Width - 1)/2 ? (Width - 1)/2 : RoundedWidth; int roundedHeight = RoundedHeight &gt; (Height - 1)/2 ? (Height - 1)/2 : RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick != null) { TextClick(this, e); } } } } </code></pre> <p>(there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code).</p> <hr> <p>I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel ;)</p> <p>I basically hate the autosize property "on by default".</p>
[ { "answer_id": 699553, "author": "ESRogs", "author_id": 88, "author_profile": "https://Stackoverflow.com/users/88", "pm_score": 0, "selected": false, "text": "this.AutoSize = false" }, { "answer_id": 1651394, "author": "iard68", "author_id": 199835, "author_profile": "https://Stackoverflow.com/users/199835", "pm_score": 2, "selected": false, "text": "Private _Autosize As Boolean \n\nPublic Sub New()\n _Autosize=False\nEnd Sub\n\nPublic Overrides Property AutoSize() As Boolean\n Get\n Return MyBase.AutoSize\n End Get\n\n Set(ByVal Value As Boolean)\n If _Autosize <> Value And _Autosize = False Then\n MyBase.AutoSize = False\n _Autosize = Value\n Else\n MyBase.AutoSize = Value\n End If\n End Set\nEnd Property\n" }, { "answer_id": 73418023, "author": "Lamizor Prod", "author_id": 18461283, "author_profile": "https://Stackoverflow.com/users/18461283", "pm_score": 0, "selected": false, "text": "protected override void OnCreateControl()\n{\n AutoSize = false;\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25200", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684/" ]
25,224
<p>I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata:</p> <pre><code>15, 'QHS', '20', '2008-08-24 13:36:33.465567-04' 15, 'QHE', '8', '2008-08-24 12:07:08.660519-04' 15, 'QHS', '21', '2008-08-24 09:44:44.39354-04' 15, 'QHE', '10', '2008-08-24 08:47:57.672058-04' </code></pre> <p>I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.</p>
[ { "answer_id": 27159, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 2, "selected": false, "text": "SELECT DISTINCT ON (code) code, content, createtime\nFROM metatable\nWHERE userid = 15\nORDER BY code, createtime DESC;\n" }, { "answer_id": 30312, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 0, "selected": false, "text": "SELECT * \nFROM Table\nJOIN (\n SELECT UserId, Code, MAX(Date) as LastDate\n FROM Table\n GROUP BY UserId, Code\n) as Latest ON\n Table.UserId = Latest.UserId\n AND Table.Code = Latest.Code\n AND Table.Date = Latest.Date\nWHERE\n UserId = @userId\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2462/" ]
25,225
<p>I have a couple of files containing a value in each line.</p> <p><strong>EDIT :</strong></p> <p>I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state.</p> <p>I was trying to do:</p> <pre><code>paste -d ',' file1 file2 file 3 file 4 &gt; file5.csv </code></pre> <p>and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 25229, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 0, "selected": false, "text": "cat filetwo >> fileone\n" }, { "answer_id": 25231, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 3, "selected": true, "text": "paste --delimiters=\\; file1 file2\n" }, { "answer_id": 25236, "author": "wilhelmtell", "author_id": 456, "author_profile": "https://Stackoverflow.com/users/456", "pm_score": 1, "selected": false, "text": "file1: file2: file3:\n1 a A\n2 b B\n3 c C\n\n~$ paste file{1,2,3} |sed 's/^\\|$/\"/g; s/\\t/\",\"/g'\n\"1\",\"a\",\"A\"\n\"2\",\"b\",\"B\"\n\"3\",\"c\",\"C\"\n ~$ paste --delimiter , file{1,2,3}\n1,a,A\n2,b,B\n3,c,C\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1582/" ]
25,238
<blockquote> <p>What's the best way to make an element of 100% minimum height across a wide range of browsers ?</p> </blockquote> <p>In particular if you have a layout with a <code>header</code> and <code>footer</code> of fixed <code>height</code>,</p> <p>how do you make the middle content part fill <code>100%</code> of the space in between with the <code>footer</code> fixed to the bottom ?</p>
[ { "answer_id": 25249, "author": "ollifant", "author_id": 2078, "author_profile": "https://Stackoverflow.com/users/2078", "pm_score": 7, "selected": false, "text": "html,body {\n margin:0;\n padding:0;\n height:100%; /* needed for container min-height */\n background:gray;\n\n font-family:arial,sans-serif;\n font-size:small;\n color:#666;\n}\n\nh1 { \n font:1.5em georgia,serif; \n margin:0.5em 0;\n}\n\nh2 {\n font:1.25em georgia,serif; \n margin:0 0 0.5em;\n}\n h1, h2, a {\n color:orange;\n }\n\np { \n line-height:1.5; \n margin:0 0 1em;\n}\n\ndiv#container {\n position:relative; /* needed for footer positioning*/\n margin:0 auto; /* center, not in IE5 */\n width:750px;\n background:#f0f0f0;\n\n height:auto !important; /* real browsers */\n height:100%; /* IE6: treaded as min-height*/\n\n min-height:100%; /* real browsers */\n}\n\ndiv#header {\n padding:1em;\n background:#ddd url(\"../csslayout.gif\") 98% 10px no-repeat;\n border-bottom:6px double gray;\n}\n div#header p {\n font-style:italic;\n font-size:1.1em;\n margin:0;\n }\n\ndiv#content {\n padding:1em 1em 5em; /* bottom padding for footer */\n}\n div#content p {\n text-align:justify;\n padding:0 1em;\n }\n\ndiv#footer {\n position:absolute;\n width:100%;\n bottom:0; /* stick to bottom */\n background:#ddd;\n border-top:6px double gray;\n}\ndiv#footer p {\n padding:1em;\n margin:0;\n}\n" }, { "answer_id": 42854, "author": "levik", "author_id": 4465, "author_profile": "https://Stackoverflow.com/users/4465", "pm_score": 3, "selected": false, "text": "CSS #content { min-height: 100%; } <div> function resizeContent() {\n var contentDiv = document.getElementById('content');\n var headerDiv = document.getElementById('header');\n // This may need to be done differently on IE than FF, but you get the idea.\n var viewPortHeight = window.innerHeight - headerDiv.clientHeight;\n contentDiv.style.height = \n Math.max(viewportHeight, contentDiv.clientHeight) + 'px';\n}\n onLoad onResize <body onload=\"resizeContent()\" onresize=\"resizeContent()\">\n . . .\n</body>\n" }, { "answer_id": 2684612, "author": "MilanBSD", "author_id": 322482, "author_profile": "https://Stackoverflow.com/users/322482", "pm_score": 2, "selected": false, "text": "body{ height: 100%; }\n#content { \n min-height: 500px;\n height: 100%;\n}\n#footer {\n height: 100px;\n clear: both !important;\n}\n div clear:both" }, { "answer_id": 5486053, "author": "Chris", "author_id": 683864, "author_profile": "https://Stackoverflow.com/users/683864", "pm_score": 5, "selected": false, "text": "body, html {\n height: 100%;\n}\n#outerbox {\n width: 100%;\n position: absolute; /* to place it somewhere on the screen */\n top: 130px; /* free space at top */\n bottom: 0; /* makes it lock to the bottom */\n}\n#innerbox {\n width: 100%;\n position: absolute; \n min-height: 100% !important; /* browser fill */\n height: auto; /*content fill */\n} <div id=\"outerbox\">\n <div id=\"innerbox\"></div>\n</div>" }, { "answer_id": 6870037, "author": "Yuda Prawira", "author_id": 454229, "author_profile": "https://Stackoverflow.com/users/454229", "pm_score": 0, "selected": false, "text": "#content{\n height: auto;\n min-height:350px;\n}\n" }, { "answer_id": 12856368, "author": "Afshin Mehrabani", "author_id": 375966, "author_profile": "https://Stackoverflow.com/users/375966", "pm_score": 2, "selected": false, "text": "div id='footer' content <html>\n <body>\n <div id=\"content\">\n ...\n </div>\n <div id=\"footer\"></div>\n </body>\n</html>\n ​html, body {\n height: 100%; \n}\n#content {\n height: 100%;\n}\n#footer {\n clear: both; \n}\n" }, { "answer_id": 18486705, "author": "vsync", "author_id": 104380, "author_profile": "https://Stackoverflow.com/users/104380", "pm_score": 3, "selected": false, "text": "min-height min-height 1px min-height" }, { "answer_id": 18918955, "author": "Konstantin Smolyanin", "author_id": 1823469, "author_profile": "https://Stackoverflow.com/users/1823469", "pm_score": 2, "selected": false, "text": "\"the middle content part fill 100% of the space in between with the footer fixed to the bottom\" html, body { height: 100%; }\nyour_container { min-height: calc(100% - height_of_your_footer); }\n <html><head></head><body>\n <main> your main content </main>\n </footer> your footer content </footer>\n </body></html>\n html, body { height: 100%; }\n main { min-height: calc(100% - 2em); }\n footer { height: 2em; }\n" }, { "answer_id": 21079633, "author": "Fanky", "author_id": 2095642, "author_profile": "https://Stackoverflow.com/users/2095642", "pm_score": 0, "selected": false, "text": "#pagewrapper{\n/* Firefox */\nheight: -moz-calc(100% - 100px); /*assume i.e. your header above the wrapper is 80 and the footer bellow is 20*/\n/* WebKit */\nheight: -webkit-calc(100% - 100px);\n/* Opera */\nheight: -o-calc(100% - 100px);\n/* Standard */\nheight: calc(100% - 100px);\n}\n" }, { "answer_id": 32027464, "author": "Stanislav", "author_id": 2213164, "author_profile": "https://Stackoverflow.com/users/2213164", "pm_score": 5, "selected": false, "text": "vh viewpoint height * {\n /* personal preference */\n margin: 0;\n padding: 0;\n}\nhtml {\n /* make sure we use up the whole viewport */\n width: 100%;\n min-height: 100vh;\n /* for debugging, a red background lets us see any seams */\n background-color: red;\n}\nbody {\n /* make sure we use the full width but allow for more height */\n width: 100%;\n min-height: 100vh; /* this helps with the sticky footer */\n}\nmain {\n /* for debugging, a blue background lets us see the content */\n background-color: skyblue;\n min-height: calc(100vh - 2.5em); /* this leaves space for the sticky footer */\n}\nfooter {\n /* for debugging, a gray background lets us see the footer */\n background-color: gray;\n min-height:2.5em;\n} <main>\n <p>This is the content. Resize the viewport vertically to see how the footer behaves.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n <p>This is the content.</p>\n</main>\n<footer>\n <p>This is the footer. Resize the viewport horizontally to see how the height behaves when text wraps.</p>\n <p>This is the footer.</p>\n</footer> 1vw (viewport width) = 1% of viewport width\n1vh (viewport height) = 1% of viewport height\n1vmin (viewport minimum) = 1vw or 1vh, whatever is smallest\n1vmax (viewport minimum) = 1vw or 1vh, whatever is largest\n" }, { "answer_id": 66713668, "author": "peja", "author_id": 3617261, "author_profile": "https://Stackoverflow.com/users/3617261", "pm_score": 0, "selected": false, "text": "html,\n body {\n height: 100%;\n }\n\n<html>\n <body>\n\n </body>\n</html>\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1725/" ]
25,240
<p>FCKeditor has InsertHtml API (<a href="http://docs.fckeditor.net/FCKeditor_2.x/Developers_Guide/JavaScript_API" rel="nofollow noreferrer">JavaScript API document</a>) that inserts HTML in the current cursor position. How do I insert at the very end of the document?</p> <p>Do I need to start browser sniffing with something like this</p> <pre><code>if ( element.insertAdjacentHTML ) // IE element.insertAdjacentHTML( 'beforeBegin', html ) ; else // Gecko { var oRange = document.createRange() ; oRange.setStartBefore( element ) ; var oFragment = oRange.createContextualFragment( html ); element.parentNode.insertBefore( oFragment, element ) ; } </code></pre> <p>or is there a blessed way that I missed?</p> <p>Edit: Of course, I can rewrite the whole HTML, as answers suggest, but I cannot believe that is the "blessed" way. That means that the browser should destroy whatever it has and re-parse the document from scratch. That cannot be good. For example, I expect that to break the undo stack.</p>
[ { "answer_id": 720544, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "var oEditor = FCKeditorAPI.GetInstance('Editor_instance') ;\n OldText=oEditor.GetXHTML( true );\n\n oEditor.SetData( OldText+\"Your text\");\n" }, { "answer_id": 5564221, "author": "francois saab", "author_id": 694541, "author_profile": "https://Stackoverflow.com/users/694541", "pm_score": 1, "selected": false, "text": ":element.insertAdjacentHTML('beforeBegin', html); try {\n $(html).insertBefore($(element));\n // element.insertAdjacentHTML('beforeBegin', html);\n\n} catch (err) { }\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25240", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2515/" ]
25,252
<p>I'm using <a href="http://www.zend.com/en/products/studio/" rel="nofollow noreferrer">Zend Studio</a> to do remote debugging of my php scripts on a dev server. It works great for web code, but can I make it work with command line scripts?</p> <p>I have several helper apps to make my application run. It would be really useful to fire up the remote debugger through command line instead of a web browser so I can test these out. </p> <p>I assume it's possible, since I think Zend is using xdebug to talk to Eclipse. Apparently, it adds some parameters to the request to wake the Zend code up on a request. I'm guessing I'd need to tap into that?</p> <p><em>UPDATE</em></p> <p>I ended up using xdebug with <a href="http://protoeditor.sourceforge.net/" rel="nofollow noreferrer">protoeditor</a> over X to do my debugging.</p>
[ { "answer_id": 3091577, "author": "Ramon Poca", "author_id": 117188, "author_profile": "https://Stackoverflow.com/users/117188", "pm_score": 0, "selected": false, "text": "export QUERY_STRING=start_debug=1&debug_host=<host name or IP of the local machine>&debug_port=<the port that is configured in your ZDE settings>&debug_stop=1\n" }, { "answer_id": 4786171, "author": "amateur barista", "author_id": 467453, "author_profile": "https://Stackoverflow.com/users/467453", "pm_score": 0, "selected": false, "text": "QUERY_STRING" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25252", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2506/" ]
25,259
<p>What is a good complete <a href="http://en.wikipedia.org/wiki/Regular_expression" rel="noreferrer">regular expression</a> or some other process that would take the title:</p> <blockquote> <p>How do you change a title to be part of the URL like Stack Overflow?</p> </blockquote> <p>and turn it into </p> <pre class="lang-none prettyprint-override"><code>how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow </code></pre> <p>that is used in the SEO-friendly URLs on Stack&nbsp;Overflow?</p> <p>The development environment I am using is <a href="http://en.wikipedia.org/wiki/Ruby_on_Rails" rel="noreferrer">Ruby on Rails</a>, but if there are some other platform-specific solutions (.NET, PHP, <a href="http://en.wikipedia.org/wiki/Django_%28web_framework%29" rel="noreferrer">Django</a>), I would love to see those too. </p> <p>I am sure I (or another reader) will come across the same problem on a different platform down the line. </p> <p>I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.</p>
[ { "answer_id": 25263, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 4, "selected": false, "text": "def permalink_for(str)\n str.gsub(/[^\\w\\/]|[!\\(\\)\\.]+/, ' ').strip.downcase.gsub(/\\ +/, '-')\nend\n" }, { "answer_id": 25275, "author": "Vegard Larsen", "author_id": 1606, "author_profile": "https://Stackoverflow.com/users/1606", "pm_score": 3, "selected": false, "text": "$sURL = \"This is a title to convert to URL-format. It has 1 number in it!\";\n// To lower-case\n$sURL = strtolower($sURL);\n\n// Replace all non-word characters with spaces\n$sURL = preg_replace(\"/\\W+/\", \" \", $sURL);\n\n// Remove trailing spaces (so we won't end with a separator)\n$sURL = trim($sURL);\n\n// Replace spaces with separators (hyphens)\n$sURL = str_replace(\" \", \"-\", $sURL);\n\necho $sURL;\n// outputs: this-is-a-title-to-convert-to-url-format-it-has-1-number-in-it\n" }, { "answer_id": 25279, "author": "Brian", "author_id": 683, "author_profile": "https://Stackoverflow.com/users/683", "pm_score": 2, "selected": false, "text": "my $title = \"How do you change a title to be part of the url like Stackoverflow?\";\n\nmy $url = lc $title; # Change to lower case and copy to URL.\n$url =~ s/^\\s+//g; # Remove leading spaces.\n$url =~ s/\\s+$//g; # Remove trailing spaces.\n$url =~ s/\\s+/\\-/g; # Change one or more spaces to single hyphen.\n$url =~ s/[^\\w\\-]//g; # Remove any non-word characters.\n\nprint \"$title\\n$url\\n\";\n" }, { "answer_id": 25280, "author": "John Topley", "author_id": 1450, "author_profile": "https://Stackoverflow.com/users/1450", "pm_score": 2, "selected": false, "text": "def to_param\n title.downcase.gsub(/ /, '-')\nend\n validates_format_of :title, :with => /^[a-z0-9-]+$/,\n :message => 'can only contain letters, numbers and hyphens'\n" }, { "answer_id": 25285, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "title.downcase.strip.gsub(/\\ /, '-').gsub(/[^\\w\\-]/, '')\n downcase strip gsub" }, { "answer_id": 25486, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 9, "selected": true, "text": "/// <summary>\n/// Produces optional, URL-friendly version of a title, \"like-this-one\". \n/// hand-tuned for speed, reflects performance refactoring contributed\n/// by John Gietzen (user otac0n) \n/// </summary>\npublic static string URLFriendly(string title)\n{\n if (title == null) return \"\";\n\n const int maxlen = 80;\n int len = title.Length;\n bool prevdash = false;\n var sb = new StringBuilder(len);\n char c;\n\n for (int i = 0; i < len; i++)\n {\n c = title[i];\n if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))\n {\n sb.Append(c);\n prevdash = false;\n }\n else if (c >= 'A' && c <= 'Z')\n {\n // tricky way to convert to lowercase\n sb.Append((char)(c | 32));\n prevdash = false;\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || \n c == '\\\\' || c == '-' || c == '_' || c == '=')\n {\n if (!prevdash && sb.Length > 0)\n {\n sb.Append('-');\n prevdash = true;\n }\n }\n else if ((int)c >= 128)\n {\n int prevlen = sb.Length;\n sb.Append(RemapInternationalCharToAscii(c));\n if (prevlen != sb.Length) prevdash = false;\n }\n if (i == maxlen) break;\n }\n\n if (prevdash)\n return sb.ToString().Substring(0, sb.Length - 1);\n else\n return sb.ToString();\n}\n RemapInternationalCharToAscii" }, { "answer_id": 37922, "author": "fijter", "author_id": 3215, "author_profile": "https://Stackoverflow.com/users/3215", "pm_score": 4, "selected": false, "text": "function makeSlug(urlString, filter) {\n // Changes, e.g., \"Petty theft\" to \"petty_theft\".\n // Remove all these words from the string before URLifying\n\n if(filter) {\n removelist = [\"a\", \"an\", \"as\", \"at\", \"before\", \"but\", \"by\", \"for\", \"from\",\n \"is\", \"in\", \"into\", \"like\", \"of\", \"off\", \"on\", \"onto\", \"per\",\n \"since\", \"than\", \"the\", \"this\", \"that\", \"to\", \"up\", \"via\", \"het\", \"de\", \"een\", \"en\",\n \"with\"];\n }\n else {\n removelist = [];\n }\n s = urlString;\n r = new RegExp('\\\\b(' + removelist.join('|') + ')\\\\b', 'gi');\n s = s.replace(r, '');\n s = s.replace(/[^-\\w\\s]/g, ''); // Remove unneeded characters\n s = s.replace(/^\\s+|\\s+$/g, ''); // Trim leading/trailing spaces\n s = s.replace(/[-\\s]+/g, '-'); // Convert spaces to hyphens\n s = s.toLowerCase(); // Convert to lowercase\n return s; // Trim to first num_chars characters\n}\n" }, { "answer_id": 47633, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 2, "selected": false, "text": "CREATE FUNCTION dbo.Slug(@string varchar(1024))\nRETURNS varchar(3072)\nAS\nBEGIN\n DECLARE @count int, @c char(1), @i int, @slug varchar(3072)\n\n SET @string = replace(lower(ltrim(rtrim(@string))),' ','-')\n\n SET @count = Len(@string)\n SET @i = 1\n SET @slug = ''\n\n WHILE (@i <= @count)\n BEGIN\n SET @c = substring(@string, @i, 1)\n\n IF @c LIKE '[a-z0-9--]'\n SET @slug = @slug + @c\n\n SET @i = @i +1\n END\n\n RETURN @slug\nEND\n" }, { "answer_id": 399903, "author": "Thibaut Barrère", "author_id": 20302, "author_profile": "https://Stackoverflow.com/users/20302", "pm_score": 3, "selected": false, "text": " class Person\n def to_param\n \"#{id}-#{name.parameterize}\"\n end\n end\n\n @person = Person.find(1)\n # => #<Person id: 1, name: \"Donald E. Knuth\">\n\n <%= link_to(@person.name, person_path(@person)) %>\n # => <a href=\"/person/1-donald-e-knuth\">Donald E. Knuth</a>\n DiacriticsFu::escape(\"éphémère\")\n=> \"ephemere\"\n\nDiacriticsFu::escape(\"räksmörgås\")\n=> \"raksmorgas\"\n" }, { "answer_id": 645130, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<?php\n function slug($str)\n {\n $args = func_get_args();\n array_filter($args); //remove blanks\n $slug = mb_strtolower(implode('-', $args));\n\n $real_slug = '';\n $hyphen = '';\n foreach(SU::mb_str_split($slug) as $c)\n {\n if (strlen($c) > 1 && mb_strlen($c)===1)\n {\n $real_slug .= $hyphen . $c;\n $hyphen = '';\n }\n else\n {\n switch($c)\n {\n case '&':\n $hyphen = $real_slug ? '-and-' : '';\n break;\n case 'a':\n case 'b':\n case 'c':\n case 'd':\n case 'e':\n case 'f':\n case 'g':\n case 'h':\n case 'i':\n case 'j':\n case 'k':\n case 'l':\n case 'm':\n case 'n':\n case 'o':\n case 'p':\n case 'q':\n case 'r':\n case 's':\n case 't':\n case 'u':\n case 'v':\n case 'w':\n case 'x':\n case 'y':\n case 'z':\n\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n case 'E':\n case 'F':\n case 'G':\n case 'H':\n case 'I':\n case 'J':\n case 'K':\n case 'L':\n case 'M':\n case 'N':\n case 'O':\n case 'P':\n case 'Q':\n case 'R':\n case 'S':\n case 'T':\n case 'U':\n case 'V':\n case 'W':\n case 'X':\n case 'Y':\n case 'Z':\n\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n $real_slug .= $hyphen . $c;\n $hyphen = '';\n break;\n\n default:\n $hyphen = $hyphen ? $hyphen : ($real_slug ? '-' : '');\n }\n }\n }\n return $real_slug;\n }\n $str = \"~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 コリン ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 トーマス ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04 アーノルド ~!@#$%^&*()_+-=[]\\{}|;':\\\",./<>?\\n\\r\\t\\x07\\x00\\x04\";\necho slug($str);\n" }, { "answer_id": 6740497, "author": "DanH", "author_id": 644682, "author_profile": "https://Stackoverflow.com/users/644682", "pm_score": 5, "selected": false, "text": "public static class Slug\n{\n public static string Create(bool toLower, params string[] values)\n {\n return Create(toLower, String.Join(\"-\", values));\n }\n\n /// <summary>\n /// Creates a slug.\n /// References:\n /// http://www.unicode.org/reports/tr15/tr15-34.html\n /// https://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696\n /// https://stackoverflow.com/questions/25259/how-do-you-include-a-webpage-title-as-part-of-a-webpage-url/25486#25486\n /// https://stackoverflow.com/questions/3769457/how-can-i-remove-accents-on-a-string\n /// </summary>\n /// <param name=\"toLower\"></param>\n /// <param name=\"normalised\"></param>\n /// <returns></returns>\n public static string Create(bool toLower, string value)\n {\n if (value == null)\n return \"\";\n\n var normalised = value.Normalize(NormalizationForm.FormKD);\n\n const int maxlen = 80;\n int len = normalised.Length;\n bool prevDash = false;\n var sb = new StringBuilder(len);\n char c;\n\n for (int i = 0; i < len; i++)\n {\n c = normalised[i];\n if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n sb.Append(c);\n }\n else if (c >= 'A' && c <= 'Z')\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n // Tricky way to convert to lowercase\n if (toLower)\n sb.Append((char)(c | 32));\n else\n sb.Append(c);\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\\\' || c == '-' || c == '_' || c == '=')\n {\n if (!prevDash && sb.Length > 0)\n {\n prevDash = true;\n }\n }\n else\n {\n string swap = ConvertEdgeCases(c, toLower);\n\n if (swap != null)\n {\n if (prevDash)\n {\n sb.Append('-');\n prevDash = false;\n }\n sb.Append(swap);\n }\n }\n\n if (sb.Length == maxlen)\n break;\n }\n return sb.ToString();\n }\n\n static string ConvertEdgeCases(char c, bool toLower)\n {\n string swap = null;\n switch (c)\n {\n case 'ı':\n swap = \"i\";\n break;\n case 'ł':\n swap = \"l\";\n break;\n case 'Ł':\n swap = toLower ? \"l\" : \"L\";\n break;\n case 'đ':\n swap = \"d\";\n break;\n case 'ß':\n swap = \"ss\";\n break;\n case 'ø':\n swap = \"o\";\n break;\n case 'Þ':\n swap = \"th\";\n break;\n }\n return swap;\n }\n}\n" }, { "answer_id": 9898628, "author": "Peyman Mehrabani", "author_id": 1138725, "author_profile": "https://Stackoverflow.com/users/1138725", "pm_score": 2, "selected": false, "text": "public static string ConvertTextToSlug(string s)\n{\n StringBuilder sb = new StringBuilder();\n\n bool wasHyphen = true;\n\n foreach (char c in s)\n {\n if (char.IsLetterOrDigit(c))\n {\n sb.Append(char.ToLower(c));\n wasHyphen = false;\n }\n else\n if (char.IsWhiteSpace(c) && !wasHyphen)\n {\n sb.Append('-');\n wasHyphen = true;\n }\n }\n\n // Avoid trailing hyphens\n if (wasHyphen && sb.Length > 0)\n sb.Length--;\n\n return sb.ToString().Replace(\"--\",\"-\");\n}\n" }, { "answer_id": 20423735, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "is_between function is_between($val, $min, $max)\n{\n $val = (int) $val; $min = (int) $min; $max = (int) $max;\n\n return ($val >= $min && $val <= $max);\n}\n\nfunction international_char_to_ascii($char)\n{\n if (mb_strpos('àåáâäãåa', $char) !== false)\n {\n return 'a';\n }\n\n if (mb_strpos('èéêëe', $char) !== false)\n {\n return 'e';\n }\n\n if (mb_strpos('ìíîïi', $char) !== false)\n {\n return 'i';\n }\n\n if (mb_strpos('òóôõö', $char) !== false)\n {\n return 'o';\n }\n\n if (mb_strpos('ùúûüuu', $char) !== false)\n {\n return 'u';\n }\n\n if (mb_strpos('çccc', $char) !== false)\n {\n return 'c';\n }\n\n if (mb_strpos('zzž', $char) !== false)\n {\n return 'z';\n }\n\n if (mb_strpos('ssšs', $char) !== false)\n {\n return 's';\n }\n\n if (mb_strpos('ñn', $char) !== false)\n {\n return 'n';\n }\n\n if (mb_strpos('ýÿ', $char) !== false)\n {\n return 'y';\n }\n\n if (mb_strpos('gg', $char) !== false)\n {\n return 'g';\n }\n\n if (mb_strpos('r', $char) !== false)\n {\n return 'r';\n }\n\n if (mb_strpos('l', $char) !== false)\n {\n return 'l';\n }\n\n if (mb_strpos('d', $char) !== false)\n {\n return 'd';\n }\n\n if (mb_strpos('ß', $char) !== false)\n {\n return 'ss';\n }\n\n if (mb_strpos('Þ', $char) !== false)\n {\n return 'th';\n }\n\n if (mb_strpos('h', $char) !== false)\n {\n return 'h';\n }\n\n if (mb_strpos('j', $char) !== false)\n {\n return 'j';\n }\n return '';\n}\n\nfunction url_friendly_title($url_title)\n{\n if (empty($url_title))\n {\n return '';\n }\n\n $url_title = mb_strtolower($url_title);\n\n $url_title_max_length = 80;\n $url_title_length = mb_strlen($url_title);\n $url_title_friendly = '';\n $url_title_dash_added = false;\n $url_title_char = '';\n\n for ($i = 0; $i < $url_title_length; $i++)\n {\n $url_title_char = mb_substr($url_title, $i, 1);\n\n if (strlen($url_title_char) == 2)\n {\n $url_title_ascii = ord($url_title_char[0]) * 256 + ord($url_title_char[1]) . \"\\r\\n\";\n }\n else\n {\n $url_title_ascii = ord($url_title_char);\n }\n\n if (is_between($url_title_ascii, 97, 122) || is_between($url_title_ascii, 48, 57))\n {\n $url_title_friendly .= $url_title_char;\n\n $url_title_dash_added = false;\n }\n elseif(is_between($url_title_ascii, 65, 90))\n {\n $url_title_friendly .= chr(($url_title_ascii | 32));\n\n $url_title_dash_added = false;\n }\n elseif($url_title_ascii == 32 || $url_title_ascii == 44 || $url_title_ascii == 46 || $url_title_ascii == 47 || $url_title_ascii == 92 || $url_title_ascii == 45 || $url_title_ascii == 47 || $url_title_ascii == 95 || $url_title_ascii == 61)\n {\n if (!$url_title_dash_added && mb_strlen($url_title_friendly) > 0)\n {\n $url_title_friendly .= chr(45);\n\n $url_title_dash_added = true;\n }\n }\n else if ($url_title_ascii >= 128)\n {\n $url_title_previous_length = mb_strlen($url_title_friendly);\n\n $url_title_friendly .= international_char_to_ascii($url_title_char);\n\n if ($url_title_previous_length != mb_strlen($url_title_friendly))\n {\n $url_title_dash_added = false;\n }\n }\n\n if ($i == $url_title_max_length)\n {\n break;\n }\n }\n\n if ($url_title_dash_added)\n {\n return mb_substr($url_title_friendly, 0, -1);\n }\n else\n {\n return $url_title_friendly;\n }\n}\n" }, { "answer_id": 25063322, "author": "giammin", "author_id": 921690, "author_profile": "https://Stackoverflow.com/users/921690", "pm_score": 2, "selected": false, "text": "public static string ToFriendlyUrl(string title, bool useUTF8Encoding = false)\n{\n ...\n\n else if (c >= 128)\n {\n int prevlen = sb.Length;\n if (useUTF8Encoding )\n {\n sb.Append(HttpUtility.UrlEncode(c.ToString(CultureInfo.InvariantCulture),Encoding.UTF8));\n }\n else\n {\n sb.Append(RemapInternationalCharToAscii(c));\n }\n ...\n}\n RemapInternationalCharToAscii" }, { "answer_id": 29551373, "author": "Ronnie Overby", "author_id": 64334, "author_profile": "https://Stackoverflow.com/users/64334", "pm_score": 2, "selected": false, "text": "public static string URLFriendly(string title)\n{\n char? prevRead = null,\n prevWritten = null;\n\n var seq = \n from c in title\n let norm = RemapInternationalCharToAscii(char.ToLowerInvariant(c).ToString())[0]\n let keep = char.IsLetterOrDigit(norm)\n where prevRead.HasValue || keep\n let replaced = keep ? norm\n : prevWritten != '-' ? '-'\n : (char?)null\n where replaced != null\n let s = replaced + (prevRead == null ? \"\"\n : norm == '#' && \"cf\".Contains(prevRead.Value) ? \"sharp\"\n : norm == '+' ? \"plus\"\n : \"\")\n let _ = prevRead = norm\n from written in s\n let __ = prevWritten = written\n select written;\n\n const int maxlen = 80; \n return string.Concat(seq.Take(maxlen)).TrimEnd('-');\n}\n\npublic static string RemapInternationalCharToAscii(string text)\n{\n var seq = text.Normalize(NormalizationForm.FormD)\n .Where(c => CharUnicodeInfo.GetUnicodeCategory(c) != UnicodeCategory.NonSpacingMark);\n\n return string.Concat(seq).Normalize(NormalizationForm.FormC);\n}\n \" I love C#, F#, C++, and... Crème brûlée!!! They see me codin'... they hatin'... tryin' to catch me codin' dirty... \"" }, { "answer_id": 32794641, "author": "Rotem", "author_id": 628659, "author_profile": "https://Stackoverflow.com/users/628659", "pm_score": 2, "selected": false, "text": "\\\\p{^L}+ var text = 'This ! can @ have # several $ letters % from different languages such as עברית or Español';\n\nvar slugRegEx = XRegExp('((?!\\\\d)\\\\p{^L})+', 'g');\n\nvar slug = XRegExp.replace(text, slugRegEx, '-').toLowerCase();\n\nconsole.log(slug) ==> \"this-can-have-several-letters-from-different-languages-such-as-עברית-or-español\"\n" }, { "answer_id": 49909421, "author": "Sam", "author_id": 2138442, "author_profile": "https://Stackoverflow.com/users/2138442", "pm_score": 1, "selected": false, "text": ".contains String .includes if (!String.prototype.contains) {\n String.prototype.contains = function (check) {\n return this.indexOf(check, 0) !== -1;\n };\n}\n\ndeclare interface String {\n contains(check: string): boolean;\n}\n\nexport function MakeUrlFriendly(title: string) {\n if (title == null || title == '')\n return '';\n\n const maxlen = 80;\n let len = title.length;\n let prevdash = false;\n let result = '';\n let c: string;\n let cc: number;\n let remapInternationalCharToAscii = function (c: string) {\n let s = c.toLowerCase();\n if (\"àåáâäãåą\".contains(s)) {\n return \"a\";\n }\n else if (\"èéêëę\".contains(s)) {\n return \"e\";\n }\n else if (\"ìíîïı\".contains(s)) {\n return \"i\";\n }\n else if (\"òóôõöøőð\".contains(s)) {\n return \"o\";\n }\n else if (\"ùúûüŭů\".contains(s)) {\n return \"u\";\n }\n else if (\"çćčĉ\".contains(s)) {\n return \"c\";\n }\n else if (\"żźž\".contains(s)) {\n return \"z\";\n }\n else if (\"śşšŝ\".contains(s)) {\n return \"s\";\n }\n else if (\"ñń\".contains(s)) {\n return \"n\";\n }\n else if (\"ýÿ\".contains(s)) {\n return \"y\";\n }\n else if (\"ğĝ\".contains(s)) {\n return \"g\";\n }\n else if (c == 'ř') {\n return \"r\";\n }\n else if (c == 'ł') {\n return \"l\";\n }\n else if (c == 'đ') {\n return \"d\";\n }\n else if (c == 'ß') {\n return \"ss\";\n }\n else if (c == 'Þ') {\n return \"th\";\n }\n else if (c == 'ĥ') {\n return \"h\";\n }\n else if (c == 'ĵ') {\n return \"j\";\n }\n else {\n return \"\";\n }\n };\n\n for (let i = 0; i < len; i++) {\n c = title[i];\n cc = c.charCodeAt(0);\n\n if ((cc >= 97 /* a */ && cc <= 122 /* z */) || (cc >= 48 /* 0 */ && cc <= 57 /* 9 */)) {\n result += c;\n prevdash = false;\n }\n else if ((cc >= 65 && cc <= 90 /* A - Z */)) {\n result += c.toLowerCase();\n prevdash = false;\n }\n else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\\\' || c == '-' || c == '_' || c == '=') {\n if (!prevdash && result.length > 0) {\n result += '-';\n prevdash = true;\n }\n }\n else if (cc >= 128) {\n let prevlen = result.length;\n result += remapInternationalCharToAscii(c);\n if (prevlen != result.length) prevdash = false;\n }\n if (i == maxlen) break;\n }\n\n if (prevdash)\n return result.substring(0, result.length - 1);\n else\n return result;\n }\n" }, { "answer_id": 63829335, "author": "David", "author_id": 817565, "author_profile": "https://Stackoverflow.com/users/817565", "pm_score": -1, "selected": false, "text": " public static string RemapInternationalCharToAscii(char c)\n {\n var s = c.ToString().ToLowerInvariant();\n\n var mappings = new Dictionary<string, string>\n {\n { \"a\", \"àåáâäãåą\" },\n { \"c\", \"çćčĉ\" },\n { \"d\", \"đ\" },\n { \"e\", \"èéêëę\" },\n { \"g\", \"ğĝ\" },\n { \"h\", \"ĥ\" },\n { \"i\", \"ìíîïı\" },\n { \"j\", \"ĵ\" },\n { \"l\", \"ł\" },\n { \"n\", \"ñń\" },\n { \"o\", \"òóôõöøőð\" },\n { \"r\", \"ř\" },\n { \"s\", \"śşšŝ\" },\n { \"ss\", \"ß\" },\n { \"th\", \"Þ\" },\n { \"u\", \"ùúûüŭů\" },\n { \"y\", \"ýÿ\" },\n { \"z\", \"żźž\" }\n };\n\n foreach(var mapping in mappings)\n {\n if (mapping.Value.Contains(s))\n return mapping.Key;\n }\n\n return string.Empty;\n }\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1632/" ]
25,268
<p>Has anybody out there used the <a href="http://www.swig.org/exec.html" rel="noreferrer">SWIG</a> library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my .NET application.</p> Edit: Some clarification on target OS's. <p>I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.</p>
[ { "answer_id": 1067011, "author": "Roark Fan", "author_id": 25362, "author_profile": "https://Stackoverflow.com/users/25362", "pm_score": 4, "selected": true, "text": "Examples/csharp/class mystuff.dll mystuffnet.dll" }, { "answer_id": 1070469, "author": "Marc Bernier", "author_id": 23569, "author_profile": "https://Stackoverflow.com/users/23569", "pm_score": 4, "selected": false, "text": "%module mdProject\n\n%{\n#include \"mdProject.h\"\n%}\n swig -csharp -c++ -I../../Include mdProject.i\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1117/" ]
25,269
<p>I'm having an amazing amount of trouble starting and stopping a service on my remote server from my msbuild script.</p> <p>SC.EXE and the ServiceController MSBuild task don't provide switches to allow a username/password so they won't authenticate, so I'm using RemoteService.exe from www.intelliadmin.com</p> <p>-Authenticating with \xx.xx.xx.xxx -Authentication complete -Stopping service -Error: Access Denied</p> <p>The user account details I'm specifying are for a local admin on the server, so whats up?! I'm tearing my hair out!</p> <h3>Update:</h3> <p>OK here's a bit more background. I have an an XP machine in the office running the CI server. The build script connects a VPN to the datacentre, where I have a Server 2008 machine. Neither of them are on a domain.</p>
[ { "answer_id": 25326, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 3, "selected": false, "text": "C:\\> net use \\\\xx.xx.xx.xx\\ipc$ * /user:username\n *" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086/" ]
25,277
<p>There is a <a href="https://web.archive.org/web/20081014140251/http://stackoverflow.uservoice.com:80/pages/general/suggestions/16644" rel="nofollow noreferrer">request</a> to make the SO search default to an AND style functionality over the current OR when multiple terms are used.</p> <p>The official response was:</p> <blockquote> <p>not as simple as it sounds; we use SQL Server 2005's <a href="https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms176078%28v=sql.90%29" rel="nofollow noreferrer">FREETEXT()</a> function, and I can't find a way to specify AND vs. OR -- can you?</p> </blockquote> <p>So, is there a way?</p> <p>There are a <a href="https://learn.microsoft.com/en-us/previous-versions/sql/sql-server-2005/ms142519%28v=sql.90%29" rel="nofollow noreferrer">number of resources</a> on it I can find, but I am not an expert.</p>
[ { "answer_id": 25287, "author": "Martin Marconcini", "author_id": 2684, "author_profile": "https://Stackoverflow.com/users/2684", "pm_score": 2, "selected": false, "text": "WHERE FREETEXT('You gotta love MS-SQL') > 0\n AND FREETEXT('You gotta love MySQL too...') > 0\n" }, { "answer_id": 25456, "author": "Jeff Atwood", "author_id": 1, "author_profile": "https://Stackoverflow.com/users/1", "pm_score": 2, "selected": true, "text": "CONTAINS() AND FREETEXT() OR" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25277", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2134/" ]
25,282
<p>The point of this question is to collect a list of examples of hashtable implementations using arrays in different languages. It would also be nice if someone could throw in a pretty detailed overview of how they work, and what is happening with each example. </p> <p><strong>Edit:</strong> </p> <p>Why not just use the built in hash functions in your specific language? </p> <p>Because we should know how hash tables work and be able to implement them. This may not seem like a super important topic, but knowing how one of the most used data structures works seems pretty important to me. If this is to become the wikipedia of programming, then these are some of the types of questions that I will come here for. I'm not looking for a CS book to be written here. I could go pull Intro to Algorithms off the shelf and read up on the chapter on hash tables and get that type of info. More specifically what I am looking for are <strong>code examples</strong>. Not only for me in particular, but also for others who would maybe one day be searching for similar info and stumble across this page. </p> <p>To be more specific: If you <strong>had</strong> to implement them, and could not use built-in functions, how would you do it? </p> <p>You don't need to put the code here. Put it in pastebin and just link it. </p>
[ { "answer_id": 25365, "author": "SemiColon", "author_id": 1994, "author_profile": "https://Stackoverflow.com/users/1994", "pm_score": 4, "selected": false, "text": "int ComputeHash(char* key)\n{\n int hash = 5381;\n while (*key)\n hash = ((hash << 5) + hash) + *(key++);\n return hash % hashTable.totalBuckets;\n}\n typedef struct HashTable{\n HashTable* nextEntry;\n char* key;\n char* value;\n}HashBucket;\n\ntypedef struct HashTableEntry{\n int totalBuckets; // Total number of buckets allocated for the hash table\n HashTable** hashBucketArray; // Pointer to array of buckets\n}HashTableEntry;\nHashTableEntry hashTable;\n\nbool InitHashTable(int totalBuckets)\n{\n if(totalBuckets > 0)\n {\n hashTable.totalBuckets = totalBuckets;\n hashTable.hashBucketArray = (HashTable**)malloc(totalBuckets * sizeof(HashTable));\n if(hashTable.hashBucketArray != NULL)\n {\n memset(hashTable.hashBucketArray, 0, sizeof(HashTable) * totalBuckets);\n return true;\n }\n }\n return false;\n}\n\nbool AddNode(char* key, char* value)\n{\n int offset = ComputeHash(key);\n if(hashTable.hashBucketArray[offset] == NULL)\n {\n hashTable.hashBucketArray[offset] = NewNode(key, value);\n if(hashTable.hashBucketArray[offset] != NULL)\n return true;\n }\n\n else\n {\n if(AppendLinkedNode(hashTable.hashBucketArray[offset], key, value) != NULL)\n return true;\n }\n return false;\n}\n\nHashTable* NewNode(char* key, char* value)\n{\n HashTable* tmpNode = (HashTable*)malloc(sizeof(HashTable));\n if(tmpNode != NULL)\n {\n tmpNode->nextEntry = NULL;\n tmpNode->key = (char*)malloc(strlen(key));\n tmpNode->value = (char*)malloc(strlen(value));\n\n strcpy(tmpNode->key, key);\n strcpy(tmpNode->value, value);\n }\n return tmpNode;\n}\n if(InitHashTable(100) == false) return -1;\nAddNode(\"10\", \"TEN\");\n HashTable* FindNode(char* key)\n{\n int offset = ComputeHash(key);\n HashTable* tmpNode = hashTable.hashBucketArray[offset];\n while(tmpNode != NULL)\n {\n if(strcmp(tmpNode->key, key) == 0)\n return tmpNode;\n tmpNode = tmpNode->nextEntry;\n }\n return NULL;\n}\n char* value = FindNode(\"10\");\n" }, { "answer_id": 828242, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "tmpNode->key = (char*)malloc(strlen(key)+1); //must have +1 for '\\0'\ntmpNode->value = (char*)malloc(strlen(value)+1); //must have +1\nstrcpy(tmpNode->key, key);\nstrcpy(tmpNode->value, value);\n HashNode* AppendLinkedNode(HashNode* ptr, char* key, char* value)\n{\n //follow pointer till end\n while (ptr->nextEntry!=NULL)\n {\n if (strcmp(ptr->value,value)==0) return NULL;\n ptr=ptr->nextEntry;\n }\n ptr->nextEntry=newNode(key,value);\n return ptr->nextEntry;\n}\n" }, { "answer_id": 1148515, "author": "Pranav", "author_id": 58385, "author_profile": "https://Stackoverflow.com/users/58385", "pm_score": 1, "selected": false, "text": "public class HashTable\n{\n private LinkedList[] hashArr=new LinkedList[128];\n public static int HFunc(int key)\n {\n return key%128;\n }\n\n\n public boolean Put(Val V)\n {\n\n int hashval = HFunc(V.getKey());\n LinkedNode ln = new LinkedNode(V,null);\n hashArr[hashval].Insert(ln);\n System.out.println(\"Inserted!\");\n return true; \n }\n\n public boolean Find(Val V)\n {\n int hashval = HFunc(V.getKey());\n if (hashArr[hashval].getInitial()!=null && hashArr[hashval].search(V)==true)\n {\n System.out.println(\"Found!!\");\n return true;\n }\n else\n {\n System.out.println(\"Not Found!!\");\n return false;\n }\n\n }\n public boolean delete(Val v)\n {\n int hashval = HFunc(v.getKey());\n if (hashArr[hashval].getInitial()!=null && hashArr[hashval].delete(v)==true)\n {\n System.out.println(\"Deleted!!\");\n return true;\n }\n else \n {\n System.out.println(\"Could not be found. How can it be deleted?\");\n return false;\n }\n }\n\n public HashTable()\n {\n for(int i=0; i<hashArr.length;i++)\n hashArr[i]=new LinkedList();\n }\n\n}\n\nclass Val\n{\n private int key;\n private int val;\n public int getKey()\n {\n return key;\n }\n public void setKey(int k)\n {\n this.key=k;\n }\n public int getVal()\n {\n return val;\n }\n public void setVal(int v)\n {\n this.val=v;\n }\n public Val(int key,int value)\n {\n this.key=key;\n this.val=value;\n }\n public boolean equals(Val v1)\n {\n if (v1.getVal()==this.val)\n {\n //System.out.println(\"hello im here\");\n return true;\n }\n else \n return false;\n }\n}\n\nclass LinkedNode\n{\n private LinkedNode next;\n private Val obj;\n public LinkedNode(Val v,LinkedNode next)\n {\n this.obj=v;\n this.next=next;\n }\n public LinkedNode()\n {\n this.obj=null;\n this.next=null;\n }\n public Val getObj()\n {\n return this.obj; \n }\n public void setNext(LinkedNode ln)\n {\n this.next = ln;\n }\n\n public LinkedNode getNext()\n {\n return this.next;\n }\n public boolean equals(LinkedNode ln1, LinkedNode ln2)\n {\n if (ln1.getObj().equals(ln2.getObj()))\n {\n return true;\n }\n else \n return false;\n\n }\n\n}\n\nclass LinkedList\n{\n private LinkedNode initial;\n public LinkedList()\n {\n this.initial=null;\n }\n public LinkedList(LinkedNode initial)\n {\n this.initial = initial;\n }\n public LinkedNode getInitial()\n {\n return this.initial;\n }\n public void Insert(LinkedNode ln)\n {\n LinkedNode temp = this.initial;\n this.initial = ln;\n ln.setNext(temp);\n }\n public boolean search(Val v)\n {\n if (this.initial==null)\n return false;\n else \n {\n LinkedNode temp = this.initial;\n while (temp!=null)\n {\n //System.out.println(\"encountered one!\");\n if (temp.getObj().equals(v))\n return true;\n else \n temp=temp.getNext();\n }\n return false;\n }\n\n }\n public boolean delete(Val v)\n {\n if (this.initial==null)\n return false;\n else \n {\n LinkedNode prev = this.initial;\n if (prev.getObj().equals(v))\n {\n this.initial = null;\n return true;\n }\n else\n {\n LinkedNode temp = this.initial.getNext();\n while (temp!=null)\n {\n if (temp.getObj().equals(v))\n {\n prev.setNext(temp.getNext());\n return true;\n }\n else\n {\n prev=temp;\n temp=temp.getNext();\n }\n }\n return false;\n }\n }\n }\n}\n" }, { "answer_id": 2901567, "author": "J D", "author_id": 13924, "author_profile": "https://Stackoverflow.com/users/13924", "pm_score": 0, "selected": false, "text": "> let hashtbl xs =\n let spine = [|for _ in xs -> ResizeArray()|]\n let f k = spine.[abs(k.GetHashCode()) % spine.Length]\n Seq.iter (fun (k, v) -> (f k).Add (k, v)) xs\n fun k -> Seq.pick (fun (k', v) -> if k=k' then Some v else None) (f k);;\nval hashtbl : seq<'a * 'b> -> ('a -> 'b) when 'a : equality\n" }, { "answer_id": 11068369, "author": "Korbi", "author_id": 2555491, "author_profile": "https://Stackoverflow.com/users/2555491", "pm_score": 3, "selected": false, "text": "import java.util.ArrayList;\nimport java.util.List;\nimport java.util.Random;\n\n\npublic class HashTable {\n\n class KeyValuePair {\n\n Object key;\n\n Object value;\n\n public KeyValuePair(Object key, Object value) {\n this.key = key;\n this.value = value;\n }\n }\n\n private Object[] values;\n\n private int capacity;\n\n public HashTable(int capacity) {\n values = new Object[capacity];\n this.capacity = capacity;\n }\n\n private int hash(Object key) {\n return Math.abs(key.hashCode()) % capacity;\n }\n\n public void add(Object key, Object value) throws IllegalArgumentException {\n\n if (key == null || value == null)\n throw new IllegalArgumentException(\"key or value is null\");\n\n int index = hash(key);\n\n List<KeyValuePair> list;\n if (values[index] == null) {\n list = new ArrayList<KeyValuePair>();\n values[index] = list;\n\n } else {\n // collision\n list = (List<KeyValuePair>) values[index];\n }\n\n list.add(new KeyValuePair(key, value));\n }\n\n public Object get(Object key) {\n List<KeyValuePair> list = (List<KeyValuePair>) values[hash(key)];\n if (list == null) {\n return null;\n }\n for (KeyValuePair kvp : list) {\n if (kvp.key.equals(key)) {\n return kvp.value;\n }\n }\n return null;\n }\n\n /**\n * Test\n */\n public static void main(String[] args) {\n\n HashTable ht = new HashTable(100);\n\n for (int i = 1; i <= 1000; i++) {\n ht.add(\"key\" + i, \"value\" + i);\n }\n\n Random random = new Random();\n for (int i = 1; i <= 10; i++) {\n String key = \"key\" + random.nextInt(1000);\n System.out.println(\"ht.get(\\\"\" + key + \"\\\") = \" + ht.get(key));\n } \n }\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25282", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1797/" ]
25,297
<p>I would like to use <code>as</code> and <code>is</code> as members of an enumeration. I know that this is possible in VB.NET to write it like this:</p> <pre><code>Public Enum Test [as] = 1 [is] = 2 End Enum </code></pre> <p>How do I write the equivalent statement in C#? The following code does not compile:</p> <pre><code>public enum Test { as = 1, is = 2 } </code></pre>
[ { "answer_id": 25300, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 6, "selected": true, "text": "public enum Test\n{\n @as = 1,\n @is = 2\n}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2717/" ]
25,349
<p>I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. </p> <p>What would be, in your opinion, the best way to do this using C#.NET 2.0?</p>
[ { "answer_id": 25350, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "string.Replace" }, { "answer_id": 25351, "author": "Bjorn Reppen", "author_id": 1324220, "author_profile": "https://Stackoverflow.com/users/1324220", "pm_score": 2, "selected": false, "text": "string sample = \"abc\" + Environment.NewLine + \"def\";\nstring replaced = sample.Replace(Environment.NewLine, \",\");\n" }, { "answer_id": 25352, "author": "Fredrik Kalseth", "author_id": 1710, "author_profile": "https://Stackoverflow.com/users/1710", "pm_score": 2, "selected": false, "text": "myString.Replace(Environment.NewLine, \",\")\n" }, { "answer_id": 25353, "author": "Steve", "author_id": 1857, "author_profile": "https://Stackoverflow.com/users/1857", "pm_score": 3, "selected": false, "text": "string s = \"hello\\nworld\";\ns = s.Replace(Environment.NewLine, \",\");\n" }, { "answer_id": 25354, "author": "mmattax", "author_id": 1638, "author_profile": "https://Stackoverflow.com/users/1638", "pm_score": 5, "selected": true, "text": "string s = \"foobar\\ngork\";\nstring v = s.Replace(Environment.NewLine,\",\");\nSystem.Console.WriteLine(v);\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2684/" ]
25,376
<p>I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions?</p> <p>They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer?</p> <p>Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.</p>
[ { "answer_id": 25385, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 3, "selected": false, "text": "List<int> myInts = GetAll();\nIEnumerable<int> evenNumbers = myInts.Where(x => x % 2 == 0);\n x=> x % 2 == 0\n" }, { "answer_id": 25391, "author": "Corey", "author_id": 1595, "author_profile": "https://Stackoverflow.com/users/1595", "pm_score": 3, "selected": false, "text": "List<int> myList = new List<int>{ 1, 2, 3, 4, 5, 6, 7, 8, 9 };\nmyList.RemoveAll(x => x > 5);\n//myList now == {1,2,3,4,5}\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2757/" ]
25,396
<p>I'm working on a website built with pure HTML and CSS, and I need a way to restrict access to pages located within particular directories within the site. The solution I came up with was, of course, ASP.NET Forms Authorization. I created the default Visual Studio log in form and set up the users, roles, and access restrictions with Visual Studio's wizard. The problem is, I can't log in to the website with the credentials that I have set.</p> <p>I'm using IIS 7. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 25451, "author": "Steve", "author_id": 1857, "author_profile": "https://Stackoverflow.com/users/1857", "pm_score": 0, "selected": false, "text": "<authentication mode=\"Forms\" />\n" }, { "answer_id": 872068, "author": "Brad Crandell", "author_id": 97949, "author_profile": "https://Stackoverflow.com/users/97949", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.web>\n <authentication mode=\"Forms\" >\n <forms loginUrl=\"~/login.aspx\" defaultUrl=\"~/\">\n <credentials passwordFormat=\"Clear\">\n <user name=\"YourUsername\" password=\"superSecret\" />\n </credentials>\n </forms>\n </authentication>\n <authorization>\n <deny users=\"?\"/>\n </authorization>\n <system.web>\n</configuration>\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1857/" ]
25,449
<p>I want to create a Java program that can be extended with plugins. How can I do that and where should I look for?</p> <p>I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow.</p> <hr> <p>Although I do like Eclipse RCP, I think it's too much for my simple needs.</p> <p>Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it.</p> <p>But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.</p>
[ { "answer_id": 25492, "author": "Steve M", "author_id": 1693, "author_profile": "https://Stackoverflow.com/users/1693", "pm_score": 7, "selected": true, "text": "File dir = new File(\"put path to classes you want to load here\");\nURL loadPath = dir.toURI().toURL();\nURL[] classUrl = new URL[]{loadPath};\n\nClassLoader cl = new URLClassLoader(classUrl);\n\nClass loadedClass = cl.loadClass(\"classname\"); // must be in package.class name format\n MyModule modInstance = (MyModule)loadedClass.newInstance();\n" }, { "answer_id": 383779, "author": "Steen", "author_id": 1448983, "author_profile": "https://Stackoverflow.com/users/1448983", "pm_score": 3, "selected": false, "text": "plugins\n`-com.my.package.plugins\n `-com\n `-my\n `-package\n `-plugins\n |- Class1.class\n `- Class2.class\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2644/" ]
25,450
<p>Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier.</p> <p>Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc.</p> <p>Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole? </p>
[ { "answer_id": 25467, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 4, "selected": true, "text": "template engine variables calculated fields" }, { "answer_id": 25534, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 3, "selected": false, "text": "a { color: red }\n.entry { color: red }\nh1 { color: red }\n a, .entry, h1 { color: red }\n" }, { "answer_id": 25553, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "<?\nheader('content-type:text/css');\nheader(\"Expires: \".gmdate(\"D, d M Y H:i:s\", (time()+900)) . \" GMT\"); \n\n$someColorVar = \"#cc0000\";\n?>\nBODY {\n background-color: <?= someColorVar ?>;\n }\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
25,455
<p>While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range).</p> <p>I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural.</p> <p>So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times.</p> <p>Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 25467, "author": "grom", "author_id": 486, "author_profile": "https://Stackoverflow.com/users/486", "pm_score": 4, "selected": true, "text": "template engine variables calculated fields" }, { "answer_id": 25534, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 3, "selected": false, "text": "a { color: red }\n.entry { color: red }\nh1 { color: red }\n a, .entry, h1 { color: red }\n" }, { "answer_id": 25553, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": "<?\nheader('content-type:text/css');\nheader(\"Expires: \".gmdate(\"D, d M Y H:i:s\", (time()+900)) . \" GMT\"); \n\n$someColorVar = \"#cc0000\";\n?>\nBODY {\n background-color: <?= someColorVar ?>;\n }\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1581/" ]
25,458
<p>I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... </p> <p>For those who have used reflection in applications, have you measured performance hits and, is it really so bad?</p>
[ { "answer_id": 25472, "author": "lomaxx", "author_id": 493, "author_profile": "https://Stackoverflow.com/users/493", "pm_score": 2, "selected": false, "text": "FillObject" }, { "answer_id": 4440657, "author": "grenade", "author_id": 68115, "author_profile": "https://Stackoverflow.com/users/68115", "pm_score": 6, "selected": false, "text": "entity.GetType().GetProperty(\"PropName\")" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/392/" ]
25,461
<p>In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such.</p> <pre><code>#ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if !defined(__cplusplus) #if !defined(__GNUC__) /* _Bool builtin type is included in GCC */ typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; #endif #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif </code></pre> <p>Some structures have <code>bool</code> members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C.</p> <p>Does anyone have any advice to how to overcome this without resorting to my current solution which is</p> <pre><code>//#define bool _Bool #define bool unsigned char </code></pre> <p>Which is against the C99 standard for <a href="http://www.opengroup.org/onlinepubs/000095399/basedefs/stdbool.h.html" rel="noreferrer">stdbool.h</a></p>
[ { "answer_id": 25658, "author": "Josh", "author_id": 257, "author_profile": "https://Stackoverflow.com/users/257", "pm_score": 0, "selected": false, "text": "union boolean {\n bool value_cpp;\n int value_c;\n}; \n extern \"C\" bool library_func_1(int i, char c, bool b);\n bool library_func_1_cpp(int i, char c, bool b)\n{\n int result = library_func_1(i, c, static_cast<int>(b));\n return (result==true);\n}\n" }, { "answer_id": 29300, "author": "JProgrammer", "author_id": 1675, "author_profile": "https://Stackoverflow.com/users/1675", "pm_score": 5, "selected": true, "text": "stdbool.h #ifndef _STDBOOL_H\n#define _STDBOOL_H\n\n#include <stdint.h>\n\n/* C99 Boolean types for compilers without C99 support */\n/* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */\n#if !defined(__cplusplus)\n\n#if !defined(__GNUC__)\n/* _Bool builtin type is included in GCC */\n/* ISO C Standard: 5.2.5 An object declared as \ntype _Bool is large enough to store \nthe values 0 and 1. */\n/* We choose 8 bit to match C++ */\n/* It must also promote to integer */\ntypedef int8_t _Bool;\n#endif\n\n/* ISO C Standard: 7.16 Boolean type */\n#define bool _Bool\n#define true 1\n#define false 0\n#define __bool_true_false_are_defined 1\n\n#endif\n\n#endif\n" } ]
2008/08/24
[ "https://Stackoverflow.com/questions/25461", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1675/" ]
25,481
<p>I'm trying to call an Antlr task in my Ant build.xml as follows:</p> <pre><code>&lt;path id="classpath.build"&gt; &lt;fileset dir="${dir.lib.build}" includes="**/*.jar" /&gt; &lt;/path&gt; ... &lt;target name="generate-lexer" depends="init"&gt; &lt;antlr target="${file.antlr.lexer}"&gt; &lt;classpath refid="classpath.build"/&gt; &lt;/antlr&gt; &lt;/target&gt; </code></pre> <p>But Ant can't find the task definition. I've put all of the following in that <code>dir.lib.build</code>:</p> <ul> <li>antlr-3.1.jar</li> <li>antlr-2.7.7.jar</li> <li>antlr-runtime-3.1.jar</li> <li>stringtemplate-3.2.jar</li> </ul> <p>But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)</p>
[ { "answer_id": 4515467, "author": "Terence Parr", "author_id": 275496, "author_profile": "https://Stackoverflow.com/users/275496", "pm_score": 2, "selected": false, "text": "<path id=\"classpath\">\n <pathelement location=\"${antlr3.jar}\"/>\n <pathelement location=\"${ant-antlr3.jar}\"/>\n</path>\n\n<target name=\"antlr\" depends=\"init\">\n <antlr:ant-antlr3 xmlns:antlr=\"antlib:org/apache/tools/ant/antlr\"\n target=\"src/T.g\"\n outputdirectory=\"build\">\n <classpath refid=\"classpath\"/>\n </antlr:ant-antlr3>\n</target>\n" }, { "answer_id": 6350676, "author": "Andy Balaam", "author_id": 22610, "author_profile": "https://Stackoverflow.com/users/22610", "pm_score": 0, "selected": false, "text": "sudo apt-get install ant-optional" }, { "answer_id": 10456313, "author": "Bruno Girin", "author_id": 1175223, "author_profile": "https://Stackoverflow.com/users/1175223", "pm_score": 0, "selected": false, "text": "ant-optional ~/.ant/lib ant -diagnostics antlr3.jar stringtemplate.jar ant-antlr3.jar" }, { "answer_id": 21280786, "author": "ceving", "author_id": 402322, "author_profile": "https://Stackoverflow.com/users/402322", "pm_score": 1, "selected": false, "text": "<project default=\"antlr\">\n <target name=\"antlr\">\n <java jar=\"antlr-4.1-complete.jar\" fork=\"true\">\n <arg value=\"grammar.g4\"/>\n </java>\n </target>\n</project>\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25481", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1190/" ]
25,499
<p>I'm using Visual C++ 2005 and would like to know the simplest way to connect to a MS SQL Server and execute a query.</p> <p>I'm looking for something as simple as ADO.NET's SqlCommand class with it's ExecuteNonQuery(), ExecuteScalar() and ExecuteReader().</p> <p>Sigh offered an answer using CDatabase and ODBC.</p> <p>Can anybody demonstrate how it would be done using ATL consumer templates for OleDb?</p> <p>Also what about returning a scalar value from the query?</p>
[ { "answer_id": 25544, "author": "Sigh", "author_id": 1866, "author_profile": "https://Stackoverflow.com/users/1866", "pm_score": 2, "selected": false, "text": "CDatabase db(ODBCConnectionString);\ndb.Open();\ndb.ExecuteSQL(blah);\ndb.Close();\n" }, { "answer_id": 154431, "author": "rec", "author_id": 14022, "author_profile": "https://Stackoverflow.com/users/14022", "pm_score": 1, "selected": false, "text": "#include <ole2.h>\n#import \"msado15.dll\" no_namespace rename(\"EOF\", \"EndOfFile\")\n#include <oledb.h> \nvoid CMyDlg::OnBnClickedButton1()\n{\n if ( FAILED(::CoInitialize(NULL)) )\n return;\n _RecordsetPtr pRs = NULL;\n\n //use your connection string here\n _bstr_t strCnn(_T(\"Provider=SQLNCLI;Server=.\\\\SQLExpress;AttachDBFilename=C:\\\\Program Files\\\\Microsoft SQL Server\\\\MSSQL.1\\\\MSSQL\\\\Data\\\\db\\\\db.mdf;Database=mydb;Trusted_Connection=Yes;MARS Connection=true\"));\n _bstr_t a_Select(_T(\"select * from Table\"));\n\n\n try {\n\n pRs.CreateInstance(__uuidof(Recordset));\n pRs->Open(a_Select.AllocSysString(), strCnn.AllocSysString(), adOpenStatic, adLockReadOnly, adCmdText);\n\n //obtain entire restult as comma separated text:\n CString text((LPCWSTR)pRs->GetString(adClipString, -1, _T(\",\"), _T(\"\"), _T(\"NULL\")));\n\n //iterate thru recordset:\n long count = pRs->GetRecordCount();\n\n COleVariant var;\n CString strColumn1;\n CString column1(_T(\"column1_name\")); \n\n for(int i = 1; i <= count; i++)\n {\n var = pRs->GetFields()->GetItem(column1.AllocSysString())->GetValue();\n strColumn1 = (LPCTSTR)_bstr_t(var);\n }\n }\n catch(_com_error& e) {\n CString err((LPCTSTR)(e.Description()));\n MessageBox(err, _T(\"error\"), MB_OK);\n _asm nop; //\n }\n // Clean up objects before exit.\n if (pRs)\n if (pRs->State == adStateOpen)\n pRs->Close();\n\n\n\n ::CoUninitialize();\n}\n" }, { "answer_id": 154495, "author": "Zathrus", "author_id": 16220, "author_profile": "https://Stackoverflow.com/users/16220", "pm_score": 2, "selected": false, "text": "#define OTL_ODBC_MSSQL_2008 // Compile OTL 4/ODBC, MS SQL 2008\n//#define OTL_ODBC // Compile OTL 4/ODBC. Uncomment this when used with MS SQL 7.0/ 2000\n#include <otlv4.h> // include the OTL 4.0 header file\n#include <stdio>\n\nint main()\n{\n otl_connect db; // connect object\n otl_connect::otl_initialize(); // initialize ODBC environment\n try\n {\n int myint;\n\n db.rlogon(\"scott/tiger@mssql2008\"); // connect to the database\n otl_stream select(10, \"select someint from test_tab\", db);\n\n while (!select.eof())\n {\n select >> myint;\n std::cout<<\"myint = \" << myint << std::endl;\n }\n }\n catch(otl_exception& p)\n {\n std::cerr << p.code << std::endl; // print out error code\n std::cerr << p.sqlstate << std::endl; // print out error SQLSTATE\n std::cerr << p.msg << std::endl; // print out error message\n std::cerr << p.stm_text << std::endl; // print out SQL that caused the error\n std::cerr << p.var_info << std::endl; // print out the variable that caused the error\n }\n\n db.logoff(); // disconnect from the database\n\n return 0;\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2768/" ]
25,532
<p>What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages? </p> <p>I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages.</p> <p>Any examples would be great!!</p>
[ { "answer_id": 33270, "author": "tonygambone", "author_id": 3344, "author_profile": "https://Stackoverflow.com/users/3344", "pm_score": 4, "selected": false, "text": "<ui:insert/> <asp:ContentPlaceHolder/> <ui:composition/> <ui:composition/> <ui:define/> <asp:Content/> <!-- HTML header content here -->\n<ui:insert name=\"AreaOne\">Default content for AreaOne</ui:insert>\n<ui:insert name=\"AreaTwo\">Default content for AreaTwo</ui:insert>\n<!-- HTML footer content here -->\n <ui:composition template=\"/WEB-INF/templates/master.xhtml\">\n <ui:define name=\"AreaOne\">Here is some new content</ui:define>\n <ui:define name=\"AreaTwo\">\n <p>Some new content here too</p>\n </ui:define>\n</ui:composition>\n <!-- HTML header content here -->\nHere is some new content\n<p>Some new content here too</p>\n<!-- HTML footer content here -->\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2572/" ]
25,552
<p>I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows.</p> <p>Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming?</p> <p>Preferrably I'd like to get this information without using JNI.</p>
[ { "answer_id": 25596, "author": "William Brendel", "author_id": 2405, "author_profile": "https://Stackoverflow.com/users/2405", "pm_score": 9, "selected": true, "text": "public class Main {\n public static void main(String[] args) {\n /* Total number of processors or cores available to the JVM */\n System.out.println(\"Available processors (cores): \" + \n Runtime.getRuntime().availableProcessors());\n\n /* Total amount of free memory available to the JVM */\n System.out.println(\"Free memory (bytes): \" + \n Runtime.getRuntime().freeMemory());\n\n /* This will return Long.MAX_VALUE if there is no preset limit */\n long maxMemory = Runtime.getRuntime().maxMemory();\n /* Maximum amount of memory the JVM will attempt to use */\n System.out.println(\"Maximum memory (bytes): \" + \n (maxMemory == Long.MAX_VALUE ? \"no limit\" : maxMemory));\n\n /* Total memory currently available to the JVM */\n System.out.println(\"Total memory available to JVM (bytes): \" + \n Runtime.getRuntime().totalMemory());\n\n /* Get a list of all filesystem roots on this system */\n File[] roots = File.listRoots();\n\n /* For each filesystem root, print some info */\n for (File root : roots) {\n System.out.println(\"File system root: \" + root.getAbsolutePath());\n System.out.println(\"Total space (bytes): \" + root.getTotalSpace());\n System.out.println(\"Free space (bytes): \" + root.getFreeSpace());\n System.out.println(\"Usable space (bytes): \" + root.getUsableSpace());\n }\n }\n}\n" }, { "answer_id": 27502, "author": "staffan", "author_id": 988, "author_profile": "https://Stackoverflow.com/users/988", "pm_score": 3, "selected": false, "text": "OperatingSystemMXBean.getSystemLoadAverage() ThreadMXBean.getCurrentThreadCpuTime() ThreadMXBean.getCurrentThreadUserTime()" }, { "answer_id": 61727, "author": "Patrick Wilkes", "author_id": 6370, "author_profile": "https://Stackoverflow.com/users/6370", "pm_score": 7, "selected": false, "text": "ManagementFactory.getMemoryMXBean().getHeapMemoryUsage() ManagementFactory.getMemoryMXBean().getNonHeapMemoryUsage() java.lang.management.OperatingSystemMXBean com.sun.management.OperatingSystemMXBean public class PerformanceMonitor { \n private int availableProcessors = getOperatingSystemMXBean().getAvailableProcessors();\n private long lastSystemTime = 0;\n private long lastProcessCpuTime = 0;\n\n public synchronized double getCpuUsage()\n {\n if ( lastSystemTime == 0 )\n {\n baselineCounters();\n return;\n }\n\n long systemTime = System.nanoTime();\n long processCpuTime = 0;\n\n if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n {\n processCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n }\n\n double cpuUsage = (double) ( processCpuTime - lastProcessCpuTime ) / ( systemTime - lastSystemTime );\n\n lastSystemTime = systemTime;\n lastProcessCpuTime = processCpuTime;\n\n return cpuUsage / availableProcessors;\n }\n\n private void baselineCounters()\n {\n lastSystemTime = System.nanoTime();\n\n if ( getOperatingSystemMXBean() instanceof OperatingSystemMXBean )\n {\n lastProcessCpuTime = ( (OperatingSystemMXBean) getOperatingSystemMXBean() ).getProcessCpuTime();\n }\n }\n}\n" }, { "answer_id": 8076368, "author": "petro", "author_id": 1039268, "author_profile": "https://Stackoverflow.com/users/1039268", "pm_score": 2, "selected": false, "text": "JMXServiceURL url = new JMXServiceURL(\"service:jmx:rmi:///jndi/rmi://my.tomcat.host:8080/jmxrmi\");\nJMXConnector jmxc = JMXConnectorFactory.connect(url, null); \nMBeanServerConnection conn = jmxc.getMBeanServerConnection(); \nObjectName name = new ObjectName(\"oracle.jrockit.management:type=Runtime\");\nDouble jvmCpuLoad =(Double)conn.getAttribute(name, \"VMGeneratedCPULoad\");\n" }, { "answer_id": 11989443, "author": "Alexandr", "author_id": 634281, "author_profile": "https://Stackoverflow.com/users/634281", "pm_score": 4, "selected": false, "text": "System.getenv() System.getenv(\"PROCESSOR_IDENTIFIER\")\nSystem.getenv(\"PROCESSOR_ARCHITECTURE\")\nSystem.getenv(\"PROCESSOR_ARCHITEW6432\")\nSystem.getenv(\"NUMBER_OF_PROCESSORS\")\n" }, { "answer_id": 35758362, "author": "profesor_falken", "author_id": 1774614, "author_profile": "https://Stackoverflow.com/users/1774614", "pm_score": 2, "selected": false, "text": "ProcessorInfo info = HardwareInfo.getProcessorInfo();\n//Get named info\nSystem.out.println(\"Cache size: \" + info.getCacheSize()); \nSystem.out.println(\"Family: \" + info.getFamily());\nSystem.out.println(\"Speed (Mhz): \" + info.getMhz());\n//[...]\n" }, { "answer_id": 36533445, "author": "Oleksii Kyslytsyn", "author_id": 1851286, "author_profile": "https://Stackoverflow.com/users/1851286", "pm_score": 3, "selected": false, "text": "<dependency>\n <groupId>com.github.dblock</groupId>\n <artifactId>oshi-core</artifactId>\n <version>2.2</version>\n</dependency>\n SystemInfo si = new SystemInfo();\nHardwareAbstractionLayer hal = si.getHardware();\nfor (PowerSource pSource : hal.getPowerSources()) {\n System.out.println(String.format(\"%n %s @ %.1f%%\", pSource.getName(), pSource.getRemainingCapacity() * 100d));\n}\n" }, { "answer_id": 38127012, "author": "Yan Khonski", "author_id": 1839360, "author_profile": "https://Stackoverflow.com/users/1839360", "pm_score": 4, "selected": false, "text": " com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();\n\n long physicalMemorySize = os.getTotalPhysicalMemorySize();\n long freePhysicalMemory = os.getFreePhysicalMemorySize();\n long freeSwapSize = os.getFreeSwapSpaceSize();\n long commitedVirtualMemorySize = os.getCommittedVirtualMemorySize();\n" }, { "answer_id": 40281599, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 2, "selected": false, "text": "Windows systeminfo private static class WindowsSystemInformation\n{\n static String get() throws IOException\n {\n Runtime runtime = Runtime.getRuntime();\n Process process = runtime.exec(\"systeminfo\");\n BufferedReader systemInformationReader = new BufferedReader(new InputStreamReader(process.getInputStream()));\n\n StringBuilder stringBuilder = new StringBuilder();\n String line;\n\n while ((line = systemInformationReader.readLine()) != null)\n {\n stringBuilder.append(line);\n stringBuilder.append(System.lineSeparator());\n }\n\n return stringBuilder.toString().trim();\n }\n}\n" }, { "answer_id": 55832821, "author": "Amandeep Singh", "author_id": 771226, "author_profile": "https://Stackoverflow.com/users/771226", "pm_score": 2, "selected": false, "text": " OperatingSystemMXBean osBean =\n (OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();\n return osBean.getProcessCpuLoad();\n" }, { "answer_id": 59552028, "author": "krishna Prasad", "author_id": 3181159, "author_profile": "https://Stackoverflow.com/users/3181159", "pm_score": 2, "selected": false, "text": "cat /proc/loadavg Runtime runtime = Runtime.getRuntime();\n\n BufferedReader br = new BufferedReader(\n new InputStreamReader(runtime.exec(\"cat /proc/loadavg\").getInputStream()));\n\n String avgLine = br.readLine();\n System.out.println(avgLine);\n List<String> avgLineList = Arrays.asList(avgLine.split(\"\\\\s+\"));\n System.out.println(avgLineList);\n System.out.println(\"Average load 1 minute : \" + avgLineList.get(0));\n System.out.println(\"Average load 5 minutes : \" + avgLineList.get(1));\n System.out.println(\"Average load 15 minutes : \" + avgLineList.get(2));\n free -m Runtime runtime = Runtime.getRuntime();\n\nBufferedReader br = new BufferedReader(\n new InputStreamReader(runtime.exec(\"free -m\").getInputStream()));\n\nString line;\nString memLine = \"\";\nint index = 0;\nwhile ((line = br.readLine()) != null) {\n if (index == 1) {\n memLine = line;\n }\n index++;\n}\n// total used free shared buff/cache available\n// Mem: 15933 3153 9683 310 3097 12148\n// Swap: 3814 0 3814\n\nList<String> memInfoList = Arrays.asList(memLine.split(\"\\\\s+\"));\nint totalSystemMemory = Integer.parseInt(memInfoList.get(1));\nint totalSystemUsedMemory = Integer.parseInt(memInfoList.get(2));\nint totalSystemFreeMemory = Integer.parseInt(memInfoList.get(3));\n\nSystem.out.println(\"Total system memory in mb: \" + totalSystemMemory);\nSystem.out.println(\"Total system used memory in mb: \" + totalSystemUsedMemory);\nSystem.out.println(\"Total system free memory in mb: \" + totalSystemFreeMemory);\n" }, { "answer_id": 73582584, "author": "Priidu Neemre", "author_id": 1021943, "author_profile": "https://Stackoverflow.com/users/1021943", "pm_score": 0, "selected": false, "text": "commons-lang3 import static org.apache.commons.lang3.ArchUtils.*;\nimport static org.apache.commons.lang3.SystemUtils.*;\n\nSystem.out.printf(\"OS architecture: %s\\n\", OS_ARCH); // OS architecture: amd64\nSystem.out.printf(\"OS name: %s\\n\", OS_NAME); // OS name: Linux\nSystem.out.printf(\"OS version: %s\\n\", OS_VERSION); // OS version: 5.18.16-200.fc36.x86_64\n\nSystem.out.printf(\"Is Linux? - %b\\n\", IS_OS_LINUX); // Is Linux? - true\nSystem.out.printf(\"Is Mac? - %b\\n\", IS_OS_MAC); // Is Mac? - false\nSystem.out.printf(\"Is Windows? - %b\\n\", IS_OS_WINDOWS); // Is Windows? - false\n\nSystem.out.printf(\"JVM name: %s\\n\", JAVA_VM_NAME); // JVM name: Java HotSpot(TM) 64-Bit Server VM\nSystem.out.printf(\"JVM vendor: %s\\n\", JAVA_VM_VENDOR); // JVM vendor: Oracle Corporation\nSystem.out.printf(\"JVM version: %s\\n\", JAVA_VM_VERSION); // JVM version: 11.0.12+8-LTS-237\n\nSystem.out.printf(\"Username: %s\\n\", getUserName()); // Username: johndoe\nSystem.out.printf(\"Hostname: %s\\n\", getHostName()); // Hostname: garage-pc\n\nvar processor = getProcessor();\nSystem.out.printf(\"CPU arch: %s\\n\", processor.getArch()) // CPU arch: BIT_64\nSystem.out.printf(\"CPU type: %s\\n\", processor.getType()); // CPU type: X86\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1693/" ]
25,561
<p>I am attempting to parse a string like the following using a .NET regular expression:</p> <pre><code>H3Y5NC8E-TGA5B6SB-2NVAQ4E0 </code></pre> <p>and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0</p> <p>I validate each character against a specific character set (note that the letters 'I', 'O', 'U' &amp; 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression:</p> <pre><code>([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} </code></pre> <p>This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this:</p> <pre><code>(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} </code></pre> <p>But this does not work.</p> <p>Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. </p> <hr> <p>Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' &amp; 'W' are not in the character set.</p> <p>The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy &amp; paste.</p>
[ { "answer_id": 25569, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 0, "selected": false, "text": "Dim stringArray As Array = someString.Split(\"-\")\n" }, { "answer_id": 25591, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 0, "selected": false, "text": "Regex.Split(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\", \"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}+)-?\")\n" }, { "answer_id": 25597, "author": "Dale Ragan", "author_id": 1117, "author_profile": "https://Stackoverflow.com/users/1117", "pm_score": 2, "selected": false, "text": "RegexOptions options = RegexOptions.None;\nRegex regex = new Regex(@\"([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})\", options);\nstring input = @\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n\nMatchCollection matches = regex.Matches(input);\nfor (int i = 0; i != matches.Count; ++i)\n{\n string match = matches[i].Value;\n}\n" }, { "answer_id": 25601, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 0, "selected": false, "text": "system.text.RegularExpressions.Regex.Match(\"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\",\"(([ABCDEFGHJKLMNPQRSTVXYZ0123456789]+)-?)*\").Groups(2).Captures(i).Value\n" }, { "answer_id": 25622, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 3, "selected": true, "text": " static void Main(string[] args)\n {\n string pattern = @\"^\\s*((?<group>[ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\\s*$\";\n string input = \"H3Y5NC8E-TGA5B6SB-2NVAQ4E0\";\n Regex re = new Regex(pattern);\n Match m = re.Match(input);\n\n if (m.Success)\n foreach (Capture c in m.Groups[\"group\"].Captures)\n Console.WriteLine(c.Value);\n }\n" }, { "answer_id": 25909, "author": "Imran", "author_id": 1897, "author_profile": "https://Stackoverflow.com/users/1897", "pm_score": 3, "selected": false, "text": "[[A-Z\\d]-[IOUW]]\n ([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}-([[A-Z\\d]-[IOUW]]){8}\n return \"$1 $2 $3\";\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2754/" ]
25,566
<p>I wrote an O(n!) sort for my amusement that can't be trivially optimized to run faster without replacing it entirely. [And no, I didn't just randomize the items until they were sorted]. </p> <p>How might I write an even worse Big-O sort, without just adding extraneous junk that could be pulled out to reduce the time complexity?</p> <p><a href="http://en.wikipedia.org/wiki/Big_O_notation#Orders_of_common_functions" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Big_O_notation</a> has various time complexities sorted in growing order.</p> <p>Edit: I found the code, here is my O(n!) deterministic sort with amusing hack to generate list of all combinations of a list. I have a slightly longer version of get_all_combinations that returns an iterable of combinations, but unfortunately I couldn't make it a single statement. [Hopefully I haven't introduced bugs by fixing typos and removing underscores in the below code]</p> <pre><code>def mysort(somelist): for permutation in get_all_permutations(somelist): if is_sorted(permutation): return permutation def is_sorted(somelist): # note: this could be merged into return... something like return len(foo) &lt;= 1 or reduce(barf) if (len(somelist) &lt;= 1): return True return 1 &gt; reduce(lambda x,y: max(x,y),map(cmp, somelist[:-1], somelist[1:])) def get_all_permutations(lst): return [[itm] + cbo for idx, itm in enumerate(lst) for cbo in get_all_permutations(lst[:idx] + lst[idx+1:])] or [lst] </code></pre>
[ { "answer_id": 25605, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 2, "selected": false, "text": "def never_sort(array)\n while(true)\n end\n return quicksort(array)\nend\n def never_sort(array)\n i=0\n while(true) { i += 1 }\n puts \"done with loop after #{i} iterations!\"\n return quicksort(array)\nend\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2775/" ]
25,637
<p>Is there a way to shutdown a computer using a built-in Java method?</p>
[ { "answer_id": 25644, "author": "David McGraw", "author_id": 568, "author_profile": "https://Stackoverflow.com/users/568", "pm_score": 8, "selected": true, "text": "public static void main(String arg[]) throws IOException{\n Runtime runtime = Runtime.getRuntime();\n Process proc = runtime.exec(\"shutdown -s -t 0\");\n System.exit(0);\n}\n" }, { "answer_id": 25666, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 6, "selected": false, "text": "public static void shutdown() throws RuntimeException, IOException {\n String shutdownCommand;\n String operatingSystem = System.getProperty(\"os.name\");\n\n if (\"Linux\".equals(operatingSystem) || \"Mac OS X\".equals(operatingSystem)) {\n shutdownCommand = \"shutdown -h now\";\n }\n // This will work on any version of windows including version 11 \n else if (operatingSystem.contains(\"Windows\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n }\n else {\n throw new RuntimeException(\"Unsupported operating system.\");\n }\n\n Runtime.getRuntime().exec(shutdownCommand);\n System.exit(0);\n}\n" }, { "answer_id": 2153270, "author": "Ra.", "author_id": 260787, "author_profile": "https://Stackoverflow.com/users/260787", "pm_score": 3, "selected": false, "text": "String osName = System.getProperty(\"os.name\"); \nif (osName.startsWith(\"Win\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n} else if (osName.startsWith(\"Linux\") || osName.startsWith(\"Mac\")) {\n shutdownCommand = \"shutdown -h now\";\n} else {\n System.err.println(\"Shutdown unsupported operating system ...\");\n //closeApp();\n}\n" }, { "answer_id": 2213729, "author": "Jonathan Barbero", "author_id": 14811, "author_profile": "https://Stackoverflow.com/users/14811", "pm_score": 3, "selected": false, "text": " public class Shutdown {\n public static void main(String[] args) {\n\n int minutes = Integer.valueOf(args[0]);\n Timer timer = new Timer();\n timer.schedule(new TimerTask() {\n\n @Override\n public void run() {\n ProcessBuilder processBuilder = new ProcessBuilder(\"shutdown\",\n \"/s\");\n try {\n processBuilder.start();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n }, minutes * 60 * 1000);\n\n System.out.println(\" Shutting down in \" + minutes + \" minutes\");\n }\n }\n" }, { "answer_id": 14297352, "author": "Kezz", "author_id": 1590990, "author_profile": "https://Stackoverflow.com/users/1590990", "pm_score": 5, "selected": false, "text": "public static boolean shutdown(int time) throws IOException {\n String shutdownCommand = null, t = time == 0 ? \"now\" : String.valueOf(time);\n\n if(SystemUtils.IS_OS_AIX)\n shutdownCommand = \"shutdown -Fh \" + t;\n else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX)\n shutdownCommand = \"shutdown -h \" + t;\n else if(SystemUtils.IS_OS_HP_UX)\n shutdownCommand = \"shutdown -hy \" + t;\n else if(SystemUtils.IS_OS_IRIX)\n shutdownCommand = \"shutdown -y -g \" + t;\n else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS)\n shutdownCommand = \"shutdown -y -i5 -g\" + t;\n else if(SystemUtils.IS_OS_WINDOWS)\n shutdownCommand = \"shutdown.exe /s /t \" + t;\n else\n return false;\n\n Runtime.getRuntime().exec(shutdownCommand);\n return true;\n}\n os.name" }, { "answer_id": 26782022, "author": "Andrea Bori", "author_id": 4216184, "author_profile": "https://Stackoverflow.com/users/4216184", "pm_score": 1, "selected": false, "text": "Runtime.getRuntime().exec(\"shutdown -s -t 0\");\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25637", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2598/" ]
25,642
<p>I want to catch the NavigationService.Navigating event from my Page, to prevent the user from navigating forward. I have an event handler defined thusly:</p> <pre><code>void PreventForwardNavigation(object sender, NavigatingCancelEventArgs e) { if (e.NavigationMode == NavigationMode.Forward) { e.Cancel = true; } } </code></pre> <p>... and that works fine. However, I am unsure exactly where to place this code:</p> <pre><code>NavigationService.Navigating += PreventForwardNavigation; </code></pre> <p>If I place it in the constructor of the page, or the Initialized event handler, then NavigationService is still null and I get a NullReferenceException. However, if I place it in the Loaded event handler for the Page, then it is called every time the page is navigated to. If I understand right, that means I'm handling the same event multiple times. </p> <p>Am I ok to add the same handler to the event multiple times (as would happen were I to use the page's Loaded event to hook it up)? If not, is there some place in between Initialized and Loaded where I can do this wiring?</p>
[ { "answer_id": 25644, "author": "David McGraw", "author_id": 568, "author_profile": "https://Stackoverflow.com/users/568", "pm_score": 8, "selected": true, "text": "public static void main(String arg[]) throws IOException{\n Runtime runtime = Runtime.getRuntime();\n Process proc = runtime.exec(\"shutdown -s -t 0\");\n System.exit(0);\n}\n" }, { "answer_id": 25666, "author": "David Crow", "author_id": 2783, "author_profile": "https://Stackoverflow.com/users/2783", "pm_score": 6, "selected": false, "text": "public static void shutdown() throws RuntimeException, IOException {\n String shutdownCommand;\n String operatingSystem = System.getProperty(\"os.name\");\n\n if (\"Linux\".equals(operatingSystem) || \"Mac OS X\".equals(operatingSystem)) {\n shutdownCommand = \"shutdown -h now\";\n }\n // This will work on any version of windows including version 11 \n else if (operatingSystem.contains(\"Windows\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n }\n else {\n throw new RuntimeException(\"Unsupported operating system.\");\n }\n\n Runtime.getRuntime().exec(shutdownCommand);\n System.exit(0);\n}\n" }, { "answer_id": 2153270, "author": "Ra.", "author_id": 260787, "author_profile": "https://Stackoverflow.com/users/260787", "pm_score": 3, "selected": false, "text": "String osName = System.getProperty(\"os.name\"); \nif (osName.startsWith(\"Win\")) {\n shutdownCommand = \"shutdown.exe -s -t 0\";\n} else if (osName.startsWith(\"Linux\") || osName.startsWith(\"Mac\")) {\n shutdownCommand = \"shutdown -h now\";\n} else {\n System.err.println(\"Shutdown unsupported operating system ...\");\n //closeApp();\n}\n" }, { "answer_id": 2213729, "author": "Jonathan Barbero", "author_id": 14811, "author_profile": "https://Stackoverflow.com/users/14811", "pm_score": 3, "selected": false, "text": " public class Shutdown {\n public static void main(String[] args) {\n\n int minutes = Integer.valueOf(args[0]);\n Timer timer = new Timer();\n timer.schedule(new TimerTask() {\n\n @Override\n public void run() {\n ProcessBuilder processBuilder = new ProcessBuilder(\"shutdown\",\n \"/s\");\n try {\n processBuilder.start();\n } catch (IOException e) {\n throw new RuntimeException(e);\n }\n }\n\n }, minutes * 60 * 1000);\n\n System.out.println(\" Shutting down in \" + minutes + \" minutes\");\n }\n }\n" }, { "answer_id": 14297352, "author": "Kezz", "author_id": 1590990, "author_profile": "https://Stackoverflow.com/users/1590990", "pm_score": 5, "selected": false, "text": "public static boolean shutdown(int time) throws IOException {\n String shutdownCommand = null, t = time == 0 ? \"now\" : String.valueOf(time);\n\n if(SystemUtils.IS_OS_AIX)\n shutdownCommand = \"shutdown -Fh \" + t;\n else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX)\n shutdownCommand = \"shutdown -h \" + t;\n else if(SystemUtils.IS_OS_HP_UX)\n shutdownCommand = \"shutdown -hy \" + t;\n else if(SystemUtils.IS_OS_IRIX)\n shutdownCommand = \"shutdown -y -g \" + t;\n else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS)\n shutdownCommand = \"shutdown -y -i5 -g\" + t;\n else if(SystemUtils.IS_OS_WINDOWS)\n shutdownCommand = \"shutdown.exe /s /t \" + t;\n else\n return false;\n\n Runtime.getRuntime().exec(shutdownCommand);\n return true;\n}\n os.name" }, { "answer_id": 26782022, "author": "Andrea Bori", "author_id": 4216184, "author_profile": "https://Stackoverflow.com/users/4216184", "pm_score": 1, "selected": false, "text": "Runtime.getRuntime().exec(\"shutdown -s -t 0\");\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
25,646
<p>The following code writes no data to the back buffer on Intel integrated video cards,for example, on a MacBook. On ATI cards, such as in the iMac, it draws to the back buffer. The width and height are correct (and 800x600 buffer) and m_PixelBuffer is correctly filled with 0xAA00AA00.</p> <p>My best guess so far is that there is something amiss with needing glWindowPos set. I do not currently set it (or the raster position), and when I get GL_CURRENT_RASTER_POSITION I noticed that the default on the ATI card is 0,0,0,0 and the Intel it's 0,0,0,1. When I set the raster pos on the ATI card to 0,0,0,1 I get the same result as the Intel card, nothing drawn to the back buffer. Is there some transform state I'm missing? This is a 2D application so the view transform is a very simple glOrtho.</p> <pre><code>glDrawPixels(GetBufferWidth(), GetBufferHeight(), GL_BGRA, GL_UNSIGNED_INT_8_8_8_8_REV, m_PixelBuffer); </code></pre> <p>Any more info I can provide, please ask. I'm pretty much an OpenGL and Mac newb so I don't know if I'm providing enough information.</p>
[ { "answer_id": 154444, "author": "Adrian", "author_id": 23624, "author_profile": "https://Stackoverflow.com/users/23624", "pm_score": 1, "selected": false, "text": "GLint valid;\nglGet(GL_CURRENT_RASTER_POSITION_VALID, &valid);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1329401/" ]
25,652
<p>I want to programatically create an NSTextView. How can I determine the correct frame height so that the view displays one line of text in the current default font?</p>
[ { "answer_id": 90694, "author": "Ken", "author_id": 17320, "author_profile": "https://Stackoverflow.com/users/17320", "pm_score": 2, "selected": false, "text": "[textField setFont:myFont];\n[textField sizeToFit];\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25652", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2140/" ]
25,653
<p>Is there any way to apply an attribute to a model file in ASP.NET Dynamic Data to hide the column?</p> <p>For instance, I can currently set the display name of a column like this:</p> <pre><code>[DisplayName("Last name")] public object Last_name { get; set; } </code></pre> <p>Is there a similar way to hide a column?</p> <p><strong>Edit</strong>: Many thanks to Christian Hagelid for going the extra mile and giving a spot-on answer :-)</p>
[ { "answer_id": 25667, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 5, "selected": true, "text": "[ScaffoldColumn(false)]\n [ScaffoldTable(false)]\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25653", "https://Stackoverflow.com", "https://Stackoverflow.com/users/364/" ]
25,665
<p>Is there any python module to convert PDF files into text? I tried <a href="http://code.activestate.com/recipes/511465/" rel="noreferrer">one piece of code</a> found in Activestate which uses pypdf but the text generated had no space between and was of no use. </p>
[ { "answer_id": 48154, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 6, "selected": false, "text": "import pyPdf\npdf = pyPdf.PdfFileReader(open(filename, \"rb\"))\nfor page in pdf.pages:\n print page.extractText()\n" }, { "answer_id": 314249, "author": "codeape", "author_id": 3571, "author_profile": "https://Stackoverflow.com/users/3571", "pm_score": 4, "selected": false, "text": "\ndef pdf_to_csv(filename):\n from pdflib.page import TextItem, TextConverter\n from pdflib.pdfparser import PDFDocument, PDFParser\n from pdflib.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\n class CsvConverter(TextConverter):\n def __init__(self, *args, **kwargs):\n TextConverter.__init__(self, *args, **kwargs)\n\n def end_page(self, i):\n from collections import defaultdict\n lines = defaultdict(lambda : {})\n for child in self.cur_item.objs:\n if isinstance(child, TextItem):\n (_,_,x,y) = child.bbox\n line = lines[int(-y)]\n line[x] = child.text\n\n for y in sorted(lines.keys()):\n line = lines[y]\n self.outfp.write(\";\".join(line[x] for x in sorted(line.keys())))\n self.outfp.write(\"\\n\")\n\n # ... the following part of the code is a remix of the \n # convert() function in the pdfminer/tools/pdf2text module\n rsrc = PDFResourceManager()\n outfp = StringIO()\n device = CsvConverter(rsrc, outfp, \"ascii\")\n\n doc = PDFDocument()\n fp = open(filename, 'rb')\n parser = PDFParser(doc, fp)\n doc.initialize('')\n\n interpreter = PDFPageInterpreter(rsrc, device)\n\n for i, page in enumerate(doc.get_pages()):\n outfp.write(\"START PAGE %d\\n\" % i)\n interpreter.process_page(page)\n outfp.write(\"END PAGE %d\\n\" % i)\n\n device.close()\n fp.close()\n\n return outfp.getvalue()\n\n" }, { "answer_id": 1257121, "author": "tgray", "author_id": 64206, "author_profile": "https://Stackoverflow.com/users/64206", "pm_score": 7, "selected": false, "text": "20100213 >>> import pdfminer\n>>> pdfminer.__version__\n'20100213'\n def pdf_to_csv(filename):\n from cStringIO import StringIO #<-- added so you can copy/paste this to try it\n from pdfminer.converter import LTTextItem, TextConverter\n from pdfminer.pdfparser import PDFDocument, PDFParser\n from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\n class CsvConverter(TextConverter):\n def __init__(self, *args, **kwargs):\n TextConverter.__init__(self, *args, **kwargs)\n\n def end_page(self, i):\n from collections import defaultdict\n lines = defaultdict(lambda : {})\n for child in self.cur_item.objs:\n if isinstance(child, LTTextItem):\n (_,_,x,y) = child.bbox #<-- changed\n line = lines[int(-y)]\n line[x] = child.text.encode(self.codec) #<-- changed\n\n for y in sorted(lines.keys()):\n line = lines[y]\n self.outfp.write(\";\".join(line[x] for x in sorted(line.keys())))\n self.outfp.write(\"\\n\")\n\n # ... the following part of the code is a remix of the \n # convert() function in the pdfminer/tools/pdf2text module\n rsrc = PDFResourceManager()\n outfp = StringIO()\n device = CsvConverter(rsrc, outfp, codec=\"utf-8\") #<-- changed \n # becuase my test documents are utf-8 (note: utf-8 is the default codec)\n\n doc = PDFDocument()\n fp = open(filename, 'rb')\n parser = PDFParser(fp) #<-- changed\n parser.set_document(doc) #<-- added\n doc.set_parser(parser) #<-- added\n doc.initialize('')\n\n interpreter = PDFPageInterpreter(rsrc, device)\n\n for i, page in enumerate(doc.get_pages()):\n outfp.write(\"START PAGE %d\\n\" % i)\n interpreter.process_page(page)\n outfp.write(\"END PAGE %d\\n\" % i)\n\n device.close()\n fp.close()\n\n return outfp.getvalue()\n 20100619p1 LTTextItem LTChar def pdf_to_csv(filename):\n from cStringIO import StringIO \n from pdfminer.converter import LTChar, TextConverter #<-- changed\n from pdfminer.layout import LAParams\n from pdfminer.pdfparser import PDFDocument, PDFParser\n from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\n class CsvConverter(TextConverter):\n def __init__(self, *args, **kwargs):\n TextConverter.__init__(self, *args, **kwargs)\n\n def end_page(self, i):\n from collections import defaultdict\n lines = defaultdict(lambda : {})\n for child in self.cur_item.objs:\n if isinstance(child, LTChar): #<-- changed\n (_,_,x,y) = child.bbox \n line = lines[int(-y)]\n line[x] = child.text.encode(self.codec)\n\n for y in sorted(lines.keys()):\n line = lines[y]\n self.outfp.write(\";\".join(line[x] for x in sorted(line.keys())))\n self.outfp.write(\"\\n\")\n\n # ... the following part of the code is a remix of the \n # convert() function in the pdfminer/tools/pdf2text module\n rsrc = PDFResourceManager()\n outfp = StringIO()\n device = CsvConverter(rsrc, outfp, codec=\"utf-8\", laparams=LAParams()) #<-- changed\n # becuase my test documents are utf-8 (note: utf-8 is the default codec)\n\n doc = PDFDocument()\n fp = open(filename, 'rb')\n parser = PDFParser(fp) \n parser.set_document(doc) \n doc.set_parser(parser) \n doc.initialize('')\n\n interpreter = PDFPageInterpreter(rsrc, device)\n\n for i, page in enumerate(doc.get_pages()):\n outfp.write(\"START PAGE %d\\n\" % i)\n if page is not None:\n interpreter.process_page(page)\n outfp.write(\"END PAGE %d\\n\" % i)\n\n device.close()\n fp.close()\n\n return outfp.getvalue()\n 20110515 def pdf_to_csv(filename):\n from cStringIO import StringIO \n from pdfminer.converter import LTChar, TextConverter\n from pdfminer.layout import LAParams\n from pdfminer.pdfparser import PDFDocument, PDFParser\n from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\n\n class CsvConverter(TextConverter):\n def __init__(self, *args, **kwargs):\n TextConverter.__init__(self, *args, **kwargs)\n\n def end_page(self, i):\n from collections import defaultdict\n lines = defaultdict(lambda : {})\n for child in self.cur_item._objs: #<-- changed\n if isinstance(child, LTChar):\n (_,_,x,y) = child.bbox \n line = lines[int(-y)]\n line[x] = child._text.encode(self.codec) #<-- changed\n\n for y in sorted(lines.keys()):\n line = lines[y]\n self.outfp.write(\";\".join(line[x] for x in sorted(line.keys())))\n self.outfp.write(\"\\n\")\n\n # ... the following part of the code is a remix of the \n # convert() function in the pdfminer/tools/pdf2text module\n rsrc = PDFResourceManager()\n outfp = StringIO()\n device = CsvConverter(rsrc, outfp, codec=\"utf-8\", laparams=LAParams())\n # becuase my test documents are utf-8 (note: utf-8 is the default codec)\n\n doc = PDFDocument()\n fp = open(filename, 'rb')\n parser = PDFParser(fp) \n parser.set_document(doc) \n doc.set_parser(parser) \n doc.initialize('')\n\n interpreter = PDFPageInterpreter(rsrc, device)\n\n for i, page in enumerate(doc.get_pages()):\n outfp.write(\"START PAGE %d\\n\" % i)\n if page is not None:\n interpreter.process_page(page)\n outfp.write(\"END PAGE %d\\n\" % i)\n\n device.close()\n fp.close()\n\n return outfp.getvalue()\n" }, { "answer_id": 3276880, "author": "Skylar Saveland", "author_id": 177293, "author_profile": "https://Stackoverflow.com/users/177293", "pm_score": 3, "selected": false, "text": "convert_pdf(path)\n def convert_pdf(path, outtype='txt', opts={}):\n import sys\n from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter, process_pdf\n from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter, TagExtractor\n from pdfminer.layout import LAParams\n from pdfminer.pdfparser import PDFDocument, PDFParser\n from pdfminer.pdfdevice import PDFDevice\n from pdfminer.cmapdb import CMapDB\n\n outfile = path[:-3] + outtype\n outdir = '/'.join(path.split('/')[:-1])\n\n debug = 0\n # input option\n password = ''\n pagenos = set()\n maxpages = 0\n # output option\n codec = 'utf-8'\n pageno = 1\n scale = 1\n showpageno = True\n laparams = LAParams()\n for (k, v) in opts:\n if k == '-d': debug += 1\n elif k == '-p': pagenos.update( int(x)-1 for x in v.split(',') )\n elif k == '-m': maxpages = int(v)\n elif k == '-P': password = v\n elif k == '-o': outfile = v\n elif k == '-n': laparams = None\n elif k == '-A': laparams.all_texts = True\n elif k == '-D': laparams.writing_mode = v\n elif k == '-M': laparams.char_margin = float(v)\n elif k == '-L': laparams.line_margin = float(v)\n elif k == '-W': laparams.word_margin = float(v)\n elif k == '-O': outdir = v\n elif k == '-t': outtype = v\n elif k == '-c': codec = v\n elif k == '-s': scale = float(v)\n #\n CMapDB.debug = debug\n PDFResourceManager.debug = debug\n PDFDocument.debug = debug\n PDFParser.debug = debug\n PDFPageInterpreter.debug = debug\n PDFDevice.debug = debug\n #\n rsrcmgr = PDFResourceManager()\n if not outtype:\n outtype = 'txt'\n if outfile:\n if outfile.endswith('.htm') or outfile.endswith('.html'):\n outtype = 'html'\n elif outfile.endswith('.xml'):\n outtype = 'xml'\n elif outfile.endswith('.tag'):\n outtype = 'tag'\n if outfile:\n outfp = file(outfile, 'w')\n else:\n outfp = sys.stdout\n if outtype == 'txt':\n device = TextConverter(rsrcmgr, outfp, codec=codec, laparams=laparams)\n elif outtype == 'xml':\n device = XMLConverter(rsrcmgr, outfp, codec=codec, laparams=laparams, outdir=outdir)\n elif outtype == 'html':\n device = HTMLConverter(rsrcmgr, outfp, codec=codec, scale=scale, laparams=laparams, outdir=outdir)\n elif outtype == 'tag':\n device = TagExtractor(rsrcmgr, outfp, codec=codec)\n else:\n return usage()\n\n fp = file(path, 'rb')\n process_pdf(rsrcmgr, device, fp, pagenos, maxpages=maxpages, password=password)\n fp.close()\n device.close()\n\n outfp.close()\n return\n" }, { "answer_id": 4169679, "author": "Decora", "author_id": 506335, "author_profile": "https://Stackoverflow.com/users/506335", "pm_score": 1, "selected": false, "text": "pdftohtml -xml subprocess.Popen()" }, { "answer_id": 4846622, "author": "Tim McNamara", "author_id": 395287, "author_profile": "https://Stackoverflow.com/users/395287", "pm_score": 4, "selected": false, "text": "slate >>> with open('example.pdf') as f:\n... doc = slate.PDF(f)\n...\n>>> doc\n[..., ..., ...]\n>>> doc[1]\n'Text from page 2...' \n" }, { "answer_id": 16796554, "author": "gonz", "author_id": 323751, "author_profile": "https://Stackoverflow.com/users/323751", "pm_score": 3, "selected": false, "text": "from cStringIO import StringIO\nfrom pdfminer.pdfinterp import PDFResourceManager, process_pdf\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\n\ndef to_txt(pdf_path):\n input_ = file(pdf_path, 'rb')\n output = StringIO()\n\n manager = PDFResourceManager()\n converter = TextConverter(manager, output, laparams=LAParams())\n process_pdf(manager, converter, input_)\n\n return output.getvalue() \n" }, { "answer_id": 21564675, "author": "user3272884", "author_id": 3272884, "author_profile": "https://Stackoverflow.com/users/3272884", "pm_score": 6, "selected": false, "text": "process_pdf import sys\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.converter import XMLConverter, HTMLConverter, TextConverter\nfrom pdfminer.layout import LAParams\nfrom cStringIO import StringIO\n\ndef pdfparser(data):\n\n fp = file(data, 'rb')\n rsrcmgr = PDFResourceManager()\n retstr = StringIO()\n codec = 'utf-8'\n laparams = LAParams()\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n # Create a PDF interpreter object.\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n # Process each page contained in the document.\n\n for page in PDFPage.get_pages(fp):\n interpreter.process_page(page)\n data = retstr.getvalue()\n\n print data\n\nif __name__ == '__main__':\n pdfparser(sys.argv[1]) \n import sys\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.converter import XMLConverter, HTMLConverter, TextConverter\nfrom pdfminer.layout import LAParams\nimport io\n\ndef pdfparser(data):\n\n fp = open(data, 'rb')\n rsrcmgr = PDFResourceManager()\n retstr = io.StringIO()\n codec = 'utf-8'\n laparams = LAParams()\n device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)\n # Create a PDF interpreter object.\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n # Process each page contained in the document.\n\n for page in PDFPage.get_pages(fp):\n interpreter.process_page(page)\n data = retstr.getvalue()\n\n print(data)\n\nif __name__ == '__main__':\n pdfparser(sys.argv[1]) \n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25665", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
25,672
<p>Been going over my predecessor's code and see usage of the "request" scope frequently. What is the appropriate usage of this scope?</p>
[ { "answer_id": 26725, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 5, "selected": true, "text": "<cfif not structKeyExists(application, \"dsn\")>\n <cflock scope=\"application\" type=\"exclusive\" timeout=\"30\">\n <cfif not structKeyExists(application, \"dsn\")>\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n </cfif>\n </cflock>\n</cfif>\n <cfcomponent>\n <cfset this.name = \"myApplicationName\" />\n\n <cffunction name=\"onApplicationStart\" returnType=\"boolean\" output=\"false\">\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n <cfreturn true />\n </cffunction>\n</cfcomponent>\n" }, { "answer_id": 3463290, "author": "RandomCoder", "author_id": 417786, "author_profile": "https://Stackoverflow.com/users/417786", "pm_score": 0, "selected": false, "text": "<cfif not structKeyExists(application, \"dsn\")>\n <cflock scope=\"application\" type=\"exclusive\" timeout=\"30\">\n <cfset application.dsn = \"MyDSN\" />\n <cfset foo = \"bar\" />\n <cfset x = 5 />\n </cflock>\n</cfif>\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25672", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
25,746
<p>I'm learning objective-C and Cocoa and have come across this statement:</p> <blockquote> <p>The Cocoa frameworks expect that global string constants rather than string literals are used for dictionary keys, notification and exception names, and some method parameters that take strings.</p> </blockquote> <p>I've only worked in higher level languages so have never had to consider the details of strings that much. What's the difference between a string constant and string literal?</p>
[ { "answer_id": 25750, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 2, "selected": false, "text": "const std::string mystring = \"my string\";\n someMethod(mystring);\n someMethod(\"my string\");\n" }, { "answer_id": 25798, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 7, "selected": true, "text": "@\"foo\" NSString // MyExample.h - declaration, other code references this\nextern NSString * const MyExampleNotification;\n\n// MyExample.m - definition, compiled for other code to reference\nNSString * const MyExampleNotification = @\"MyExampleNotification\";\n const NSNotificationCenter" }, { "answer_id": 12327650, "author": "Jano", "author_id": 412916, "author_profile": "https://Stackoverflow.com/users/412916", "pm_score": 4, "selected": false, "text": "10 const int age = 10; @\"\" NSString NSString NSString *const name = @\"John\"; objc_sendMsg const @\"\" NSConstantString NSString NSString const NSString* name = @\"John\"; NSString const* name= @\"John\"; const <object> NSString NSConstantString const const NSMutableArray *array = [NSMutableArray new]; [array removeAllObjects]; RewriteModernObjC::RewriteObjCStringLiteral NSConstantString // string literal\n[dic objectForKey:@\"a\"];\n\n// string constant\nNSString *const a = @\"a\";\n[dic objectForKey:a];\n [a isEqualToString:b] (a==b) isEqualToString: strcmp // header\nextern NSString *const name;\n// implementation\nNSString *const name = @\"john\";\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2799/" ]
25,749
<p>I'm learning objective-c and keep bumping into the @ symbol. It is used in different scenarios, for example at the start of a string or to synthesise accessor methods. </p> <p>What's does the @ symbol mean in objective-c?</p>
[ { "answer_id": 25784, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 8, "selected": true, "text": "@ @ id Class nil Nil typedef #define id in out inout oneway byref bycopy @property copy retain assign readonly readwrite nonatomic getter setter @property" }, { "answer_id": 9107765, "author": "pabloelustondo", "author_id": 1173878, "author_profile": "https://Stackoverflow.com/users/1173878", "pm_score": 4, "selected": false, "text": "NSString *myString = @\"My String\\n\";\nNSString *anotherString = [NSString stringWithFormat:@\"%d %@\", 1, @\"String\"];\n" }, { "answer_id": 73092408, "author": "Carl G", "author_id": 39396, "author_profile": "https://Stackoverflow.com/users/39396", "pm_score": 1, "selected": false, "text": "@ @ @ #define #ifdef @ @interface @implementation @interface @protocol @optional @required @class @property @synthesize @dynamic @interface @try @throw @catch @finally @end @interface @implementation @protocol @encode @synchronized @selector @protocol SEL @defs struct @public @package @protected @private @available @autoreleasepool autorelease release @ @... NSNumber *fortyTwo = @42; // equivalent to [NSNumber numberWithInt:42]\nNSNumber *yesNumber = @YES; // equivalent to [NSNumber numberWithBool:YES]\n @(...) // numbers.\nNSNumber *piOverTwo = @(M_PI / 2); // [NSNumber numberWithDouble:(M_PI / 2)]\n// strings.\nNSString *path = @(getenv(\"PATH\")); // [NSString stringWithUTF8String:(getenv(\"PATH\"))]\n// structs.\nNSValue *center = @(view.center); // Point p = view.center;\n // [NSValue valueWithBytes:&p objCType:@encode(Point)];\n @\"...\" @[] @{} NSArray *array = @[ @\"Hello\", NSApp, [NSNumber numberWithInt:42] ];\nNSDictionary *dictionary = @{\n @\"name\" : NSUserName(),\n @\"date\" : [NSDate date],\n @\"processInfo\" : [NSProcessInfo processInfo]\n};\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2799/" ]
25,752
<p>In a drop down list, I need to add spaces in front of the options in the list. I am trying</p> <pre><code>&lt;select&gt; &lt;option&gt;&amp;#32;&amp;#32;Sample&lt;/option&gt; &lt;/select&gt; </code></pre> <p>for adding two spaces but it displays no spaces. How can I add spaces before option texts?</p>
[ { "answer_id": 25754, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "&nbsp;\n" }, { "answer_id": 25758, "author": "Rob Cooper", "author_id": 832, "author_profile": "https://Stackoverflow.com/users/832", "pm_score": 6, "selected": true, "text": "&#160 <select>\n<option>&#160;option 1</option>\n<option> option 2</option>\n</select>\n &nbsp;" }, { "answer_id": 25759, "author": "Matt Sheppard", "author_id": 797, "author_profile": "https://Stackoverflow.com/users/797", "pm_score": 4, "selected": false, "text": "&nbsp; &#160; <select>\n <option>&nbsp;&nbsp;Sample</option>\n</select>\n <select>\n <option>&#160;&#160;Sample</option>\n</select>\n" }, { "answer_id": 25840, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 2, "selected": false, "text": "<option>" }, { "answer_id": 25888, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 2, "selected": false, "text": "<select>\n <option style=\"padding-left: 0px;\">Blah</option>\n <option style=\"padding-left: 5px;\">Blah</option>\n <option style=\"padding-left: 10px;\">Blah</option>\n <option style=\"padding-left: 0px;\">Blah</option>\n <option style=\"padding-left: 5px;\">Blah</option>\n</select>\n" }, { "answer_id": 3685564, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": false, "text": "Server.HtmlDecode(\"&nbsp;\") \n" }, { "answer_id": 5092184, "author": "user630071", "author_id": 630071, "author_profile": "https://Stackoverflow.com/users/630071", "pm_score": 1, "selected": false, "text": "Server.HtmlDecode(\"&nbsp;\")" }, { "answer_id": 10986354, "author": "Alain Holloway", "author_id": 1449740, "author_profile": "https://Stackoverflow.com/users/1449740", "pm_score": 2, "selected": false, "text": "Courier New" }, { "answer_id": 17855282, "author": "Riyaz Hameed", "author_id": 1570636, "author_profile": "https://Stackoverflow.com/users/1570636", "pm_score": 5, "selected": false, "text": " SectionsList.ForEach(p => { p.Text = \"\\xA0\\xA0Section: \" + p.Text; });\n" }, { "answer_id": 23674381, "author": "Shahid Riaz Bhatti", "author_id": 3640138, "author_profile": "https://Stackoverflow.com/users/3640138", "pm_score": 1, "selected": false, "text": "0160 ALT+0160 ListItem(\"ALT+0160 ALT+0160 TEST\", \"TESTVAL\")\n" }, { "answer_id": 24847659, "author": "dabobert", "author_id": 1332316, "author_profile": "https://Stackoverflow.com/users/1332316", "pm_score": 3, "selected": false, "text": "$(\"#project_product_parent_id option\").each(function(i,option){\n $option = $(option);\n $option.text($option.text().replace(/─/g,'\\u00A0\\u00A0\\u00A0'))\n});\n" }, { "answer_id": 47038372, "author": "Busch4Al", "author_id": 5975805, "author_profile": "https://Stackoverflow.com/users/5975805", "pm_score": -1, "selected": false, "text": "for(var x = 0; x < dd.options.length; x++)\n{\n item = dd.options[x];\n //if a line that needs indenting\n item.text = ' ' + item.text; //indent\n}\n" }, { "answer_id": 47790035, "author": "Jay", "author_id": 6703661, "author_profile": "https://Stackoverflow.com/users/6703661", "pm_score": -1, "selected": false, "text": "foreach (var item in q)\n{\n StringWriter myWriter = new StringWriter();\n\n myWriter.Lable = HttpUtility.HtmlDecode(item.Label.Replace(\" \", \"&nbsp;\"));\n}\n" }, { "answer_id": 57414845, "author": "Diogo Toscano", "author_id": 4047580, "author_profile": "https://Stackoverflow.com/users/4047580", "pm_score": 1, "selected": false, "text": "obj_dat.options[0] = new Option('Menu 1', 'Menu 1');\nobj_dat.options[1] = new Option('<?php echo html_entity_decode('&nbsp;&nbsp;&nbsp;'); ?>Menu 1.1', 'Menu 1.1');\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
25,765
<p>I'm in the process of weeding out all hardcoded values in a Java library and was wondering what framework would be the best (in terms of zero- or close-to-zero configuration) to handle run-time configuration? I would prefer XML-based configuration files, but it's not essential. </p> <p>Please do only reply if you have practical experience with a framework. I'm not looking for examples, but experience...</p>
[ { "answer_id": 25819, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 2, "selected": false, "text": "java.util.Properties" }, { "answer_id": 34397, "author": "John Meagher", "author_id": 3535, "author_profile": "https://Stackoverflow.com/users/3535", "pm_score": 5, "selected": false, "text": "server.host=myHost\nserver.url=http://${server.host}/somePath\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25765", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448983/" ]
25,767
<p>What is the quickest way to get a large amount of data (think golf) and the most efficient (think performance) to get a large amount of data from a MySQL database to a session without having to continue doing what I already have:</p> <pre><code>$sql = "SELECT * FROM users WHERE username='" . mysql_escape_string($_POST['username']) . "' AND password='" . mysql_escape_string(md5($_POST['password'])) . "'"; $result = mysql_query($sql, $link) or die("There was an error while trying to get your information.\n&lt;!--\n" . mysql_error($link) . "\n--&gt;"); if(mysql_num_rows($result) &lt; 1) { $_SESSION['username'] = $_POST['username']; redirect('index.php?p=signup'); } $_SESSION['id'] = mysql_result($result, '0', 'id'); $_SESSION['fName'] = mysql_result($result, '0', 'fName'); $_SESSION['lName'] = mysql_result($result, '0', 'lName'); ... </code></pre> <p>And before anyone asks yes I do really need to 'SELECT </p> <p>Edit: Yes, I am sanitizing the data, so that there can be no SQL injection, that is further up in the code.</p>
[ { "answer_id": 25776, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 0, "selected": false, "text": "$_SESSION['data'] = json_encode(mysql_fetch_array($result));\n json_decode $_SESSION['data'] json_encode json_decode json_encoding $fname = json_decode($_SESSION['data'])['fname'];\n" }, { "answer_id": 25782, "author": "Anders Sandvig", "author_id": 1709, "author_profile": "https://Stackoverflow.com/users/1709", "pm_score": 0, "selected": false, "text": "$_SESSION['data'] = json_encode(mysql_fetch_array($result));" }, { "answer_id": 25805, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 2, "selected": true, "text": "while($row = mysql_fetch_assoc($result))\n {\n $_SESSION = array_merge_recursive($_SESSION, $row);\n }\n" }, { "answer_id": 25839, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "SELECT" }, { "answer_id": 9407270, "author": "Sir", "author_id": 1076743, "author_profile": "https://Stackoverflow.com/users/1076743", "pm_score": 1, "selected": false, "text": "$get = mysql_query(\"SELECT * FROM table_name WHERE field_name=$something\") or die(mysql_error());\n\n$_SESSION['data'] = mysql_fetch_assoc($get);\n echo $_SESSION['data']['username'];\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/115/" ]
25,771
<p>How can I insert compilation timestamp information into an executable I build with Visual C++ 2005? I want to be able to output something like this when I execute the program:</p> <blockquote> <p>This build XXXX was compiled at dd-mm-yy, hh:mm.</p> </blockquote> <p>where date and time reflect the time when the project was built. They should not change with each successive call of the program, unless it's recompiled.</p>
[ { "answer_id": 25780, "author": "sparkes", "author_id": 269, "author_profile": "https://Stackoverflow.com/users/269", "pm_score": 3, "selected": false, "text": "__DATE__ \n__TIME__\n" }, { "answer_id": 25802, "author": "Eric Scrivner", "author_id": 2594, "author_profile": "https://Stackoverflow.com/users/2594", "pm_score": 0, "selected": false, "text": "__TIMESTAMP__ __TIMESTAMP__" }, { "answer_id": 25813, "author": "Jim Buck", "author_id": 2666, "author_profile": "https://Stackoverflow.com/users/2666", "pm_score": 5, "selected": false, "text": "const char *buildString = \"This build XXXX was compiled at \" __DATE__ \", \" __TIME__ \".\";\n" }, { "answer_id": 25887, "author": "Joe Schneider", "author_id": 1541, "author_profile": "https://Stackoverflow.com/users/1541", "pm_score": 3, "selected": false, "text": "__TIME__ __DATE__ __TIME__ __DATE__ __DATE__ __TIME__" }, { "answer_id": 26297, "author": "Mat Noguchi", "author_id": 1799, "author_profile": "https://Stackoverflow.com/users/1799", "pm_score": 3, "selected": false, "text": "__ImageBase EXTERN_C IMAGE_DOS_HEADER __ImageBase; const IMAGE_NT_HEADERS *nt_header= (const IMAGE_NT_HEADERS *)((char *)&__ImageBase + __ImageBase.e_lfanew); nt_header->FileHeader.TimeDateStamp" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
25,785
<p>Is there a simple way, in a pretty standard UNIX environment with bash, to run a command to delete all but the most recent X files from a directory?</p> <p>To give a bit more of a concrete example, imagine some cron job writing out a file (say, a log file or a tar-ed up backup) to a directory every hour. I'd like a way to have another cron job running which would remove the oldest files in that directory until there are less than, say, 5.</p> <p>And just to be clear, there's only one file present, it should never be deleted.</p>
[ { "answer_id": 25789, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 7, "selected": false, "text": "rm `ls -t | awk 'NR>5'`\n" }, { "answer_id": 25790, "author": "thelsdj", "author_id": 163, "author_profile": "https://Stackoverflow.com/users/163", "pm_score": 6, "selected": false, "text": "(ls -t|head -n 5;ls)|sort|uniq -u|xargs rm\n (ls -t|head -n 5;ls)|sort|uniq -u|sed -e 's,.*,\"&\",g'|xargs rm\n" }, { "answer_id": 25792, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 2, "selected": false, "text": "ls -C1 -t| awk 'NR>5'|xargs rm\n ls -C1 -t | awk 'NR>5' | sed -e \"s/^/rm '/\" -e \"s/$/'/\" | sh\n" }, { "answer_id": 299534, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "find . -maxdepth 1 -type f | xargs -x ls -t | awk 'NR>5' | xargs -L1 rm\n xargs -x" }, { "answer_id": 299911, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 4, "selected": false, "text": "find . -maxdepth 1 -type f -printf '%T@ %p\\0' | sort -r -z -n | awk 'BEGIN { RS=\"\\0\"; ORS=\"\\0\"; FS=\"\" } NR > 5 { sub(\"^[0-9]*(.[0-9]*)? \", \"\"); print }' | xargs -0 rm -f\n" }, { "answer_id": 990575, "author": "Ian Kelling", "author_id": 14456, "author_profile": "https://Stackoverflow.com/users/14456", "pm_score": 3, "selected": false, "text": "while IFS= read -rd ''; do \n x+=(\"${REPLY#* }\"); \ndone < <(find . -maxdepth 1 -printf '%T@ %p\\0' | sort -r -z -n )\n" }, { "answer_id": 8216367, "author": "lolesque", "author_id": 787216, "author_profile": "https://Stackoverflow.com/users/787216", "pm_score": 2, "selected": false, "text": "[ 6 -le `ls *(.)|wc -l` ] && rm *(.om[6,999])\n *(.om[6,999]) . o m a c [6,999]" }, { "answer_id": 10119963, "author": "Fabien", "author_id": 21132, "author_profile": "https://Stackoverflow.com/users/21132", "pm_score": 6, "selected": false, "text": "ls -tr | head -n -5 | xargs --no-run-if-empty rm \n" }, { "answer_id": 16978637, "author": "Pavel Tankov", "author_id": 1154183, "author_profile": "https://Stackoverflow.com/users/1154183", "pm_score": 0, "selected": false, "text": "leaveCount=5\nfileCount=$(ls -1 *.log | wc -l)\ntailCount=$((fileCount - leaveCount))\n\n# avoid negative tail argument\n[[ $tailCount < 0 ]] && tailCount=0\n\nls -t *.log | tail -$tailCount | xargs rm -f\n" }, { "answer_id": 17850033, "author": "Mark", "author_id": 3915, "author_profile": "https://Stackoverflow.com/users/3915", "pm_score": 4, "selected": false, "text": "ls -tQ | tail -n+4 | xargs rm\n" }, { "answer_id": 34862475, "author": "mklement0", "author_id": 45375, "author_profile": "https://Stackoverflow.com/users/45375", "pm_score": 8, "selected": false, "text": "rm rm `...` rm ls ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}\n (...) cd (cd /path/to && ls -tp | grep -v '/$' | tail -n +6 | xargs -I {} rm -- {}) xargs rm xargs xargs -d '\\n' xargs ls -tp | grep -v '/$' | tail -n +6 | xargs -d '\\n' -r rm --\n -r --no-run-if-empty rm xargs xargs -0 NUL NUL 0x0 ls -tp | grep -v '/$' | tail -n +6 | tr '\\n' '\\0' | xargs -0 rm --\n ls -tp -t / -p ls -tp (cd /path/to && ls -tp ...) grep -v '/$' -v / /$ tail -n +6 N N+1 tail -n + xargs -I {} rm -- {} rm xargs xargs -I {} rm -- {} {} rm -- - rm # One by one, in a shell loop (POSIX-compliant):\nls -tp | grep -v '/$' | tail -n +6 | while IFS= read -r f; do echo \"$f\"; done\n\n# One by one, but using a Bash process substitution (<(...), \n# so that the variables inside the `while` loop remain in scope:\nwhile IFS= read -r f; do echo \"$f\"; done < <(ls -tp | grep -v '/$' | tail -n +6)\n\n# Collecting the matches in a Bash *array*:\nIFS=$'\\n' read -d '' -ra files < <(ls -tp | grep -v '/$' | tail -n +6)\nprintf '%s\\n' \"${files[@]}\" # print array elements\n" }, { "answer_id": 35184103, "author": "Bulrush", "author_id": 3617046, "author_profile": "https://Stackoverflow.com/users/3617046", "pm_score": 0, "selected": false, "text": "keep NUM DIR #!/bin/bash\n# Keep last N files by date.\n# Usage: keep NUMBER DIRECTORY\necho \"\"\nif [ $# -lt 2 ]; then\n echo \"Usage: $0 NUMFILES DIR\"\n echo \"Keep last N newest files.\"\n exit 1\nfi\nif [ ! -e $2 ]; then\n echo \"ERROR: directory '$1' does not exist\"\n exit 1\nfi\nif [ ! -d $2 ]; then\n echo \"ERROR: '$1' is not a directory\"\n exit 1\nfi\npushd $2 > /dev/null\nls -tp | grep -v '/' | tail -n +\"$1\" | xargs -I {} rm -- {}\npopd > /dev/null\necho \"Done. Kept $1 most recent files in $2.\"\nls $2|wc -l\n" }, { "answer_id": 39280903, "author": "tim", "author_id": 6785145, "author_profile": "https://Stackoverflow.com/users/6785145", "pm_score": 1, "selected": false, "text": " #!/bin/bash\n # sed cmd chng #2 to value file wish to retain\n\n cd /opt/depot \n\n ls -1 MyMintFiles*.zip > BigList\n sed -n -e :a -e '1,2!{P;N;D;};N;ba' BigList > DeList\n\n for i in `cat DeList` \n do \n echo \"Deleted $i\" \n rm -f $i \n #echo \"File(s) gonzo \" \n #read junk \n done \n exit 0\n" }, { "answer_id": 41579911, "author": "TopherGopher", "author_id": 679458, "author_profile": "https://Stackoverflow.com/users/679458", "pm_score": 3, "selected": false, "text": "for F in $(find . -maxdepth 1 -type f -name \"*_srv_logs_*.tar.gz\" -printf '%T@ %p\\n' | sort -r -z -n | tail -n+5 | awk '{ print $2; }'); do rm $F; done\n find . -maxdepth 1 -type f -name \"*_srv_logs_*.tar.gz\" -printf '%T@ %p\\n'\n sort -r -z -n\n tail -n+5\n awk '{ print $2; }'\n for F in $(); do rm $F; done\n" }, { "answer_id": 44247584, "author": "fabrice", "author_id": 8082652, "author_profile": "https://Stackoverflow.com/users/8082652", "pm_score": 1, "selected": false, "text": "ls -t1 | head -n $(echo $(ls -1 | wc -l) - 10 | bc) | xargs rm\n" }, { "answer_id": 52632917, "author": "Pila", "author_id": 9901844, "author_profile": "https://Stackoverflow.com/users/9901844", "pm_score": 1, "selected": false, "text": "rm \"$(ls -td *.tar | awk 'NR>7')\" 2>&-\n eval $(ls -td *.tar | awk 'NR>7 { print \"rm \\\"\" $0 \"\\\"\"}')\n ls -td *.tar awk 'NR>7... print \"rm \\\"\" $0 \"\\\"\" eval rm (cd /FolderToDeleteWithin && eval $(ls -td *.tar | awk 'NR>7 { print \"rm \\\"\" $0 \"\\\"\"}'))\n ls -t touch 'foo \" bar' touch 'hello * world' print \"VarName=\"$1\n VarName $1 VarName eval $(ls -td *.tar | awk 'NR>7 { print \"VarName=\\\"\"$1\"\\\"\" }'); echo \"$VarName\"\n" }, { "answer_id": 73465873, "author": "Eduardo Lucio", "author_id": 3223785, "author_profile": "https://Stackoverflow.com/users/3223785", "pm_score": 2, "selected": false, "text": "TARGET_FOLDER=\"/my/folder/path\"\nFILES_KEEP=5\nls -tp \"$TARGET_FOLDER\"**/* | grep -v '/$' | tail -n +$((FILES_KEEP+1)) | xargs -d '\\n' -r rm --\n" }, { "answer_id": 73613596, "author": "Fravadona", "author_id": 3387716, "author_profile": "https://Stackoverflow.com/users/3387716", "pm_score": 4, "selected": true, "text": "n n=5\n\nfind . -maxdepth 1 -type f -printf '%T@ %p\\0' |\nsort -z -nrt ' ' -k1,1 |\nsed -z -e \"1,${n}d\" -e 's/[^ ]* //' |\nxargs -0r rm -f\n find -printf stat sed awk NULL #!/bin/bash\nn=5\n\nfind . -maxdepth 1 -type f ! -path $'*\\n*' -exec stat -f '%.9Fm %N' {} + |\nsort -nrt ' ' -k1,1 |\nawk -v n=\"$n\" -F'^[^ ]* ' 'NR > n {printf \"%s%c\", $2, 0}' |\nxargs -0 rm -f\n bash $'\\n' sh ls -b find -printf stat NULL stat sort awk sed xargs perl perl stat perl stat perl-5.8.9 stat Time::HiRes perl ‑MTime::HiRes=stat n=5\n\nfind . '(' -name '.' -o -prune ')' -type f -exec \\\nperl -MTime::HiRes=stat -le '\n foreach (@ARGV) {\n @st = stat($_);\n if ( @st > 0 ) {\n s/([\\\\\\n])/sprintf( \"\\\\%03o\", ord($1) )/ge;\n print sprintf( \"%.9f %s\", $st[9], $_ );\n }\n else { print STDERR \"stat: $_: $!\"; }\n }\n' {} + |\n\nsort -nrt ' ' -k1,1 |\n\nsed -e \"1,${n}d\" -e 's/[^ ]* //' |\n\nperl -l -ne '\n s/\\\\([0-7]{3})/chr(oct($1))/ge;\n s/([\"\\n])/\"\\\\$1\"/g;\n print \"\\\"$_\\\"\"; \n' |\n\nxargs -E '' sh -c '[ \"$#\" -gt 0 ] && rm -f \"$@\"' sh\n perl newline backslash \\n \\\\ time filename sort sed perl xargs xargs rm sh xargs rm" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25785", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
25,794
<p>Without local access to the server, is there any way to duplicate/clone a MySQL db (with content and without content) into another without using <code>mysqldump</code>?</p> <p>I am currently using MySQL 4.0.</p>
[ { "answer_id": 26091, "author": "Gary Richardson", "author_id": 2506, "author_profile": "https://Stackoverflow.com/users/2506", "pm_score": 7, "selected": false, "text": "CREATE TABLE x LIKE y;\n SHOW TABLES CREATE TABLE x LIKE other_db.y;\n INSERT INTO x SELECT * FROM other_db.y;\n INSERT INTO SELECT ALTER TABLE x DISABLE KEYS" }, { "answer_id": 1995186, "author": "jozjan", "author_id": 1843623, "author_profile": "https://Stackoverflow.com/users/1843623", "pm_score": 6, "selected": false, "text": "#!/bin/bash\n\nDBUSER=user\nDBPASSWORD=pwd\nDBSNAME=sourceDb\nDBNAME=destinationDb\nDBSERVER=db.example.com\n\nfCreateTable=\"\"\nfInsertData=\"\"\necho \"Copying database ... (may take a while ...)\"\nDBCONN=\"-h ${DBSERVER} -u ${DBUSER} --password=${DBPASSWORD}\"\necho \"DROP DATABASE IF EXISTS ${DBNAME}\" | mysql ${DBCONN}\necho \"CREATE DATABASE ${DBNAME}\" | mysql ${DBCONN}\nfor TABLE in `echo \"SHOW TABLES\" | mysql $DBCONN $DBSNAME | tail -n +2`; do\n createTable=`echo \"SHOW CREATE TABLE ${TABLE}\"|mysql -B -r $DBCONN $DBSNAME|tail -n +2|cut -f 2-`\n fCreateTable=\"${fCreateTable} ; ${createTable}\"\n insertData=\"INSERT INTO ${DBNAME}.${TABLE} SELECT * FROM ${DBSNAME}.${TABLE}\"\n fInsertData=\"${fInsertData} ; ${insertData}\"\ndone;\necho \"$fCreateTable ; $fInsertData\" | mysql $DBCONN $DBNAME\n" }, { "answer_id": 7111224, "author": "Rafe", "author_id": 163884, "author_profile": "https://Stackoverflow.com/users/163884", "pm_score": 9, "selected": false, "text": "mysqldump db2 db1 mysqldump -h [server] -u [user] -p[password] db1 | mysql -h [server] -u [user] -p[password] db2 -p [password]" }, { "answer_id": 7256328, "author": "mr_app", "author_id": 919557, "author_profile": "https://Stackoverflow.com/users/919557", "pm_score": 4, "selected": false, "text": "function cloneDatabase($dbName, $newDbName){\n global $admin;\n $db_check = @mysql_select_db ( $dbName );\n $getTables = $admin->query(\"SHOW TABLES\"); \n $tables = array();\n while($row = mysql_fetch_row($getTables)){\n $tables[] = $row[0];\n }\n $createTable = mysql_query(\"CREATE DATABASE `$newDbName` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;\") or die(mysql_error());\n foreach($tables as $cTable){\n $db_check = @mysql_select_db ( $newDbName );\n $create = $admin->query(\"CREATE TABLE $cTable LIKE \".$dbName.\".\".$cTable);\n if(!$create) {\n $error = true;\n }\n $insert = $admin->query(\"INSERT INTO $cTable SELECT * FROM \".$dbName.\".\".$cTable);\n }\n return !isset($error);\n}\n\n\n// usage\n$clone = cloneDatabase('dbname','newdbname'); // first: toCopy, second: new database\n" }, { "answer_id": 44257011, "author": "Remy Mellet", "author_id": 352173, "author_profile": "https://Stackoverflow.com/users/352173", "pm_score": 1, "selected": false, "text": "ssh vps:/etc/init.d/mysql stop\nscp -rC vps:/var/lib/mysql/ /tmp/var_lib_mysql\nssh vps:/etc/init.d/apache2 start\n /etc/init.d/mysql stop\nsudo chown -R mysql:mysql /tmp/var_lib_mysql\nsudo nano /etc/mysql/my.cnf\n-> [mysqld]\n-> datadir=/tmp/var_lib_mysql\n/etc/init.d/mysql start\n /etc/init.d/mysql stop\nmysql_upgrade -u root -pPASSWORD --force #that step took almost 1hrs\n/etc/init.d/mysql start\n" }, { "answer_id": 47740658, "author": "Alexander Goncharov", "author_id": 3654176, "author_profile": "https://Stackoverflow.com/users/3654176", "pm_score": 1, "selected": false, "text": "SET @NewSchema = 'your_new_db';\nSET @OldSchema = 'your_exists_db';\nSELECT CONCAT('CREATE TABLE ',@NewSchema,'.',table_name, ' LIKE ', TABLE_SCHEMA ,'.',table_name,';INSERT INTO ',@NewSchema,'.',table_name,' SELECT * FROM ', TABLE_SCHEMA ,'.',table_name,';') \nFROM information_schema.TABLES where TABLE_SCHEMA = @OldSchema AND TABLE_TYPE != 'VIEW';\n mysqldump --no-data --triggers -uroot -ppassword" }, { "answer_id": 48144503, "author": "Dustin", "author_id": 6519977, "author_profile": "https://Stackoverflow.com/users/6519977", "pm_score": 2, "selected": false, "text": "/* This function takes the database connection, an existing database, and the new database and duplicates everything in the new database. */\nfunction copyDatabase($c, $oldDB, $newDB) {\n\n // creates the schema if it does not exist\n $schema = \"CREATE SCHEMA IF NOT EXISTS {$newDB};\";\n mysqli_query($c, $schema);\n\n // selects the new schema\n mysqli_select_db($c, $newDB);\n\n // gets all tables in the old schema\n $tables = \"SELECT table_name\n FROM information_schema.tables\n WHERE table_schema = '{$oldDB}'\n AND table_type = 'BASE TABLE'\";\n $results = mysqli_query($c, $tables);\n\n // checks if any tables were returned and recreates them in the new schema, adds the foreign keys, and inserts the associated data\n if (mysqli_num_rows($results) > 0) {\n\n // recreates all tables first\n while ($row = mysqli_fetch_array($results)) {\n $table = \"CREATE TABLE {$newDB}.{$row[0]} LIKE {$oldDB}.{$row[0]}\";\n mysqli_query($c, $table);\n }\n\n // resets the results to loop through again\n mysqli_data_seek($results, 0);\n\n // loops through each table to add foreign key and insert data\n while ($row = mysqli_fetch_array($results)) {\n\n // inserts the data into each table\n $data = \"INSERT IGNORE INTO {$newDB}.{$row[0]} SELECT * FROM {$oldDB}.{$row[0]}\";\n mysqli_query($c, $data);\n\n // gets all foreign keys for a particular table in the old schema\n $fks = \"SELECT constraint_name, column_name, table_name, referenced_table_name, referenced_column_name\n FROM information_schema.key_column_usage\n WHERE referenced_table_name IS NOT NULL\n AND table_schema = '{$oldDB}'\n AND table_name = '{$row[0]}'\";\n $fkResults = mysqli_query($c, $fks);\n\n // checks if any foreign keys were returned and recreates them in the new schema\n // Note: ON UPDATE and ON DELETE are not pulled from the original so you would have to change this to your liking\n if (mysqli_num_rows($fkResults) > 0) {\n while ($fkRow = mysqli_fetch_array($fkResults)) {\n $fkQuery = \"ALTER TABLE {$newDB}.{$row[0]} \n ADD CONSTRAINT {$fkRow[0]}\n FOREIGN KEY ({$fkRow[1]}) REFERENCES {$newDB}.{$fkRow[3]}({$fkRow[1]})\n ON UPDATE CASCADE\n ON DELETE CASCADE;\";\n mysqli_query($c, $fkQuery);\n }\n }\n } \n }\n\n // gets all views in the old schema\n $views = \"SHOW FULL TABLES IN {$oldDB} WHERE table_type LIKE 'VIEW'\"; \n $results = mysqli_query($c, $views);\n\n // checks if any views were returned and recreates them in the new schema\n if (mysqli_num_rows($results) > 0) {\n while ($row = mysqli_fetch_array($results)) {\n $view = \"SHOW CREATE VIEW {$oldDB}.{$row[0]}\";\n $viewResults = mysqli_query($c, $view);\n $viewRow = mysqli_fetch_array($viewResults);\n mysqli_query($c, preg_replace(\"/CREATE(.*?)VIEW/\", \"CREATE VIEW\", str_replace($oldDB, $newDB, $viewRow[1])));\n }\n }\n\n // gets all triggers in the old schema\n $triggers = \"SELECT trigger_name, action_timing, event_manipulation, event_object_table, created\n FROM information_schema.triggers\n WHERE trigger_schema = '{$oldDB}'\"; \n $results = mysqli_query($c, $triggers);\n\n // checks if any triggers were returned and recreates them in the new schema\n if (mysqli_num_rows($results) > 0) {\n while ($row = mysqli_fetch_array($results)) {\n $trigger = \"SHOW CREATE TRIGGER {$oldDB}.{$row[0]}\";\n $triggerResults = mysqli_query($c, $trigger);\n $triggerRow = mysqli_fetch_array($triggerResults);\n mysqli_query($c, str_replace($oldDB, $newDB, $triggerRow[2]));\n }\n }\n\n // gets all procedures in the old schema\n $procedures = \"SHOW PROCEDURE STATUS WHERE db = '{$oldDB}'\";\n $results = mysqli_query($c, $procedures);\n\n // checks if any procedures were returned and recreates them in the new schema\n if (mysqli_num_rows($results) > 0) {\n while ($row = mysqli_fetch_array($results)) {\n $procedure = \"SHOW CREATE PROCEDURE {$oldDB}.{$row[1]}\";\n $procedureResults = mysqli_query($c, $procedure);\n $procedureRow = mysqli_fetch_array($procedureResults);\n mysqli_query($c, str_replace($oldDB, $newDB, $procedureRow[2]));\n }\n }\n\n // gets all functions in the old schema\n $functions = \"SHOW FUNCTION STATUS WHERE db = '{$oldDB}'\";\n $results = mysqli_query($c, $functions);\n\n // checks if any functions were returned and recreates them in the new schema\n if (mysqli_num_rows($results) > 0) {\n while ($row = mysqli_fetch_array($results)) {\n $function = \"SHOW CREATE FUNCTION {$oldDB}.{$row[1]}\";\n $functionResults = mysqli_query($c, $function);\n $functionRow = mysqli_fetch_array($functionResults);\n mysqli_query($c, str_replace($oldDB, $newDB, $functionRow[2]));\n }\n }\n\n // selects the old schema (a must for copying events)\n mysqli_select_db($c, $oldDB);\n\n // gets all events in the old schema\n $query = \"SHOW EVENTS\n WHERE db = '{$oldDB}';\";\n $results = mysqli_query($c, $query);\n\n // selects the new schema again\n mysqli_select_db($c, $newDB);\n\n // checks if any events were returned and recreates them in the new schema\n if (mysqli_num_rows($results) > 0) {\n while ($row = mysqli_fetch_array($results)) {\n $event = \"SHOW CREATE EVENT {$oldDB}.{$row[1]}\";\n $eventResults = mysqli_query($c, $event);\n $eventRow = mysqli_fetch_array($eventResults);\n mysqli_query($c, str_replace($oldDB, $newDB, $eventRow[3]));\n }\n }\n}\n" }, { "answer_id": 55256951, "author": "Shimon Doodkin", "author_id": 466363, "author_profile": "https://Stackoverflow.com/users/466363", "pm_score": 0, "selected": false, "text": "select @fromdb:=\"crm\";\nselect @todb:=\"crmen\";\n\nSET group_concat_max_len=100000000;\n\n\nSELECT GROUP_CONCAT( concat(\"CREATE TABLE `\",@todb,\"`.`\",table_name,\"` LIKE `\",@fromdb,\"`.`\",table_name,\"`;\\n\",\n\"INSERT INTO `\",@todb,\"`.`\",table_name,\"` SELECT * FROM `\",@fromdb,\"`.`\",table_name,\"`;\") \n\nSEPARATOR '\\n\\n')\n\nas sqlstatement\n FROM information_schema.tables where table_schema=@fromdb and TABLE_TYPE='BASE TABLE';\n" }, { "answer_id": 57918255, "author": "GDY", "author_id": 2593099, "author_profile": "https://Stackoverflow.com/users/2593099", "pm_score": 2, "selected": false, "text": "// Database variables\n\n$DB_HOST = 'localhost';\n$DB_USER = 'root';\n$DB_PASS = '1234';\n\n$DB_SRC = 'existing_db';\n$DB_DST = 'newly_created_db';\n\n\n\n// MYSQL Connect\n\n$mysqli = new mysqli( $DB_HOST, $DB_USER, $DB_PASS ) or die( $mysqli->error );\n\n\n\n// Create destination database\n\n$mysqli->query( \"CREATE DATABASE $DB_DST\" ) or die( $mysqli->error );\n\n\n\n// Iterate through tables of source database\n\n$tables = $mysqli->query( \"SHOW TABLES FROM $DB_SRC\" ) or die( $mysqli->error );\n\nwhile( $table = $tables->fetch_array() ): $TABLE = $table[0];\n\n\n // Copy table and contents in destination database\n\n $mysqli->query( \"CREATE TABLE $DB_DST.$TABLE LIKE $DB_SRC.$TABLE\" ) or die( $mysqli->error );\n $mysqli->query( \"INSERT INTO $DB_DST.$TABLE SELECT * FROM $DB_SRC.$TABLE\" ) or die( $mysqli->error );\n\n\nendwhile;\n" }, { "answer_id": 59750583, "author": "Andy Al", "author_id": 2874743, "author_profile": "https://Stackoverflow.com/users/2874743", "pm_score": -1, "selected": false, "text": "mysqldump -uusername -ppass dbname1 | mysql -uusername -ppass dbname2 mysqldump -uusername -ppass dbname1 | sed 's/InnoDB/RocksDB/' | mysql -uusername -ppass dbname2" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/211/" ]
25,803
<p>For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). </p> <p>How do I accomplish this assuming that: </p> <ul> <li>I don't want to use any 3rd party AOP libraries for C#,</li> <li>I don't want to add duplicate code to all the methods that I want to trace, </li> <li>I don't want to change the public API of the class - users of the class should be able to call all the methods in exactly the same way. </li> </ul> <p>To make the question more concrete let's assume there are 3 classes: </p> <pre><code> public class Caller { public static void Call() { Traced traced = new Traced(); traced.Method1(); traced.Method2(); } } public class Traced { public void Method1(String name, Int32 value) { } public void Method2(Object object) { } } public class Logger { public static void LogStart(MethodInfo method, Object[] parameterValues); public static void LogEnd(MethodInfo method); } </code></pre> <p>How do I invoke <em>Logger.LogStart</em> and <em>Logger.LogEnd</em> for every call to <em>Method1</em> and <em>Method2</em> without modifying the <em>Caller.Call</em> method and without adding the calls explicitly to <em>Traced.Method1</em> and <em>Traced.Method2</em>?</p> <p>Edit: What would be the solution if I'm allowed to slightly change the Call method?</p>
[ { "answer_id": 25808, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 1, "selected": false, "text": "LogStart LogEnd" }, { "answer_id": 25810, "author": "Steen", "author_id": 1448983, "author_profile": "https://Stackoverflow.com/users/1448983", "pm_score": 3, "selected": false, "text": "Using( Tracing tracing = new Tracing() ){ ... method body ...}\n public class Traced \n {\n public void Method1(String name, Int32 value) {\n using(Tracing tracer = new Tracing()) \n {\n [... method body ...]\n }\n }\n\n public void Method2(Object object) { \n using(Tracing tracer = new Tracing())\n {\n [... method body ...]\n }\n }\n }\n" }, { "answer_id": 25820, "author": "Jorge Córdoba", "author_id": 2695, "author_profile": "https://Stackoverflow.com/users/2695", "pm_score": 7, "selected": true, "text": "[Log()]\npublic void Method1(String name, Int32 value);\n" }, { "answer_id": 5345043, "author": "Jay", "author_id": 390720, "author_profile": "https://Stackoverflow.com/users/390720", "pm_score": 3, "selected": false, "text": "[WebMethod]\n public object InvokeMethod(string methodName, Dictionary<string, object> methodArguments)\n {\n try\n {\n string lowerMethodName = '_' + methodName.ToLowerInvariant();\n List<object> tempParams = new List<object>();\n foreach (MethodInfo methodInfo in serviceMethods.Where(methodInfo => methodInfo.Name.ToLowerInvariant() == lowerMethodName))\n {\n ParameterInfo[] parameters = methodInfo.GetParameters();\n if (parameters.Length != methodArguments.Count()) continue;\n else foreach (ParameterInfo parameter in parameters)\n {\n object argument = null;\n if (methodArguments.TryGetValue(parameter.Name, out argument))\n {\n if (parameter.ParameterType.IsValueType)\n {\n System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(parameter.ParameterType);\n argument = tc.ConvertFrom(argument);\n\n }\n tempParams.Insert(parameter.Position, argument);\n\n }\n else goto ContinueLoop;\n }\n\n foreach (object attribute in methodInfo.GetCustomAttributes(true))\n {\n if (attribute is YourAttributeClass)\n {\n RequiresPermissionAttribute attrib = attribute as YourAttributeClass;\n YourAttributeClass.YourMethod();//Mine throws an ex\n }\n }\n\n return methodInfo.Invoke(this, tempParams.ToArray());\n ContinueLoop:\n continue;\n }\n return null;\n }\n catch\n {\n throw;\n }\n }\n [WebMethod]\n public void BroadcastMessage(string Message)\n {\n //MessageBus.GetInstance().SendAll(\"<span class='system'>Web Service Broadcast: <b>\" + Message + \"</b></span>\");\n //return;\n InvokeMethod(\"BroadcastMessage\", new Dictionary<string, object>() { {\"Message\", Message} });\n }\n\n [RequiresPermission(\"editUser\")]\n void _BroadcastMessage(string Message)\n {\n MessageBus.GetInstance().SendAll(\"<span class='system'>Web Service Broadcast: <b>\" + Message + \"</b></span>\");\n return;\n }\n" }, { "answer_id": 5985377, "author": "Nitro", "author_id": 751485, "author_profile": "https://Stackoverflow.com/users/751485", "pm_score": 1, "selected": false, "text": "public class Wrapper\n{\n public static Exception TryCatch(Action actionToWrap, Action<Exception> exceptionHandler = null)\n {\n Exception retval = null;\n try\n {\n actionToWrap();\n }\n catch (Exception exception)\n {\n retval = exception;\n if (exceptionHandler != null)\n {\n exceptionHandler(retval);\n }\n }\n return retval;\n }\n\n public static Exception LogOnError(Action actionToWrap, string errorMessage = \"\", Action<Exception> afterExceptionHandled = null)\n {\n return Wrapper.TryCatch(actionToWrap, (e) =>\n {\n if (afterExceptionHandled != null)\n {\n afterExceptionHandled(e);\n }\n });\n }\n}\n var exception = Wrapper.LogOnError(() =>\n{\n MessageBox.Show(\"test\");\n throw new Exception(\"test\");\n}, \"Hata\");\n" }, { "answer_id": 31364170, "author": "irriss", "author_id": 684004, "author_profile": "https://Stackoverflow.com/users/684004", "pm_score": -1, "selected": false, "text": " public void MyMethod(int age, string name)\n {\n log.DebugTrace(() => age, () => name);\n\n //do your stuff\n }\n Method 'MyMethod' parameters age: 20 name: Mike\n //TODO: replace with 'nameof' in C# 6\n public static void DebugTrace(this ILog log, params Expression<Func<object>>[] args)\n {\n #if DEBUG\n\n var method = (new StackTrace()).GetFrame(1).GetMethod();\n\n var parameters = new List<string>();\n\n foreach(var arg in args)\n {\n MemberExpression memberExpression = null;\n if (arg.Body is MemberExpression)\n memberExpression = (MemberExpression)arg.Body;\n\n if (arg.Body is UnaryExpression && ((UnaryExpression)arg.Body).Operand is MemberExpression)\n memberExpression = (MemberExpression)((UnaryExpression)arg.Body).Operand;\n\n parameters.Add(memberExpression == null ? \"NA\" : memberExpression.Member.Name + \": \" + arg.Compile().DynamicInvoke().ToString());\n }\n\n log.Debug(string.Format(\"Method '{0}' parameters {1}\", method.Name, string.Join(\" \", parameters)));\n\n #endif\n }\n" }, { "answer_id": 32238417, "author": "Ibrahim ben Salah", "author_id": 1906989, "author_profile": "https://Stackoverflow.com/users/1906989", "pm_score": 2, "selected": false, "text": "interface ITraced {\n void Method1();\n void Method2()\n}\nclass Traced: ITraced { .... }\n class MethodLogInterceptor: RealProxy\n{\n public MethodLogInterceptor(Type interfaceType, object decorated) \n : base(interfaceType)\n {\n _decorated = decorated;\n }\n\n public override IMessage Invoke(IMessage msg)\n {\n var methodCall = msg as IMethodCallMessage;\n var methodInfo = methodCall.MethodBase;\n Console.WriteLine(\"Precall \" + methodInfo.Name);\n var result = methodInfo.Invoke(_decorated, methodCall.InArgs);\n Console.WriteLine(\"Postcall \" + methodInfo.Name);\n\n return new ReturnMessage(result, null, 0,\n methodCall.LogicalCallContext, methodCall);\n }\n}\n public class Caller \n {\n public static void Call() \n {\n ITraced traced = (ITraced)new MethodLogInterceptor(typeof(ITraced), new Traced()).GetTransparentProxy();\n traced.Method1();\n traced.Method2(); \n }\n }\n" }, { "answer_id": 41128743, "author": "plog17", "author_id": 1180998, "author_profile": "https://Stackoverflow.com/users/1180998", "pm_score": 4, "selected": false, "text": "public class RequireInterception : IContributeComponentModelConstruction\n{\n public void ProcessModel(IKernel kernel, ComponentModel model)\n {\n if (HasAMethodDecoratedByLoggingAttribute(model.Implementation))\n {\n model.Interceptors.Add(new InterceptorReference(typeof(ConsoleLoggingInterceptor)));\n model.Interceptors.Add(new InterceptorReference(typeof(NLogInterceptor)));\n }\n }\n\n private bool HasAMethodDecoratedByLoggingAttribute(Type implementation)\n {\n foreach (var memberInfo in implementation.GetMembers())\n {\n var attribute = memberInfo.GetCustomAttributes(typeof(LogAttribute)).FirstOrDefault() as LogAttribute;\n if (attribute != null)\n {\n return true;\n }\n }\n\n return false;\n }\n}\n container.Kernel.ComponentModelBuilder.AddContributor(new RequireInterception());\n public class ConsoleLoggingInterceptor : IInterceptor\n{\n public void Intercept(IInvocation invocation)\n {\n Console.Writeline(\"Log before executing\");\n invocation.Proceed();\n Console.Writeline(\"Log after executing\");\n }\n}\n public class Traced \n {\n [Log]\n public void Method1(String name, Int32 value) { }\n\n [Log]\n public void Method2(Object object) { }\n }\n" }, { "answer_id": 63240528, "author": "Javier Contreras", "author_id": 5508250, "author_profile": "https://Stackoverflow.com/users/5508250", "pm_score": 0, "selected": false, "text": "namespace SmartWay.Application.Behaviours\n{\n public class RequestLoggerBehaviour<TRequest, TResponse> : IPipelineBehavior<TRequest, TResponse>\n {\n private readonly ILogger _logger;\n private readonly IAppSession _appSession;\n private readonly ICreateLogGrain _createLogGrain;\n\n public RequestLoggerBehaviour(ILogger<TRequest> logger, IAppSession appSession, IClusterClient clusterClient)\n {\n _logger = logger;\n _appSession = appSession;\n _createLogGrain = clusterClient.GetGrain<ICreateLogGrain>(Guid.NewGuid());\n }\n\n public async Task<TResponse> Handle(TRequest request, CancellationToken cancellationToken, RequestHandlerDelegate<TResponse> next)\n {\n var name = typeof(TRequest).Name;\n _logger.LogInformation($\"SmartWay request started: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}\");\n\n var response = await next();\n\n _logger.LogInformation($\"SmartWay request ended: ClientId: {_appSession.ClientId} UserId: {_appSession.UserId} Operation: {name} Request: {request}\");\n\n return response;\n }\n }\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25803", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2800/" ]
25,807
<p>If I have Python code</p> <pre><code>class A(): pass class B(): pass class C(A, B): pass </code></pre> <p>and I have class <code>C</code>, is there a way to iterate through it's super classed (<code>A</code> and <code>B</code>)? Something like pseudocode:</p> <pre><code>&gt;&gt;&gt; magicGetSuperClasses(C) (&lt;type 'A'&gt;, &lt;type 'B'&gt;) </code></pre> <p>One solution seems to be <a href="http://docs.python.org/lib/module-inspect.html" rel="noreferrer">inspect module</a> and <code>getclasstree</code> function.</p> <pre><code>def magicGetSuperClasses(cls): return [o[0] for o in inspect.getclasstree([cls]) if type(o[0]) == type] </code></pre> <p>but is this a "Pythonian" way to achieve the goal?</p>
[ { "answer_id": 25815, "author": "John", "author_id": 2168, "author_profile": "https://Stackoverflow.com/users/2168", "pm_score": 6, "selected": true, "text": "C.__bases__ def magicGetSuperClasses(cls):\n return cls.__bases__\n cls.__bases__" }, { "answer_id": 35111, "author": "cdleary", "author_id": 3594, "author_profile": "https://Stackoverflow.com/users/3594", "pm_score": 4, "selected": false, "text": "cls.__bases__ class A: pass\nclass B: pass\nclass C(A, B): pass\n\nc = C() # Instance\n\nassert C.__bases__ == (A, B) # Works\nassert c.__class__.__bases__ == (A, B) # Works\n\ndef magicGetSuperClasses(clz):\n return tuple([base.__class__ for base in clz.__bases__])\n\nassert magicGetSuperClasses(C) == (A, B) # Fails\n tuple def get_base_metaclasses(cls):\n \"\"\"Returns the metaclass of all the base classes of cls.\"\"\"\n return tuple(base.__class__ for base in clz.__bases__)\n" }, { "answer_id": 552862, "author": "Torsten Marek", "author_id": 9567, "author_profile": "https://Stackoverflow.com/users/9567", "pm_score": 2, "selected": false, "text": ">>> class A: pass\n>>> class B: pass\n>>> class C(A, B): pass\n>>> import inspect\n>>> inspect.getmro(C)[1:]\n(<class __main__.A at 0x8c59f2c>, <class __main__.B at 0x8c59f5c>)\n C" }, { "answer_id": 553927, "author": "sinzi", "author_id": 62904, "author_profile": "https://Stackoverflow.com/users/62904", "pm_score": 2, "selected": false, "text": "C.__mro__ inspect" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2679/" ]
25,841
<p>How do you get the maximum number of bytes that can be passed to a <code>sendto(..)</code> call for a socket opened as a UDP port?</p>
[ { "answer_id": 25853, "author": "Kristof Provost", "author_id": 1466, "author_profile": "https://Stackoverflow.com/users/1466", "pm_score": 2, "selected": false, "text": "SO_MAX_MSG_SIZE" }, { "answer_id": 25976, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 3, "selected": false, "text": "getsockopt(sock, SOL_SOCKET, SO_SNDBUF, (int *)&optval, &optlen);\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25841", "https://Stackoverflow.com", "https://Stackoverflow.com/users/842/" ]
25,846
<p>I know that MAC OS X 10.5 comes with Apache installed but I would like to install the latest Apache without touching the OS Defaults incase it causes problems in the future with other udpates. So I have used the details located at: <a href="http://diymacserver.com/installing-apache/compiling-apache-on-leopard/" rel="nofollow noreferrer">http://diymacserver.com/installing-apache/compiling-apache-on-leopard/</a> But I'm unsure how to make this the 64 Bit version of Apache as it seems to still install the 32 bit version.</p> <p>Any help is appreciated</p> <p>Cheers</p>
[ { "answer_id": 25851, "author": "Espo", "author_id": 2257, "author_profile": "https://Stackoverflow.com/users/2257", "pm_score": 2, "selected": false, "text": "export CFLAGS=\"-arch x86_64\"\n" }, { "answer_id": 25854, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 0, "selected": false, "text": "maix64" }, { "answer_id": 26856, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 0, "selected": false, "text": "autoconf make" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25846", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2196/" ]
25,865
<p>My good friend, Wikipedia, <a href="http://en.wikipedia.org/wiki/Language_binding" rel="noreferrer">didn't give me a very good response</a> to that question. So:</p> <ul> <li>What are language bindings?</li> <li>How do they work?</li> </ul> <p>Specifically accessing functions from code written in language X of a library written in language Y.</p>
[ { "answer_id": 25868, "author": "Matt MacLean", "author_id": 22, "author_profile": "https://Stackoverflow.com/users/22", "pm_score": -1, "selected": false, "text": "<mx:TextInput id=\"LNameInput\"></mx:TextInput>\n...\n<mx:Label text=\"{LNameInput.text}\"></mx:Label>\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/416/" ]
25,871
<p>We created several custom web parts for SharePoint 2007. They work fine. However whenever they are loaded, we get an error in the event log saying:</p> <blockquote> <p>error initializing safe control - Assembly: ...</p> </blockquote> <p>The assembly actually loads fine. Additionally, it is correctly listed in the <code>web.config</code> and <code>GAC</code>.</p> <p>Any ideas about how to stop these (Phantom?) errors would be appreciated. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 25882, "author": "Daniel Pollard", "author_id": 2758, "author_profile": "https://Stackoverflow.com/users/2758", "pm_score": 2, "selected": false, "text": "<SafeControls>\n <SafeControl\n Assembly = \"Text\"\n Namespace = \"Text\"\n Safe = \"TRUE\" | \"FALSE\"\n TypeName = \"Text\"/>\n ...\n</SafeControls>\n" }, { "answer_id": 229923, "author": "Kwirk", "author_id": 21879, "author_profile": "https://Stackoverflow.com/users/21879", "pm_score": 2, "selected": false, "text": "<SafeControl Assembly=\"AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5bac12230d2e4a0a\" Namespace=\"AssemblyName\" **TypeName=\"AssemblyName\"** Safe=\"True\" />\n <SafeControl Assembly=\"AssemblyName, Version=1.0.0.0, Culture=neutral, PublicKeyToken=5bac12230d2e4a0a\" Namespace=\"AssemblyName\" **TypeName=\"*\"** Safe=\"True\" />\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25871", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
25,914
<p>I'm trying to setup CruiseControl.net webdashboard at the moment. So far it works nice, but I have a problem with the NAnt Build Timing Report.</p> <p>Firstly, my current <code>ccnet.config</code> file looks something like this:</p> <pre><code>&lt;project name="bla"&gt; ... &lt;prebuild&gt; &lt;nant .../&gt; &lt;/prebuild&gt; &lt;tasks&gt; &lt;nant .../&gt; &lt;/tasks&gt; &lt;publishers&gt; &lt;nant .../&gt; &lt;/publishers&gt; ... &lt;/project&gt; </code></pre> <p>As the build completes, NAnt timing report displays three duplicate summaries. Is there a way to fix this without changing the project structure? ­­­­­­­­­­­­­­­­­­­­­­­­­­­</p>
[ { "answer_id": 392610, "author": "cordis", "author_id": 1085, "author_profile": "https://Stackoverflow.com/users/1085", "pm_score": 2, "selected": false, "text": "<buildresults> <div id=\"NAntTimingReport\"> <xsl:variable name=\"buildresults\" select=\"//build/buildresults[1]\" />\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1085/" ]
25,952
<p>Back when I was at school, I remember tinkering with a Mac game where you programmed little robots in a sort of pseudo-assembler language which could then battle each other. They could move themselves around the arena, look for opponents in different directions, and fire some sort of weapon. Pretty basic stuff, but I remember it quite fondly, even if I can't remember the name.</p> <p>Are there any good modern day equivalents?</p>
[ { "answer_id": 25959, "author": "Pascal Paradis", "author_id": 1291, "author_profile": "https://Stackoverflow.com/users/1291", "pm_score": 5, "selected": false, "text": " public class MyFirstRobot extends Robot {\n public void run() {\n while (true) {\n ahead(100);\n turnGunRight(360);\n back(100);\n turnGunRight(360);\n }\n }\n\n public void onScannedRobot(ScannedRobotEvent e) {\n fire(1);\n }\n }\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/797/" ]
25,969
<p>I am trying to <code>INSERT INTO</code> a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the <code>SQL</code> engine of the day (<a href="http://en.wikipedia.org/wiki/MySQL" rel="noreferrer">MySQL</a>, <a href="http://en.wikipedia.org/wiki/Oracle_Database" rel="noreferrer">Oracle</a>, <a href="http://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="noreferrer">SQL Server</a>, <a href="http://en.wikipedia.org/wiki/IBM_Informix" rel="noreferrer">Informix</a>, and <a href="http://en.wikipedia.org/wiki/IBM_DB2" rel="noreferrer">DB2</a>).</p> <p>Is there a silver-bullet syntax coming from an SQL standard (for example, <a href="http://en.wikipedia.org/wiki/SQL-92" rel="noreferrer">SQL-92</a>) that would allow me to insert the values without worrying about the underlying database?</p>
[ { "answer_id": 25971, "author": "Claude Houle", "author_id": 244, "author_profile": "https://Stackoverflow.com/users/244", "pm_score": 12, "selected": true, "text": "INSERT INTO table1 ( column1 )\nSELECT col1\nFROM table2 \n" }, { "answer_id": 26080, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 10, "selected": false, "text": "INSERT INTO table1 ( column1, column2, someInt, someVarChar )\nSELECT table2.column1, table2.column2, 8, 'some string etc.'\nFROM table2\nWHERE table2.ID = 7;\n" }, { "answer_id": 145115, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 6, "selected": false, "text": "INSERT INTO target_table[(<column-list>)] SELECT ... FROM ...;\n [dbase[@server]:][owner.]table\n table\n\"owner\".table\ndbase:table\ndbase:owner.table\ndbase@server:table\ndbase@server:owner.table\n someone.table\n\"someone\".table\nSOMEONE.table\n CREATE TABLE someone.table ( ... )\n" }, { "answer_id": 10914430, "author": "SWATI BISWAS", "author_id": 1439766, "author_profile": "https://Stackoverflow.com/users/1439766", "pm_score": 4, "selected": false, "text": "INSERT INTO cesc_pf_stmt_ext_wrk( \n PF_EMP_CODE ,\n PF_DEPT_CODE ,\n PF_SEC_CODE ,\n PF_PROL_NO ,\n PF_FM_SEQ ,\n PF_SEQ_NO ,\n PF_SEP_TAG ,\n PF_SOURCE) \nSELECT\n PFl_EMP_CODE ,\n PFl_DEPT_CODE ,\n PFl_SEC ,\n PFl_PROL_NO ,\n PF_FM_SEQ ,\n PF_SEQ_NO ,\n PFl_SEP_TAG ,\n PF_SOURCE\n FROM cesc_pf_stmt_ext,\n cesc_pfl_emp_master\n WHERE pfl_sep_tag LIKE '0'\n AND pfl_emp_code=pf_emp_code(+);\n\nCOMMIT;\n" }, { "answer_id": 12916793, "author": "northben", "author_id": 1125584, "author_profile": "https://Stackoverflow.com/users/1125584", "pm_score": 5, "selected": false, "text": "INSERT INTO SELECT INSERT INTO table1\nSELECT col1, col2\nFROM table2\n col2 INSERT INTO table1\nSELECT col1\nFROM table2\n" }, { "answer_id": 12939439, "author": "Faiz", "author_id": 82961, "author_profile": "https://Stackoverflow.com/users/82961", "pm_score": 4, "selected": false, "text": "[ WITH <common_table_expression> [ ,...n ] ]\nINSERT \n{\n [ TOP ( expression ) [ PERCENT ] ] \n [ INTO ] \n { <object> | rowset_function_limited \n [ WITH ( <Table_Hint_Limited> [ ...n ] ) ]\n }\n {\n [ ( column_list ) ] \n [ <OUTPUT Clause> ]\n { VALUES ( { DEFAULT | NULL | expression } [ ,...n ] ) [ ,...n ] \n | derived_table <<<<------- Look here ------------------------\n | execute_statement <<<<------- Look here ------------------------\n | <dml_table_source> <<<<------- Look here ------------------------\n | DEFAULT VALUES \n }\n }\n}\n[;]\n" }, { "answer_id": 15573450, "author": "Grungondola", "author_id": 1164019, "author_profile": "https://Stackoverflow.com/users/1164019", "pm_score": 4, "selected": false, "text": "SELECT Table1.Column1, Table1.Column2, Table2.Column1, Table2.Column2, 'Some String' AS SomeString, 8 AS SomeInt\nINTO Table3\nFROM Table1 INNER JOIN Table2 ON Table1.Column1 = Table2.Column3\n" }, { "answer_id": 15741466, "author": "Santhosh", "author_id": 1970734, "author_profile": "https://Stackoverflow.com/users/1970734", "pm_score": 5, "selected": false, "text": "INSERT INTO TABLE_NAME\nSELECT COL1, COL2 ...\nFROM TABLE_YOU_NEED_TO_TAKE_FROM\n;\n DB2 SQL Server MY SQL PostgresQL" }, { "answer_id": 20095817, "author": "elijah7", "author_id": 3013029, "author_profile": "https://Stackoverflow.com/users/3013029", "pm_score": 4, "selected": false, "text": "insert into table1 select * from table2\n" }, { "answer_id": 21056554, "author": "kylieCatt", "author_id": 1318181, "author_profile": "https://Stackoverflow.com/users/1318181", "pm_score": 8, "selected": false, "text": "INSERT INSERT INTO column_1 ( val_1, val_from_other_table ) \nVALUES('val_1', (SELECT val_2 FROM table_2 WHERE val_2 = something))\n" }, { "answer_id": 21754160, "author": "RameezAli", "author_id": 3098077, "author_profile": "https://Stackoverflow.com/users/3098077", "pm_score": 4, "selected": false, "text": " Insert into Table1\n values(1,2,...)\n Insert into Table1(col2,col4)\n values(1,2)\n Insert into Table1 {Column sequence}\n Select * -- column sequence should be same.\n from #table2\n Insert into Table1 (Column1,Column2 ....Desired Column from Table1) \n Select Column1,Column2..desired column from #table2\n from #table2\n" }, { "answer_id": 22528220, "author": "Sarvar N", "author_id": 2490074, "author_profile": "https://Stackoverflow.com/users/2490074", "pm_score": 5, "selected": false, "text": "INSERT INTO table1(desc, id, email) \nSELECT \"Hello World\", 3, email FROM table2 WHERE ...\n" }, { "answer_id": 23715783, "author": "Pavel", "author_id": 3115912, "author_profile": "https://Stackoverflow.com/users/3115912", "pm_score": 3, "selected": false, "text": "select *\ninto tmp\nfrom orders\n set identity_insert tmp on\n\ninsert tmp \n([OrderID]\n ,[CustomerID]\n ,[EmployeeID]\n ,[OrderDate]\n ,[RequiredDate]\n ,[ShippedDate]\n ,[ShipVia]\n ,[Freight]\n ,[ShipName]\n ,[ShipAddress]\n ,[ShipCity]\n ,[ShipRegion]\n ,[ShipPostalCode]\n ,[ShipCountry] )\n select * from orders\n\nset identity_insert tmp off\n" }, { "answer_id": 29544903, "author": "Weslor", "author_id": 4140711, "author_profile": "https://Stackoverflow.com/users/4140711", "pm_score": 6, "selected": false, "text": "INSERT INTO TABLE1\n(COLUMN1, COLUMN2, COLUMN3, COLUMN4) \nVALUES (value1, value2, \n(SELECT COLUMN_TABLE2 \nFROM TABLE2\nWHERE COLUMN_TABLE2 like \"blabla\"),\nvalue4);\n" }, { "answer_id": 29769671, "author": "logan", "author_id": 975199, "author_profile": "https://Stackoverflow.com/users/975199", "pm_score": 5, "selected": false, "text": "VALUES INSERT SELECT INSERT INTO table1 ( column1 , 2, 3... )\nSELECT col1, 2, 3... FROM table2\n" }, { "answer_id": 30344570, "author": "Matt", "author_id": 2641576, "author_profile": "https://Stackoverflow.com/users/2641576", "pm_score": 4, "selected": false, "text": "INSERT INTO yourtable\nSELECT fielda, fieldb, fieldc\nFROM donortable;\n" }, { "answer_id": 36181014, "author": "Ciarán Bruen", "author_id": 177347, "author_profile": "https://Stackoverflow.com/users/177347", "pm_score": 4, "selected": false, "text": "insert into StudentCourseMap (StudentId, CourseId) \nSELECT Student.Id, Course.Id FROM Student, Course \nWHERE Student.Name = 'Paddy Murphy' AND Course.Name = 'Basket weaving for beginners'\n" }, { "answer_id": 37879263, "author": "Bharath theorare", "author_id": 2700841, "author_profile": "https://Stackoverflow.com/users/2700841", "pm_score": 4, "selected": false, "text": "SELECT * INTO SELECT *\nINTO Table2\nFROM Table1;\n" }, { "answer_id": 44449020, "author": "Sebastian", "author_id": 6248747, "author_profile": "https://Stackoverflow.com/users/6248747", "pm_score": 2, "selected": false, "text": "INSERT INTO `receiving_table`\n (id,\n first_name,\n last_name)\nVALUES \n (1002,'Charles','Babbage'),\n (1003,'George', 'Boole'),\n (1001,'Donald','Chamberlin'),\n (1004,'Alan','Turing'),\n (1005,'My','Widenius');\n" }, { "answer_id": 48771455, "author": "Gaurav", "author_id": 8527035, "author_profile": "https://Stackoverflow.com/users/8527035", "pm_score": 4, "selected": false, "text": "INSERT INTO FIRST_TABLE_NAME (COLUMN_NAME)\nSELECT COLUMN_NAME\nFROM ANOTHER_TABLE_NAME \nWHERE CONDITION;\n" }, { "answer_id": 50734798, "author": "Manish Vadher", "author_id": 6313628, "author_profile": "https://Stackoverflow.com/users/6313628", "pm_score": 3, "selected": false, "text": "INSERT INTO dbo.Users\n ( UserID ,\n Full_Name ,\n Login_Name ,\n Password\n )\n SELECT UserID ,\n Full_Name ,\n Login_Name ,\n Password\n FROM Users_Table\n (INNER JOIN / LEFT JOIN ...)\n (WHERE CONDITION...)\n (OTHER CLAUSE)\n" }, { "answer_id": 52476225, "author": "Dasikely", "author_id": 5721196, "author_profile": "https://Stackoverflow.com/users/5721196", "pm_score": 5, "selected": false, "text": "INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)\nVALUES (\n 'col1_value', \n 'col2_value',\n (SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),\n 'col3_value'\n);\n" }, { "answer_id": 55507700, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 6, "selected": false, "text": "INSERT INTO <table_name> (<field1>, <field2>, <field3>) \nVALUES ('DUMMY1', (SELECT <field> FROM <table_name> ),'DUMMY2');\n INSERT INTO <table_name> (<field1>, <field2>, <field3>) \nSELECT 'DUMMY1', <field>, 'DUMMY2' FROM <table_name>;\n" }, { "answer_id": 59300010, "author": "Miroslav Savel", "author_id": 10839776, "author_profile": "https://Stackoverflow.com/users/10839776", "pm_score": 0, "selected": false, "text": "INSERT INTO table (column1, column2) \nVALUES (value1, value2); \n" }, { "answer_id": 62135236, "author": "S.M.Fazle Rabbi", "author_id": 5803730, "author_profile": "https://Stackoverflow.com/users/5803730", "pm_score": 3, "selected": false, "text": "INSERT INTO CUSTOMER_INFO\n (SELECT CUSTOMER_NAME,\n MOBILE_NO,\n ADDRESS\n FROM OWNER_INFO cm)\n CUSTOMER_INFO || OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|--------- || --------------|-----------|--------- \n A | +1 | DC || B | +55 | RR \n CUSTOMER_INFO || OWNER_INFO\n----------------------------------------||-------------------------------------\nCUSTOMER_NAME | MOBILE_NO | ADDRESS || CUSTOMER_NAME | MOBILE_NO | ADDRESS \n--------------|-----------|--------- || --------------|-----------|--------- \n A | +1 | DC || B | +55 | RR\n B | +55 | RR ||\n" }, { "answer_id": 68365315, "author": "Serdin Çelik", "author_id": 7834559, "author_profile": "https://Stackoverflow.com/users/7834559", "pm_score": 2, "selected": false, "text": " select * INTO TableYedek From Table\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/244/" ]
25,975
<p>The Compact Framework doesn't support Assembly.GetEntryAssembly to determine the launching .exe. So is there another way to get the name of the executing .exe?</p> <p>EDIT: I found the answer on Peter Foot's blog: <a href="http://peterfoot.net/default.aspx" rel="nofollow noreferrer">http://peterfoot.net/default.aspx</a> Here is the code:</p> <pre><code>byte[] buffer = new byte[MAX_PATH * 2]; int chars = GetModuleFileName(IntPtr.Zero, buffer, MAX_PATH); if (chars &gt; 0) { string assemblyPath = System.Text.Encoding.Unicode.GetString(buffer, 0, chars * 2); } [DllImport("coredll.dll", SetLastError = true)] private static extern int GetModuleFileName(IntPtr hModule, byte[] lpFilename, int nSize); </code></pre>
[ { "answer_id": 117572, "author": "Martin Liesén", "author_id": 20715, "author_profile": "https://Stackoverflow.com/users/20715", "pm_score": 1, "selected": false, "text": "string exefile = Assembly.GetExecutingAssembly().GetName().CodeBase;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1382/" ]
25,977
<p>I would like to compare a screenshot of one application (could be a Web page) with a previously taken screenshot to determine whether the application is displaying itself correctly. I don't want an exact match comparison, because the aspect could be slightly different (in the case of a Web app, depending on the browser, some element could be at a slightly different location). It should give a measure of how similar are the screenshots.</p> <p>Is there a library / tool that already does that? How would you implement it?</p>
[ { "answer_id": 6801185, "author": "Shachar", "author_id": 859398, "author_profile": "https://Stackoverflow.com/users/859398", "pm_score": 4, "selected": false, "text": "O(n^2) C = sum(Pij*Qij)^2/(sum(Pij^2)*sum(Qij^2)) Pij=Qij i,j Qij = 1 Pij = 255 nxn n C=1/n^2" }, { "answer_id": 42481370, "author": "cpwah", "author_id": 7396273, "author_profile": "https://Stackoverflow.com/users/7396273", "pm_score": 1, "selected": false, "text": "L2" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2680/" ]
25,982
<p>Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?</p> <p>This is what I'm doing at the moment:</p> <pre><code>ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port)); </code></pre>
[ { "answer_id": 27450, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": true, "text": "//obtain another marshalbyref object of the type ISessionManager:\nISessionManager = MyServerObject.GetSessionManager();\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/25982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2373/" ]
26,002
<p>I want our team to develop against local instances of an Oracle database. With MS SQL, I can use SQL Express Edition. What are my options?</p>
[ { "answer_id": 38346, "author": "morais", "author_id": 2846, "author_profile": "https://Stackoverflow.com/users/2846", "pm_score": 3, "selected": false, "text": "ALTER SYSTEM SET PROCESSES=150 SCOPE=SPFILE;\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2676/" ]
26,007
<p>Is there an easy way to iterate over an associative array of this structure in PHP:</p> <p>The array <code>$searches</code> has a numbered index, with between 4 and 5 associative parts. So I not only need to iterate over <code>$searches[0]</code> through <code>$searches[n]</code>, but also <code>$searches[0]["part0"]</code> through <code>$searches[n]["partn"]</code>. The hard part is that different indexes have different numbers of parts (some might be missing one or two).</p> <p>Thoughts on doing this in a way that's nice, neat, and understandable?</p>
[ { "answer_id": 26013, "author": "Re0sless", "author_id": 2098, "author_profile": "https://Stackoverflow.com/users/2098", "pm_score": 3, "selected": false, "text": "/* foreach example 4: multi-dimensional arrays */\n$a = array();\n$a[0][0] = \"a\";\n$a[0][1] = \"b\";\n$a[1][0] = \"y\";\n$a[1][1] = \"z\";\n\nforeach ($a as $v1) {\n foreach ($v1 as $v2) {\n echo \"$v2\\n\";\n }\n}\n" }, { "answer_id": 26018, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "foreach foreach ($array as $i => $values) {\n print \"$i {\\n\";\n foreach ($values as $key => $value) {\n print \" $key => $value\\n\";\n }\n print \"}\\n\";\n}\n" }, { "answer_id": 26023, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "foreach($array as $id => $assoc)\n{\n foreach($assoc as $part => $data)\n {\n // code\n }\n}\n" }, { "answer_id": 177476, "author": "Milan Babuškov", "author_id": 14690, "author_profile": "https://Stackoverflow.com/users/14690", "pm_score": 4, "selected": false, "text": "function doSomething(&$complex_array)\n{\n foreach ($complex_array as $n => $v)\n {\n if (is_array($v))\n doSomething($v);\n else\n do whatever you want to do with a single node\n }\n}\n" }, { "answer_id": 2149106, "author": "Gordon", "author_id": 208809, "author_profile": "https://Stackoverflow.com/users/208809", "pm_score": 5, "selected": false, "text": "$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));\n\nforeach($iterator as $key=>$value) {\n echo $key.' -- '.$value.'<br />';\n}\n" }, { "answer_id": 12755040, "author": "mana", "author_id": 939723, "author_profile": "https://Stackoverflow.com/users/939723", "pm_score": 0, "selected": false, "text": "$n = array('customer' => array('address' => 'Kenmore street',\n 'phone' => '121223'),\n 'consumer' => 'wellington consumer',\n 'employee' => array('name' => array('fname' => 'finau', 'lname' => 'kaufusi'),\n 'age' => 32,\n 'nationality' => 'Tonga')\n );\n\n\n\niterator($n);\n\nfunction iterator($arr){\n\n foreach($arr as $key => $val){\n\n if(is_array($val))iterator($val);\n\n echo '<p>key: '.$key.' | value: '.$val.'</p>';\n\n //filter the $key and $val here and do what you want\n }\n\n}\n" } ]
2008/08/25
[ "https://Stackoverflow.com/questions/26007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]