qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
155,544
<p>I need to create a unique ID for a given location, and the location's ID must be sequential. So its basically like a primary key, except that it is also tied to the locationID. So 3 different locations will all have ID's like 1,2,3,4,5,...,n</p> <p>What is the best way to do this? I also need a safe way of getting the nextID for a given location, I'm guessing I can just put a transaction on the stored procedure that gets the next ID?</p>
[ { "answer_id": 155557, "author": "Chris Marasti-Georg", "author_id": 96, "author_profile": "https://Stackoverflow.com/users/96", "pm_score": 1, "selected": false, "text": "transaction {\n id = getId\n}\n\n... other processing\n\ntransaction {\n createRowWithNewId\n}\n" }, { "answer_id": 155592, "author": "David Smith", "author_id": 17201, "author_profile": "https://Stackoverflow.com/users/17201", "pm_score": 2, "selected": false, "text": "CREATE TABLE LocationID {\n Location varchar(32) PRIMARY KEY,\n NextID int DEFAULT(1)\n}\n ...\nUPDATE LocationID SET @nextID = NextID, NextID = NextID + 1 WHERE Location = @Location\n...\n" }, { "answer_id": 44853081, "author": "S3S", "author_id": 6167855, "author_profile": "https://Stackoverflow.com/users/6167855", "pm_score": 0, "selected": false, "text": "select\n locationID\n ,row_number() over (partition by locationID order by (select null)) as LocationPK\nFrom\n YourTable\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
155,560
<p>I want a function like GetCurrentThread which returns a TThread object of the current executing thread. I know there is a Win32 API call GetCurrentThread, but it returns the thread Id. If there is a possibility to get TThread object from that ID that's also fine.</p>
[ { "answer_id": 155773, "author": "Hugh Allen", "author_id": 15069, "author_profile": "https://Stackoverflow.com/users/15069", "pm_score": 5, "selected": false, "text": "if Windows.GetCurrentThreadId() = System.MainThreadID then\n// ...\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
155,566
<p>Please provide tips for effectively using git with svn. What are your "best practices"?</p>
[ { "answer_id": 155577, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "git svn rebase git svn dcommit dcommit svn dcommit" }, { "answer_id": 155643, "author": "andy", "author_id": 21482, "author_profile": "https://Stackoverflow.com/users/21482", "pm_score": 3, "selected": true, "text": "--prefix=svn/ --trunk --tags --branches clone init git svn fetch git svn fetch git svn rebase git svn rebase fetch git branch -r git reflog git svn dcommit" }, { "answer_id": 155647, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 1, "selected": false, "text": "git svn dcommit git rebase -i" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3146/" ]
155,584
<p>I need a way to allow each letter of a word to rotate through 3 different colors. I know of some not so clean ways I can do this with asp.NET, but I'm wondering if there might be a cleaner CSS/JavaScript solution that is more search engine friendly.</p> <p>The designer is including <a href="http://stlartworks.efficionconsulting.com/Portals/6/Skins/ArtWorks/img/ProgramsHeading.png" rel="noreferrer">a file like this</a> for each page. I'd rather not have to manually generate an image for every page as that makes it hard for the non-technical site editors to add pages and change page names.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i < words.length; i++) {\n print(\"<span class=\\\"color\" + c + \"\\\">\" + words[i] + \"</span> \");\n c = c + 1; if (c > 3) c = 1;\n}\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": ":first-letter" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "var message = \"The quick brown fox.\";\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\n\nfor (var i = 0; i < message.length; i++){\n document.write(\"<span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\">\" + message[i] + \"</span>\");\n}" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4318/" ]
155,586
<p>We use the DesignSurface and all that good IDesignerHost goodness in our own designer. The designed forms are then persisted in our own bespoke format and all that works great. WE also want to export the forms to a text-based format (which we've done as it isn't that difficult).</p> <p>However, we also want to import that text back into a document for the designer which involves getting the designer code back into a CodeCompileUnit. Unfortunately, the Parse method is not implemented (for, no doubt, good reasons). Is there an alternative? We don't want to use anything that wouldn't exist on a standard .NET installation (like .NET libraries installed with Visual Studio).</p> <p>My current idea is to compile the imported text and then instantiate the form and copy its properties and controls over to the design surface object, and just capture the new CodeCompileUnit, but I was hoping there was a better way. Thanks.</p> <hr> <p>UPDATE: I though some might be interested in our progress. So far, not so good. A brief overview of what I've discovered is that the Parse method was not implemented because it was deemed too difficult, open source parsers exist that do the work but they're not complete and therefore aren't guaranteed to work in all cases (NRefactory is one of those from the SharpDevelop project, I believe), and the copying of controls across from an instance to the designer isn't working as yet. I believe this is because although the controls are getting added to the form instance that the designer surface wraps, the designer surface is not aware of their inclusion. Our next attempt is to mimic cut/paste to see if that solves it. Obviously, this is a huge nasty workaround, but we need it working so we'll take the hit and keep an eye out for alternatives.</p>
[ { "answer_id": 155595, "author": "Brendan Kidwell", "author_id": 13958, "author_profile": "https://Stackoverflow.com/users/13958", "pm_score": 3, "selected": false, "text": "// This server-side code example is in JavaScript because that's\n// what I know best.\nvar words = split(message, \" \");\nvar c = 1;\nfor(var i = 0; i < words.length; i++) {\n print(\"<span class=\\\"color\" + c + \"\\\">\" + words[i] + \"</span> \");\n c = c + 1; if (c > 3) c = 1;\n}\n" }, { "answer_id": 157458, "author": "Paul D. Waite", "author_id": 20578, "author_profile": "https://Stackoverflow.com/users/20578", "pm_score": 3, "selected": false, "text": ":first-letter" }, { "answer_id": 163986, "author": "Peter Boughton", "author_id": 9360, "author_profile": "https://Stackoverflow.com/users/9360", "pm_score": 1, "selected": false, "text": "<img src=\"images/redblueyellow.cfm/programs.png\" alt=\"programs\"/>\n" }, { "answer_id": 164131, "author": "Ryan Rodemoyer", "author_id": 1444511, "author_profile": "https://Stackoverflow.com/users/1444511", "pm_score": 5, "selected": true, "text": "var message = \"The quick brown fox.\";\nvar colors = new Array(\"#ff0000\",\"#00ff00\",\"#0000ff\"); // red, green, blue\n\nfor (var i = 0; i < message.length; i++){\n document.write(\"<span style=\\\"color:\" + colors[(i % colors.length)] + \";\\\">\" + message[i] + \"</span>\");\n}" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23234/" ]
155,593
<p>Is there a way to determine the number of users that have active sessions in an ASP.NET application? I have an admin/tools page in a particular application, and I would like to display info regarding all open sessions, such as the number of sessions, and perhaps the requesting machines' addresses, or other credential information for each user.</p>
[ { "answer_id": 659879, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 4, "selected": false, "text": "void Application_Start(object sender, EventArgs e)\n{\n // Code that runs on application startup\n Application[\"OnlineUsers\"] = 0;\n}\n\nvoid Session_Start(object sender, EventArgs e)\n{\n // Code that runs when a new session is started\n Application.Lock();\n Application[\"OnlineUsers\"] = (int)Application[\"OnlineUsers\"] + 1;\n Application.UnLock();\n}\n\nvoid Session_End(object sender, EventArgs e)\n{\n // Code that runs when a session ends. \n // Note: The Session_End event is raised only when the sessionstate \n // mode is set to InProc in the Web.config file. \n // If session mode is set to StateServer or SQLServer, \n // the event is not raised.\n Application.Lock();\n Application[\"OnlineUsers\"] = (int)Application[\"OnlineUsers\"] - 1;\n Application.UnLock();\n}\n <system.web>\n <sessionState mode=\"InProc\" cookieless=\"false\" timeout=\"20\" />\n </system.web>\n Visitors online: <%= Application[\"OnlineUsers\"].ToString() %>\n" }, { "answer_id": 659909, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "Membership.GetNumberOfUsersOnline()\n" }, { "answer_id": 18960415, "author": "Vlad Bezden", "author_id": 30038, "author_profile": "https://Stackoverflow.com/users/30038", "pm_score": 0, "selected": false, "text": "void Main()\n{\n var pc = new PerformanceCounter(\"ASP.NET Applications\", \"Sessions Active\", \"__Total__\");\n\n Console.WriteLine(pc.NextValue());\n}\n void Main()\n{\n var pc = new PerformanceCounter(\"ASP.NET Applications\", \"Sessions Active\", \"__Total__\", \"ServerHostName.domain\");\n\n Console.WriteLine(pc.NextValue());\n}\n" }, { "answer_id": 51016352, "author": "Mojtaba Madadyar", "author_id": 5353426, "author_profile": "https://Stackoverflow.com/users/5353426", "pm_score": 2, "selected": false, "text": "SELECT Count(*) As Onlines FROM ASPStateTempSessions WHERE Expires>getutcdate()\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155593", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23886/" ]
155,609
<p>Can someone provide a simple explanation of <strong>methods</strong> vs. <strong>functions</strong> in OOP context?</p>
[ { "answer_id": 155648, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 3, "selected": false, "text": "class Example\n{\n public int data = 0; // Each instance of Example holds its internal data. This is a \"field\", or \"member variable\".\n\n public void UpdateData() // .. and manipulates it (This is a method by the way)\n {\n data = data + 1;\n }\n\n public void PrintData() // This is also a method\n {\n Console.WriteLine(data);\n }\n}\n\nclass Program\n{\n public static void Main()\n {\n Example exampleObject1 = new Example();\n Example exampleObject2 = new Example();\n\n exampleObject1.UpdateData();\n exampleObject1.UpdateData();\n\n exampleObject2.UpdateData();\n\n exampleObject1.PrintData(); // Prints \"2\"\n exampleObject2.PrintData(); // Prints \"1\"\n }\n}\n" }, { "answer_id": 155700, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 5, "selected": false, "text": "employe whatAreYouDoing.\n employee whatIsYourName\nemployee whatIsYourDepartmentsName\n // pseudo-code\nfunction addValues( int x, int y ) return x + y \n// call it \nresult = addValues( 8,8 )\nprint result // output is 16...\n int addValues( int x, int y ) \n{\n return x + y;\n}\n public static int addValues( int x, int y ) {\n return x + y;\n}\n public class Employee {\n\n Department department;\n String name;\n\n public String whatsYourName(){\n return this.name;\n }\n public String whatsYourDeparmentsName(){\n return this.department.name();\n }\n public String whatAreYouDoing(){\n return \"nothing\";\n } \n // Ignore the following, only set here for completness\n public Employee( String name ) {\n this.name = name;\n }\n\n}\n\n// Usage sample.\nEmployee employee = new Employee( \"John\" ); // Creates an employee called John\n\n// If I want to display what is this employee doing I could use its methods.\n// to know it.\nString name = employee.whatIsYourName():\nString doingWhat = employee.whatAreYouDoint();\n\n// Print the info to the console.\n\n System.out.printf(\"Employee %s is doing: %s\", name, doingWhat );\n\nOutput:\nEmployee John is doing nothing.\n" }, { "answer_id": 155722, "author": "Gustavo Rubio", "author_id": 14533, "author_profile": "https://Stackoverflow.com/users/14533", "pm_score": 7, "selected": false, "text": "class Door:\n def open(self):\n print 'hello stranger'\n\ndef knock_door():\n a_door = Door()\n Door.open(a_door)\n\nknock_door()\n" }, { "answer_id": 155767, "author": "Bradley Mazurek", "author_id": 10737, "author_profile": "https://Stackoverflow.com/users/10737", "pm_score": 4, "selected": false, "text": "f(x,y) = sin(x) + cos(y)\n Z.g(x) = sin(x) + cos(Z.y)\n" }, { "answer_id": 155827, "author": "Sam Stokes", "author_id": 20131, "author_profile": "https://Stackoverflow.com/users/20131", "pm_score": 3, "selected": false, "text": "# perfectly normal function\ndef hello(greetee):\n print \"Hello\", greetee\n\n# generalise a bit (still a function though)\ndef greet(greeting, greetee):\n print greeting, greetee\n\n# hide the greeting behind a layer of abstraction (still a function!)\ndef greet_with_greeter(greeter, greetee):\n print greeter.greeting, greetee\n\n# very simple class we can pass to greet_with_greeter\nclass Greeter(object):\n def __init__(self, greeting):\n self.greeting = greeting\n\n # while we're at it, here's a method that uses self.greeting...\n def greet(self, greetee):\n print self.greeting, greetee\n\n# save an object of class Greeter for later\nhello_greeter = Greeter(\"Hello\")\n\n# now all of the following print the same message\nhello(\"World\")\ngreet(\"Hello\", \"World\")\ngreet_with_greeter(hello_greeter, \"World\")\nhello_greeter.greet(\"World\")\n greet_with_greeter greet greet greet_with_greeter Greeter.greet(hello_greeter, \"World\")\n Greeter.greet2 = greet_with_greeter\nhello_greeter.greet2(\"World\")\n greet_with_greeter greet2 object.method(args) method(object, args)" }, { "answer_id": 10138680, "author": "Dirk Schumacher", "author_id": 845117, "author_profile": "https://Stackoverflow.com/users/845117", "pm_score": 3, "selected": false, "text": "new Employer().calculateSum( 8, 8 );\n" }, { "answer_id": 21594420, "author": "Abdullah Leghari", "author_id": 2091803, "author_profile": "https://Stackoverflow.com/users/2091803", "pm_score": 4, "selected": false, "text": "result = mySum(num1, num2);\n result = MyCalc.mySum(num1,num2);\n" }, { "answer_id": 34734498, "author": "Jaimin Patel", "author_id": 3396808, "author_profile": "https://Stackoverflow.com/users/3396808", "pm_score": 4, "selected": false, "text": "public void DoSomething() {} // method\npublic int DoSomethingAndReturnMeANumber(){} // function\n" }, { "answer_id": 46471318, "author": "Lahar Shah", "author_id": 5236174, "author_profile": "https://Stackoverflow.com/users/5236174", "pm_score": 2, "selected": false, "text": "test(20, 50); var x = myFunction(4, 3); // Function is called, return value will end up in x\n\nfunction myFunction(a, b) {\n return a * b; // Function returns the product of a and b\n}\n var test = something.test(); var message = \"Hello world!\";\nvar x = message.toUpperCase();\n//Output: HELLO WORLD!\n function person(firstName, lastName, age, eyeColor) {\n this.firstName = firstName; \n this.lastName = lastName;\n this.age = age;\n this.eyeColor = eyeColor;\n this.changeName = function (name) {\n this.lastName = name;\n };\n}\n\nsomething.changeName(\"SomeName\"); //This will change 'something' objject's name to 'SomeName'\n String.prototype.distance = function (char) {\n var index = this.indexOf(char);\n\n if (index === -1) {\n console.log(char + \" does not appear in \" + this);\n } else {\n console.log(char + \" is \" + (this.length - index) + \" characters from the end of the string!\");\n }\n};\n\nvar something = \"ThisIsSomeString\"\n\n// now use distance like this, run and check console log\n\nsomething.distance(\"m\");" }, { "answer_id": 47838166, "author": "Siraj Alam", "author_id": 5132337, "author_profile": "https://Stackoverflow.com/users/5132337", "pm_score": 2, "selected": false, "text": "constructor" }, { "answer_id": 58048948, "author": "Sapphire_Brick", "author_id": 11714860, "author_profile": "https://Stackoverflow.com/users/11714860", "pm_score": 1, "selected": false, "text": "# function\ndef putSqr(a)\n puts a ** 2\nend\n\n\nclass Math2\n # method\n def putSqr(a)\n puts a ** 2\n end\nend\n\n" }, { "answer_id": 59421186, "author": "yogendra saxena", "author_id": 6144937, "author_profile": "https://Stackoverflow.com/users/6144937", "pm_score": 2, "selected": false, "text": "\nfunction sum(){\n console.log(\"sum\")l\n}\n const obj = {\na:1,\nb:2,\nsum(){\n }\n}\n" }, { "answer_id": 60544808, "author": "raiks", "author_id": 412965, "author_profile": "https://Stackoverflow.com/users/412965", "pm_score": 2, "selected": false, "text": "class User {\n public string name; // I made it public intentionally\n\n // Each instance method takes a hidden reference to \"this\"\n public void printName(/*User & this*/) {\n cout << this.name << endl;\n }\n};\n public getName(User & user) {\n // No syntactic sugar, passing a reference explicitly\n cout << user.name << endl;\n}\n user->printName() getName(user) this" }, { "answer_id": 65513101, "author": "user1742529", "author_id": 1742529, "author_profile": "https://Stackoverflow.com/users/1742529", "pm_score": 2, "selected": false, "text": "method function static methods functions were rudiment of C in C++ and dropped in Java without this whith this" }, { "answer_id": 68731476, "author": "Md. Raju Ahmed", "author_id": 14135563, "author_profile": "https://Stackoverflow.com/users/14135563", "pm_score": 1, "selected": false, "text": "method function function method" }, { "answer_id": 70417274, "author": "Gabriel Staples", "author_id": 4561887, "author_profile": "https://Stackoverflow.com/users/4561887", "pm_score": 1, "selected": false, "text": "self" }, { "answer_id": 74326977, "author": "devsam247", "author_id": 6138547, "author_profile": "https://Stackoverflow.com/users/6138547", "pm_score": 0, "selected": false, "text": "//firstName() is the function\n\nfunction firstName(){\n cosole.log('John');\n}\n\nfirstName() //Invoked without any object\n\n const person = {\n firstName: \"John\",\n lastName: \"Doe\",\n id: 5566,\n};\n\n//person.name is the method\nperson.name = function() {\n return this.firstName + \" \" + this.lastName;\n};\n\ndocument.getElementById(\"demo\").innerHTML =\n\"My father is \" + person.name() //performs action on object; \n\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23973/" ]
155,610
<p>I have a trivial console application in .NET. It's just a test part of a larger application. I'd like to specify the "exit code" of my console application. How do I do this?</p>
[ { "answer_id": 155611, "author": "palehorse", "author_id": 312, "author_profile": "https://Stackoverflow.com/users/312", "pm_score": 5, "selected": false, "text": "int code = 2;\nEnvironment.Exit( code );\n" }, { "answer_id": 155613, "author": "albertein", "author_id": 23020, "author_profile": "https://Stackoverflow.com/users/23020", "pm_score": 5, "selected": false, "text": "System.Environment.ExitCode \n" }, { "answer_id": 155614, "author": "Esteban Araya", "author_id": 781, "author_profile": "https://Stackoverflow.com/users/781", "pm_score": 4, "selected": false, "text": "int Main(string[] args)\n{\n return 0; // Or exit code of your choice\n}\n" }, { "answer_id": 155619, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 10, "selected": true, "text": "Main Main int Environment.Exit(code) Environment.ExitCode = -1;" }, { "answer_id": 156134, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 8, "selected": false, "text": "enum ExitCode : int {\n Success = 0,\n InvalidLogin = 1,\n InvalidFilename = 2,\n UnknownError = 10\n}\n\nint Main(string[] args) {\n return (int)ExitCode.Success;\n}\n" }, { "answer_id": 8220145, "author": "David", "author_id": 342994, "author_profile": "https://Stackoverflow.com/users/342994", "pm_score": 3, "selected": false, "text": "enum ExitCodes : int\n{\n Success = 0,\n SignToolNotInPath = 1,\n AssemblyDirectoryBad = 2,\n PFXFilePathBad = 4,\n PasswordMissing = 8,\n SignFailed = 16,\n UnknownError = 32\n}\n" }, { "answer_id": 8230568, "author": "Aron Tsang", "author_id": 1060255, "author_profile": "https://Stackoverflow.com/users/1060255", "pm_score": 5, "selected": false, "text": "[Flags]\nenum ExitCodes : int\n{\n Success = 0,\n SignToolNotInPath = 1,\n AssemblyDirectoryBad = 2,\n PFXFilePathBad = 4,\n PasswordMissing = 8,\n SignFailed = 16,\n UnknownError = 32\n}\n (ExitCodes.SignFailed | ExitCodes.UnknownError)\n" }, { "answer_id": 12134636, "author": "Scott Munro", "author_id": 81595, "author_profile": "https://Stackoverflow.com/users/81595", "pm_score": 6, "selected": false, "text": "Main int void Integer Sub Main void Sub 0" }, { "answer_id": 38873670, "author": "Fred Mauroy", "author_id": 2988301, "author_profile": "https://Stackoverflow.com/users/2988301", "pm_score": 2, "selected": false, "text": "net helpmsg decimal_code\n net helpmsg 1\n Incorrect function\n" }, { "answer_id": 39986501, "author": "Vern DeHaven", "author_id": 4598767, "author_profile": "https://Stackoverflow.com/users/4598767", "pm_score": 3, "selected": false, "text": "Main main" }, { "answer_id": 54960642, "author": "Swastik Bhattacharyya", "author_id": 9818599, "author_profile": "https://Stackoverflow.com/users/9818599", "pm_score": 1, "selected": false, "text": "Environment.Exit(0);\n" }, { "answer_id": 64406231, "author": "isxaker", "author_id": 364429, "author_profile": "https://Stackoverflow.com/users/364429", "pm_score": -1, "selected": false, "text": "public static class ApplicationExitCodes\n{\n public static readonly int Failure = 1;\n public static readonly int Success = 0;\n}\n" }, { "answer_id": 68150110, "author": "Victor Petrov", "author_id": 15942876, "author_profile": "https://Stackoverflow.com/users/15942876", "pm_score": 0, "selected": false, "text": "int exitCode = 0;\nEnvironment.Exit(exitCode);\n throw new ArgumentException(\"Code 0, Environment Exit\");\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
155,615
<p>I understand that server-side validation is an absolute must to prevent malicious users (or simply users who choose to disable javascript) from bypassing client-side validation. But that's mainly to protect your application, not to provide value for those who are running browsers with javascript disabled. Is it reasonable to assume visitors have javascript enabled and simply have an unusable site for those who don't?</p>
[ { "answer_id": 157042, "author": "James", "author_id": 21677, "author_profile": "https://Stackoverflow.com/users/21677", "pm_score": 2, "selected": false, "text": "<noscript>" }, { "answer_id": 4316596, "author": "Master Morality", "author_id": 304299, "author_profile": "https://Stackoverflow.com/users/304299", "pm_score": 0, "selected": false, "text": "<noscript>" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
155,649
<p>What's the best way to add the coordinates of a circle to an array in JavaScript? So far I've only been able to do a half circle, but I need a formula that returns the whole circle to two different arrays: <code>xValues</code> and <code>yValues</code>. (I'm trying to get the coordinates so I can animate an object along a path.)</p> <p><strong>Here's what I have so far:</strong></p> <pre><code>circle: function(radius, steps, centerX, centerY){ var xValues = [centerX]; var yValues = [centerY]; for (var i = 1; i &lt; steps; i++) { xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps-Math.PI/2)); yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps-Math.PI/2)); } } </code></pre>
[ { "answer_id": 155653, "author": "shoosh", "author_id": 9611, "author_profile": "https://Stackoverflow.com/users/9611", "pm_score": 1, "selected": false, "text": "+ sin(...) - sin(...)" }, { "answer_id": 155662, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 2, "selected": false, "text": "function circle(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n var table=\"<tr><th>Step</th><th>X</th><th>Y</th></tr>\";\n var ctx = document.getElementById(\"canvas\").getContext(\"2d\");\n ctx.fillStyle = \"red\"\n ctx.beginPath();\n for (var i = 0; i <= steps; i++) {\n var radian = (2*Math.PI) * (i/steps);\n xValues[i+1] = centerX + radius * Math.cos(radian);\n yValues[i+1] = centerY + radius * Math.sin(radian);\n if(0==i){ctx.moveTo(xValues[i+1],yValues[i+1]);}else{ctx.lineTo(xValues[i+1],yValues[i+1]);}\n table += \"<tr><td>\" + i + \"</td><td>\" + xValues[i+1] + \"</td><td>\" + yValues[i+1] + \"</td></tr>\";\n }\n ctx.fill();\n return table;\n}\ndocument.body.innerHTML=\"<canvas id=\\\"canvas\\\" width=\\\"300\\\" height=\\\"300\\\"></canvas><table id=\\\"table\\\"/>\";\ndocument.getElementById(\"table\").innerHTML+=circle(150,15,150,150);\n" }, { "answer_id": 155678, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 0, "selected": false, "text": "circle: function(radius, steps, centerX, centerY){\n var xValues = [centerX];\n var yValues = [centerY];\n for (var i = 1; i < steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(Math.PI * i / steps*2-Math.PI/2));\n yValues[i] = (centerY + radius * Math.sin(Math.PI * i / steps*2-Math.PI/2));\n }\n}\n" }, { "answer_id": 155680, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 6, "selected": true, "text": "for (var i = 0; i < steps; i++) {\n xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));\n yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));\n}\n var xValues = [centerX]; var yValues = [centerY];" }, { "answer_id": 155688, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "Math.PI * i / steps\n 2*Math.PI * i / steps\n" } ]
2008/09/30
[ "https://Stackoverflow.com/questions/155649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
155,669
<p>I have Flex based consumer <a href="http://www.rollingrazor.com" rel="nofollow noreferrer">website</a> where I would like to change various look and feel type settings based on random and other criteria, and then track these through to what results in the most sales. </p> <p>For instance I might completely switch out the homepage, show different things depending upon where people come from. I might show or hide certain features, or change certain text. The things i might change are as yet undefined and will likely become quite complicated.</p> <p>I want to design the most flexible database schema but it must be efficient and easy to search. Currently I have a 'SiteVisit' table which contains information about each distinct visitor.</p> <p>I want to find the right balance between a single table with columns for each setting, and a table containing just key value pairs.</p> <p>Any suggestions? </p>
[ { "answer_id": 627904, "author": "David Pokluda", "author_id": 223, "author_profile": "https://Stackoverflow.com/users/223", "pm_score": 2, "selected": false, "text": "+----------------\n| User\n+----------------\n| UserId (PK)\n| ...\n+----------------\n +----------------\n| CustomProperty\n+----------------\n| PropId (PK)\n| UserId (FK)\n| Data of type memo/binary/...\n+----------------\n +----------------\n| HomePage\n+----------------\n| HomePageId (PK)\n| UserId (FK)\n| Value of type string\n+----------------\n +----------------\n| CustomPropertyEnum\n+----------------\n| PropertyId (PK)\n| Name of type string\n+----------------\n\n+----------------\n| CustomProperty\n+----------------\n| PropId (PK)\n| PropertyId (FK)\n| UserId (FK)\n| Value of type string\n+----------------\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155669", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16940/" ]
155,670
<p>I want to invert a 4x4 matrix. My numbers are stored in fixed-point format (1.15.16 to be exact).</p> <p>With floating-point arithmetic I usually just build the adjoint matrix and divide by the determinant (e.g. brute force the solution). That worked for me so far, but when dealing with fixed point numbers I get an unacceptable precision loss due to all of the multiplications used. </p> <p>Note: In fixed point arithmetic I always throw away some of the least significant bits of immediate results.</p> <p>So - What's the most numerical stable way to invert a matrix? I don't mind much about the performance, but simply going to floating-point would be to slow on my target architecture.</p>
[ { "answer_id": 155705, "author": "Adrian", "author_id": 23624, "author_profile": "https://Stackoverflow.com/users/23624", "pm_score": 4, "selected": false, "text": "[ux vx wx tx]\n[uy vy wy ty]\n[uz vz wz tz]\n[ 0 0 0 1]\n [ux uy uz -dot(u,t)]\n[vx vy vz -dot(v,t)]\n[wx wy wz -dot(w,t)]\n[ 0 0 0 1 ]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155670", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15955/" ]
155,681
<p>I have saved input from a textarea element to a TEXT column in MySQL. I'm using PHP to pull that data out of the database and want to display it in a p element while still showing the whitespace that the user entered (e.g. multiple spaces and newlines). I've tried a pre tag but it doesn't obey the width set in the containing div element. Other than creating a PHP function to convert spaces to &amp;nbsp and new lines to br tags, what are my options? I'd prefer a clean HTML/CSS solution, but any input is welcome! Thanks!</p>
[ { "answer_id": 155698, "author": "Vincent McNabb", "author_id": 16299, "author_profile": "https://Stackoverflow.com/users/16299", "pm_score": 5, "selected": true, "text": "pre pre {\n white-space: pre-wrap; /* css-3 */\n white-space: -moz-pre-wrap; /* Mozilla, since 1999 */\n white-space: -pre-wrap; /* Opera 4-6 */\n white-space: -o-pre-wrap; /* Opera 7 */\n word-wrap: break-word; /* Internet Explorer 5.5+ */\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155681", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23976/" ]
155,685
<p>I need to replace the contents of a node in an XElement hierarchy when the element name and all the attribute names and values match an input element. (If there is no match, the new element can be added.)</p> <p>For example, if my data looks like this:</p> <pre><code>&lt;root&gt; &lt;thing1 a1="a" a2="b"&gt;one&lt;/thing1&gt; &lt;thing2 a1="a" a2="a"&gt;two&lt;/thing2&gt; &lt;thing2 a1="a" a3="b"&gt;three&lt;/thing2&gt; &lt;thing2 a1="a"&gt;four&lt;/thing2&gt; &lt;thing2 a1="a" a2="b"&gt;five&lt;/thing2&gt; &lt;root&gt; </code></pre> <p>I want to find the last element when I call a method with this input:</p> <pre><code>&lt;thing2 a1="a" a2="b"&gt;new value&lt;/thing2&gt; </code></pre> <p>The method should have no hard-coded element or attribute names - it simply matches the input to the data.</p>
[ { "answer_id": 155787, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 4, "selected": true, "text": "public static void ReplaceOrAdd(this XElement source, XElement node)\n{\n var q = from x in source.Elements()\n where x.Name == node.Name\n && x.Attributes().All(a =>node.Attributes().Any(b =>a.Name==b.Name && a.Value==b.Value))\n select x;\n\n var n = q.LastOrDefault();\n\n if (n == null) source.Add(node);\n else n.ReplaceWith(node); \n}\n\nvar root = XElement.Parse(data);\nvar newElem =XElement.Parse(\"<thing2 a1=\\\"a\\\" a2=\\\"b\\\">new value</thing2>\");\n\nroot.ReplaceOrAdd(newElem);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14842/" ]
155,706
<p>I have been looking at a few options for enabling localization and internationalization of a dynamic php application. There appears to be a variety of tools available such as gettext and Yahoo's R3 and I am interested in hearing from both developers and translators about which tools are good to use and what functionality is important in easing the task of implementation and translation.</p>
[ { "answer_id": 426915, "author": "Gabriel Sosa", "author_id": 31039, "author_profile": "https://Stackoverflow.com/users/31039", "pm_score": 1, "selected": false, "text": "<?php\ninclude('lang/en.php');\ninclude('lang/en_us.php'); // this file overrides few keys from the last one.\n?>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11979/" ]
155,712
<p>Here's my problem - I have some code like this:</p> <pre><code>&lt;mx:Canvas width="300" height="300"&gt; &lt;mx:Button x="800" /&gt; &lt;/mx:Canvas&gt; </code></pre> <p>So the problem is that the Button inside the canvas has an x property way in excess of the Canvas's width - since it's a child of the Canvas, the Canvas masks it and creates some scrollbars for me to scroll over to the button.</p> <p>What I'd like is to display the button - 800 pixels to the left of the Canvas without the scrollbars while still leaving the button as a child of the Canvas. How do I do that?</p>
[ { "answer_id": 155817, "author": "Paul Mignard", "author_id": 3435, "author_profile": "https://Stackoverflow.com/users/3435", "pm_score": 4, "selected": true, "text": "<mx:Canvas width=\"300\" height=\"300\" clipContent=\"false\" >\n <mx:Button x=\"800\" />\n</mx:Canvas>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3435/" ]
155,719
<p>Internationalizing web apps always seems to be a chore. No matter how much you plan ahead for pluggable languages, there's always issues with encoding, funky phrasing that doesn't fit your templates, and other problems.</p> <p>I think it would be useful to get the SO community's input for a set of things that programmers should look out for when deciding to internationalize their web apps.</p>
[ { "answer_id": 157833, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "Click here\n [~~ Çļïčк н∑ѓё ~~ タウ ~~]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14032/" ]
155,721
<p>Please post a working source code example (or link) of how to search string in another process memory and getting offset of match if found. The similar way its done in game cheating utils which search for values in game memory using ReadProcessMemory.</p>
[ { "answer_id": 157833, "author": "Kip", "author_id": 18511, "author_profile": "https://Stackoverflow.com/users/18511", "pm_score": 4, "selected": false, "text": "Click here\n [~~ Çļïčк н∑ѓё ~~ タウ ~~]\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21582/" ]
155,739
<p>I have a requirement to implement an "Unsaved Changes" prompt in an ASP .Net application. If a user modifies controls on a web form, and attempts to navigate away before saving, a prompt should appear warning them that they have unsaved changes, and give them the option to cancel and stay on the current page. The prompt should not display if the user hasn't touched any of the controls.</p> <p>Ideally I'd like to implement this in JavaScript, but before I go down the path of rolling my own code, are there any existing frameworks or recommended design patterns for achieving this? Ideally I'd like something that can easily be reused across multiple pages with minimal changes.</p>
[ { "answer_id": 155760, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 4, "selected": false, "text": "<script language=\"javascript\">\n var isDirty = false;\n\n function setDirty() {\n isDirty = true;\n }\n\n function checkSave() {\n var sSave;\n if (isDirty == true) {\n sSave = window.confirm(\"You have some changes that have not been saved. Click OK to save now or CANCEL to continue without saving.\");\n if (sSave == true) {\n document.getElementById('__EVENTTARGET').value = 'btnSubmit';\n document.getElementById('__EVENTARGUMENT').value = 'Click'; \n window.document.formName.submit();\n } else {\n return true;\n }\n }\n }\n</script>\n<body class=\"StandardBody\" onunload=\"checkSave()\">\n btnSubmit.Attributes.Add(\"onclick\", \"isDirty = 0;\");\nbtnCancel.Attributes.Add(\"onclick\", \"isDirty = 0;\");\ntxtName.Attributes.Add(\"onchange\", \"setDirty();\");\ntxtAddress.Attributes.Add(\"onchange\", \"setDirty();\");\n//etc..\n" }, { "answer_id": 155776, "author": "Adam Davis", "author_id": 2915, "author_profile": "https://Stackoverflow.com/users/2915", "pm_score": 0, "selected": false, "text": "<body onLoad=\"lookForChanges()\" onBeforeUnload=\"return warnOfUnsavedChanges()\">\n<form>\n<select name=a multiple>\n <option value=1>1\n <option value=2>2\n <option value=3>3\n</select>\n<input name=b value=123>\n<input type=submit>\n</form>\n\n<script>\nvar changed = 0;\nfunction recordChange() {\n changed = 1;\n}\nfunction recordChangeIfChangeKey(myevent) {\n if (myevent.which && !myevent.ctrlKey && !myevent.ctrlKey)\n recordChange(myevent);\n}\nfunction ignoreChange() {\n changed = 0;\n}\nfunction lookForChanges() {\n var origfunc;\n for (i = 0; i < document.forms.length; i++) {\n for (j = 0; j < document.forms[i].elements.length; j++) {\n var formField=document.forms[i].elements[j];\n var formFieldType=formField.type.toLowerCase();\n if (formFieldType == 'checkbox' || formFieldType == 'radio') {\n addHandler(formField, 'click', recordChange);\n } else if (formFieldType == 'text' || formFieldType == 'textarea') {\n if (formField.attachEvent) {\n addHandler(formField, 'keypress', recordChange);\n } else {\n addHandler(formField, 'keypress', recordChangeIfChangeKey);\n }\n } else if (formFieldType == 'select-multiple' || formFieldType == 'select-one') {\n addHandler(formField, 'change', recordChange);\n }\n }\n addHandler(document.forms[i], 'submit', ignoreChange);\n }\n}\nfunction warnOfUnsavedChanges() {\n if (changed) {\n if (\"event\" in window) //ie\n event.returnValue = 'You have unsaved changes on this page, which will be discarded if you leave now. Click \"Cancel\" in order to save them first.';\n else //netscape\n return false;\n }\n}\nfunction addHandler(target, eventName, handler) {\n if (target.attachEvent) {\n target.attachEvent('on'+eventName, handler);\n } else {\n target.addEventListener(eventName, handler, false);\n }\n}\n</script>\n" }, { "answer_id": 155812, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 6, "selected": false, "text": "/**\n * Determines if a form is dirty by comparing the current value of each element\n * with its default value.\n *\n * @param {Form} form the form to be checked.\n * @return {Boolean} <code>true</code> if the form is dirty, <code>false</code>\n * otherwise.\n */\nfunction formIsDirty(form) {\n for (var i = 0; i < form.elements.length; i++) {\n var element = form.elements[i];\n var type = element.type;\n if (type == \"checkbox\" || type == \"radio\") {\n if (element.checked != element.defaultChecked) {\n return true;\n }\n }\n else if (type == \"hidden\" || type == \"password\" ||\n type == \"text\" || type == \"textarea\") {\n if (element.value != element.defaultValue) {\n return true;\n }\n }\n else if (type == \"select-one\" || type == \"select-multiple\") {\n for (var j = 0; j < element.options.length; j++) {\n if (element.options[j].selected !=\n element.options[j].defaultSelected) {\n return true;\n }\n }\n }\n }\n return false;\n}\n window.onbeforeunload = function(e) {\n e = e || window.event; \n if (formIsDirty(document.forms[\"someForm\"])) {\n // For IE and Firefox\n if (e) {\n e.returnValue = \"You have unsaved changes.\";\n }\n // For Safari\n return \"You have unsaved changes.\";\n }\n};\n var confirmExitIfModified = (function() {\n function formIsDirty(form) {\n // ...as above\n }\n\n return function(form, message) {\n window.onbeforeunload = function(e) {\n e = e || window.event;\n if (formIsDirty(document.forms[form])) {\n // For IE and Firefox\n if (e) {\n e.returnValue = message;\n }\n // For Safari\n return message;\n }\n };\n };\n})();\n\nconfirmExitIfModified(\"someForm\", \"You have unsaved changes.\");\n beforeunload LIBRARY_OF_CHOICE" }, { "answer_id": 155841, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 8, "selected": true, "text": "var _isDirty = false;\n$(\"input[type='text']\").change(function(){\n _isDirty = true;\n});\n// replicate for other input types and selects\n onunload onbeforeunload $(':input').change(function () {\n $(\":input\")" }, { "answer_id": 160493, "author": "mde", "author_id": 22440, "author_profile": "https://Stackoverflow.com/users/22440", "pm_score": 1, "selected": false, "text": "fleegix.form.diff fleegix.form.toObject fleegix.form.diff" }, { "answer_id": 906026, "author": "reto", "author_id": 102200, "author_profile": "https://Stackoverflow.com/users/102200", "pm_score": 3, "selected": false, "text": "/* use this function to announce changes from your own scripts/event handlers.\n * Example: onClick=\"makeDirty($(this).up('form'));\"\n */\nfunction makeDirty(form) {\n form.fire(\"form:changed\");\n}\n\nfunction handleChange(form, event) {\n makeDirty(form);\n}\n\n/* generic form observer, ensure that form:changed is being fired whenever\n * a field is being changed in that particular for\n */\nfunction setupFormChangeObserver(form) {\n var handler = handleChange.curry(form);\n\n form.getElements().each(function (element) {\n element.observe(\"change\", handler);\n });\n}\n\n/* installs a form protector to a form marked with class 'protectForm' */\nfunction setupProtectForm() {\n var form = $$(\"form.protectForm\").first();\n\n /* abort if no form */\n if (!form) return;\n\n setupFormChangeObserver(form);\n\n var dirty = false;\n form.observe(\"form:changed\", function(event) {\n dirty = true;\n });\n\n /* submitting the form makes the form clean again */\n form.observe(\"submit\", function(event) {\n dirty = false;\n });\n\n /* unfortunatly a propper event handler doesn't appear to work with IE and Safari */\n window.onbeforeunload = function(event) {\n if (dirty) {\n return \"There are unsaved changes, they will be lost if you leave now.\";\n }\n };\n}\n\ndocument.observe(\"dom:loaded\", setupProtectForm);\n" }, { "answer_id": 1744350, "author": "Colin Houghton", "author_id": 212333, "author_profile": "https://Stackoverflow.com/users/212333", "pm_score": 3, "selected": false, "text": "dataChanged = 0; // global variable flags unsaved changes \n\nfunction bindForChange(){ \n $('input,checkbox,textarea,radio,select').bind('change',function(event) { dataChanged = 1})\n $(':reset,:submit').bind('click',function(event) { dataChanged = 0 })\n}\n\n\nfunction askConfirm(){ \n if (dataChanged){ \n return \"You have some unsaved changes. Press OK to continue without saving.\" \n }\n}\n\nwindow.onbeforeunload = askConfirm;\nwindow.onload = bindForChange;\n" }, { "answer_id": 9272081, "author": "PeterX", "author_id": 845584, "author_profile": "https://Stackoverflow.com/users/845584", "pm_score": 2, "selected": false, "text": "<script type=\"text/javascript\">\n var _isDirty = false;\n $(document).ready(function () { \n\n // Set exclude CSS class on radio-button list elements\n $('table.srSearch input:radio').addClass(\"srSearch\");\n\n $(\"input[type='text'],input[type='radio'],select,textarea\").not(\".srSearch\").change(function () {\n _isDirty = true;\n });\n });\n\n $(window).bind('beforeunload', function () {\n if (_isDirty) {\n return 'You have unsaved changes.';\n }\n }); \n" }, { "answer_id": 19525717, "author": "skibulk", "author_id": 1017480, "author_profile": "https://Stackoverflow.com/users/1017480", "pm_score": 3, "selected": false, "text": "function formUnloadPrompt(formSelector) {\n var formA = $(formSelector).serialize(), formB, formSubmit = false;\n\n // Detect Form Submit\n $(formSelector).submit( function(){\n formSubmit = true;\n });\n\n // Handle Form Unload \n window.onbeforeunload = function(){\n if (formSubmit) return;\n formB = $(formSelector).serialize();\n if (formA != formB) return \"Your changes have not been saved.\";\n };\n}\n\n$(function(){\n formUnloadPrompt('form');\n});\n" }, { "answer_id": 24624798, "author": "Ankit", "author_id": 2353426, "author_profile": "https://Stackoverflow.com/users/2353426", "pm_score": 2, "selected": false, "text": " var unsaved = false;\n $(\":input\").change(function () { \n unsaved = true;\n });\n\n function unloadPage() { \n if (unsaved) { \n alert(\"You have unsaved changes on this page. Do you want to leave this page and discard your changes or stay on this page?\");\n }\n } \n" }, { "answer_id": 27482349, "author": "v.babak", "author_id": 2400627, "author_profile": "https://Stackoverflow.com/users/2400627", "pm_score": 2, "selected": false, "text": "var formInitVal = $('#formId').serialize(); // detect form init value after form is displayed\n\n// check for form changes\nif ($('#formId').serialize() != formInitVal) {\n // show confirmation alert\n}\n" }, { "answer_id": 30374461, "author": "MhdSyrwan", "author_id": 923894, "author_profile": "https://Stackoverflow.com/users/923894", "pm_score": 3, "selected": false, "text": "$(document).ready(function() {\n $('form :input').change(function() {\n $(this).closest('form').addClass('form-dirty');\n });\n\n $(window).bind('beforeunload', function() {\n if($('form:not(.ignore-changes).form-dirty').length > 0) {\n return 'You have unsaved changes, are you sure you want to discard them?';\n }\n });\n\n $('form').bind('submit',function() {\n $(this).closest('form').removeClass('form-dirty');\n return true;\n });\n});\n" }, { "answer_id": 31238701, "author": "Krupall", "author_id": 2003093, "author_profile": "https://Stackoverflow.com/users/2003093", "pm_score": 0, "selected": false, "text": " $(document).ready(function () {\n $(window).bind(\"load\", function () { \n $(\"input, select\").change(function () {});\n });\n});\n" }, { "answer_id": 64871468, "author": "darryn.ten", "author_id": 618172, "author_profile": "https://Stackoverflow.com/users/618172", "pm_score": 1, "selected": false, "text": "let dirty = false\ndocument.querySelectorAll('form').forEach(e => e.onchange = () => dirty = true)\n" }, { "answer_id": 73828635, "author": "dfcii", "author_id": 15461890, "author_profile": "https://Stackoverflow.com/users/15461890", "pm_score": 0, "selected": false, "text": "dataChanged = 0; // global variable flags unsaved changes\n\nfunction bindForChange() {\n $(\"input,checkbox,textarea,radio,select\").bind(\"change\", function (_event) {\n dataChanged = 1;\n });\n $(\":reset,:submit\").bind(\"click\", function (_event) {\n dataChanged = 0;\n });\n}\n\nfunction askConfirm() {\n if (dataChanged) {\n var message =\n \"You have some unsaved changes. Press OK to continue without saving.\";\n return message;\n }\n}\n\nwindow.onbeforeunload = askConfirm;\n\nwindow.onload = bindForChange;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/637/" ]
155,740
<p>I am working on an application that will sport a web-based point of sale interface.</p> <p>The point of sale PC (I am not sure as of now whether it will run on Linux or Windows) must have a fiscal printer attached to it, but like any web app, it is the server which processes all stuff. Both server and PoS machines are on the same LAN.</p> <p>I must send the sale data in real time, and via the fiscal printer which uses the serial port, so printing a PDF or even a web page is not an option.</p> <p>I've been told I could have a little app listening on web services on the client, which in turn talks to the printer instead of the server or the browser, but don't have a clue how to do it. Also, I'll most likely need to listen to any printer feedback (coupon number, for instance, which is generated by the printer) and hand it back to the server.</p> <p>Any ideas?</p>
[ { "answer_id": 155782, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 1, "selected": false, "text": "DocFlavor flavor = DocFlavor.INPUT_STREAM.POSTSCRIPT;\nPrintRequestAttributeSet aset = new HashPrintRequestHashAttributeSet();\naset.add(MediaSizeName.ISO_A4);\nPrintService[] pservices =\n PrintServiceLookup.lookupPrintServices(flavor, aset);\nif (pservices.length > 0) {\n DocPrintJob pj = pservices[0].createPrintJob();\n // InputStreamDoc is an implementation of the Doc interface //\n Doc doc = new InputStreamDoc(\"test.ps\", flavor);\n try {\n pj.print(doc, aset);\n } catch (PrintException e) { \n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22116/" ]
155,751
<p>In my php web app, suppose I want to go the extra mile and in addition to going gang-busters and being anal-retentive about sanitizing my inputs, I also want to ensure that no JavaScript is being output in strings I am inserting into html templates. </p> <p>Is there a standard way to make sure I don't put JavaScript in the generated html content?</p>
[ { "answer_id": 155768, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 0, "selected": false, "text": "<img src=\"${path}\"> ${path} http://p0wned.com/jpg.jpg\" /><script src=\"p0wned.com/js.js\"/> #from http://www.perlmonks.org/?node_id=161281\nsub untag {\n local $_ = $_[0] || $_;\n# ALGORITHM:\n# find < ,\n# comment <!-- ... -->,\n# or comment <? ... ?> ,\n# or one of the start tags which require correspond\n# end tag plus all to end tag\n# or if \\s or =\"\n# then skip to next \"\n# else [^>]\n# >\n s{\n < # open tag\n (?: # open group (A)\n (!--) | # comment (1) or\n (\\?) | # another comment (2) or\n (?i: # open group (B) for /i\n ( TITLE | # one of start tags\n SCRIPT | # for which\n APPLET | # must be skipped\n OBJECT | # all content\n STYLE # to correspond\n ) # end tag (3)\n ) | # close group (B), or\n ([!/A-Za-z]) # one of these chars, remember in (4)\n ) # close group (A)\n (?(4) # if previous case is (4)\n (?: # open group (C)\n (?! # and next is not : (D)\n [\\s=] # \\s or \"=\"\n [\"`'] # with open quotes\n ) # close (D)\n [^>] | # and not close tag or\n [\\s=] # \\s or \"=\" with\n `[^`]*` | # something in quotes ` or\n [\\s=] # \\s or \"=\" with\n '[^']*' | # something in quotes ' or\n [\\s=] # \\s or \"=\" with\n \"[^\"]*\" # something in quotes \"\n )* # repeat (C) 0 or more times\n | # else (if previous case is not (4))\n .*? # minimum of any chars\n ) # end if previous char is (4)\n (?(1) # if comment (1)\n (?<=--) # wait for \"--\"\n ) # end if comment (1)\n (?(2) # if another comment (2)\n (?<=\\?) # wait for \"?\"\n ) # end if another comment (2)\n (?(3) # if one of tags-containers (3)\n </ # wait for end\n (?i:\\3) # of this tag\n (?:\\s[^>]*)? # skip junk to \">\"\n ) # end if (3)\n > # tag closed\n }{}gsx; # STRIP THIS TAG\n return $_ ? $_ : \"\";\n}\n" }, { "answer_id": 158346, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "$output = strip_tags($input);\n $output = strip_tags($input, '<code><em><strong>');\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
155,780
<p>What is SafeHandle? how does it differ from IntPtr? When should I use one? What are its advantages?</p>
[ { "answer_id": 27453342, "author": "Mike Ness", "author_id": 4286419, "author_profile": "https://Stackoverflow.com/users/4286419", "pm_score": 4, "selected": false, "text": "static class Examples\n{\n static void Example1_SafeUserToken()\n {\n const string user = \"SomeLocalUser\";\n const string domain = null;\n const string password = \"ExamplePassword\";\n NativeMethods.SafeTokenHandle userToken;\n WindowsIdentity identity;\n\n NativeMethods.LogonUser(user, domain, password, NativeMethods.LogonType.LOGON32_LOGON_INTERACTIVE, NativeMethods.LogonProvider.LOGON32_PROVIDER_DEFAULT, out userToken);\n\n using (userToken)\n {\n // get a WindowsIdentity object for the user\n // WindowsIdentity will duplicate the token, so it is safe to free the original token after this is called\n identity = userToken.GetWindowsIdentity();\n }\n\n // impersonate the user\n using (identity)\n using (WindowsImpersonationContext impersonationContext = identity.Impersonate())\n {\n Console.WriteLine(\"I'm running as {0}!\", Thread.CurrentPrincipal.Identity.Name);\n }\n }\n\n static void Example2_SafeLocalAllocWStrArray()\n {\n const string commandLine = \"/example /command\";\n int argc;\n string[] args;\n\n using (NativeMethods.SafeLocalAllocWStrArray argv = NativeMethods.CommandLineToArgvW(commandLine, out argc))\n {\n // CommandLineToArgvW returns NULL on failure; since SafeLocalAllocWStrArray inherits from\n // SafeHandleZeroOrMinusOneIsInvalid, it will see this value as invalid\n // if that happens, throw an exception containing the last Win32 error that occurred\n if (argv.IsInvalid)\n {\n int lastError = Marshal.GetHRForLastWin32Error();\n throw new Win32Exception(lastError, \"An error occurred when calling CommandLineToArgvW.\");\n }\n\n // the one unsafe aspect of this is that the developer calling this function must be trusted to\n // pass in an array of length argc or specify the length of the copy as the value of argc\n // if the developer does not do this, the array may end up containing some garbage or an\n // AccessViolationException could be thrown\n args = new string[argc];\n argv.CopyTo(args);\n }\n\n for (int i = 0; i < args.Length; ++i)\n {\n Console.WriteLine(\"Argument {0}: {1}\", i, args[i]);\n }\n }\n}\n\n/// <summary>\n/// P/Invoke methods and helper classes used by this example.\n/// </summary>\ninternal static class NativeMethods\n{\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa378184(v=vs.85).aspx\n [DllImport(\"advapi32.dll\", SetLastError = true, CharSet = CharSet.Unicode)]\n public static extern bool LogonUser(string lpszUsername, string lpszDomain, string lpszPassword, LogonType dwLogonType, LogonProvider dwLogonProvider, out SafeTokenHandle phToken);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/ms724211(v=vs.85).aspx\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern bool CloseHandle(IntPtr handle);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/bb776391(v=vs.85).aspx\n [DllImport(\"shell32.dll\", CharSet = CharSet.Unicode, SetLastError = true)]\n public static extern SafeLocalAllocWStrArray CommandLineToArgvW(string lpCmdLine, out int pNumArgs);\n\n // documentation: http://msdn.microsoft.com/en-us/library/windows/desktop/aa366730(v=vs.85).aspx\n [DllImport(\"kernel32.dll\", SetLastError = true)]\n public static extern IntPtr LocalFree(IntPtr hLocal);\n\n /// <summary>\n /// Wraps a handle to a user token.\n /// </summary>\n public class SafeTokenHandle : SafeHandleZeroOrMinusOneIsInvalid\n {\n /// <summary>\n /// Creates a new SafeTokenHandle. This constructor should only be called by P/Invoke.\n /// </summary>\n private SafeTokenHandle()\n : base(true)\n {\n }\n\n /// <summary>\n /// Creates a new SafeTokenHandle to wrap the specified user token.\n /// </summary>\n /// <param name=\"arrayPointer\">The user token to wrap.</param>\n /// <param name=\"ownHandle\"><c>true</c> to close the token when this object is disposed or finalized,\n /// <c>false</c> otherwise.</param>\n public SafeTokenHandle(IntPtr handle, bool ownHandle)\n : base(ownHandle)\n {\n this.SetHandle(handle);\n }\n\n /// <summary>\n /// Provides a <see cref=\"WindowsIdentity\" /> object created from this user token. Depending\n /// on the type of token, this can be used to impersonate the user. The WindowsIdentity\n /// class will duplicate the token, so it is safe to use the WindowsIdentity object created by\n /// this method after disposing this object.\n /// </summary>\n /// <returns>a <see cref=\"WindowsIdentity\" /> for the user that this token represents.</returns>\n /// <exception cref=\"InvalidOperationException\">This object does not contain a valid handle.</exception>\n /// <exception cref=\"ObjectDisposedException\">This object has been disposed and its token has\n /// been released.</exception>\n public WindowsIdentity GetWindowsIdentity()\n {\n if (this.IsClosed)\n {\n throw new ObjectDisposedException(\"The user token has been released.\");\n }\n if (this.IsInvalid)\n {\n throw new InvalidOperationException(\"The user token is invalid.\");\n }\n\n return new WindowsIdentity(this.handle);\n }\n\n /// <summary>\n /// Calls <see cref=\"NativeMethods.CloseHandle\" /> to release this user token.\n /// </summary>\n /// <returns><c>true</c> if the function succeeds, <c>false otherwise</c>. To get extended\n /// error information, call <see cref=\"Marshal.GetLastWin32Error\"/>.</returns>\n protected override bool ReleaseHandle()\n {\n return NativeMethods.CloseHandle(this.handle);\n }\n }\n\n /// <summary>\n /// A wrapper around a pointer to an array of Unicode strings (LPWSTR*) using a contiguous block of\n /// memory that can be freed by a single call to LocalFree.\n /// </summary>\n public sealed class SafeLocalAllocWStrArray : SafeLocalAllocArray<string>\n {\n /// <summary>\n /// Creates a new SafeLocalAllocWStrArray. This constructor should only be called by P/Invoke.\n /// </summary>\n private SafeLocalAllocWStrArray()\n : base(true)\n {\n }\n\n /// <summary>\n /// Creates a new SafeLocalallocWStrArray to wrap the specified array.\n /// </summary>\n /// <param name=\"handle\">The pointer to the unmanaged array to wrap.</param>\n /// <param name=\"ownHandle\"><c>true</c> to release the array when this object\n /// is disposed or finalized, <c>false</c> otherwise.</param>\n public SafeLocalAllocWStrArray(IntPtr handle, bool ownHandle)\n : base(ownHandle)\n {\n this.SetHandle(handle);\n }\n\n /// <summary>\n /// Returns the Unicode string referred to by an unmanaged pointer in the wrapped array.\n /// </summary>\n /// <param name=\"index\">The index of the value to retrieve.</param>\n /// <returns>the value at the position specified by <paramref name=\"index\" /> as a string.</returns>\n protected override string GetArrayValue(int index)\n {\n return Marshal.PtrToStringUni(Marshal.ReadIntPtr(this.handle + IntPtr.Size * index));\n }\n }\n\n // This class is similar to the built-in SafeBuffer class. Major differences are:\n // 1. This class is less safe because it does not implicitly know the length of the array it wraps.\n // 2. The array is read-only.\n // 3. The type parameter is not limited to value types.\n /// <summary>\n /// Wraps a pointer to an unmanaged array of objects that can be freed by calling LocalFree.\n /// </summary>\n /// <typeparam name=\"T\">The type of the objects in the array.</typeparam>\n public abstract class SafeLocalAllocArray<T> : SafeHandleZeroOrMinusOneIsInvalid\n {\n /// <summary>\n /// Creates a new SafeLocalArray which specifies that the array should be freed when this\n /// object is disposed or finalized.\n /// <param name=\"ownsHandle\"><c>true</c> to reliably release the handle during the finalization phase;\n /// <c>false</c> to prevent reliable release (not recommended).</param>\n /// </summary>\n protected SafeLocalAllocArray(bool ownsHandle)\n : base(ownsHandle)\n {\n }\n\n /// <summary>\n /// Converts the unmanaged object referred to by <paramref name=\"valuePointer\" /> to a managed object\n /// of type T.\n /// </summary>\n /// <param name=\"index\">The index of the value to retrieve.</param>\n /// <returns>the value at the position specified by <paramref name=\"index\" /> as a managed object of\n /// type T.</returns>\n protected abstract T GetArrayValue(int index);\n\n // \n /// <summary>\n /// Frees the wrapped array by calling LocalFree.\n /// </summary>\n /// <returns><c>true</c> if the call to LocalFree succeeds, <c>false</c> if the call fails.</returns>\n protected override bool ReleaseHandle()\n {\n return (NativeMethods.LocalFree(this.handle) == IntPtr.Zero);\n }\n\n /// <summary>\n /// Copies the unmanaged array to the specified managed array.\n /// \n /// It is important that the length of <paramref name=\"array\"/> be less than or equal to the length of\n /// the unmanaged array wrapped by this object. If it is not, at best garbage will be read and at worst\n /// an exception of type <see cref=\"AccessViolationException\" /> will be thrown.\n /// </summary>\n /// <param name=\"array\">The managed array to copy the unmanaged values to.</param>\n /// <exception cref=\"ObjectDisposedException\">The unmanaged array wrapped by this object has been\n /// freed.</exception>\n /// <exception cref=\"InvalidOperationException\">The pointer to the unmanaged array wrapped by this object\n /// is invalid.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"array\"/> is null.</exception>\n public void CopyTo(T[] array)\n {\n if (array == null)\n {\n throw new ArgumentNullException(\"array\");\n }\n\n this.CopyTo(array, 0, array.Length);\n }\n\n /// <summary>\n /// Copies the unmanaged array to the specified managed array.\n /// \n /// It is important that <paramref name=\"length\" /> be less than or equal to the length of\n /// the array wrapped by this object. If it is not, at best garbage will be read and at worst\n /// an exception of type <see cref=\"AccessViolationException\" /> will be thrown.\n /// </summary>\n /// <param name=\"array\">The managed array to copy the unmanaged values to.</param>\n /// <param name=\"index\">The index to start at when copying to <paramref name=\"array\" />.</param>\n /// <param name=\"length\">The number of items to copy to <paramref name=\"array\" /></param>\n /// <exception cref=\"ObjectDisposedException\">The unmanaged array wrapped by this object has been\n /// freed.</exception>\n /// <exception cref=\"InvalidOperationException\">The pointer to the unmanaged array wrapped by this object\n /// is invalid.</exception>\n /// <exception cref=\"ArgumentNullException\"><paramref name=\"array\"/> is null.</exception>\n /// <exception cref=\"ArgumentOutOfRangeException\"><paramref name=\"index\"/> is less than zero.-or- \n /// <paramref name=\"index\" /> is greater than the length of <paramref name=\"array\"/>.-or-\n /// <paramref name=\"length\"/> is less than zero.</exception>\n /// <exception cref=\"ArgumentException\">The sum of <paramref name=\"index\" /> and <paramref name=\"length\" />\n /// is greater than the length of <paramref name=\"array\" />.</exception>\n public void CopyTo(T[] array, int index, int length)\n {\n if (this.IsClosed)\n {\n throw new ObjectDisposedException(this.ToString());\n }\n if (this.IsInvalid)\n {\n throw new InvalidOperationException(\"This object's buffer is invalid.\");\n }\n if (array == null)\n {\n throw new ArgumentNullException(\"array\");\n }\n if (index < 0 || array.Length < index)\n {\n throw new ArgumentOutOfRangeException(\"index\", \"index must be a nonnegative integer that is less than array's length.\");\n }\n if (length < 0)\n {\n throw new ArgumentOutOfRangeException(\"length\", \"length must be a nonnegative integer.\");\n }\n if (array.Length < index + length)\n {\n throw new ArgumentException(\"length\", \"length is greater than the number of elements from index to the end of array.\");\n }\n\n for (int i = 0; i < length; ++i)\n {\n array[index + i] = this.GetArrayValue(i);\n }\n }\n }\n\n /// <summary>\n /// The type of logon operation to perform.\n /// </summary>\n internal enum LogonType : uint\n {\n LOGON32_LOGON_BATCH = 1,\n LOGON32_LOGON_INTERACTIVE = 2,\n LOGON32_LOGON_NETWORK = 3,\n LOGON32_LOGON_NETWORK_CLEARTEXT = 4,\n LOGON32_LOGON_NEW_CREDENTIALS = 5,\n LOGON32_LOGON_SERVICE = 6,\n LOGON32_LOGON_UNLOCK = 7\n }\n\n /// <summary>\n /// The logon provider to use.\n /// </summary>\n internal enum LogonProvider : uint\n {\n LOGON32_PROVIDER_DEFAULT = 0,\n LOGON32_PROVIDER_WINNT50 = 1,\n LOGON32_PROVIDER_WINNT40 = 2\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155780", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7418/" ]
155,792
<p>I'm working on a method that accepts an expression tree as a parameter, along with a type (or instance) of a class.</p> <p>The basic idea is that this method will add certain things to a collection that will be used for validation.</p> <pre><code>public interface ITestInterface { //Specify stuff here. } private static void DoSomething&lt;T&gt;(Expression&lt;Func&lt;T, object&gt;&gt; expression, params IMyInterface[] rule) { // Stuff is done here. } </code></pre> <p>The method is called as follows:</p> <pre><code>class TestClass { public int MyProperty { get; set; } } class OtherTestClass : ITestInterface { // Blah Blah Blah. } static void Main(string[] args) { DoSomething&lt;TestClass&gt;(t =&gt; t.MyProperty, new OtherTestClass()); } </code></pre> <p>I'm doing it this way because I'd like for the property names that are passed in to be strong typed.</p> <p>A couple of things I'm struggling with..</p> <ol> <li>Within DoSomething, I'd like to get a <code>PropertyInfo</code> type (from the body passed in) of T and add it to a collection along with rule[]. Currently, I'm thinking about using expression.Body and removing [propertyname] from &quot;Convert.([propertyname])&quot; and using reflection to get what I need. This seems cumbersome and wrong. Is there a better way?</li> <li>Is this a specific pattern I'm using?</li> <li>Lastly, any suggestions or clarifications as to my misunderstanding of what I'm doing are appreciated and / or resources or good info on C# expression trees are appreciated as well.</li> </ol> <p>Thanks!</p> <p>Ian</p> <h1>Edit:</h1> <p>An example of what <code>expression.Body.ToString()</code> returns within the DoSomething method is a string that contains &quot;Convert(t.MyProperty)&quot; if called from the example above.</p> <p>I do need it to be strongly typed, so it will not compile if I change a property name.</p> <p>Thanks for the suggestions!</p>
[ { "answer_id": 155845, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 2, "selected": false, "text": "DoSomething(\"MyProperty\", new OtherClass());\n [DoSomething(typeof(OtherClass), typeof(OtherClass2))]\npublic int MyProperty\n{\n get;\n set;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10853/" ]
155,797
<p>ADO.NET has the notorious DataRow class which you cannot instantiate using new. This is a problem now that I find a need to mock it using Rhino Mocks. </p> <p>Does anyone have any ideas how I could get around this problem?</p>
[ { "answer_id": 155813, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 5, "selected": true, "text": "SetupResult.For(someMockClass.GetDataRow(input)).Return(GetReturnRow());\n\npublic DataRow GetReturnRow()\n{\n DataTable table = new DataTable(\"FakeTable\");\n DataRow row = table.NewRow();\n row.value1 = \"someValue\";\n row.value2 = 234;\n\n return row;\n}\n" }, { "answer_id": 69921036, "author": "Alison Rodrigues", "author_id": 14218167, "author_profile": "https://Stackoverflow.com/users/14218167", "pm_score": 0, "selected": false, "text": " private DataRow GetReturnRow()\n {\n DataTable table = new DataTable(\"FakeTable\");\n table.Columns.Add(\"column_name\");\n\n DataRow row = table.NewRow();\n row[\"column_name\"] = your_value;\n\n return row;\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5056/" ]
155,810
<p>When you double click on a class (in 'solution explorer')... if that class happens to be an .asmx.cs webservice... then you get this...</p> <blockquote> <p>To add components to your class, drag them from the Toolbox and use the Properties window to set their properties. To create methods and events for your class, click here to switch to code view.</p> </blockquote> <p>...it's a 'visual design surface' for webservices.</p> <p>(Who actually uses that surface to write webservices?)</p> <p>So what I want to know, how do I configure visual studio to never show me that design view?</p> <p>Or at least, to show me the code view by default?</p>
[ { "answer_id": 3196200, "author": "Bob Sidie", "author_id": 385681, "author_profile": "https://Stackoverflow.com/users/385681", "pm_score": 1, "selected": false, "text": "<System.ComponentModel.DesignerCategory(\"\")>\n" }, { "answer_id": 4246213, "author": "Steinar Herland", "author_id": 111182, "author_profile": "https://Stackoverflow.com/users/111182", "pm_score": 2, "selected": false, "text": "[System.ComponentModel.DesignerCategory(\"Code\")] \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/49/" ]
155,829
<p>I am getting this error but only very occasionally. 99.9% of the time it works fine:</p> <p>Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.</p> <p>Does anyone have any idea on what the cause could be? I only use that datatable for viewing and not updating so is it possible to easily turn off all constraints somehow?</p>
[ { "answer_id": 38776066, "author": "Nick", "author_id": 1931573, "author_profile": "https://Stackoverflow.com/users/1931573", "pm_score": 0, "selected": false, "text": "varchar(100) InitClass()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155829", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10102/" ]
155,848
<p>I need to create an access (mdb) database without using the ADOX interop assembly. </p> <p>How can this be done?</p>
[ { "answer_id": 155851, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 5, "selected": true, "text": "if (!File.Exists(DB_FILENAME))\n{\n var cnnStr = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\" + DB_FILENAME;\n\n // Use a late bound COM object to create a new catalog. This is so we avoid an interop assembly. \n var catType = Type.GetTypeFromProgID(\"ADOX.Catalog\");\n object o = Activator.CreateInstance(catType);\n catType.InvokeMember(\"Create\", BindingFlags.InvokeMethod, null, o, new object[] {cnnStr});\n\n OleDbConnection cnn = new OleDbConnection(cnnStr);\n cnn.Open();\n var cmd = cnn.CreateCommand();\n cmd.CommandText = \"CREATE TABLE VideoPosition (filename TEXT , pos LONG)\";\n cmd.ExecuteNonQuery();\n\n}\n" }, { "answer_id": 155880, "author": "Aaron Fischer", "author_id": 5618, "author_profile": "https://Stackoverflow.com/users/5618", "pm_score": 0, "selected": false, "text": "Provider=Microsoft.ACE.OLEDB.12.0;Data\nSource=C:\\myFolder\\myAccess2007file.accdb;Persist\nSecurity Info=False;\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155848", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
155,852
<p>I have created a non-visual component in C# which is designed as a placeholder for meta-data on a form.<br> The component has a property which is a collection of custom objects, this object is marked as Serializable and implements the GetObjectData for serilizing and public constuctor for deserilizing.<br></p> <p>In the resx file for the form it will generate binary data for storing the collection, however any time I make a change to the serialized class I get designer errors and need to delete the data manually out of the resx file and then recreate this data.</p> <p>I have tried changing the constuctor to have a try / catch block around each property in the class</p> <pre><code>try { _Name = info.GetString("Name"); } catch (SerializationException) { this._Name = string.Empty; } </code></pre> <p>but it still crashes. The last error I got was that I had to implement IConvertible.<br></p> <p>I would prefer to use xml serialization because I can at least see it, is this possible for use by the designer?<br></p> <p>Is there a way to make the serialization more stable and less resistant to changes?</p> <p>Edit:<br> More information...better description maybe<br> I have a class which inherits from Component, it has one property which is a collection of Rules. The RulesCollection seems to have to be marked as Serializable, otherwise it does not retain its members.<br> </p> <p>The Rules class is also a Component with the attribute DesignTimeVisible(false) to stop it showing in the component tray, this clas is not marked Serializable.<br></p> <p>Having the collection marked as Serializable generates binary data in the resx file (not ideal) and the IDE reports that the Rules class is not Serializable.<br></p> <p>I think this issue is getting beyond a simple question. So I will probably close it shortly.<br> If anyone has any links to something similar that would help a lot.</p>
[ { "answer_id": 199307, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 3, "selected": true, "text": "private List<Rule> _Rules;\n[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]\npublic List<Rule> Rules\n{\n get { return _Rules; }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155852", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
155,864
<p>I have a controller with an action method as follows:</p> <pre><code>public class InventoryController : Controller { public ActionResult ViewStockNext(int firstItem) { // Do some stuff } } </code></pre> <p>And when I run it I get an error stating:</p> <blockquote> <p>The parameters dictionary does not contain a valid value of type 'System.Int32' for parameter 'firstItem'. To make a parameter optional its type should either be a reference type or a Nullable type.</p> </blockquote> <p>I had it working at one point and I decided to try the function without parameters. Finding out that the controller was not persistant I put the parameter back in, now it refuses to recognise the parameter when I call the method.</p> <p>I'm using this url syntax to call the action:</p> <pre><code>http://localhost:2316/Inventory/ViewStockNext/11 </code></pre> <p>Any ideas why I would get this error and what I need to do to fix it? </p> <p>I've tried adding another method that takes an integer to the class it it also fails with the same reason. I've tried adding one that takes a string, and the string is set to null. I've tried adding one without parameters and that works fine, but of course it won't suit my needs.</p>
[ { "answer_id": 155895, "author": "Jarrett Meyer", "author_id": 5834, "author_profile": "https://Stackoverflow.com/users/5834", "pm_score": 8, "selected": true, "text": "{controller}/{action}/{firstItem} {controller}/{action}/{id} global.asax.cs id routes.MapRoute(\n \"Inventory\",\n \"Inventory/{action}/{firstItem}\",\n new { controller = \"Inventory\", action = \"ListAll\", firstItem = \"\" }\n);\n" }, { "answer_id": 155902, "author": "Matt Mitchell", "author_id": 364, "author_profile": "https://Stackoverflow.com/users/364", "pm_score": 4, "selected": false, "text": "routes.MapRoute(\n \"ViewStockNext\", // Route name\n \"Inventory/ViewStockNext/{firstItem}\", // URL with parameters\n new { controller = \"Inventory\", action = \"ViewStockNext\" } // Parameter defaults\n );\n" }, { "answer_id": 355023, "author": "RAL", "author_id": 44844, "author_profile": "https://Stackoverflow.com/users/44844", "pm_score": 0, "selected": false, "text": "public ActionResult ViewNextItem(string id)...\n" }, { "answer_id": 477963, "author": "Oskar Duveborn", "author_id": 49293, "author_profile": "https://Stackoverflow.com/users/49293", "pm_score": 3, "selected": false, "text": "public ActionResult ViewNextItem(int? id) id" }, { "answer_id": 1551423, "author": "Felix", "author_id": 184509, "author_profile": "https://Stackoverflow.com/users/184509", "pm_score": 1, "selected": false, "text": "Html.ActionLink(\"Next page\", \"Index\", routeData)\n public ViewResult Index(int? page)\n" }, { "answer_id": 8363659, "author": "Bart Calixto", "author_id": 826568, "author_profile": "https://Stackoverflow.com/users/826568", "pm_score": 6, "selected": false, "text": "http://localhost:2316/Inventory/ViewStockNext?firstItem=11\n @Url.Action(\"ViewStockNext\", \"Inventory\", new {firstItem=11});\n" }, { "answer_id": 8923030, "author": "Aristoteles", "author_id": 247949, "author_profile": "https://Stackoverflow.com/users/247949", "pm_score": 0, "selected": false, "text": "routes.MapRoute (\"Default\", \"{controller}/{action}/{id}\", \n new { controller = \"Home\", action = \"Index\", id = \"\" });\n routes.MapRoute (\"Default\", \"{controller}/{action}\", \n new { controller = \"Home\", action = \"Index\" });\n" }, { "answer_id": 12394449, "author": "Matthew Nichols", "author_id": 165031, "author_profile": "https://Stackoverflow.com/users/165031", "pm_score": 3, "selected": false, "text": "[ParameterAlias(\"firstItem\", \"id\", Order = 3)]\npublic ActionResult ViewStockNext(int firstItem)\n{\n // Do some stuff\n}\n" }, { "answer_id": 32272225, "author": "Yar", "author_id": 2517730, "author_profile": "https://Stackoverflow.com/users/2517730", "pm_score": 4, "selected": false, "text": "public class InventoryController : Controller\n{\n [Route(\"whatever/{firstItem}\")]\n public ActionResult ViewStockNext(int firstItem)\n {\n int yourNewVariable = firstItem;\n // ...\n }\n}\n" }, { "answer_id": 43215223, "author": "Sasha Yakobchuk", "author_id": 4691615, "author_profile": "https://Stackoverflow.com/users/4691615", "pm_score": 3, "selected": false, "text": "<a asp-controller=\"Home\" asp-action=\"SetLanguage\" asp-route-yourparam1=\"@item.Value\">@item.Text</a>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155864", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11908/" ]
155,869
<p>The Interwebs are no help on this one. We're encoding data in ColdFusion using <code>serializeJSON</code> and trying to decode it in PHP using <code>json_decode</code>. Most of the time, this is working fine, but in some cases, <code>json_decode</code> returns <code>NULL</code>. We've looked for the obvious culprits, but <code>serializeJSON</code> seems to be formatting things as expected. What else could be the problem?</p> <p>UPDATE: A couple of people (wisely) asked me to post the output that is causing the problem. I would, except we just discovered that the result set is all of our data (listing information for 2300+ rental properties for a total of 565,135 ASCII characters)! That could be a problem, though I didn't see anything in the PHP docs about a max size for the string. What would be the limiting factor there? RAM?</p> <p>UPDATE II: It looks like the problem was that a couple of our users had copied and pasted Microsoft Word text with "smart" quotes. Those pesky users...</p>
[ { "answer_id": 171521, "author": "Ates Goral", "author_id": 23501, "author_profile": "https://Stackoverflow.com/users/23501", "pm_score": 2, "selected": false, "text": "json_decode <meta http-equiv=\"Content-Type\" content=\"text/html;charset=utf-8\"/>\n json_decode" }, { "answer_id": 1184143, "author": "Stewart Robinson", "author_id": 47424, "author_profile": "https://Stackoverflow.com/users/47424", "pm_score": 1, "selected": false, "text": "$string = preg_replace('/[\\x00-\\x1F\\x80-\\xFF]/', '', $string);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11577/" ]
155,884
<p>What is a realistic use for VB.Net's MyClass keyword?</p> <p>I understand the <a href="http://msdn.microsoft.com/en-us/library/b3b35kyk.aspx" rel="noreferrer">technical usage of MyClass</a>; I don't understand the practical usage of it in the real world.</p> <p>Using MyClass only makes sense if you have any virtual (overridable) members. But it also means that you want to ignore the overridden implementations in sub classes. It appears to be self-contradicting.</p> <p>I can think of some contrived examples, but they are simply bad design rather than practical usage.</p>
[ { "answer_id": 169787, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": -1, "selected": false, "text": "Public Sub New(ByVal accountKey As Integer)\n MyClass.New(accountKey, Nothing)\nEnd Sub\n\nPublic Sub New(ByVal accountKey As Integer, ByVal accountName As String)\n MyClass.New(accountKey, accountName, Nothing)\nEnd Sub\n\nPublic Sub New(ByVal accountKey As Integer, ByVal accountName As String, ByVal accountNumber As String)\n m_AccountKey = accountKey\n m_AccountName = accountName\n m_AccountNumber = accountNumber\nEnd Sub\n" }, { "answer_id": 19080080, "author": "Allen Clark Copeland Jr", "author_id": 557100, "author_profile": "https://Stackoverflow.com/users/557100", "pm_score": 3, "selected": true, "text": "MyClass callvirt call callvirt MyClass call MyBase MyBase MyClass MyClass" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155884", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6375/" ]
155,891
<p>Can't seem to rename an existing Verity collection in ColdFusion without deleting, recreating, and rebuilding the collection. Problem is, I have some very large collections I'd rather not have to delete and rebuild from scratch. Any one have a handy trick for this conundrum?</p>
[ { "answer_id": 158948, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 2, "selected": false, "text": "<cfcollection action=\"map\" ...>\n" }, { "answer_id": 571061, "author": "crb", "author_id": 51691, "author_profile": "https://Stackoverflow.com/users/51691", "pm_score": 2, "selected": true, "text": "rcadmin> indexdetach\nServer Alias:YourDocserver\nIndex Alias:CollectionName\nIndex Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n\nrcadmin> collpurge\nCollection alias:CollectionName\nAdmin Alias:AdminServer\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n\nrcadmin> adminsignal\nAdmin Alias:AdminServer\nType of signal (Shutdown=2,WSRefresh=3,RestartAllServers=4):4\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n rcadmin> collset\nAdmin Alias:AdminServer\nCollection Alias:NewCollectionName\nModify Type (Update=0, Insert=1):1\nPath:\nGateway[(o)dbc|(n)otes|(e)xchange|(d)ocumentum|(f)ilesys|(w)eb|o(t)her]:\nStyle Alias:\nDocument Access (Public=0,Secure=1,Anonymous=2):\nQuery Parser [(s)imple|(b)oolPlus|(f)reeText|(o)ldFreeText|O(l)dSimple|O(t)her]:\n\nDescription:\nMax. Search Time(msecs):\nSave changes? [y|n]:y\n\nrcadmin> indexattach\nIndex Alias:NewCollectionName\nIndex Type [(c)ollection,(t)ree,(p)arametric,(r)ecommendation]:c\nServer Alias:YourDocserver\nModify Type (Update=0, Insert=1):1\nIndex State (offline=0,hidden=1,online=2):2\nThreads (default=3):\nSave changes? [y|n]:y\n<<Return>> SUCCESS\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10750/" ]
155,908
<p>I have defined tomcat:catalina:5.5.23 as a dependency to the cargo plugin, however I still get the following exception:</p> <pre><code>java.lang.ClassNotFoundException: org.apache.catalina.Connector at java.net.URLClassLoader$1.run(URLClassLoader.java:200) at java.security.AccessController.doPrivileged(Native Method) at java.net.URLClassLoader.findClass(URLClassLoader.java:188) at java.lang.ClassLoader.loadClass(ClassLoader.java:316) at org.codehaus.classworlds.RealmClassLoader.loadClassDirect(RealmClassLoader.java:195) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:255) at org.codehaus.classworlds.DefaultClassRealm.loadClass(DefaultClassRealm.java:274) at org.codehaus.classworlds.RealmClassLoader.loadClass(RealmClassLoader.java:214) at java.lang.ClassLoader.loadClass(ClassLoader.java:251) at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:374) at java.lang.Class.forName0(Native Method) at java.lang.Class.forName(Class.java:247) at org.codehaus.cargo.container.tomcat.internal.Tomcat5xEmbedded.preloadEmbedded(Tomcat5xEmbedded.java:232) </code></pre> <p>It looks like the RealmClassLoader is not finding the class, possibly due to java.security.AccessController.doPrivileged denying access. </p> <p>Has anyone got tomcat to run in embedded mode from within maven?</p>
[ { "answer_id": 169029, "author": "Hugo", "author_id": 972, "author_profile": "https://Stackoverflow.com/users/972", "pm_score": 1, "selected": false, "text": "mvn jetty6:run\n <project>\n <build>\n <plugins>\n <plugin>\n <groupId>org.mortbay.jetty</groupId>\n <artifactId>maven-jetty6-plugin</artifactId>\n <configuration>\n <scanIntervalSeconds>5</scanIntervalSeconds>\n <!--\n <webXml>${basedir}/WEB-INF/web.xml</webXml>\n -->\n </configuration>\n </plugin>\n </plugins>\n </build>\n</project>\n" }, { "answer_id": 640436, "author": "Nathan Feger", "author_id": 8563, "author_profile": "https://Stackoverflow.com/users/8563", "pm_score": 0, "selected": false, "text": "<plugins>\n <plugin>\n <groupId>org.codehaus.mojo</groupId>\n <artifactId>tomcat-maven-plugin</artifactId>\n </plugin>\n</plugins>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2767300/" ]
155,911
<p>During software development, there may be bugs in the codebase which are known issues. These bugs will cause the regression/unit tests to fail, if the tests have been written well.</p> <p>There is constant debate in our teams about how failing tests should be managed:</p> <ol> <li><p>Comment out failing test cases with a REVISIT or TODO comment.</p> <ul> <li><strong>Advantage</strong>: We will always know when a <em>new</em> defect has been introduced, and not one we are already aware of.</li> <li><strong>Disadvantage</strong>: May forget to REVISIT the commented-out test case, meaning that the defect could slip through the cracks.</li> </ul></li> <li><p>Leave the test cases failing.</p> <ul> <li><strong>Advantage</strong>: Will not forget to fix the defects, as the script failures will constantly reminding you that a defect is present.</li> <li><strong>Disadvantage</strong>: Difficult to detect when a <em>new</em> defect is introduced, due to failure noise.</li> </ul></li> </ol> <p>I'd like to explore what the best practices are in this regard. Personally, I think a tri-state solution is the best for determining whether a script is passing. For example when you run a script, you could see the following:</p> <ul> <li>Percentage passed: 75%</li> <li>Percentage failed (expected): 20%</li> <li>Percentage failed (unexpected): 5%</li> </ul> <p>You would basically mark any test cases which you <em>expect</em> to fail (due to some defect) with some metadata. This ensures you still see the failure result at the end of the test, but immediately know if there is a <em>new</em> failure which you weren't expecting. This appears to take the best parts of the 2 proposals above.</p> <p>Does anyone have any best practices for managing this?</p>
[ { "answer_id": 155942, "author": "Mark", "author_id": 4405, "author_profile": "https://Stackoverflow.com/users/4405", "pm_score": 4, "selected": true, "text": "// TODO: fix test case\n // HAHA: you'll never revisit me\n" }, { "answer_id": 155971, "author": "Georgi", "author_id": 13209, "author_profile": "https://Stackoverflow.com/users/13209", "pm_score": 1, "selected": false, "text": "3. Connect to a web service\n ...\n3.1. Get the version number\n ...\n3.2. Data:\n 3.2.1. Get the version number\n 3.2.2. Retrieve simple data\n 3.2.3. Retrieve detailed data\n 3.2.4. Change data\n" }, { "answer_id": 156047, "author": "Dave Sherohman", "author_id": 18914, "author_profile": "https://Stackoverflow.com/users/18914", "pm_score": 2, "selected": false, "text": "TODO: {\n local $TODO = \"This has not been implemented yet.\"\n\n # Tests expected to fail go here\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22489/" ]
155,912
<p>Calling <code>Validate()</code> on an <strong>XmlDocument</strong> requires passing in a <code>ValidationEventHandler</code> delegate. That event function gets a <code>ValidationEventArgs</code> parameter which in turn has an <code>Exception</code> property of the type <code>XmlSchemaException</code>. Whew!</p> <p>My current code looks like this:</p> <pre><code>ValidationEventHandler onValidationError = delegate(object sender, ValidationEventArgs args) { throw(args.Exception); } doc.Validate(onValidationError); </code></pre> <p>Is there some other method I'm overlooking which simply <em>throws</em> the <code>XmlSchemaException</code> if validation fails (warnings ignored entirely)?</p>
[ { "answer_id": 57436064, "author": "Adam Porad", "author_id": 21353, "author_profile": "https://Stackoverflow.com/users/21353", "pm_score": 0, "selected": false, "text": "null validationEventHandler validationEventHandler ValidationEventHandler null" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9642/" ]
155,913
<p>The project I'm working is using n-tier architecture. Our layers are as follows:</p> <ul> <li>Data Access</li> <li>Business Logic</li> <li>Business Entities</li> <li>Presentation</li> </ul> <p>The Business Logic calls down into the data access layer, and the Presentation layer calls down into the Business Logic layer, and the Business entities are referenced by all of them. </p> <p>Our business entities essentially match our data model 1-1. For every table, we have a class. Initially when the framework was designed, there was no consideration for managing master-detail or child-parent relationships. So all of the Business logic, data access, and business entities, only referenced a single table in the database. Once we started developing the application it quickly became apparent that not having these relationships in our object model was severely hurting us.</p> <p>All of your layers (including the database) are all generated from an in-house metadata-database which we use to drive our home-grown code generator.</p> <p>The question is what is the best way to load or lazy load the relationships in our entities. For instance Let's say we have a person class that has a master-child relationship to an address table. This shows up in the business entity as a collection property of Addresses on the Person object. If we have a one-to-one relationship then this would show up as a single entity property. What is the best approach for filling and saving the relationship objects? Our Business entities have no knowledge of the Business Logic layer, so it can't be done internally when the property get's called.</p> <p>I'm sure there is some sort of standard patter out there for doing this. Any suggestions?</p> <p>Also, one caveat is that the DataAcess layer uses reflection to build our entities. The stored procedures return one result selt based on one table, and using reflection we populate our business object by matching the names of the properties with the names of the columns. So doing joins would be difficult.</p>
[ { "answer_id": 155965, "author": "Andrew Kennan", "author_id": 22506, "author_profile": "https://Stackoverflow.com/users/22506", "pm_score": 1, "selected": false, "text": "public class Relation<T>\n{\n private T _value;\n\n private void FetchData()\n {\n if( LoadData != null ) {\n LoadDataEventArgs args = new LoadDataEventArgs(typeof(T), /* magic to get correct object */);\n LoadData(this, args);\n _value = (T)args.Value;\n }\n }\n\n public event EventHandler<LoadDataEventArgs> LoadData;\n\n public T Value {\n get {\n if( _value == default(T) )\n FetchData();\n return _value; \n }\n set { /* Do magic here. */ }\n }\n}\n [RelationCriteria(\"ID\", EqualsMyProperty=\"AddressID\")]\npublic Relation<Address> Address {\n get; set;\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
155,920
<p>I have one of those "I swear I didn't touch the server" situations. I honestly didn't touch any of the php scripts. The problem I am having is that php data is not being saved across different pages or page refreshes. I know a new session is being created correctly because I can set a session variable (e.g. $_SESSION['foo'] = "foo" and print it back out on the same page just fine. But when I try to use that same variable on another page it is not set! Is there any php functions or information I can use on my hosts server to see what is going on?</p> <p>Here is an example script that does not work on my hosts' server as of right now:</p> <pre><code>&lt;?php session_start(); if(isset($_SESSION['views'])) $_SESSION['views'] = $_SESSION['views']+ 1; else $_SESSION['views'] = 1; echo "views = ". $_SESSION['views']; echo '&lt;p&gt;&lt;a href="page1.php"&gt;Refresh&lt;/a&gt;&lt;/p&gt;'; ?&gt; </code></pre> <p>The 'views' variable never gets incremented after doing a page refresh. I'm thinking this is a problem on their side, but I wanted to make sure I'm not a complete idiot first.</p> <p>Here is the phpinfo() for my hosts' server (PHP Version 4.4.7): <img src="https://i.stack.imgur.com/3bv0K.png" alt="alt text"></p>
[ { "answer_id": 155941, "author": "vIceBerg", "author_id": 17766, "author_profile": "https://Stackoverflow.com/users/17766", "pm_score": 3, "selected": false, "text": "phpinfo() session.* print_r($_SESSION); phpinfo() session.save_path" }, { "answer_id": 155945, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 2, "selected": false, "text": "if (isset($_SESSION['views'])) {\n if (!is_numeric($_SESSION['views'])) {\n echo \"CRAP!\";\n }\n ++$_SESSION['views'];\n} else {\n $_SESSION['views'] = 1;\n}\n" }, { "answer_id": 159948, "author": "Crackerjack", "author_id": 13556, "author_profile": "https://Stackoverflow.com/users/13556", "pm_score": 6, "selected": true, "text": "ini_set(' session.save_path','SOME WRITABLE PATH');" }, { "answer_id": 6428807, "author": "Aleks G", "author_id": 717214, "author_profile": "https://Stackoverflow.com/users/717214", "pm_score": 2, "selected": false, "text": "$_SESSION['full_list'] = $full_list $full_list $full_list" }, { "answer_id": 6777970, "author": "harry", "author_id": 856186, "author_profile": "https://Stackoverflow.com/users/856186", "pm_score": 3, "selected": false, "text": "<?\n session_start();\n $_SESSION['a'] = 123;\n header('location:index2.php');\n?>\n <?\n session_start();\n echo $_SESSION['a'];\n?>\n $_SESSION['a'] index.php <?\n session_start();\n $_SESSION['a'] = 123;\n session_write_close();\n header('location:index2.php');\n?>\n" }, { "answer_id": 12554786, "author": "emaniacs", "author_id": 1286248, "author_profile": "https://Stackoverflow.com/users/1286248", "pm_score": 1, "selected": false, "text": "session.gc_probability=0\n" }, { "answer_id": 26180998, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "www.mysite.com mysite.com www" }, { "answer_id": 26191908, "author": "Pete855217", "author_id": 855217, "author_profile": "https://Stackoverflow.com/users/855217", "pm_score": 0, "selected": false, "text": "session.use_trans_sid=0 ; Do not add session id to URI (osc does this)\nsession.use_cookies=0; ; ensure cookies are not used\nsession.use_only_cookies=0 ; ensure sessions are OK to use IMPORTANT\nsession.save_path=~/tmp/osc; ; Set to same as admin setting\nsession.auto_start = off; Tell PHP not to start sessions, osc code will do this\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13556/" ]
155,930
<p>I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.</p> <p>Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each time and doesn't show the URL that I pass in. I would like it to NOT launch a new version each time but just open a new page in the current open one if it is already running. </p> <p>For windows I use:</p> <pre><code>ShellExecute(NULL,"open",filename,NULL,NULL,SW_SHOWNORMAL); </code></pre> <p>For Linux I currently use:</p> <pre><code>pid_t pid; char *args[2]; char *prog=0; char firefox[]={"/usr/bin/firefox"}; if(strstri(filename,".html")) prog=firefox; if(prog) { args[0]=(char *)filename; args[1]=0; pid=fork(); if(!pid) execvp(prog,args); } </code></pre>
[ { "answer_id": 155946, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": true, "text": "xdg-open $ xdg-open http://google.com/\n gnome-open exo-open" }, { "answer_id": 159102, "author": "matli", "author_id": 23896, "author_profile": "https://Stackoverflow.com/users/23896", "pm_score": 0, "selected": false, "text": "firefox -remote 'openurl(http://stackoverflow.com)'\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155930", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13676/" ]
155,932
<p>I would like to know how to loop through each line in a text file using a Windows batch file and process each line of text in succession.</p>
[ { "answer_id": 155937, "author": "Michael Ratanapintha", "author_id": 1879, "author_profile": "https://Stackoverflow.com/users/1879", "pm_score": 3, "selected": false, "text": "cmd.exe" }, { "answer_id": 155950, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 6, "selected": false, "text": "for /F \"eol=; tokens=2,3* delims=,\" %i in (myfile.txt) do @echo %i %j %k\n \"C:\\WINDOWS\\Help\\ntcmds.chm\"\n" }, { "answer_id": 155954, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "REM ******************************************************************\nREM Runs all *.sql scripts sorted by filename in the current folder.\nREM To use integrated auth change -U <user> -P <password> to -E\nREM ******************************************************************\n\ndir /B /O:n *.sql > RunSqlScripts.tmp\nfor /F %%A in (RunSqlScripts.tmp) do osql -S (local) -d DEFAULT_DATABASE_NAME -U USERNAME_GOES_HERE -P PASSWORD_GOES_HERE -i %%A\ndel RunSqlScripts.tmp\n" }, { "answer_id": 163873, "author": "Mr. Kraus", "author_id": 5132, "author_profile": "https://Stackoverflow.com/users/5132", "pm_score": 9, "selected": true, "text": "for /F \"tokens=*\" %%A in (myfile.txt) do [process] %%A\n usebackq for /F \"usebackq tokens=*\" %%A in (\"my file.txt\") do [process] %%A\n" }, { "answer_id": 1266109, "author": "Paul", "author_id": 121257, "author_profile": "https://Stackoverflow.com/users/121257", "pm_score": 4, "selected": false, "text": "FOR /F %%i IN (myfile.txt) DO ECHO %%i\n" }, { "answer_id": 2766240, "author": "user332474", "author_id": 332474, "author_profile": "https://Stackoverflow.com/users/332474", "pm_score": 5, "selected": false, "text": "%% % help for for /F \"tokens=1,2,3\" %%i in (myfile.txt) do call :process %%i %%j %%k\ngoto thenextstep\n:process\nset VAR1=%1\nset VAR2=%2\nset VAR3=%3\nCOMMANDS TO PROCESS INFORMATION\ngoto :EOF\n set VAR1=%1\n set VAR2=%2\n set VAR3=%3\n" }, { "answer_id": 8976789, "author": "Yogesh Mahajan", "author_id": 1852508, "author_profile": "https://Stackoverflow.com/users/1852508", "pm_score": 5, "selected": false, "text": "for /F \"tokens=*\" %A in (MyList.txt) do CALL %A ARG1\n for /F \"tokens=*\" %A in (MuList.txt) do (\nECHO Processing %A....\nCALL %A ARG1\n)\n ---START of MyScript.bat---\n@echo off\nfor /F \"tokens=*\" %%A in ( MyList.TXT) do (\n ECHO Processing %%A.... \n CALL %%A ARG1 \n)\n@echo on\n;---END of MyScript.bat---\n" }, { "answer_id": 14285280, "author": "DotDotJames", "author_id": 625754, "author_profile": "https://Stackoverflow.com/users/625754", "pm_score": 1, "selected": false, "text": "cmd /C \"heroku list > heroku_apps.txt\"\nfind /v \"=\" heroku_apps.txt | find /v \".TXT\" | findstr /r /v /c:\"^$\" > heroku_apps_list.txt\nfor /F \"tokens=1\" %%i in (heroku_apps_list.txt) do heroku run bundle show rails --app %%i\n" }, { "answer_id": 16792536, "author": "Marvin Thobejane", "author_id": 1358924, "author_profile": "https://Stackoverflow.com/users/1358924", "pm_score": 5, "selected": false, "text": "cd /d %~dp0\nfor /F \"tokens=*\" %%A in (myfile.txt) do [process] %%A\n for /F \"tokens=*\" %%A in ('type \"my file.txt\"') do [process] %%A\n type" }, { "answer_id": 17723989, "author": "jeb", "author_id": 463115, "author_profile": "https://Stackoverflow.com/users/463115", "pm_score": 4, "selected": false, "text": "; @echo off\nSETLOCAL DisableDelayedExpansion\nFOR /F \"usebackq delims=\" %%a in (`\"findstr /n ^^ text.txt\"`) do (\n set \"var=%%a\"\n SETLOCAL EnableDelayedExpansion\n set \"var=!var:*:=!\"\n echo(!var!\n ENDLOCAL\n)\n %%a ! ^ set \"var=!var:*:=!\" delims=:" }, { "answer_id": 52806421, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "cmd.exe for /F \"tokens=*\" %F in (file.txt) do whatever \"%F\" ...\n [IO.File]::ReadLines(\"file.txt\") | ForEach-Object { whatever \"$_\" }\n foreach($line in [System.IO.File]::ReadLines(\"file.txt\")) { whatever \"$line\" } \n for /F ... foreach ForEach-Object" }, { "answer_id": 60025292, "author": "Zimba", "author_id": 5958708, "author_profile": "https://Stackoverflow.com/users/5958708", "pm_score": 1, "selected": false, "text": "set input=\"path/to/file.txt\"\n\nfor /f \"tokens=* delims=[\" %i in ('type \"%input%\" ^| find /v /n \"\"') do (\nset a=%i\nset a=!a:*]=]!\necho:!a:~1!)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155932", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5132/" ]
155,934
<p>What GNU/Linux command-line tool would I use for performing a search and replace on a file? </p> <p>Can the search text, and replacement, be specified in a regex format?</p>
[ { "answer_id": 155939, "author": "Michael Cramer", "author_id": 1496728, "author_profile": "https://Stackoverflow.com/users/1496728", "pm_score": 5, "selected": false, "text": "perl -pi -e 's/foo/bar/g;' *.txt\n perl -pi.bak -e 's/foo/bar/g;' *.txt\n cat file.txt | perl -ne 's/foo/bar/g;' | less\n" }, { "answer_id": 155956, "author": "Cristian Ciupitu", "author_id": 12892, "author_profile": "https://Stackoverflow.com/users/12892", "pm_score": 7, "selected": true, "text": "sed 's/a.*b/xyz/g;' old_file > new_file\n sed -r --in-place 's/a(.*)b/x\\1y/g;' your_file\n" }, { "answer_id": 159354, "author": "Brian Carper", "author_id": 23070, "author_profile": "https://Stackoverflow.com/users/23070", "pm_score": 3, "selected": false, "text": "-i -p -l -e -n $_ ruby -pi.bak -e '$_.gsub!(/foo|bar/){|x| x.upcase}' *.txt perl -pi.bak -e 's/(foo|bar)/\\U\\1/g' *.txt" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155934", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2045/" ]
155,959
<p>The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources?</p> <pre><code>using (OleDbConnection conn = new OleDbConnection(connectionString)) using (OleDbCommand cmd = new OleDbCommand(commandText, conn)) { conn.Open(); cmd.ExecuteNonQuery(); } </code></pre>
[ { "answer_id": 155961, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 4, "selected": true, "text": "using (OleDBConnection conn = new OleDBConnection(connstr))\n{\n while (IHaveData)\n {\n using (OldDBCommand cmd = new OldDBCommand())\n {\n cmd.Connection = conn;\n cmd.ExecuteScalar();\n }\n }\n}\n" }, { "answer_id": 21227708, "author": "jaymeht", "author_id": 1703129, "author_profile": "https://Stackoverflow.com/users/1703129", "pm_score": -1, "selected": false, "text": "OledbCommand.Dispose();\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2669/" ]
155,964
<p>I know about the <a href="http://developer.apple.com/library/mac/#documentation/UserExperience/Conceptual/AppleHIGuidelines/Intro/Intro.html" rel="noreferrer">HIG</a> (which is quite handy!), but what programming practices do you use when writing Objective-C, and more specifically when using Cocoa (or CocoaTouch).</p>
[ { "answer_id": 155966, "author": "JamesSugrue", "author_id": 1075, "author_profile": "https://Stackoverflow.com/users/1075", "pm_score": 6, "selected": false, "text": "alloc release" }, { "answer_id": 156098, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 10, "selected": true, "text": "#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n - (NSCachedURLResponse *)connection:(NSURLConnection *)connection\n willCacheResponse:(NSCachedURLResponse *)cachedResponse\n{\n return nil;\n}\n float val = someFloat * 2.2f;\n someFloat nonatomic atomic BEGIN; COMMIT; @synchronize() {}" }, { "answer_id": 156186, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 6, "selected": false, "text": "@interface MyClass (private)\n- (void) someMethod\n- (void) someOtherMethod\n@end\n @interface MyClass ()\n- (void) someMethod\n- (void) someOtherMethod\n@end\n" }, { "answer_id": 156288, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 4, "selected": false, "text": "- (void)dealloc\n{\n self.someAttribute = NULL;\n [super dealloc];\n}\n" }, { "answer_id": 156295, "author": "schwa", "author_id": 23113, "author_profile": "https://Stackoverflow.com/users/23113", "pm_score": 7, "selected": false, "text": "dealloc - (void)dealloc\n{\nself.someObject.delegate = NULL;\nself.someObject = NULL;\n//\n[super dealloc];\n}\n dealloc self.someObject.delegate = NULL;\n if (self.someObject.delegate == self)\n self.someObject.delegate = NULL;\n" }, { "answer_id": 156665, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 5, "selected": false, "text": "*Listener EventArgs" }, { "answer_id": 158304, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 7, "selected": false, "text": "id m_something; something _something -getSomething -something -something: -setSomething: -[NSObject performSelector:withObject:] NSObject::performSelector" }, { "answer_id": 167495, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "@interface MyClass :NSObject {\n NSTextField *textField;\n}\n@property (nonatomic, retain) IBOutlet NSTextField *textField;\n@end\n" }, { "answer_id": 169783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "cd scan-build -k -V xcodebuild" }, { "answer_id": 175118, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 7, "selected": false, "text": "NSLog NSString *aString = // get a string from somewhere;\n NSLog(aString);\n NSLog(@\"%@\", aString);\n" }, { "answer_id": 175134, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "compare: localizedCompare: localizedCaseInsensitiveCompare:" }, { "answer_id": 175874, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 6, "selected": false, "text": "aVariable = [AClass convenienceMethod];\n aVariable = [[AClass alloc] init];\n// do things with aVariable\n[aVariable release];\n - (MyClass *)convenienceMethod {\n MyClass *instance = [[[self alloc] init] autorelease];\n // configure instance\n return instance;\n}\n - (MyClass *)newInstance {\n MyClass *instance = [[self alloc] init];\n // configure instance\n return instance;\n}\n newObject" }, { "answer_id": 195969, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "nil nil" }, { "answer_id": 297307, "author": "Marc Charbonneau", "author_id": 35136, "author_profile": "https://Stackoverflow.com/users/35136", "pm_score": 6, "selected": false, "text": "#pragma mark [section] #define NSLog( @\"stub\" )" }, { "answer_id": 3583204, "author": "Özgür", "author_id": 12652, "author_profile": "https://Stackoverflow.com/users/12652", "pm_score": 5, "selected": false, "text": "@interface FooInt:NSObject{}\n-(int) print;\n@end\n\n@implementation FooInt\n-(int) print{\n return 5;\n}\n@end\n\n@interface FooFloat:NSObject{}\n-(float) print;\n@end\n\n@implementation FooFloat\n-(float) print{\n return 3.3;\n}\n@end\n\nint main (int argc, const char * argv[]) {\n\n NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; \n id f1=[[FooFloat alloc]init];\n //prints 0, runtime considers [f1 print] to return int, as f1's type is \"id\" and FooInt precedes FooBar\n NSLog(@\"%f\",[f1 print]);\n\n FooFloat* f2=[[FooFloat alloc]init];\n //prints 3.3 expectedly as the static type is FooFloat\n NSLog(@\"%f\",[f2 print]);\n\n [f1 release];\n [f2 release]\n [pool drain];\n\n return 0;\n} \n" }, { "answer_id": 5476751, "author": "eonil", "author_id": 246776, "author_profile": "https://Stackoverflow.com/users/246776", "pm_score": 3, "selected": false, "text": "CGRectMake() CGAffineTransformMake() -copy -retain -[UIViewController view] view UIImage -autorelease -retain/-release" }, { "answer_id": 6977572, "author": "Tuan Nguyen", "author_id": 504257, "author_profile": "https://Stackoverflow.com/users/504257", "pm_score": 2, "selected": false, "text": "self.<property> = nil;\n" }, { "answer_id": 7816085, "author": "Sulthan", "author_id": 669586, "author_profile": "https://Stackoverflow.com/users/669586", "pm_score": 3, "selected": false, "text": "\n@synthesize property = property_;\n \nif (self) {\n //... long initialization code ...\n}\n\nreturn self;\n\n \nif (!self) {\n return nil;\n}\n\n//... long initialization code ...\n\nreturn self;\n\n \nview.frame = CGRectMake(view.frame.origin.x, view.frame.origin.y, view.frame.size.width, view.frame.size.height + 20);\n \nCGRect frame = view.frame;\nframe.size.height += 20;\nview.frame = frame;\n" }, { "answer_id": 10314854, "author": "Nirmit Pathak", "author_id": 1302622, "author_profile": "https://Stackoverflow.com/users/1302622", "pm_score": 0, "selected": false, "text": "#import \"MyClass.h\"\n\n@interface MyClass ()\n- (void) someMethod;\n- (void) someOtherMethod;\n@end\n\n@implementation MyClass\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21804/" ]
155,977
<p>I have the following markup, and I want to make the <code>All</code> radio button checked.</p> <pre><code>&lt;ul&gt; &lt;li&gt;&lt;input type="radio" value="All" name="Foo"/&gt;All&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="New" name="Foo"/&gt;New&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Removed" name="Foo"/&gt;Removed&lt;/li&gt; &lt;li&gt;&lt;input type="radio" value="Updated" name="Foo"/&gt;Updated&lt;/li&gt; &lt;/ul&gt; </code></pre> <p>I'd like to match via attribute, but I need to match on 2 attributes, <code>@name='Foo'</code> and <code>@value='All'</code>.</p> <p>Something like this:</p> <pre><code>$("input[@name='Foo' @value='all']").attr('checked','checked'); </code></pre> <p>Can someone show how this can be done?</p>
[ { "answer_id": 156027, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 7, "selected": true, "text": "<html>\n <head>\n <script type=\"text/javascript\" src=\"jquery-1.2.6.pack.js\"></script>\n <script type=\"text/javascript\">\n $(document).ready(function(){\n $(\"a\").click(function(event){\n $(\"input[name='Foo'][value='All']\").attr('checked','checked');\n event.preventDefault();\n });\n });\n </script>\n </head>\n <body>\n <ul>\n <li><input type=\"radio\" value=\"All\" name=\"Foo\" />All</li>\n <li><input type=\"radio\" value=\"New\" name=\"Foo\" />New</li>\n <li><input type=\"radio\" value=\"Removed\" name=\"Foo\" />Removed</li>\n <li><input type=\"radio\" value=\"Updated\" name=\"Foo\" />Updated</li>\n </ul>\n <a href=\"\" >Click here</a>\n </body>\n</html>\n checked" }, { "answer_id": 771618, "author": "easel", "author_id": 16706, "author_profile": "https://Stackoverflow.com/users/16706", "pm_score": 4, "selected": false, "text": "jQuery('input[name=field1][val=checked]') \n jQuery('input[@name=field1][@val=checked]')\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ]
155,996
<p>I have an MDI application. When I show a message box using MessageBox.Show(), the entire application disappears behind all of my open windows when I dismiss the message box.</p> <p>The code is not doing anything special. In fact, here is the line that invokes the message box from within an MDI Child form:</p> <pre><code>MessageBox.Show(String.Format("{0} saved successfully.", Me.BusinessUnitTypeName), "Save Successful", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, MessageBoxOptions.DefaultDesktopOnly) </code></pre> <p>Me.BusinessUnitTypeName() is a read only property getter that returns a string, depending upon the value of a member variable. There are no side effects in this property.</p> <p>Any ideas?</p>
[ { "answer_id": 156039, "author": "DaveK", "author_id": 4244, "author_profile": "https://Stackoverflow.com/users/4244", "pm_score": 2, "selected": false, "text": "MessageBoxOptions.DefaultDesktopOnly DefaultDesktopOnly" }, { "answer_id": 156040, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 4, "selected": true, "text": "MessageBoxOptions.DefaultDesktopOnly" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10224/" ]
155,998
<p>Given this:</p> <pre><code>Public Sub timReminder_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) If DateTime.Now() &gt; g_RemindTime Then Reminders.ShowDialog() timReminder.Enabled = False End If End Sub </code></pre> <p>I want to be able to say this (as I would in Delphi):</p> <pre><code>timReminder.Tick = timReminder_Tick </code></pre> <p>But I get errors when I try it.</p> <p>Does anyone know how I can assign a custom event to a timer's on-tick event at runtime in VB.NET?</p>
[ { "answer_id": 354784, "author": "Jon Winstanley", "author_id": 42106, "author_profile": "https://Stackoverflow.com/users/42106", "pm_score": 0, "selected": false, "text": "addHandler" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/155998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/672/" ]
156,002
<p>I have a very basic question about MVC web applications in Java.</p> <p>Since the olden days of raw JSP up until current technologies like Seam, a very basic pattern has always been the internal dispatch from the controller that initially accepted the request to the view layer that creates the output to be sent to the client.</p> <p>This internal dispatch is generally done (although the mechanism may be hidden through an extra layer of configuration) by asking the servlet container for a new resource using a URL. The mapping of these URL are done by the same web.xml that also defines the "real" URL to the outside.</p> <p>Unless special measures are taken, it is often possible to directly access the view layer directly. Witness the Seam "registration" demo, where you can bypass "register.seam" and directly go to "registered.xhtml". This is a potential security problem. At the very least, it leaks view template source code. </p> <p>I am aware that this is only a basic sample application, but it is also strange that any extra measures should need to be taken to declare these internal resources invisible to the outside.</p> <p>What is the easiest way to restrict URL entry points?</p> <p>Is there maybe something like the "WEB-INF" directory, a magic URL path component that can only be accessed by internal requests?</p>
[ { "answer_id": 453374, "author": "Simon Lieschke", "author_id": 2766, "author_profile": "https://Stackoverflow.com/users/2766", "pm_score": 2, "selected": false, "text": "security-constraint web.xml <!-- Prevent direct access to JSPs. -->\n<security-constraint>\n <web-resource-collection>\n <web-resource-name>JSP templates</web-resource-name>\n <url-pattern>*.jsp</url-pattern>\n </web-resource-collection>\n <auth-constraint/> <!-- i.e. nobody -->\n</security-constraint>\n" }, { "answer_id": 2046033, "author": "Thilo", "author_id": 14955, "author_profile": "https://Stackoverflow.com/users/14955", "pm_score": 1, "selected": true, "text": "WEB-INF/jsp" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156002", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14955/" ]
156,009
<p>Because of the more tedious way of adding hosts to be monitored in Nagios (it requires defining a host object, as opposed to the previous program which only required the IP and hostname), I figured it'd be best to automate this, and it'd be a great time to learn Perl, because all I know at the moment is C/C++ and Java. </p> <p>The file I read from looks like this:</p> <pre><code>xxx.xxx.xxx.xxx hostname #comments. i.dont. care. about </code></pre> <p>All I want are the first 2 bunches of characters. These are obviously space delimited, but for the sake of generality, it might as well be anything. To make it more general, why not the first and third, or fourth and tenth? Surely there must be some regex action involved, but I'll leave that tag off for the moment, just in case.</p>
[ { "answer_id": 156020, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 3, "selected": false, "text": "perl -nae 'print \"$F[0] $F[1]\\n\";'\n -F" }, { "answer_id": 156025, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "perl -ane 'print \"@F[0,1]\\n\";'\n perl -ape '$_=\"@F[0,1]\n\"'\n" }, { "answer_id": 156034, "author": "Trenton", "author_id": 2601671, "author_profile": "https://Stackoverflow.com/users/2601671", "pm_score": 2, "selected": false, "text": "perl -nae 'print \"$F[0] $F[1}\\n\";\n -a -a turns on autosplit mode when used with a -n or -p. An implicit split\n command to the @F array is done as the first thing inside the implicit\n while loop produced by the -n or -p.\n LINE:\n while (<>) {\n ... # your program goes here\n }\n -e -e perlrun(1)" }, { "answer_id": 156037, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "#!/usr/bin/perl -n\nchop; # strip newline (in case next line doesn't strip it)\ns/#.*//; # strip comments\nnext unless /\\S/; # don't process line if it has nothing (left)\n@fields = (split)[0,1]; # split line, and get wanted fields\nprint join(' ', @fields), \"\\n\";\n split /etc/passwd @fields = (split /:/)[0,2,4..6];\n" }, { "answer_id": 156063, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 4, "selected": true, "text": "if($line =~ m/(\\S+)\\s+(\\S+)/) {\n $ip = $1;\n $hostname = $2;\n}\n my @arr = split(/ /, $line);\n$ip = $arr[0];\n$hostname = $arr[1];\n" }, { "answer_id": 160230, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "<ARGV> while (my $line = <ARGV>) {\n chop $line;\n $line =~ s/#.*//;\n next unless $line =~ /\\S/;\n @fields = (split ' ', $line)[0,1];\n print join(' ', @fields), \"\\n\";\n}\n ARGV split ' ' split / / split /\\s+/ ' ' /\\s+/ ' '" }, { "answer_id": 20851920, "author": "Amit", "author_id": 2857960, "author_profile": "https://Stackoverflow.com/users/2857960", "pm_score": 0, "selected": false, "text": "@echo off\n\nREM Next line = Set command value to a file OR Just Choose Your File By Skipping The Line\nvol E: > %temp%\\justtmp.txt\nREM Vol E: = Find Volume Lable Of Drive E\n\nREM Next Line to choose line line no. +0 = line no. 1 \nfor /f \"usebackq delims=\" %%a in (`more +0 %temp%\\justtmp.txt`) DO (set findstringline=%%a& goto :nextstep)\n\n:nextstep\n\nREM Next line to read nth to mth Character here 22th Character to 40th Character\nset result=%findstringline:~22,40%\n\necho %result%\npause\nexit /b\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156009", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3879/" ]
156,013
<p>I can't quite figure out this syntax problem with a <code>case</code> expression in a <code>do</code> block.</p> <p>What is the correct syntax? </p> <p>If you could correct my example and explain it that would be the best.</p> <pre><code>module Main where main = do putStrLn "This is a test" s &lt;- foo putStrLn s foo = do args &lt;- getArgs return case args of [] -&gt; "No Args" [s]-&gt; "Some Args" </code></pre> <p>A little update. My source file was a mix of spaces and tabs and it was causing all kinds of problems. Just a tip for any one else starting in Haskell. If you are having problems check for tabs and spaces in your source code.</p>
[ { "answer_id": 156050, "author": "wnoise", "author_id": 15464, "author_profile": "https://Stackoverflow.com/users/15464", "pm_score": 6, "selected": true, "text": "module Main where \nimport System(getArgs)\n\nmain = do \n putStrLn \"This is a test\"\n s <- foo\n putStrLn s \n\nfoo = do\n args <- getArgs \n return (case args of\n [] -> \"No Args\"\n [s]-> \"Some Args\")\n foo = do\n args <- getArgs \n return $ case args of\n [] -> \"No Args\"\n [s]-> \"Some Args\"\n foo = do\n args <- getArgs \n return (has_args args)\n\nhas_args [] = \"No Args\"\nhas_args _ = \"Some Args\"\n" }, { "answer_id": 156459, "author": "Peter Burns", "author_id": 101, "author_profile": "https://Stackoverflow.com/users/101", "pm_score": 4, "selected": false, "text": "foo = do\n args <- getArgs \n case args of\n [] -> return \"No Args\"\n [s]-> return \"Some Args\"\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156013", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8965/" ]
156,032
<p>Java &amp; Oracle both have a <em>timestamp</em> type called Date. Developers tend to manipulate these as if they were <em>calendar</em> dates, which I've seen cause nasty one-off bugs.</p> <ol> <li><p>For a basic date quantity you can simply chop off the time portion upon input, i.e., reduce the precision. But if you do that with a date range, (e.g.: <strong>9/29-9/30</strong>), the difference between these two values is 1 day, rather than 2. Also, range comparisons require either 1) a truncate operation: <code>start &lt; trunc(now) &lt;= end</code>, or 2) arithmetic: <code>start &lt; now &lt; (end + 24hrs)</code>. Not horrible, but not <a href="http://www.artima.com/intv/dry.html" rel="nofollow noreferrer">DRY</a>.</p></li> <li><p>An alternative is to use true timestamps: <strong>9/29</strong> 00:00:00 - <strong>10/1</strong> 00:00:00. (midnight-to-midnight, so does not include any part of Oct). Now durations are intrinsically correct, and range comparisons are simpler: <code>start &lt;= now &lt; end</code>. Certainly cleaner for internal processing, however end dates do need to be converted upon initial input (+1), and for output (-1), presuming a calendar date metaphor at the user level.</p></li> </ol> <p>How do you handle date ranges on your project? Are there other alternatives? I am particularly interested in how you handle this on both the Java and the Oracle sides of the equation.</p>
[ { "answer_id": 156038, "author": "Alan", "author_id": 17205, "author_profile": "https://Stackoverflow.com/users/17205", "pm_score": 0, "selected": false, "text": "java.util.Date java.util.Date" }, { "answer_id": 156041, "author": "David Aldridge", "author_id": 6742, "author_profile": "https://Stackoverflow.com/users/6742", "pm_score": 2, "selected": false, "text": "MY_DATE = TO_DATE('2008-09-12 15:00:00') AND\nTO_DATE('2008-09-12 15:00:00') = TRUNC(TO_DATE('2008-09-12 15:00:00'))\n select ...\nfrom ...\nwhere my_date Between date '2008-01-01' and date '2008-01-05'\n select ...\nfrom ...\nwhere my_date >= date '2008-01-01' and\n my_date < date '2008-01-06'\n select ...\nfrom ...\nwhere my_date Between date '2008-01-01'\n and date '2008-01-05'-(1/24/60/60)\n select 27/24/60 from dual;\n" }, { "answer_id": 156639, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": true, "text": "start <= now < end 9/30 to 10/1 interval[n-1].end == interval[n].start start end" }, { "answer_id": 22595862, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "DateTimeZone timeZone_NewYork = DateTimeZone.forID( \"America/New_York\" );\nDateTime start = new DateTime( 2014, 9, 29, 15, 16, 17, timeZone_NewYork );\nDateTime stop = new DateTime( 2014, 9, 30, 1, 2, 3, timeZone_NewYork );\n\nint daysBetween = Days.daysBetween( start, stop ).getDays();\n\nPeriod period = new Period( start, stop );\n\nInterval interval = new Interval( start, stop );\nInterval intervalWholeDays = new Interval( start.withTimeAtStartOfDay(), stop.plusDays( 1 ).withTimeAtStartOfDay() );\n\nDateTime lateNight29th = new DateTime( 2014, 9, 29, 23, 0, 0, timeZone_NewYork );\nboolean containsLateNight29th = interval.contains( lateNight29th );\n System.out.println( \"start: \" + start );\nSystem.out.println( \"stop: \" + stop );\nSystem.out.println( \"daysBetween: \" + daysBetween );\nSystem.out.println( \"period: \" + period ); // Uses format: PnYnMnDTnHnMnS\nSystem.out.println( \"interval: \" + interval );\nSystem.out.println( \"intervalWholeDays: \" + intervalWholeDays );\nSystem.out.println( \"lateNight29th: \" + lateNight29th );\nSystem.out.println( \"containsLateNight29th: \" + containsLateNight29th );\n start: 2014-09-29T15:16:17.000-04:00\nstop: 2014-09-30T01:02:03.000-04:00\ndaysBetween: 0\nperiod: PT9H45M46S\ninterval: 2014-09-29T15:16:17.000-04:00/2014-09-30T01:02:03.000-04:00\nintervalWholeDays: 2014-09-29T00:00:00.000-04:00/2014-10-01T00:00:00.000-04:00\nlateNight29th: 2014-09-29T23:00:00.000-04:00\ncontainsLateNight29th: true\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156032", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14749/" ]
156,046
<p>I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus?</p>
[ { "answer_id": 156067, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 3, "selected": false, "text": "this.TopMost = true; // as a result the form gets thrown to the front\nthis.TopMost = false; // but we don't actually want our form to always be on top\n" }, { "answer_id": 156082, "author": "Fry", "author_id": 23553, "author_profile": "https://Stackoverflow.com/users/23553", "pm_score": -1, "selected": false, "text": "Form f = new Form();\nf.ShowDialog();\n" }, { "answer_id": 156117, "author": "Bob Nadler", "author_id": 2514, "author_profile": "https://Stackoverflow.com/users/2514", "pm_score": 2, "selected": false, "text": "Form.Shown private void StartNotfication()\n{\n Thread th = new Thread(new ThreadStart(delegate\n {\n NotificationForm frm = new NotificationForm();\n frm.OnFormOpen += NotificationOpened;\n frm.ShowDialog();\n }));\n th.Name = \"NotificationForm\";\n th.Start();\n} \n\nprivate void NotificationOpened()\n{\n this.Focus(); // Put focus back on the original calling Form\n}\n frm.Close()" }, { "answer_id": 156159, "author": "TheSoftwareJedi", "author_id": 18941, "author_profile": "https://Stackoverflow.com/users/18941", "pm_score": 6, "selected": false, "text": "private const int SW_SHOWNOACTIVATE = 4;\nprivate const int HWND_TOPMOST = -1;\nprivate const uint SWP_NOACTIVATE = 0x0010;\n\n[DllImport(\"user32.dll\", EntryPoint = \"SetWindowPos\")]\nstatic extern bool SetWindowPos(\n int hWnd, // Window handle\n int hWndInsertAfter, // Placement-order handle\n int X, // Horizontal position\n int Y, // Vertical position\n int cx, // Width\n int cy, // Height\n uint uFlags); // Window positioning flags\n\n[DllImport(\"user32.dll\")]\nstatic extern bool ShowWindow(IntPtr hWnd, int nCmdShow);\n\nstatic void ShowInactiveTopmost(Form frm)\n{\n ShowWindow(frm.Handle, SW_SHOWNOACTIVATE);\n SetWindowPos(frm.Handle.ToInt32(), HWND_TOPMOST,\n frm.Left, frm.Top, frm.Width, frm.Height,\n SWP_NOACTIVATE);\n}\n" }, { "answer_id": 157843, "author": "Martin Plante", "author_id": 4898, "author_profile": "https://Stackoverflow.com/users/4898", "pm_score": 8, "selected": true, "text": "protected override bool ShowWithoutActivation\n{\n get { return true; }\n}\n protected override CreateParams CreateParams\n{\n get\n {\n CreateParams baseParams = base.CreateParams;\n\n const int WS_EX_NOACTIVATE = 0x08000000;\n const int WS_EX_TOOLWINDOW = 0x00000080;\n baseParams.ExStyle |= ( int )( WS_EX_NOACTIVATE | WS_EX_TOOLWINDOW );\n\n return baseParams;\n }\n}\n" }, { "answer_id": 884706, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "using System.Runtime.InteropServices;\n\n[DllImport(\"user32.dll\")]\nstatic extern bool OpenIcon(IntPtr hWnd);\n\n[DllImport(\"user32.dll\")]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);\n\npublic static void ActivateInstance()\n{\n IntPtr hWnd = IntPtr hWnd = Process.GetCurrentProcess().MainWindowHandle;\n\n // Restore the program.\n bool result = OpenIcon(hWnd); \n // Activate the application.\n result = SetForegroundWindow(hWnd);\n\n // End the current instance of the application.\n //System.Environment.Exit(0); \n}\n" }, { "answer_id": 1472053, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "this.TopMost = true;\nthis.TopMost = false;\nthis.TopMost = true;\nthis.SendToBack();\n" }, { "answer_id": 8144035, "author": "pkr", "author_id": 774828, "author_profile": "https://Stackoverflow.com/users/774828", "pm_score": 2, "selected": false, "text": "this.Focus();\n" }, { "answer_id": 9370064, "author": "Ziketo", "author_id": 1222233, "author_profile": "https://Stackoverflow.com/users/1222233", "pm_score": 3, "selected": false, "text": "<Window\n x:Class=\"myApplication.winNotification\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n Title=\"Notification Popup\" Width=\"300\" SizeToContent=\"Height\"\n WindowStyle=\"None\" AllowsTransparency=\"True\" Background=\"Transparent\" ShowInTaskbar=\"False\" Topmost=\"True\" Focusable=\"False\" ShowActivated=\"False\" >\n</Window>\n" }, { "answer_id": 13790153, "author": "Pawel Pawlowski", "author_id": 1886141, "author_profile": "https://Stackoverflow.com/users/1886141", "pm_score": -1, "selected": false, "text": "window.WindowState = WindowState.Minimized;" }, { "answer_id": 15271415, "author": "Meta", "author_id": 2144113, "author_profile": "https://Stackoverflow.com/users/2144113", "pm_score": 1, "selected": false, "text": "internal static DateTime LastBringToFrontTime { get; set; }\n\nprivate void Form1_Activated(object sender, EventArgs e)\n{\n var eventTime = DateTime.Now;\n if ((eventTime - LastBringToFrontTime).TotalMilliseconds > 500)\n Core.BringAllToFront(this);\n LastBringToFrontTime = eventTime;\n}\n internal static void BringAllToFront(Form inForm)\n{\n Form1.BringToFront();\n Form2.BringToFront();\n Form3.BringToFront();\n inForm.Focus();\n}\n inForm.WindowState = FormWindowState.Normal;\n" }, { "answer_id": 25219399, "author": "RenniePet", "author_id": 253938, "author_profile": "https://Stackoverflow.com/users/253938", "pm_score": 4, "selected": false, "text": " protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n\n private const int WS_EX_TOPMOST = 0x00000008;\n protected override CreateParams CreateParams\n {\n get\n {\n CreateParams createParams = base.CreateParams;\n createParams.ExStyle |= WS_EX_TOPMOST;\n return createParams;\n }\n }\n" }, { "answer_id": 30612891, "author": "Domi", "author_id": 4733663, "author_profile": "https://Stackoverflow.com/users/4733663", "pm_score": 1, "selected": false, "text": " [DllImport(\"user32.dll\")]\n static extern IntPtr GetForegroundWindow();\n\n [DllImport(\"user32.dll\")]\n static extern IntPtr SetForegroundWindow(IntPtr hWnd);\n\n public static void ShowTopmostNoFocus(Form f)\n {\n IntPtr activeWin = GetForegroundWindow();\n\n f.Show();\n f.BringToFront();\n f.TopMost = true;\n\n if (activeWin.ToInt32() > 0)\n {\n SetForegroundWindow(activeWin);\n }\n }\n" }, { "answer_id": 35929506, "author": "Steven Cvetko", "author_id": 6047481, "author_profile": "https://Stackoverflow.com/users/6047481", "pm_score": 0, "selected": false, "text": " form.Visible = false;\n form.TopMost = false;\n ShowWindow(form.Handle, ShowNoActivate);\n SetWindowPos(form.Handle, HWND_TOPMOST,\n form.Left, form.Top, form.Width, form.Height,\n NoActivate);\n form.Visible = true; //So that Load event happens\n" }, { "answer_id": 69726485, "author": "Antony Cartwright", "author_id": 16692341, "author_profile": "https://Stackoverflow.com/users/16692341", "pm_score": 0, "selected": false, "text": "a = new Assign_Stock(); \na.MdiParent = this.ParentForm;\na.Visible = false; //hide for a bit. \na.Show(); //show the form. Invisible form now at the top.\nthis.Focus(); //focus on this form. make old form come to the top.\na.Visible = true; //make other form visible now. Behind the main form.\n" }, { "answer_id": 70596793, "author": "lava", "author_id": 7706354, "author_profile": "https://Stackoverflow.com/users/7706354", "pm_score": 0, "selected": false, "text": " protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n public partial class Form2 : Form\n {\n Form3 c;\n public Form2()\n {\n InitializeComponent();\n c = new Form3();\n }\n\n private void textchanged(object sender, EventArgs e)\n {\n\n\n c.ResetText(textBox1.Text.ToString());\n c.Location = new Point(this.Location.X+150, this.Location.Y);\n c .Show();\n\n//removethis\n//if mdiparent 2 add this.focus() after show form\n\n c.MdiParent = this.MdiParent;\n c.ResetText(textBox1.Text.ToString());\n c.Location = new Point(this.Location.X+150, this.Location.Y);\n c .Show();\n this.Focus();\n////-----------------\n\n\n }\n\n\n \n }\n public partial class Form3 : Form\n {\n public Form3()\n {\n InitializeComponent();\n //ShowWithoutActivation = false;\n }\n protected override bool ShowWithoutActivation\n {\n get { return true; }\n }\n\n\n internal void ResetText(string toString)\n {\n label2.Text = toString;\n }\n\n \n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4386/" ]
156,051
<p>I've got a dropdown list that is being populated via a webservice using ASP>NET AJAX. On the success callback of the method in javascript, I'm populating the dropdown via a loop:</p> <pre><code>function populateDropDown(dropdownId, list, enable, showCount) { var dropdown = $get(dropdownId); dropdown.options.length = 1; for (var i = 0; i &lt; list.length; i++) { var opt = document.createElement("option"); if (showCount) { opt.text = list[i].Name + ' (' + list[i].ChildCount + ')'; } else { opt.text = list[i].Name; } opt.value = list[i].Name; dropdown.options.add(opt); } dropdown.disabled = !enable; } </code></pre> <p>However when I submit the form that this control is on, the control's list is always empty on postback. How do I get the populated lists data to persist over postback?</p> <p><strong>Edit:</strong> Maybe I'm coming at this backwards. A better question would probably be, how do I populate a dropdown list from a webservice without having to use an updatepanel due to the full page lifecycle it has to run through?</p>
[ { "answer_id": 156065, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 3, "selected": true, "text": "AjaxControlToolkit.CascadingDropDownBehavior.callBaseMethod(this, 'set_ClientState', [ this._selectedValue+':::'+text ]);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2975/" ]
156,083
<p>I hear people writing these programs all the time and I know what they do, but how do they actually do it? I'm looking for general concepts.</p>
[ { "answer_id": 156312, "author": "micahwittman", "author_id": 11181, "author_profile": "https://Stackoverflow.com/users/11181", "pm_score": 2, "selected": false, "text": "//Show My SO Reputation Score\nvar repval = $('span.reputation-score:first'); alert('StackOverflow User \"' + repval.prev().attr('href').split('/').pop() + '\" has (' + repval.html() + ') Reputation Points.');\n" }, { "answer_id": 1170435, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "string pageContents = new WebClient(\"www.stackoverflow.com\").DownloadString();\nint numberOfPosts = // regex match\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
156,084
<p>Using VBA i have a set of functions that return an <code>ADODB.Recordset</code> where all the columns as <code>adVarChar</code>. Unfortunately this means numerics get sorted as text. So 1,7,16,22 becomes 1,16,22,7</p> <p>Is there any methods that can sort numerics as text columns without resorting to changing the type of the column?</p> <pre><code>Sub TestSortVarChar() Dim strBefore, strAfter As String Dim r As ADODB.RecordSet Set r = New ADODB.RecordSet r.Fields.Append "ID", adVarChar, 100 r.Fields.Append "Field1", adVarChar, 100 r.Open r.AddNew r.Fields("ID") = "1" r.Fields("Field1") = "A" r.AddNew r.Fields("ID") = "7" r.Fields("Field1") = "B" r.AddNew r.Fields("ID") = "16" r.Fields("Field1") = "C" r.AddNew r.Fields("ID") = "22" r.Fields("Field1") = "D" r.MoveFirst Do Until r.EOF strBefore = strBefore &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop r.Sort = "[ID] ASC" r.MoveFirst Do Until r.EOF strAfter = strAfter &amp; r.Fields("ID") &amp; " " &amp; r.Fields("Field1") &amp; vbCrLf r.MoveNext Loop MsgBox strBefore &amp; vbCrLf &amp; vbCrLf &amp; strAfter End Sub </code></pre> <p>NB: I am using Project 2003 and Excel 2003 and referencing <strong>Microsoft ActiveX DataObject 2.8 Library</strong></p>
[ { "answer_id": 157741, "author": "Chris OC", "author_id": 11041, "author_profile": "https://Stackoverflow.com/users/11041", "pm_score": 2, "selected": false, "text": "SELECT ID, Field1\nFROM tablename\nORDER BY Val(Field1);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4134/" ]
156,089
<p>I am just starting with SL and WPF. I am using the DataGrid control and I need to remove the mouseover effect (I actually will need to do more customizations than that). How do I do this. I think I need to do it with a control template but not sure how. I'm researching and reading right now. Any help would be appreciated.</p>
[ { "answer_id": 183936, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 2, "selected": false, "text": "<vsm:VisualState x:Name=\"MouseOver\">" }, { "answer_id": 1681462, "author": "Scott", "author_id": 38832, "author_profile": "https://Stackoverflow.com/users/38832", "pm_score": 2, "selected": false, "text": " <Style x:Key=\"CellStyle\" TargetType=\"local:DataGridCell\">\n <Setter Property=\"Background\" Value=\"Transparent\" />\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"Cursor\" Value=\"Arrow\" />\n <Setter Property=\"IsTabStop\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"local:DataGridCell\">\n <Grid Name=\"Root\" Background=\"Transparent\">\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"CurrentStates\" >\n <vsm:VisualStateGroup.Transitions>\n <vsm:VisualTransition GeneratedDuration=\"0\" />\n </vsm:VisualStateGroup.Transitions>\n\n <vsm:VisualState x:Name=\"Regular\" />\n <vsm:VisualState x:Name=\"Current\" />\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"FocusVisual\" Storyboard.TargetProperty=\"Opacity\" To=\"1\" Duration=\"0\" />\n </Storyboard>\n </vsm:VisualState>-->\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <Rectangle Name=\"FocusVisual\" Stroke=\"#FF6DBDD1\" StrokeThickness=\"1\" Fill=\"#66FFFFFF\" HorizontalAlignment=\"Stretch\" VerticalAlignment=\"Stretch\" IsHitTestVisible=\"false\" Opacity=\"0\" />\n <ContentPresenter Content=\"{TemplateBinding Content}\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" Cursor=\"{TemplateBinding Cursor}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" Margin=\"{TemplateBinding Padding}\" />\n <Rectangle Name=\"RightGridLine\" Grid.Column=\"1\" VerticalAlignment=\"Stretch\" Width=\"1\" />\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n <Style TargetType=\"local:DataGridRow\" x:Key=\"MyCustomRow\">\n <Setter Property=\"IsTabStop\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"local:DataGridRow\">\n <localprimitives:DataGridFrozenGrid x:Name=\"Root\">\n <localprimitives:DataGridFrozenGrid.Resources>\n <Storyboard x:Key=\"DetailsVisibleTransition\" >\n <DoubleAnimation Storyboard.TargetName=\"DetailsPresenter\" Storyboard.TargetProperty=\"ContentHeight\" Duration=\"00:00:0.1\" />\n </Storyboard>\n </localprimitives:DataGridFrozenGrid.Resources>\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"CommonStates\" >\n <vsm:VisualState x:Name=\"Normal\" />\n <vsm:VisualState x:Name=\"Normal AlternatingRow\">\n <Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"0\" />\n </Storyboard>\n </vsm:VisualState>\n <vsm:VisualState x:Name=\"MouseOver\" />\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\".5\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"Normal Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"MouseOver Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"Unfocused Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n <ColorAnimationUsingKeyFrames BeginTime=\"0\" Duration=\"0\" Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"0\" Value=\"#FFE1E7EC\" />\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n </vsm:VisualState>-->\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <localprimitives:DataGridFrozenGrid.RowDefinitions>\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"Auto\" />\n </localprimitives:DataGridFrozenGrid.RowDefinitions>\n <localprimitives:DataGridFrozenGrid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n </localprimitives:DataGridFrozenGrid.ColumnDefinitions>\n <Rectangle x:Name=\"BackgroundRectangle\" Grid.RowSpan=\"2\" Grid.ColumnSpan=\"2\" Opacity=\"0\" Fill=\"#FFBADDE9\" />\n <localprimitives:DataGridRowHeader Grid.RowSpan=\"3\" x:Name=\"RowHeader\" localprimitives:DataGridFrozenGrid.IsFrozen=\"True\" />\n\n <localprimitives:DataGridCellsPresenter x:Name=\"CellsPresenter\" localprimitives:DataGridFrozenGrid.IsFrozen=\"True\"/>\n\n <localprimitives:DataGridDetailsPresenter Grid.Row=\"1\" Grid.Column=\"1\" x:Name=\"DetailsPresenter\" />\n <Rectangle Grid.Row=\"2\" Grid.Column=\"1\" x:Name=\"BottomGridLine\" HorizontalAlignment=\"Stretch\" Height=\"1\" />\n </localprimitives:DataGridFrozenGrid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n <UserControl x:Class=\"DataGrid_Mouseover.Page\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" \n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\" \n xmlns:data=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data\" \n xmlns:local=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data\"\n xmlns:controls=\"clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Data\"\n xmlns:primitives=\"clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows\"\n xmlns:localprimitives=\"clr-namespace:System.Windows.Controls.Primitives;assembly=System.Windows.Controls.Data\"\n xmlns:vsm=\"clr-namespace:System.Windows;assembly=System.Windows\">\n<UserControl.Resources>\n\n <Style x:Key=\"CellStyle\" TargetType=\"local:DataGridCell\">\n\n <!-- TODO: Remove this workaround to force MouseLeftButtonDown event to be raised when root element is clicked. -->\n <Setter Property=\"Background\" Value=\"Transparent\" />\n <Setter Property=\"HorizontalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"VerticalContentAlignment\" Value=\"Stretch\" />\n <Setter Property=\"Cursor\" Value=\"Arrow\" />\n <Setter Property=\"IsTabStop\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"local:DataGridCell\">\n <Grid Name=\"Root\" Background=\"Transparent\">\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"CurrentStates\" >\n <vsm:VisualStateGroup.Transitions>\n <vsm:VisualTransition GeneratedDuration=\"0\" />\n </vsm:VisualStateGroup.Transitions>\n\n <vsm:VisualState x:Name=\"Regular\" />\n <vsm:VisualState x:Name=\"Current\" />\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"FocusVisual\" Storyboard.TargetProperty=\"Opacity\" To=\"1\" Duration=\"0\" />\n </Storyboard>\n </vsm:VisualState>-->\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <Grid.ColumnDefinitions>\n <ColumnDefinition Width=\"*\" />\n <ColumnDefinition Width=\"Auto\" />\n </Grid.ColumnDefinitions>\n <!-- TODO Refactor this if SL ever gets a FocusVisualStyle on FrameworkElement -->\n <Rectangle Name=\"FocusVisual\" Stroke=\"#FF6DBDD1\" StrokeThickness=\"1\" Fill=\"#66FFFFFF\" HorizontalAlignment=\"Stretch\" VerticalAlignment=\"Stretch\" IsHitTestVisible=\"false\" Opacity=\"0\" />\n <ContentPresenter Content=\"{TemplateBinding Content}\" ContentTemplate=\"{TemplateBinding ContentTemplate}\" Cursor=\"{TemplateBinding Cursor}\" HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\" Margin=\"{TemplateBinding Padding}\" />\n <Rectangle Name=\"RightGridLine\" Grid.Column=\"1\" VerticalAlignment=\"Stretch\" Width=\"1\" />\n </Grid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n\n <Style TargetType=\"local:DataGridRow\" x:Key=\"MyCustomRow\">\n <Setter Property=\"IsTabStop\" Value=\"False\" />\n <Setter Property=\"Template\">\n <Setter.Value>\n <ControlTemplate TargetType=\"local:DataGridRow\">\n <localprimitives:DataGridFrozenGrid x:Name=\"Root\">\n <localprimitives:DataGridFrozenGrid.Resources>\n <Storyboard x:Key=\"DetailsVisibleTransition\" >\n <DoubleAnimation Storyboard.TargetName=\"DetailsPresenter\" Storyboard.TargetProperty=\"ContentHeight\" Duration=\"00:00:0.1\" />\n </Storyboard>\n </localprimitives:DataGridFrozenGrid.Resources>\n <vsm:VisualStateManager.VisualStateGroups>\n <vsm:VisualStateGroup x:Name=\"CommonStates\" >\n <vsm:VisualState x:Name=\"Normal\" />\n <vsm:VisualState x:Name=\"Normal AlternatingRow\">\n <Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"0\" />\n </Storyboard>\n </vsm:VisualState>\n <vsm:VisualState x:Name=\"MouseOver\" />\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\".5\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"Normal Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"MouseOver Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n </Storyboard>\n </vsm:VisualState>-->\n <vsm:VisualState x:Name=\"Unfocused Selected\"/>\n <!--<Storyboard>\n <DoubleAnimation Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"Opacity\" Duration=\"0\" To=\"1\" />\n <ColorAnimationUsingKeyFrames BeginTime=\"0\" Duration=\"0\" Storyboard.TargetName=\"BackgroundRectangle\" Storyboard.TargetProperty=\"(Shape.Fill).(SolidColorBrush.Color)\">\n <SplineColorKeyFrame KeyTime=\"0\" Value=\"#FFE1E7EC\" />\n </ColorAnimationUsingKeyFrames>\n </Storyboard>\n </vsm:VisualState>-->\n </vsm:VisualStateGroup>\n </vsm:VisualStateManager.VisualStateGroups>\n <localprimitives:DataGridFrozenGrid.RowDefinitions>\n <RowDefinition Height=\"*\" />\n <RowDefinition Height=\"Auto\" />\n <RowDefinition Height=\"Auto\" />\n </localprimitives:DataGridFrozenGrid.RowDefinitions>\n <localprimitives:DataGridFrozenGrid.ColumnDefinitions>\n <ColumnDefinition Width=\"Auto\" />\n <ColumnDefinition Width=\"*\" />\n </localprimitives:DataGridFrozenGrid.ColumnDefinitions>\n <Rectangle x:Name=\"BackgroundRectangle\" Grid.RowSpan=\"2\" Grid.ColumnSpan=\"2\" Opacity=\"0\" Fill=\"#FFBADDE9\" />\n <localprimitives:DataGridRowHeader Grid.RowSpan=\"3\" x:Name=\"RowHeader\" localprimitives:DataGridFrozenGrid.IsFrozen=\"True\" />\n\n <localprimitives:DataGridCellsPresenter x:Name=\"CellsPresenter\" localprimitives:DataGridFrozenGrid.IsFrozen=\"True\"/>\n\n <localprimitives:DataGridDetailsPresenter Grid.Row=\"1\" Grid.Column=\"1\" x:Name=\"DetailsPresenter\" />\n <Rectangle Grid.Row=\"2\" Grid.Column=\"1\" x:Name=\"BottomGridLine\" HorizontalAlignment=\"Stretch\" Height=\"1\" />\n </localprimitives:DataGridFrozenGrid>\n </ControlTemplate>\n </Setter.Value>\n </Setter>\n </Style>\n</UserControl.Resources>\n\n<Grid x:Name=\"LayoutRoot\" Background=\"White\">\n <local:DataGrid x:Name=\"TestGrid\"\n HorizontalAlignment=\"Left\" \n VerticalAlignment=\"Bottom\" \n AutoGenerateColumns=\"False\"\n HeadersVisibility=\"None\"\n RowHeight=\"55\"\n Background=\"Transparent\"\n AlternatingRowBackground=\"Transparent\"\n RowBackground=\"Transparent\"\n BorderBrush=\"Transparent\"\n Foreground=\"Transparent\" \n GridLinesVisibility=\"None\" \n SelectionMode=\"Single\"\n CellStyle=\"{StaticResource CellStyle}\" \n RowStyle=\"{StaticResource MyCustomRow}\">\n\n <local:DataGrid.Columns>\n <local:DataGridTemplateColumn Header=\"Clinic\">\n <local:DataGridTemplateColumn.CellTemplate>\n <DataTemplate>\n <Button x:Name=\"btnClinic\" \n Height=\"46\" \n Width=\"580\" \n Content=\"{Binding Path=Description}\" \n Click=\"btnClinic_Click\"\n FontSize=\"24\"\n FontFamily=\"Tahoma\"\n FontWeight=\"Bold\">\n <Button.Background>\n <LinearGradientBrush EndPoint=\"0.528,1.144\" StartPoint=\"1.066,1.221\">\n <GradientStop Color=\"#FF000000\"/>\n <GradientStop Color=\"#FFEDC88F\" Offset=\"1\"/>\n </LinearGradientBrush>\n </Button.Background>\n </Button>\n </DataTemplate>\n </local:DataGridTemplateColumn.CellTemplate>\n </local:DataGridTemplateColumn>\n </local:DataGrid.Columns>\n </local:DataGrid>\n</Grid>\n</UserControl>\n Partial Public Class Page\nInherits UserControl\n\nPublic Sub New()\n InitializeComponent()\n Dim test As IList(Of String) = New List(Of String)\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n test.Add(\"test1\")\n\n TestGrid.ItemsSource = test\n\nEnd Sub\n\nPrivate Sub btnClinic_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)\n\nEnd Sub\nEnd Class\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23663/" ]
156,113
<p>I have some linq entities that inherit something like this:</p> <pre><code>public abstract class EntityBase { public int Identifier { get; } } public interface IDeviceEntity { int DeviceId { get; set; } } public abstract class DeviceEntityBase : EntityBase, IDeviceEntity { public abstract int DeviceId { get; set; } } public partial class ActualLinqGeneratedEntity : DeviceEntityBase { } </code></pre> <p>In a generic method I am querying DeviceEnityBase derived entities with:</p> <pre><code>return unitOfWork.GetRepository&lt;TEntity&gt;().FindOne(x =&gt; x.DeviceId == evt.DeviceId); </code></pre> <p>where TEntity has a contraint that is it a DeviceEntityBase. This query is always failing with an InvalidOperationException with the message "Class member DeviceEntityBase.DeviceId is unmapped". Even if I add some mapping info in the abstract base class with</p> <pre><code>[Column(Storage = "_DeviceId", DbType = "Int", Name = "DeviceId", IsDbGenerated = false, UpdateCheck = UpdateCheck.Never)] </code></pre>
[ { "answer_id": 156365, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "static Expression<Func<T, bool>> BuildWhere<T>(int deviceId) {\n var id = Expression.Constant(deviceId, typeof(int));\n var arg = Expression.Parameter(typeof(T), \"x\");\n var prop = Expression.Property(arg, \"DeviceId\");\n return Expression.Lambda<Func<T, bool>>(\n Expression.Equal(prop, id), arg);\n}\n" }, { "answer_id": 5070997, "author": "Shaul Behr", "author_id": 7850, "author_profile": "https://Stackoverflow.com/users/7850", "pm_score": 3, "selected": false, "text": "return unitOfWork.GetRepository<TEntity>().Select(x => x).FindOne(x => x.DeviceId == evt.DeviceId);\n" }, { "answer_id": 41870896, "author": "ViRuSTriNiTy", "author_id": 3936440, "author_profile": "https://Stackoverflow.com/users/3936440", "pm_score": 0, "selected": false, "text": ".OfType<>()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2281/" ]
156,114
<p>When paging through data that comes from a DB, you need to know how many pages there will be to render the page jump controls.</p> <p>Currently I do that by running the query twice, once wrapped in a <code>count()</code> to determine the total results, and a second time with a limit applied to get back just the results I need for the current page.</p> <p>This seems inefficient. Is there a better way to determine how many results would have been returned before <code>LIMIT</code> was applied?</p> <p>I am using PHP and Postgres.</p>
[ { "answer_id": 8242764, "author": "Erwin Brandstetter", "author_id": 939860, "author_profile": "https://Stackoverflow.com/users/939860", "pm_score": 8, "selected": true, "text": "SELECT foo\n , count(*) OVER() AS full_count\nFROM bar\nWHERE <some condition>\nORDER BY <some col>\nLIMIT <pagesize>\nOFFSET <offset>; full_count OFFSET LIMIT full_count OFFSET full_count SELECT WHERE JOIN GROUP BY SELECT OVER count(*) OVER() ORDER BY DISTINCT DISTINCT ON LIMIT OFFSET LIMIT OFFSET OFFSET LIMIT GET DIAGNOSTICS integer_var = ROW_COUNT;\n pg_num_rows" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156114", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20851/" ]
156,116
<p>I'm using CSS Filters to modify images on the fly within the browser. These work perfectly in Internet Explorer, but aren't supported in Firefox.</p> <p>Does anyone know what the CSS Filter equivalent for these is for Firefox? An answer that would work cross browser (Safari, WebKit, Firefox, etc.) would be preferred.</p> <pre><code>&lt;style type="text/css"&gt; .CSSClassName {filter:Invert;} .CSSClassName {filter:Xray;} .CSSClassName {filter:Gray;} .CSSClassName {filter:FlipV;} &lt;/style&gt; </code></pre> <p>Update: I know Filter is an IE specific feature. Is there any kind of equivalent for any of these that is supported by Firefox?</p>
[ { "answer_id": 156142, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "filter" }, { "answer_id": 156238, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 0, "selected": false, "text": "filter" }, { "answer_id": 26088245, "author": "aWebDeveloper", "author_id": 406659, "author_profile": "https://Stackoverflow.com/users/406659", "pm_score": 0, "selected": false, "text": "filter: <filter-function> [<filter-function>]* | none\n filter: url(svg-url#element-id)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7831/" ]
156,230
<p>Is there a framework equivalent to Guice (<a href="http://code.google.com/p/google-guice" rel="noreferrer">http://code.google.com/p/google-guice</a>) for Python?</p>
[ { "answer_id": 34346267, "author": "Aigrefin", "author_id": 1014321, "author_profile": "https://Stackoverflow.com/users/1014321", "pm_score": 0, "selected": false, "text": "from py3njection import inject\nfrom some_package import ClassToInject\n\nclass Demo:\n @inject\n def __init__(self, object_to_use: ClassToInject):\n self.dependency = object_to_use\n\ndemo = Demo()\n" }, { "answer_id": 35831886, "author": "Roman Mogylatov", "author_id": 4224605, "author_profile": "https://Stackoverflow.com/users/4224605", "pm_score": 2, "selected": false, "text": "\"\"\"Pythonic way for Dependency Injection.\"\"\"\n\nfrom dependency_injector import providers\nfrom dependency_injector import injections\n\n\n@providers.DelegatedCallable\ndef get_user_info(user_id):\n \"\"\"Return user info.\"\"\"\n raise NotImplementedError()\n\n\n@providers.Factory\n@injections.inject(get_user_info=get_user_info)\nclass AuthComponent(object):\n \"\"\"Some authentication component.\"\"\"\n\n def __init__(self, get_user_info):\n \"\"\"Initializer.\"\"\"\n self.get_user_info = get_user_info\n\n def authenticate_user(self, token):\n \"\"\"Authenticate user by token.\"\"\"\n user_info = self.get_user_info(user_id=token + '1')\n return user_info\n\n\nprint AuthComponent\nprint get_user_info\n\n\n@providers.override(get_user_info)\n@providers.DelegatedCallable\ndef get_user_info(user_id):\n \"\"\"Return user info.\"\"\"\n return {'user_id': user_id}\n\n\nprint AuthComponent().authenticate_user(token='abc')\n# {'user_id': 'abc1'}\n" }, { "answer_id": 47136116, "author": "Éttore Leandro Tognoli", "author_id": 8484999, "author_profile": "https://Stackoverflow.com/users/8484999", "pm_score": 1, "selected": false, "text": "import logging\nfrom logging import Logger\n\nfrom pycdi import Inject, Singleton, Producer\nfrom pycdi.shortcuts import call\n\n\n@Producer(str, _context='app_name')\ndef get_app_name():\n return 'PyCDI'\n\n\n@Singleton(produce_type=Logger)\n@Inject(app_name=str, _context='app_name')\ndef get_logger(app_name):\n return logging.getLogger(app_name)\n\n\n@Inject(name=(str, 'app_name'), logger=Logger)\ndef main(name, logger):\n logger.info('I\\'m starting...')\n print('Hello World!!!\\nI\\'m a example of %s' % name)\n logger.debug('I\\'m finishing...')\n\n\ncall(main)\n import logging\nfrom logging import Logger\n\nfrom pycdi import Inject, Singleton, Producer\nfrom pycdi.shortcuts import call\n\n\n@Producer(_context='app_name')\ndef get_app_name() -> str:\n return 'PyCDI'\n\n\n@Singleton()\n@Inject(logger_name='app_name')\ndef get_logger(logger_name: str) -> Logger:\n return logging.getLogger(logger_name)\n\n\n@Inject(name='app_name')\ndef main(name: str, logger: Logger):\n logger.info('I\\'m starting...')\n print('Hello World!!!\\nI\\'m a example of %s' % name)\n logger.debug('I\\'m finishing...')\n\n\ncall(main)\n" }, { "answer_id": 48965677, "author": "Rodrigo Oliveira", "author_id": 2468458, "author_profile": "https://Stackoverflow.com/users/2468458", "pm_score": 2, "selected": false, "text": "def foo(dep = None): # great for unit testing!\n ...\n # some_service.py\nclass SomeService:\n @autowired\n def __init__(\n self,\n database: Autowired(Database),\n message_brokers: Autowired(List[Broker]),\n ):\n pending = database.retrieve_pending_messages()\n for broker in message_brokers:\n broker.send_pending(pending)\n # database.py\n@injectable\nclass Database:\n ...\n # message_broker.py\nclass MessageBroker(ABC):\n def send_pending(messages):\n ...\n # kafka_producer.py\n@injectable\nclass KafkaProducer(MessageBroker):\n ...\n # sqs_producer.py\n@injectable\nclass SQSProducer(MessageBroker):\n ...\n" }, { "answer_id": 61826579, "author": "David", "author_id": 428640, "author_profile": "https://Stackoverflow.com/users/428640", "pm_score": 0, "selected": false, "text": "3.6 class MyObject:\n my_service: MyService = INJECTED\n my_config: str = INJECTED\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9940/" ]
156,243
<p>What is the difference between the following 2 ways to allocate and init an object?</p> <pre><code>AController *tempAController = [[AController alloc] init]; self.aController = tempAController; [tempAController release]; </code></pre> <p>and</p> <pre><code>self.aController= [[AController alloc] init]; </code></pre> <p>Most of the apple example use the first method. Why would you allocate, init and object and then release immediately?</p>
[ { "answer_id": 156289, "author": "benzado", "author_id": 10947, "author_profile": "https://Stackoverflow.com/users/10947", "pm_score": 7, "selected": true, "text": "@property (retain) alloc self setAController: retain release retain self.property = foo; [self setProperty:foo]; setProperty: @property (copy) @property (assign) self" }, { "answer_id": 156516, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "self.aController = [[[AController alloc] init] autorelease];\n" }, { "answer_id": 159069, "author": "Ashley Clark", "author_id": 4556, "author_profile": "https://Stackoverflow.com/users/4556", "pm_score": 2, "selected": false, "text": "@property (readwrite, retain) id aController; @property (readwrite, assign) id aController;" }, { "answer_id": 167783, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "self.aController= [[[AController alloc] init] autorelease];\n aController = [[AController alloc] init];\n AController *tempAController = [[AController alloc] init];\nself.aController = tempAController;\n[tempAController release];\n" }, { "answer_id": 1225254, "author": "mk12", "author_id": 148195, "author_profile": "https://Stackoverflow.com/users/148195", "pm_score": 2, "selected": false, "text": "@property (nonatomic, retain)AController *aController;\n...\nself.aController= [[AController alloc] init];\n[aController release];\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
156,256
<p>The sample below has two TextBoxes. The second TextBox has a handler for the LostFocus event which calls Clear() on itself. Changing focus between the two text boxes works fine; however, if the focus is on the second text box when the window is closed, TextBox.Clear() generates a NullReferenceException. Is this a bug in WPF? How can I easily detect this situation so I can avoid calling Clear() when the window is closing?</p> <p>Edit: Possibly relevant - The window is the application's main window. Test is not null at the time Clear() is called. The exception is thrown from somewhere within the call.</p> <pre><code>using System.Windows; namespace TextBoxClear { public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void Test_LostFocus(object sender, RoutedEventArgs e) { Test.Clear(); } } } &lt;Window x:Class="TextBoxClear.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"&gt; &lt;StackPanel&gt; &lt;TextBox /&gt; &lt;TextBox LostFocus="Test_LostFocus" Name="Test" /&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>Assembly references:</p> <ul> <li>mscorlib, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>PresentationCore, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>PresentationFramework, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> <li>System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</li> <li>WindowsBase, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35</li> </ul>
[ { "answer_id": 156277, "author": "Jason Anderson", "author_id": 5142, "author_profile": "https://Stackoverflow.com/users/5142", "pm_score": 2, "selected": false, "text": " private void Test_LostFocus(object sender, RoutedEventArgs e)\n {\n if (Test != null)\n Test.Clear();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,257
<p>In an AI application I am writing in C++, </p> <ol> <li>there is not much numerical computation </li> <li>there are lot of structures for which run-time polymorphism is needed </li> <li>very often, several polymorphic structures interact during computation</li> </ol> <p>In such a situation, are there any optimization techniques? While I won't care to optimize the application just now, one aspect of selecting C++ over Java for the project was to enable more leverage to optimize and to be able to use non-object oriented methods (templates, procedures, overloading). </p> <p>In particular, what are the optimization techniques related to virtual functions? Virtual functions are implemented through virtual tables in memory. Is there some way to pre-fetch these virtual tables onto L2 cache (the cost of fetching from memory/L2 cache is increasing)? </p> <p>Apart from this, are there good references for data locality techniques in C++? These techniques would reduce the wait time for data fetch into L2 cache needed for computation. </p> <p><em>Update</em>: Also see the following related forums: <a href="https://stackoverflow.com/questions/113830/performance-penalty-for-working-with-interfaces-in-c#171549">Performance Penalty for Interface</a>, <a href="https://stackoverflow.com/questions/99510/does-several-levels-of-base-classes-slow-down-a-classstruct-in-c">Several Levels of Base Classes</a> </p>
[ { "answer_id": 156420, "author": "loudej", "author_id": 6056, "author_profile": "https://Stackoverflow.com/users/6056", "pm_score": 6, "selected": true, "text": "classptr -> [vtable:4][classdata:x]\nvtable -> [first:4][second:4][third:4][fourth:4][...]\nfirst -> [code:x]\nsecond -> [code:x]\n...\n CONST SEGMENT\n??_7A@@6B@\n DD FLAT:?func1@A@@UAEXXZ\n DD FLAT:?func2@A@@UAEXXZ\n DD FLAT:?func3@A@@UAEXXZ\nCONST ENDS\n ; A* pa;\n; pa->func3();\nmov eax, DWORD PTR _pa$[ebp]\nmov edx, DWORD PTR [eax]\nmov ecx, DWORD PTR _pa$[ebp]\ncall DWORD PTR [edx+8]\n A* pa" }, { "answer_id": 157025, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 2, "selected": false, "text": "Class A {\n inline virtual int foo() {...}\n};\n class B : public A {\n inline virtual int foo() \n {\n //...do something different\n }\n\n void bar()\n {\n //logic...\n B::foo();\n // more logic\n }\n};\n foo() B foo()" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19501/" ]
156,275
<p>Is there a good reason why there is no <code>Pair&lt;L,R&gt;</code> in Java? What would be the equivalent of this C++ construct? I would rather avoid reimplementing my own.</p> <p>It seems that <strong>1.6</strong> is providing something similar (<code>AbstractMap.SimpleEntry&lt;K,V&gt;</code>), but this looks quite convoluted.</p>
[ { "answer_id": 156286, "author": "cletus", "author_id": 18393, "author_profile": "https://Stackoverflow.com/users/18393", "pm_score": 4, "selected": false, "text": "Map<String, Object> map = ... ; // just an example\nfor (Map.Entry<String, Object> entry : map.entrySet()) {\n System.out.printf(\"%s -> %s\\n\", entry.getKey(), entry.getValue());\n}\n" }, { "answer_id": 156685, "author": "Luc Touraille", "author_id": 20984, "author_profile": "https://Stackoverflow.com/users/20984", "pm_score": 10, "selected": true, "text": "comp.lang.java.help Pair Pair Pair Map.Entry Position(x,y) Range(begin,end) Entry(key,value) Pair(first,second)" }, { "answer_id": 677248, "author": "arturh", "author_id": 4186, "author_profile": "https://Stackoverflow.com/users/4186", "pm_score": 7, "selected": false, "text": "public class Pair<A, B> {\n private A first;\n private B second;\n\n public Pair(A first, B second) {\n super();\n this.first = first;\n this.second = second;\n }\n\n public int hashCode() {\n int hashFirst = first != null ? first.hashCode() : 0;\n int hashSecond = second != null ? second.hashCode() : 0;\n\n return (hashFirst + hashSecond) * hashSecond + hashFirst;\n }\n\n public boolean equals(Object other) {\n if (other instanceof Pair) {\n Pair otherPair = (Pair) other;\n return \n (( this.first == otherPair.first ||\n ( this.first != null && otherPair.first != null &&\n this.first.equals(otherPair.first))) &&\n ( this.second == otherPair.second ||\n ( this.second != null && otherPair.second != null &&\n this.second.equals(otherPair.second))) );\n }\n\n return false;\n }\n\n public String toString()\n { \n return \"(\" + first + \", \" + second + \")\"; \n }\n\n public A getFirst() {\n return first;\n }\n\n public void setFirst(A first) {\n this.first = first;\n }\n\n public B getSecond() {\n return second;\n }\n\n public void setSecond(B second) {\n this.second = second;\n }\n}\n" }, { "answer_id": 2192715, "author": "Illarion Kovalchuk", "author_id": 255667, "author_profile": "https://Stackoverflow.com/users/255667", "pm_score": 2, "selected": false, "text": "WeakHashMap<Pair<String, String>, String> map = ...\n" }, { "answer_id": 3646398, "author": "Peter Lawrey", "author_id": 57695, "author_profile": "https://Stackoverflow.com/users/57695", "pm_score": 5, "selected": false, "text": "public class Pair<FIRST, SECOND> implements Comparable<Pair<FIRST, SECOND>> {\n\n public final FIRST first;\n public final SECOND second;\n\n private Pair(FIRST first, SECOND second) {\n this.first = first;\n this.second = second;\n }\n\n public static <FIRST, SECOND> Pair<FIRST, SECOND> of(FIRST first,\n SECOND second) {\n return new Pair<FIRST, SECOND>(first, second);\n }\n\n @Override\n public int compareTo(Pair<FIRST, SECOND> o) {\n int cmp = compare(first, o.first);\n return cmp == 0 ? compare(second, o.second) : cmp;\n }\n\n // todo move this to a helper class.\n private static int compare(Object o1, Object o2) {\n return o1 == null ? o2 == null ? 0 : -1 : o2 == null ? +1\n : ((Comparable) o1).compareTo(o2);\n }\n\n @Override\n public int hashCode() {\n return 31 * hashcode(first) + hashcode(second);\n }\n\n // todo move this to a helper class.\n private static int hashcode(Object o) {\n return o == null ? 0 : o.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Pair))\n return false;\n if (this == obj)\n return true;\n return equal(first, ((Pair) obj).first)\n && equal(second, ((Pair) obj).second);\n }\n\n // todo move this to a helper class.\n private boolean equal(Object o1, Object o2) {\n return o1 == null ? o2 == null : (o1 == o2 || o1.equals(o2));\n }\n\n @Override\n public String toString() {\n return \"(\" + first + \", \" + second + ')';\n }\n}\n" }, { "answer_id": 4453599, "author": "MaxBuzz", "author_id": 543762, "author_profile": "https://Stackoverflow.com/users/543762", "pm_score": 3, "selected": false, "text": "operator < pair::operator < public class Pair<F, S> implements Comparable<Pair<? extends F, ? extends S>> {\n public final F first;\n public final S second;\n /* ... */\n public int compareTo(Pair<? extends F, ? extends S> that) {\n int cf = compare(first, that.first);\n return cf == 0 ? compare(second, that.second) : cf;\n }\n //Why null is decided to be less than everything?\n private static int compare(Object l, Object r) {\n if (l == null) {\n return r == null ? 0 : -1;\n } else {\n return r == null ? 1 : ((Comparable) (l)).compareTo(r);\n }\n }\n}\n\n/* ... */\n\nPair<Thread, HashMap<String, Integer>> a = /* ... */;\nPair<Thread, HashMap<String, Integer>> b = /* ... */;\n//Runtime error here instead of compile error!\nSystem.out.println(a.compareTo(b));\n public class Pair<\n F extends Comparable<? super F>, \n S extends Comparable<? super S>\n> implements Comparable<Pair<? extends F, ? extends S>> {\n public final F first;\n public final S second;\n /* ... */\n public int compareTo(Pair<? extends F, ? extends S> that) {\n int cf = compare(first, that.first);\n return cf == 0 ? compare(second, that.second) : cf;\n }\n //Why null is decided to be less than everything?\n private static <\n T extends Comparable<? super T>\n > int compare(T l, T r) {\n if (l == null) {\n return r == null ? 0 : -1;\n } else {\n return r == null ? 1 : l.compareTo(r);\n }\n }\n}\n\n/* ... */\n\n//Will not compile because Thread is not Comparable<? super Thread>\nPair<Thread, HashMap<String, Integer>> a = /* ... */;\nPair<Thread, HashMap<String, Integer>> b = /* ... */;\nSystem.out.println(a.compareTo(b));\n" }, { "answer_id": 4471509, "author": "Michael Piefel", "author_id": 2621917, "author_profile": "https://Stackoverflow.com/users/2621917", "pm_score": 6, "selected": false, "text": "@Data\n@AllArgsConstructor(staticName = \"of\")\npublic class Pair<F, S> {\n private F first;\n private S second;\n}\n hashCode equals toString" }, { "answer_id": 5734522, "author": "G_H", "author_id": 630136, "author_profile": "https://Stackoverflow.com/users/630136", "pm_score": 1, "selected": false, "text": "hashCode equals /**\n * The class <code>Pair</code> models a container for two objects wherein the\n * object order is of no consequence for equality and hashing. An example of\n * using Pair would be as the return type for a method that needs to return two\n * related objects. Another good use is as entries in a Set or keys in a Map\n * when only the unordered combination of two objects is of interest.<p>\n * The term \"object\" as being a one of a Pair can be loosely interpreted. A\n * Pair may have one or two <code>null</code> entries as values. Both values\n * may also be the same object.<p>\n * Mind that the order of the type parameters T and U is of no importance. A\n * Pair&lt;T, U> can still return <code>true</code> for method <code>equals</code>\n * called with a Pair&lt;U, T> argument.<p>\n * Instances of this class are immutable, but the provided values might not be.\n * This means the consistency of equality checks and the hash code is only as\n * strong as that of the value types.<p>\n */\npublic class Pair<T, U> implements Cloneable {\n\n /**\n * One of the two values, for the declared type T.\n */\n private final T object1;\n /**\n * One of the two values, for the declared type U.\n */\n private final U object2;\n private final boolean object1Null;\n private final boolean object2Null;\n private final boolean dualNull;\n\n /**\n * Constructs a new <code>Pair&lt;T, U&gt;</code> with T object1 and U object2 as\n * its values. The order of the arguments is of no consequence. One or both of\n * the values may be <code>null</code> and both values may be the same object.\n *\n * @param object1 T to serve as one value.\n * @param object2 U to serve as the other value.\n */\n public Pair(T object1, U object2) {\n\n this.object1 = object1;\n this.object2 = object2;\n object1Null = object1 == null;\n object2Null = object2 == null;\n dualNull = object1Null && object2Null;\n\n }\n\n /**\n * Gets the value of this Pair provided as the first argument in the constructor.\n *\n * @return a value of this Pair.\n */\n public T getObject1() {\n\n return object1;\n\n }\n\n /**\n * Gets the value of this Pair provided as the second argument in the constructor.\n *\n * @return a value of this Pair.\n */\n public U getObject2() {\n\n return object2;\n\n }\n\n /**\n * Returns a shallow copy of this Pair. The returned Pair is a new instance\n * created with the same values as this Pair. The values themselves are not\n * cloned.\n *\n * @return a clone of this Pair.\n */\n @Override\n public Pair<T, U> clone() {\n\n return new Pair<T, U>(object1, object2);\n\n }\n\n /**\n * Indicates whether some other object is \"equal\" to this one.\n * This Pair is considered equal to the object if and only if\n * <ul>\n * <li>the Object argument is not null,\n * <li>the Object argument has a runtime type Pair or a subclass,\n * </ul>\n * AND\n * <ul>\n * <li>the Object argument refers to this pair\n * <li>OR this pair's values are both null and the other pair's values are both null\n * <li>OR this pair has one null value and the other pair has one null value and\n * the remaining non-null values of both pairs are equal\n * <li>OR both pairs have no null values and have value tuples &lt;v1, v2> of\n * this pair and &lt;o1, o2> of the other pair so that at least one of the\n * following statements is true:\n * <ul>\n * <li>v1 equals o1 and v2 equals o2\n * <li>v1 equals o2 and v2 equals o1\n * </ul>\n * </ul>\n * In any other case (such as when this pair has two null parts but the other\n * only one) this method returns false.<p>\n * The type parameters that were used for the other pair are of no importance.\n * A Pair&lt;T, U> can return <code>true</code> for equality testing with\n * a Pair&lt;T, V> even if V is neither a super- nor subtype of U, should\n * the the value equality checks be positive or the U and V type values\n * are both <code>null</code>. Type erasure for parameter types at compile\n * time means that type checks are delegated to calls of the <code>equals</code>\n * methods on the values themselves.\n *\n * @param obj the reference object with which to compare.\n * @return true if the object is a Pair equal to this one.\n */\n @Override\n public boolean equals(Object obj) {\n\n if(obj == null)\n return false;\n\n if(this == obj)\n return true;\n\n if(!(obj instanceof Pair<?, ?>))\n return false;\n\n final Pair<?, ?> otherPair = (Pair<?, ?>)obj;\n\n if(dualNull)\n return otherPair.dualNull;\n\n //After this we're sure at least one part in this is not null\n\n if(otherPair.dualNull)\n return false;\n\n //After this we're sure at least one part in obj is not null\n\n if(object1Null) {\n if(otherPair.object1Null) //Yes: this and other both have non-null part2\n return object2.equals(otherPair.object2);\n else if(otherPair.object2Null) //Yes: this has non-null part2, other has non-null part1\n return object2.equals(otherPair.object1);\n else //Remaining case: other has no non-null parts\n return false;\n } else if(object2Null) {\n if(otherPair.object2Null) //Yes: this and other both have non-null part1\n return object1.equals(otherPair.object1);\n else if(otherPair.object1Null) //Yes: this has non-null part1, other has non-null part2\n return object1.equals(otherPair.object2);\n else //Remaining case: other has no non-null parts\n return false;\n } else {\n //Transitive and symmetric requirements of equals will make sure\n //checking the following cases are sufficient\n if(object1.equals(otherPair.object1))\n return object2.equals(otherPair.object2);\n else if(object1.equals(otherPair.object2))\n return object2.equals(otherPair.object1);\n else\n return false;\n }\n\n }\n\n /**\n * Returns a hash code value for the pair. This is calculated as the sum\n * of the hash codes for the two values, wherein a value that is <code>null</code>\n * contributes 0 to the sum. This implementation adheres to the contract for\n * <code>hashCode()</code> as specified for <code>Object()</code>. The returned\n * value hash code consistently remain the same for multiple invocations\n * during an execution of a Java application, unless at least one of the pair\n * values has its hash code changed. That would imply information used for \n * equals in the changed value(s) has also changed, which would carry that\n * change onto this class' <code>equals</code> implementation.\n *\n * @return a hash code for this Pair.\n */\n @Override\n public int hashCode() {\n\n int hashCode = object1Null ? 0 : object1.hashCode();\n hashCode += (object2Null ? 0 : object2.hashCode());\n return hashCode;\n\n }\n\n}\n" }, { "answer_id": 8444461, "author": "Bastiflew", "author_id": 1083225, "author_profile": "https://Stackoverflow.com/users/1083225", "pm_score": 0, "selected": false, "text": "public class Pair<K, V> {\n\n private final K element0;\n private final V element1;\n\n public static <K, V> Pair<K, V> createPair(K key, V value) {\n return new Pair<K, V>(key, value);\n }\n\n public Pair(K element0, V element1) {\n this.element0 = element0;\n this.element1 = element1;\n }\n\n public K getElement0() {\n return element0;\n }\n\n public V getElement1() {\n return element1;\n }\n\n}\n Pair<Integer, String> pair = Pair.createPair(1, \"test\");\npair.getElement0();\npair.getElement1();\n" }, { "answer_id": 9522297, "author": "cyberoblivion", "author_id": 1062131, "author_profile": "https://Stackoverflow.com/users/1062131", "pm_score": 5, "selected": false, "text": "Unit<A> (1 element)\nPair<A,B> (2 elements)\nTriplet<A,B,C> (3 elements)\nQuartet<A,B,C,D> (4 elements)\nQuintet<A,B,C,D,E> (5 elements)\nSextet<A,B,C,D,E,F> (6 elements)\nSeptet<A,B,C,D,E,F,G> (7 elements)\nOctet<A,B,C,D,E,F,G,H> (8 elements)\nEnnead<A,B,C,D,E,F,G,H,I> (9 elements)\nDecade<A,B,C,D,E,F,G,H,I,J> (10 elements)\n" }, { "answer_id": 13299709, "author": "Earth Engine", "author_id": 812034, "author_profile": "https://Stackoverflow.com/users/812034", "pm_score": 3, "selected": false, "text": "Pair interface Pair<L, R> {\n public L getL();\n public R getR();\n}\n ... //Calcuate the return value\nfinal Integer v1 = result1;\nfinal String v2 = result2;\nreturn new Pair<Integer, String>(){\n Integer getL(){ return v1; }\n String getR(){ return v2; }\n}\n Pair<L,R> PositionX PositionY Integer Pair<PositionX,PositionY> Pair<@PositionX Integer, @PositionY Ingeger> Pair getL class Pairs {\n static <L,R> Pair<L,R> makePair(final L l, final R r){\n return new Pair<L,R>(){\n public L getL() { return l; }\n public R getR() { return r; } \n };\n }\n}\n return Pairs.makePair(new Integer(100), \"123\");\n" }, { "answer_id": 13660918, "author": "Mr_and_Mrs_D", "author_id": 281545, "author_profile": "https://Stackoverflow.com/users/281545", "pm_score": 3, "selected": false, "text": "hashCode() public class Pair<A extends Comparable<? super A>,\n B extends Comparable<? super B>>\n implements Comparable<Pair<A, B>> {\n\n public final A first;\n public final B second;\n\n private Pair(A first, B second) {\n this.first = first;\n this.second = second;\n }\n\n public static <A extends Comparable<? super A>,\n B extends Comparable<? super B>>\n Pair<A, B> of(A first, B second) {\n return new Pair<A, B>(first, second);\n }\n\n @Override\n public int compareTo(Pair<A, B> o) {\n int cmp = o == null ? 1 : (this.first).compareTo(o.first);\n return cmp == 0 ? (this.second).compareTo(o.second) : cmp;\n }\n\n @Override\n public int hashCode() {\n return 31 * hashcode(first) + hashcode(second);\n }\n\n // TODO : move this to a helper class.\n private static int hashcode(Object o) {\n return o == null ? 0 : o.hashCode();\n }\n\n @Override\n public boolean equals(Object obj) {\n if (!(obj instanceof Pair))\n return false;\n if (this == obj)\n return true;\n return equal(first, ((Pair<?, ?>) obj).first)\n && equal(second, ((Pair<?, ?>) obj).second);\n }\n\n // TODO : move this to a helper class.\n private boolean equal(Object o1, Object o2) {\n return o1 == o2 || (o1 != null && o1.equals(o2));\n }\n\n @Override\n public String toString() {\n return \"(\" + first + \", \" + second + ')';\n }\n}\n Pair<?, ?> max(Comparable a, Comparable b)" }, { "answer_id": 14064648, "author": "Andrew Mao", "author_id": 586086, "author_profile": "https://Stackoverflow.com/users/586086", "pm_score": 0, "selected": false, "text": "Pair Table<R,C,V> Table<Vertex, Vertex, Double> weightedGraph = HashBasedTable.create();\nweightedGraph.put(v1, v2, 4);\nweightedGraph.put(v1, v3, 20);\nweightedGraph.put(v2, v3, 5);\n\nweightedGraph.row(v1); // returns a Map mapping v2 to 4, v3 to 20\nweightedGraph.column(v3); // returns a Map mapping v1 to 20, v2 to 5\n Table Map<Pair<K1,K2>, V>" }, { "answer_id": 15468967, "author": "Swapneel Patil", "author_id": 251769, "author_profile": "https://Stackoverflow.com/users/251769", "pm_score": 2, "selected": false, "text": "public class Pair<First,Second>{.. }\n" }, { "answer_id": 23468362, "author": "sherpya", "author_id": 764426, "author_profile": "https://Stackoverflow.com/users/764426", "pm_score": 4, "selected": false, "text": "Pair public class Pair<F, S> {\n public final F first;\n public final S second;\n\n public Pair(F first, S second) {\n this.first = first;\n this.second = second;\n }\n\n @Override\n public boolean equals(Object o) {\n if (!(o instanceof Pair)) {\n return false;\n }\n Pair<?, ?> p = (Pair<?, ?>) o;\n return Objects.equal(p.first, first) && Objects.equal(p.second, second);\n }\n\n @Override\n public int hashCode() {\n return (first == null ? 0 : first.hashCode()) ^ (second == null ? 0 : second.hashCode());\n }\n\n public static <A, B> Pair <A, B> create(A a, B b) {\n return new Pair<A, B>(a, b);\n }\n}\n" }, { "answer_id": 33282633, "author": "Lukas Eder", "author_id": 521799, "author_profile": "https://Stackoverflow.com/users/521799", "pm_score": 2, "selected": false, "text": "Pair" }, { "answer_id": 34976779, "author": "RAJAN_PARMAR", "author_id": 3812854, "author_profile": "https://Stackoverflow.com/users/3812854", "pm_score": 3, "selected": false, "text": "javafx.util.Pair Pair <Key, Value> \n Pair <Integer, Integer> pr = new Pair<Integer, Integer>()\n\npr.get(key);// will return corresponding value\n" }, { "answer_id": 35036111, "author": "Dominik", "author_id": 4465567, "author_profile": "https://Stackoverflow.com/users/4465567", "pm_score": 0, "selected": false, "text": "@Value(staticConstructor = \"of\") public class Pair <E> {\n E first, second;\n}\n Pair<Value> pairOfValues = Pair.of(value1, value2);" }, { "answer_id": 35358753, "author": "Denis Arkharov", "author_id": 5917590, "author_profile": "https://Stackoverflow.com/users/5917590", "pm_score": 2, "selected": false, "text": "Collections.singletonMap(left, rigth);\n" }, { "answer_id": 36493674, "author": "Sathyanarayanan Ganesan", "author_id": 4700500, "author_profile": "https://Stackoverflow.com/users/4700500", "pm_score": 3, "selected": false, "text": "Pair" }, { "answer_id": 45154057, "author": "Bill K", "author_id": 12943, "author_profile": "https://Stackoverflow.com/users/12943", "pm_score": 0, "selected": false, "text": "class SumHolder{MyObject trackedObject, double sum};\n" }, { "answer_id": 53380628, "author": "Matt Broekhuis", "author_id": 412366, "author_profile": "https://Stackoverflow.com/users/412366", "pm_score": 2, "selected": false, "text": "import lombok.Value;\n\n@Value(staticConstructor = \"of\")\npublic class Pair<F, S> {\n private final F first;\n private final S second;\n}\n" }, { "answer_id": 66396046, "author": "Arefe", "author_id": 2746110, "author_profile": "https://Stackoverflow.com/users/2746110", "pm_score": 0, "selected": false, "text": "Pair<S, T> pair = Pair.of(S type data, T type data)\n" }, { "answer_id": 69213294, "author": "HomeworkHopper", "author_id": 10334839, "author_profile": "https://Stackoverflow.com/users/10334839", "pm_score": 0, "selected": false, "text": "record Pair<K, V>(K key, V value) { }\n // Declare a pair object containing two integers\nvar integerIntegerPair = new Pair<>(1, 2);\n\n// Declare a pair object containing a String and an integer\nvar stringIntegerPair = new Pair<>(\"String\", 20);\n\n// Declare a pair object containing two other pairs!\nvar pairPairPair = new Pair<>(new Pair<>(1, 2), new Pair<>(\"String\", 20));\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156275", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13673/" ]
156,278
<p>Yet again, my teacher was unable to answer my question. I knew who may be able to...</p> <p>So, I've never really learned C. In C++, I would, obviously, use a cout statement all of the time. In a recent assignment, my teacher told us to make sure to put </p> <pre><code>setbuf( stdout , NULL ); </code></pre> <p>at the top of main() in order to get an unbuffered output, thus allowing us to see the output properly.</p> <p>My question is this: will this statement affect a cout statement, or simply a printf() statement that I call? </p> <p>Thanks in advance!</p>
[ { "answer_id": 156321, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "std::endl std::flush <ostream> std::cout << \"Hello, world!\" << std::endl;\n std::cout << \"Hello, world!\\n\" << std::flush;\n std::endl" }, { "answer_id": 156413, "author": "Greg Rogers", "author_id": 5963, "author_profile": "https://Stackoverflow.com/users/5963", "pm_score": 3, "selected": false, "text": "// make cout unbuffered\nstd::cout.rdbuf()->pubsetbuf(0, 0);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/73/" ]
156,279
<p>The title is self explanatory. Is there a way of directly doing such kind of importing?</p>
[ { "answer_id": 156479, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 7, "selected": true, "text": "sqlcmd -S <COMPUTERNAME>\\SQLExpress restore filelistonly from disk='c:\\temp\\mydbName-2009-09-29-v10.bak';\nGO\n RESTORE DATABASE mydbName FROM disk='c:\\temp\\mydbName-2009-09-29-v10.bak'\nWITH \n MOVE 'mydbName' TO 'c:\\temp\\mydbName_data.mdf', \n MOVE 'mydbName_log' TO 'c:\\temp\\mydbName_data.ldf';\nGO\n" }, { "answer_id": 7179605, "author": "Andrew", "author_id": 561698, "author_profile": "https://Stackoverflow.com/users/561698", "pm_score": 1, "selected": false, "text": "MOVE 'mydbName_log' TO 'c:\\temp\\mydbName_data.ldf',\nMOVE 'sysft_...' TO 'c:\\temp\\other';\n" }, { "answer_id": 59558734, "author": "INDRAJITH EKANAYAKE", "author_id": 8134164, "author_profile": "https://Stackoverflow.com/users/8134164", "pm_score": 3, "selected": false, "text": "MsSQL MySQL .bak MsSQL .sql MySQL .bak" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/131/" ]
156,280
<p>When using mercurial, I'd like to be able to diff the working copy of a file with the tip file in my default remote repository. Is there an easy way to do this?</p> <p>I know I can do an "hg incoming -p" to see the patch sets of changes coming in, but it'd be nice to just directly see the actual changes for a particular file that I'd get if I do a pull of the latest stuff (or what I might be about put push out).</p> <p>The easiest thing I can think of right now is to create a little script that takes a look at the default location in .hg/hgrc and downloads the file using curl (if it's over http, otherwise scp it over ssh, or just do a direct diff if it's on the local file system) and then to diff the working copy or the tip against that temporary copy.</p> <p>I'm trying to sell mercurial to my team, and one of my team members brought this up today as something that they're able to do easily in SVN with their GUI tools.</p>
[ { "answer_id": 157642, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "-R diff hg" }, { "answer_id": 164566, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 4, "selected": true, "text": "hg clone http://hg.kublai.com/mercurial/extensions/rdiff \n [extensions] \nrdiff=~/path/to/rdiff/repo/rdiff.py\n hgrdiff() {\n hg commit -m \"temp commit for remote diff\" && \n hg diff --reverse http://my_hardcoded_repo $* &&\n hg rollback # revert the temporary commit\n}\n hgrdiff <filename to diff against remote repo tip>\n" }, { "answer_id": 3367041, "author": "Ton Plomp", "author_id": 47860, "author_profile": "https://Stackoverflow.com/users/47860", "pm_score": 0, "selected": false, "text": "hg incoming --template {files}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8912/" ]
156,292
<p>I'm a bit of a DI newbie, so forgive me if this is the wrong approach or a silly question.</p> <p>Let's say I have a form which creates/updates an order, and I know it's going to need to retrieve a list of products and customers to display. I want to pass in the Order object that it's editing, but I also want to inject the ProductsService and CustomersService as dependencies. </p> <p>So I will want my IoC container (whichever one I go with) to supply the services, but it'll be up to the calling code to supply the Order object to edit.</p> <p>Should I declare the constructor as taking the Order object as the first parameter and the ProductsService and CustomersService after that, eg:</p> <pre><code>public OrderForm(Order order, ProductsService prodsSvc, CustomersService custsSvc) </code></pre> <p>... or should the dependencies come first and the Order object last, eg:</p> <pre><code>public OrderForm(ProductsService prodsSvc, CustomersService custsSvc, Order order) </code></pre> <p>Does it matter? Does it depend on which IoC container I use? Or is there a "better" way?</p>
[ { "answer_id": 63869152, "author": "Efran Cobisi", "author_id": 904178, "author_profile": "https://Stackoverflow.com/users/904178", "pm_score": 0, "selected": false, "text": "*Service Build() Order public class OrderFormFactory\n{\n private readonly ProductsService _prodsSvc;\n private readonly CustomersService _custsSvc;\n\n public OrderFormFactory(ProductsService prodsSvc, CustomersService custsSvc)\n {\n _prodsService = prodsService ?? throw new ArgumentNullException(nameof(prodsService));\n _custsSvc = custsSvc ?? throw new ArgumentNullException(nameof(custsSvc));\n }\n\n public OrderForm Build(Order order)\n {\n // TODO: Any additional logic\n\n return new OrderForm(_prodsService, _custsSvc, order);\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156292", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
156,322
<p>fossil <a href="http://www.fossil-scm.org" rel="noreferrer">http://www.fossil-scm.org</a><br> I found this recently and have started using it for my home projects. I want to hear what other people think of this VCS. </p> <p>What is missing in my mind, is IDE support. Hopefully it will come, but I use the command line just fine.</p> <p>My favorite things about fossil: single executable with built in web server wiki and bug tracking. The repository is just one SQLite (<a href="http://www.sqlite.org" rel="noreferrer">http://www.sqlite.org</a>) database file, easy to do backups on. I also like that I can run fossil from and keep the repository on my thumb drive. This means my software development has become completely portable. </p> <p>Tell me what you think....</p>
[ { "answer_id": 265829, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "for /r %i in (*.*) do fossil add \"%i\"\n find . -type f -print0 | xargs -0 fossil add --\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156322", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3576/" ]
156,329
<p>I need to pad numbers with leading zeros (total 8 digits) for display. I'm using oracle.</p> <pre><code>select to_char(1011,'00000000') OPE_NO from dual; select length(to_char(1011,'00000000')) OPE_NO from dual; </code></pre> <p>Instead of '00001011' I get ' 00001011'. Why do I get an extra leading blank space? What is the correct number formatting string to accomplish this?</p> <p>P.S. I realise I can just use <code>trim()</code>, but I want to understand number formatting better.</p> <p>@Eddie: I already read the documentation. And yet I still don't understand how to get rid of the leading whitespace. </p> <p>@David: So does that mean there's no way but to use <code>trim()</code>?</p>
[ { "answer_id": 156670, "author": "Steve Bosman", "author_id": 4389, "author_profile": "https://Stackoverflow.com/users/4389", "pm_score": 6, "selected": true, "text": "select to_char(1011,'FM00000000') OPE_NO from dual;" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3751/" ]
156,330
<p>I'm just trying to time a piece of code. The pseudocode looks like:</p> <pre><code>start = get_ticks() do_long_code() print "It took " + (get_ticks() - start) + " seconds." </code></pre> <p>How does this look in Python?</p> <p>More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?</p>
[ { "answer_id": 156335, "author": "blackwing", "author_id": 9107, "author_profile": "https://Stackoverflow.com/users/9107", "pm_score": 5, "selected": false, "text": "time() time import time\nstart = time.time()\ndo_long_code()\nprint \"it took\", time.time() - start, \"seconds.\"\n" }, { "answer_id": 156339, "author": "Harley Holcombe", "author_id": 1057, "author_profile": "https://Stackoverflow.com/users/1057", "pm_score": 2, "selected": false, "text": "import datetime\n\nstart = datetime.datetime.now()\ndo_long_code()\nfinish = datetime.datetime.now()\ndelta = finish - start\nprint delta.seconds\n import datetime\n\nmidnight = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)\nnow = datetime.datetime.now()\ndelta = now - midnight\nprint delta.seconds\n" }, { "answer_id": 157423, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 6, "selected": true, "text": "time time clock time clock clock clock clock Timer time.perf_counter() time.process_time() perf_counter timeit" }, { "answer_id": 13300640, "author": "leetNightshade", "author_id": 353094, "author_profile": "https://Stackoverflow.com/users/353094", "pm_score": 3, "selected": false, "text": "class Timer:\n def __enter__(self):\n self.begin = now()\n\n def __exit__(self, type, value, traceback):\n print(format_delta(self.begin, now()))\n with Timer():\n do_long_code()\n import datetime\n\ndef now():\n return datetime.datetime.now()\n\n# Prints one of the following formats*:\n# 1.58 days\n# 2.98 hours\n# 9.28 minutes # Not actually added yet, oops.\n# 5.60 seconds\n# 790 milliseconds\n# *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. \ndef format_delta(start,end):\n\n # Time in microseconds\n one_day = 86400000000\n one_hour = 3600000000\n one_second = 1000000\n one_millisecond = 1000\n\n delta = end - start\n\n build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day\n\n days = 0\n while build_time_us > one_day:\n build_time_us -= one_day\n days += 1\n\n if days > 0:\n time_str = \"%.2fd\" % ( days + build_time_us / float(one_day) )\n else:\n hours = 0\n while build_time_us > one_hour:\n build_time_us -= one_hour\n hours += 1\n if hours > 0:\n time_str = \"%.2fh\" % ( hours + build_time_us / float(one_hour) )\n else:\n seconds = 0\n while build_time_us > one_second:\n build_time_us -= one_second\n seconds += 1\n if seconds > 0:\n time_str = \"%.2fs\" % ( seconds + build_time_us / float(one_second) )\n else:\n ms = 0\n while build_time_us > one_millisecond:\n build_time_us -= one_millisecond\n ms += 1\n time_str = \"%.2fms\" % ( ms + build_time_us / float(one_millisecond) )\n return time_str\n" }, { "answer_id": 35675299, "author": "Mark", "author_id": 723090, "author_profile": "https://Stackoverflow.com/users/723090", "pm_score": 0, "selected": false, "text": "class Ticker:\n def __init__(self):\n self.t = clock()\n\n def __call__(self):\n dt = clock() - self.t\n self.t = clock()\n return 1000 * dt\n tick = Ticker()\n# first command\nprint('first took {}ms'.format(tick())\n# second group of commands\nprint('second took {}ms'.format(tick())\n# third group of commands\nprint('third took {}ms'.format(tick())\n t = time() 1000 * (time() - t) Ticket" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/432/" ]
156,331
<p>I was inserting data into a MS Access database using JDBC-ODBC driver. The blank mdb file was 2KB. After populating this database, the size grew to 155MB. Then I was deleting the data. But I found the size of mdb remains the same as 155MB. I don't get any errors. But is it normal this way? I would expect the file size reduces. If it is designed in this way, what is the idea behind it? Thanks</p>
[ { "answer_id": 156346, "author": "Jon Cahill", "author_id": 10830, "author_profile": "https://Stackoverflow.com/users/10830", "pm_score": 5, "selected": false, "text": "msaccess.exe \"target database.accdb\" /compact \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24020/" ]
156,360
<p>I have one thread that writes results into a Queue.</p> <p>In another thread (GUI), I periodically (in the IDLE event) check if there are results in the queue, like this:</p> <pre><code>def queue_get_all(q): items = [] while 1: try: items.append(q.get_nowait()) except Empty, e: break return items </code></pre> <p>Is this a good way to do it ? </p> <p><strong>Edit:</strong></p> <blockquote> <p>I'm asking because sometimes the waiting thread gets stuck for a few seconds without taking out new results.</p> </blockquote> <p>The "stuck" problem turned out to be because I was doing the processing in the idle event handler, without making sure that such events are actually generated by calling <code>wx.WakeUpIdle</code>, as is recommended.</p>
[ { "answer_id": 156564, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "from __future__ import with_statement\nimport threading\n\nclass ItemStore(object):\n def __init__(self):\n self.lock = threading.Lock()\n self.items = []\n\n def add(self, item):\n with self.lock:\n self.items.append(item)\n\n def getAll(self):\n with self.lock:\n items, self.items = self.items, []\n return items\n class ItemStore(object):\n def __init__(self):\n self.cond = threading.Condition()\n self.items = []\n\n def add(self, item):\n with self.cond:\n self.items.append(item)\n self.cond.notify() # Wake 1 thread waiting on cond (if any)\n\n def getAll(self, blocking=False):\n with self.cond:\n # If blocking is true, always return at least 1 item\n while blocking and len(self.items) == 0:\n self.cond.wait()\n items, self.items = self.items, []\n return items\n" }, { "answer_id": 156736, "author": "Jon Cage", "author_id": 15369, "author_profile": "https://Stackoverflow.com/users/15369", "pm_score": 4, "selected": true, "text": "get_nowait() Queue def queue_get_all(q):\n items = []\n maxItemsToRetrieve = 10\n for numOfItemsRetrieved in range(0, maxItemsToRetrieve):\n try:\n if numOfItemsRetrieved == maxItemsToRetrieve:\n break\n items.append(q.get_nowait())\n except Empty, e:\n break\n return items\n" }, { "answer_id": 25768255, "author": "Gab", "author_id": 768335, "author_profile": "https://Stackoverflow.com/users/768335", "pm_score": 4, "selected": false, "text": "def get_all_queue_result(queue):\n\n result_list = []\n while not queue.empty():\n result_list.append(queue.get())\n\n return result_list\n" }, { "answer_id": 28571101, "author": "Wraith404", "author_id": 809268, "author_profile": "https://Stackoverflow.com/users/809268", "pm_score": 2, "selected": false, "text": "responseList = []\nfor items in range(0, q.qsize()):\n responseList.append(q.get_nowait())\n" }, { "answer_id": 55519286, "author": "EvertW", "author_id": 1767653, "author_profile": "https://Stackoverflow.com/users/1767653", "pm_score": 3, "selected": false, "text": "items = [q.get() for _ in range(q.qsize())]\n range" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
156,362
<p>Just getting my head around Ruby metaprogramming. The mixin/modules always manage to confuse me. </p> <ul> <li><strong>include</strong>: mixes in specified module methods as <strong>instance methods</strong> in the target class</li> <li><strong>extend</strong>: mixes in specified module methods as <strong>class methods</strong> in the target class</li> </ul> <p><em>So is the major difference just this or is a bigger dragon lurking?</em> e.g.</p> <pre><code>module ReusableModule def module_method puts "Module Method: Hi there!" end end class ClassThatIncludes include ReusableModule end class ClassThatExtends extend ReusableModule end puts "Include" ClassThatIncludes.new.module_method # "Module Method: Hi there!" puts "Extend" ClassThatExtends.module_method # "Module Method: Hi there!" </code></pre>
[ { "answer_id": 156927, "author": "domgblackwell", "author_id": 16954, "author_profile": "https://Stackoverflow.com/users/16954", "pm_score": 9, "selected": true, "text": "Klazz Mod Mod Klazz Klazz Mod Klazz Mod Klazz Mod o.extend Mod Mod o" }, { "answer_id": 5008349, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 9, "selected": false, "text": "Klazz.extend(Mod) obj.extend(Mod) obj.class extend class Klazz; include Mod; end; include include included include class Klazz\n include Mod\nend\n @@foo @@bar super #include #included #extend #extended #extend_object #append_features" }, { "answer_id": 36247164, "author": "user1136228", "author_id": 1136228, "author_profile": "https://Stackoverflow.com/users/1136228", "pm_score": 2, "selected": false, "text": "include class A\ninclude MyMOd\nend\n\na = A.new\na.some_method\n a some_method some_method a A A extend a' A' a" }, { "answer_id": 58022371, "author": "Chintan", "author_id": 6543250, "author_profile": "https://Stackoverflow.com/users/6543250", "pm_score": 4, "selected": false, "text": "include extend Module_test module Module_test\n def func\n puts \"M - in module\"\n end\nend\n include A class A\n include Module_test\nend\n\na = A.new\na.func\n M - in module include Module_test extend Module_test undefined method 'func' for #<A:instance_num> (NoMethodError) a.func A.func M - in module include extend" }, { "answer_id": 70124407, "author": "Abdullah Numan", "author_id": 4515413, "author_profile": "https://Stackoverflow.com/users/4515413", "pm_score": 1, "selected": false, "text": "include extend prepend include extend" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
156,369
<p>It seems quite a few mainstream languages support <a href="http://en.wikipedia.org/wiki/First-class_function" rel="noreferrer">function literals</a> these days. They are also called <a href="http://en.wikipedia.org/wiki/Anonymous_function" rel="noreferrer">anonymous functions</a>, but I don't care if they have a name. The important thing is that a function literal is an expression which yields a function which hasn't already been defined elsewhere, so for example in C, <code>&amp;printf</code> doesn't count.</p> <p>EDIT to add: if you have a genuine function literal expression <code>&lt;exp&gt;</code>, you should be able to pass it to a function <code>f(&lt;exp&gt;)</code> or immediately apply it to an argument, ie. <code>&lt;exp&gt;(5)</code>. </p> <p>I'm curious which languages let you write function literals which are <em>recursive</em>. Wikipedia's "<a href="http://en.wikipedia.org/wiki/Anonymous_recursion" rel="noreferrer">anonymous recursion</a>" article doesn't give any programming examples.</p> <p>Let's use the recursive factorial function as the example.</p> <p>Here are the ones I know:</p> <ul> <li><p>JavaScript / ECMAScript can do it with <code>callee</code>:</p> <pre><code>function(n){if (n&lt;2) {return 1;} else {return n * arguments.callee(n-1);}} </code></pre></li> <li><p>it's easy in languages with <code>letrec</code>, eg Haskell (which calls it <code>let</code>):</p> <blockquote> <p><code>let fac x = if x&lt;2 then 1 else fac (x-1) * x in fac</code></p> </blockquote> <p>and there are equivalents in Lisp and Scheme. Note that the binding of <code>fac</code> is local to the expression, so the whole expression is in fact an anonymous function.</p></li> </ul> <p>Are there any others?</p>
[ { "answer_id": 156374, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 2, "selected": false, "text": "labels letrec var foo = {\"bar\": function baz() {return baz() + 1;}};\n callee function" }, { "answer_id": 156393, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 4, "selected": false, "text": "# Define Y combinator...come on Gudio, put it in functools!\nY = lambda g: (lambda f: g(lambda arg: f(f)(arg))) (lambda f: g(lambda arg: f(f)(arg)))\n\n# Define anonymous recursive factorial function\nfac = Y(lambda f: lambda n: (1 if n<2 else n*f(n-1)))\nassert fac(7) == 5040\n" }, { "answer_id": 156409, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 3, "selected": false, "text": "my $factorial = do {\n my $fac;\n $fac = sub {\n my $n = shift;\n if ($n < 2) { 1 } else { $n * $fac->($n-1) }\n };\n};\n\nprint $factorial->(4);\n do" }, { "answer_id": 156426, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "Func<int, int> fac = null;\nfac = n => n < 2 ? 1 : n * fac(n-1);\nConsole.WriteLine(fac(7));\n tail. fac fac" }, { "answer_id": 156444, "author": "helloandre", "author_id": 50, "author_profile": "https://Stackoverflow.com/users/50", "pm_score": 0, "selected": false, "text": "(labels ((factorial (x) ;define name and params\n ; body of function addrec\n (if (= x 1)\n (return 1)\n (+ (factorial (- x 1))))) ;should not close out labels\n ;call factorial inside labels function\n (factorial 5)) ;this would return 15 from labels\n" }, { "answer_id": 156468, "author": "FryHard", "author_id": 231, "author_profile": "https://Stackoverflow.com/users/231", "pm_score": 3, "selected": false, "text": "delegate Func<A, R> Recursive<A, R>(Recursive<A, R> r);\n\nstatic Func<A, R> Y<A, R>(Func<Func<A, R>, Func<A, R>> f)\n{\n Recursive<A, R> rec = r => a => f(r(r))(a);\n return rec(rec);\n}\n\nstatic void Main(string[] args)\n{\n Func<int,int> fib = Y<int,int>(f => n => n > 1 ? f(n - 1) + f(n - 2) : n);\n Func<int, int> fact = Y<int, int>(f => n => n > 1 ? n * f(n - 1) : 1);\n Console.WriteLine(fib(6)); // displays 8\n Console.WriteLine(fact(6));\n Console.ReadLine();\n} \n" }, { "answer_id": 156555, "author": "Toon Krijthe", "author_id": 18061, "author_profile": "https://Stackoverflow.com/users/18061", "pm_score": 0, "selected": false, "text": "type\n // method reference\n TProc = reference to procedure(x: Integer); \n\nprocedure Call(const proc: TProc);\nbegin\n proc(42);\nend;\n var\n proc: TProc;\nbegin\n // anonymous method\n proc := procedure(a: Integer)\n begin\n Writeln(a);\n end; \n\n Call(proc);\n readln\nend.\n" }, { "answer_id": 156655, "author": "Daniel James", "author_id": 2434, "author_profile": "https://Stackoverflow.com/users/2434", "pm_score": 2, "selected": false, "text": "foo(function(n){if (n<2) {return 1;} else {return n * arguments.callee(n-1);}});\n foo(function fac(n){if (n<2) {return 1;} else {return n * fac(n-1);}});\n" }, { "answer_id": 171023, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 2, "selected": false, "text": "my $f = -> $n { if ($n <= 1) {1} else {$n * &?BLOCK($n - 1)} }\n$f(42); # ==> 1405006117752879898543142606244511569936384000000000\n" }, { "answer_id": 642890, "author": "gnovice", "author_id": 52738, "author_profile": "https://Stackoverflow.com/users/52738", "pm_score": 0, "selected": false, "text": ">> fact = @(val,branchFcns) val*branchFcns{(val <= 1)+1}(val-1,branchFcns);\n>> returnOne = @(val,branchFcns) 1;\n>> branchFcns = {fact returnOne};\n>> fact(4,branchFcns)\n\nans =\n\n 24\n\n>> fact(5,branchFcns)\n\nans =\n\n 120\n" }, { "answer_id": 1675978, "author": "Andrew Janke", "author_id": 105904, "author_profile": "https://Stackoverflow.com/users/105904", "pm_score": 1, "selected": false, "text": "f = @(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1)\n >> f(-1)\n??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)\nto change the limit. Be aware that exceeding your available stack space can\ncrash MATLAB and/or your computer.\n >> feval(@(x) ~x || feval(str2func(getfield(dbstack, 'name')), x-1), -1)\n??? Maximum recursion limit of 500 reached. Use set(0,'RecursionLimit',N)\nto change the limit. Be aware that exceeding your available stack space can\ncrash MATLAB and/or your computer.\n\nError in ==> create@(x)~x||feval(str2func(getfield(dbstack,'name')),x-1)\n function out = basecase_or_feval(cond, baseval, fcn, args, accumfcn)\n%BASECASE_OR_FEVAL Return base case value, or evaluate next step\nif cond\n out = baseval;\nelse\n out = feval(accumfcn, feval(fcn, args{:}));\nend\n recursive_factorial = @(x) basecase_or_feval(x < 2,...\n 1,...\n str2func(getfield(dbstack, 'name')),...\n {x-1},...\n @(z)x*z);\n >> feval( @(x) basecase_or_feval(x < 2, 1, str2func(getfield(dbstack, 'name')), {x-1}, @(z)x*z), 5)\nans =\n 120\n" }, { "answer_id": 2858779, "author": "Puppy", "author_id": 298661, "author_profile": "https://Stackoverflow.com/users/298661", "pm_score": 0, "selected": false, "text": "auto kek = [](){kek();}\n" }, { "answer_id": 2870453, "author": "Zorf", "author_id": 2281094, "author_profile": "https://Stackoverflow.com/users/2281094", "pm_score": 0, "selected": false, "text": "(define-syntax lambdarec\n (syntax-rules ()\n ((lambdarec (tag . params) . body)\n ((lambda ()\n (define (tag . params) . body)\n tag)))))\n (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1)))))\n (let ;no letrec used\n ((factorial (lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1)))))))\n (factorial 4)) ; ===> 24\n ((lambdarec (f n) (if (<= n 0) 1 (* n (f (- n 1))))) 4)\n (f 4)\n \\n -> let fac x = if x<2 then 1 else fac (x-1) * x\n in fac n\n 3;\n" }, { "answer_id": 6949191, "author": "Mechanical snail", "author_id": 319931, "author_profile": "https://Stackoverflow.com/users/319931", "pm_score": 1, "selected": false, "text": "#0 (expression[#0]) &\n fac = Piecewise[{{1, #1 == 0}, {#1 * #0[#1 - 1], True}}] &;\n #i" }, { "answer_id": 41702432, "author": "Ssswift", "author_id": 7419656, "author_profile": "https://Stackoverflow.com/users/7419656", "pm_score": 0, "selected": false, "text": "fn > (def fac (fn self [n] (if (< n 2) 1 (* n (self (dec n))))))\n#'sandbox17083/fac\n> (fac 5)\n120\n> self\njava.lang.RuntimeException: Unable to resolve symbol: self in this context\n recur > (def fac (fn [n] (loop [count n result 1]\n (if (zero? count)\n result\n (recur (dec count) (* result count))))))\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156369", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15069/" ]
156,373
<p>I'm storing an object (<code>TTF_Font</code>) in a <code>shared_ptr</code> that is provided to me from a third-party API. I cannot use new or delete on the object, so the <code>shared_ptr</code> is also provided a "freeing" functor.</p> <pre><code>// Functor struct CloseFont { void operator()(TTF_Font* font) const { if(font != NULL) { TTF_CloseFont(font); } } }; boost::shared_ptr&lt;TTF_Font&gt; screenFont; screenFont = boost::shared_ptr&lt;TTF_Font&gt;( TTF_OpenFont("slkscr.ttf", 8), CloseFont() ); </code></pre> <p>If, later, I need to explicitly free this object is it correct to do this:</p> <pre><code>screenFont.reset(); </code></pre> <p>And then let <code>screenFont</code> (the actual <code>shared_ptr</code> object) be destroyed naturally?</p>
[ { "answer_id": 156386, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "TTF_OpenFont TTF_CloseFont CloseFont &TTF_CloseFont" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18265/" ]
156,394
<p>How is it that Ruby allows a class access methods outside of the class implicitly?</p> <p>Example:</p> <pre><code>class Candy def land homer end end def homer puts "Hello" end Candy.new.land #Outputs Hello </code></pre>
[ { "answer_id": 161113, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 2, "selected": false, "text": "homer Kernel Object Object homer Candy Object Kernel Object" }, { "answer_id": 8286738, "author": "Linuxios", "author_id": 1008938, "author_profile": "https://Stackoverflow.com/users/1008938", "pm_score": 0, "selected": false, "text": "def Object Object Object" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156394", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
156,395
<p>As a Java developer who is reading Apple's Objective-C 2.0 documentation: I wonder what "<em>sending a message to nil</em>" means - let alone how it is actually useful. Taking an excerpt from the documentation:</p> <blockquote> <p>There are several patterns in Cocoa that take advantage of this fact. The value returned from a message to nil may also be valid:</p> <ul> <li>If the method returns an object, any pointer type, any integer scalar of size less than or equal to sizeof(void*), a float, a double, a long double, or a long long, then a message sent to nil returns 0.</li> <li>If the method returns a struct, as defined by the Mac OS X ABI Function Call Guide to be returned in registers, then a message sent to nil returns 0.0 for every field in the data structure. Other struct data types will not be filled with zeros.</li> <li>If the method returns anything other than the aforementioned value types the return value of a message sent to nil is undefined.</li> </ul> </blockquote> <p>Has Java rendered my brain incapable of grokking the explanation above? Or is there something that I am missing that would make this as clear as glass?</p> <p>I do get the idea of messages/receivers in Objective-C, I am simply confused about a receiver that happens to be <code>nil</code>.</p>
[ { "answer_id": 156415, "author": "Rich", "author_id": 22003, "author_profile": "https://Stackoverflow.com/users/22003", "pm_score": 4, "selected": false, "text": "[someNullNSArrayReference count] => 0\n" }, { "answer_id": 156463, "author": "Michael Buckley", "author_id": 22540, "author_profile": "https://Stackoverflow.com/users/22540", "pm_score": 8, "selected": true, "text": "void foo(ArrayList list)\n{\n for(int i = 0; i < list.size(); ++i){\n System.out.println(list.get(i).toString());\n }\n}\n ArrayList list = NULL;\nlist.size();\n - (void)foo:(NSArray*)anArray\n{\n int i;\n for(i = 0; i < [anArray count]; ++i){\n NSLog(@\"%@\", [[anArray objectAtIndex:i] stringValue];\n }\n}\n [someObject foo:nil];\n" }, { "answer_id": 156498, "author": "Kendall Helmstetter Gelner", "author_id": 6330, "author_profile": "https://Stackoverflow.com/users/6330", "pm_score": 3, "selected": false, "text": "[someVariable release];\n if ( [myString length] > 0 )\n return [myArray count]; // say for number of rows in a table\n" }, { "answer_id": 195944, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 4, "selected": false, "text": "nil - (void)setValue:(MyClass *)newValue {\n if (value != newValue) { \n [value release];\n value = [newValue retain];\n }\n}\n nil value newValue nil nil if ([myArray count] > 0) {\n // do something...\n}\n nil nil nil" }, { "answer_id": 276943, "author": "Peter Hosey", "author_id": 30461, "author_profile": "https://Stackoverflow.com/users/30461", "pm_score": 6, "selected": false, "text": "nil nil Nil NULL 0 0.0" }, { "answer_id": 310215, "author": "Joe McMahon", "author_id": 39791, "author_profile": "https://Stackoverflow.com/users/39791", "pm_score": 5, "selected": false, "text": "nil" }, { "answer_id": 5530582, "author": "Rinzwind", "author_id": 276925, "author_profile": "https://Stackoverflow.com/users/276925", "pm_score": 3, "selected": false, "text": "nil nil nil nil" }, { "answer_id": 27105329, "author": "Zee", "author_id": 1210962, "author_profile": "https://Stackoverflow.com/users/1210962", "pm_score": 2, "selected": false, "text": "// For example, this expression...\nif (name != nil && [name isEqualToString:@\"Steve\"]) { ... }\n\n// ...can be simplified to:\nif ([name isEqualToString:@\"Steve\"]) { ... }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9931/" ]
156,412
<p><code>GWT</code> gets locale from either the locale property or the locale query string. If neither is specified, it uses the "default" (ie <code>en_US</code>) locale.</p> <p>Why doesn't it get it from the browser settings?</p> <p>It seems the only solution to this is to replace your static html launch page with something like a JSP that reads the browser locales and sets the locale or redirects using the query string. There has to be a better solution than this or simply hard-coding a locale, surely?</p>
[ { "answer_id": 161313, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 2, "selected": false, "text": "<!-- Slovenian in Slovenia -->\n<extend-property name=\"locale\" values=\"sl\"/>\n\n<!-- English language, independent of country -->\n<extend-property name=\"locale\" values=\"en\"/>\n" }, { "answer_id": 7992504, "author": "ljader", "author_id": 498096, "author_profile": "https://Stackoverflow.com/users/498096", "pm_score": 3, "selected": false, "text": "<set-configuration-property name=\"locale.useragent\" value=\"Y\"/>\n <set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\"/>\n" }, { "answer_id": 8259725, "author": "johnstok", "author_id": 27929, "author_profile": "https://Stackoverflow.com/users/27929", "pm_score": 0, "selected": false, "text": "Accept-Language" }, { "answer_id": 16627609, "author": "Jorge P.", "author_id": 1815133, "author_profile": "https://Stackoverflow.com/users/1815133", "pm_score": 1, "selected": false, "text": "<set-configuration-property name=\"locale.cookie\" value=\"yourCookieName\"/>\n<set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\"/>\n queryparam http" }, { "answer_id": 17296508, "author": "Manish Prajapati", "author_id": 1651893, "author_profile": "https://Stackoverflow.com/users/1651893", "pm_score": 0, "selected": false, "text": "<set-configuration-property name=\"locale.useragent\" value=\"Y\"/>" }, { "answer_id": 28435325, "author": "JuanFran Adame", "author_id": 1530949, "author_profile": "https://Stackoverflow.com/users/1530949", "pm_score": 0, "selected": false, "text": "<!-- Locales -->\n<extend-property name=\"locale\" values=\"en_US\"/>\n<extend-property name=\"locale\" values=\"es\"/> \n<set-property-fallback name=\"locale\" value=\"en_US\"/>\n<set-configuration-property name=\"locale.useragent\" value=\"Y\" />\n<set-configuration-property name=\"locale.searchorder\" value=\"queryparam,cookie,meta,useragent\" />\n extend-property" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18393/" ]
156,430
<p>I recently read somewhere that writing a regexp to match an email address, taking into account all the variations and possibilities of the standard is extremely hard and is significantly more complicated than what one would initially assume.</p> <p>Why is that?</p> <p>Are there any known and proven regexps that actually do this fully?</p> <p>What are some good alternatives to using regexps for matching email addresses?</p>
[ { "answer_id": 156449, "author": "janm", "author_id": 7256, "author_profile": "https://Stackoverflow.com/users/7256", "pm_score": 3, "selected": false, "text": "\" @ \"@example.com\n" }, { "answer_id": 156455, "author": "Mike Thompson", "author_id": 2754, "author_profile": "https://Stackoverflow.com/users/2754", "pm_score": 1, "selected": false, "text": "\"(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\"\n" }, { "answer_id": 156469, "author": "mmaibaum", "author_id": 12213, "author_profile": "https://Stackoverflow.com/users/12213", "pm_score": 5, "selected": false, "text": "Mail::VRFY RFC::RFC822::Address Mail::RFC822::Address (?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\n\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(\n?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \n\\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\0\n31]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\\n](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+\n(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:\n(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)\n?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\\nr\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[\n \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)\n?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t]\n)*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[\n \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*\n)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t]\n)+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)\n*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+\n|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\n\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\n\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t\n]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031\n]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](\n?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?\n:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?\n:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?\n:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?\n[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*:(?:(?:\\r\\n)?[ \\t])*(?:(?:(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\n\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>\n@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"\n(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?\n:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\n\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:[^()<>@,;:\\\\\".\\[\\] \\000-\n\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(\n?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)?[ \\t])*(?:@(?:[^()<>@,;\n:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([\n^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\"\n.\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\\n]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\\n[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\\nr\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \n\\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]\n|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?(?:[^()<>@,;:\\\\\".\\[\\] \\0\n00-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\\n.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,\n;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?\n:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*))*@(?:(?:\\r\\n)?[ \\t])*\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t])*(?:[\n^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]\n]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(?:\\r\\n)?[ \\t])*)(?:,\\s*(\n?:(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(\n?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\n\\[\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t\n])*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t\n])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?\n:\\.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\n\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*|(?:\n[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\\n]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)*\\<(?:(?:\\r\\n)\n?[ \\t])*(?:@(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"\n()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)\n?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>\n@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*(?:,@(?:(?:\\r\\n)?[\n \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,\n;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\\r\\n)?[ \\t]\n)*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\n\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*)*:(?:(?:\\r\\n)?[ \\t])*)?\n(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\n\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])*)(?:\\.(?:(?:\n\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z|(?=[\\[\n\"()<>@,;:\\\\\".\\[\\]]))|\"(?:[^\\\"\\r\\\\]|\\\\.|(?:(?:\\r\\n)?[ \\t]))*\"(?:(?:\\r\\n)?[ \\t])\n*))*@(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])\n+|\\Z|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*)(?:\\\n.(?:(?:\\r\\n)?[ \\t])*(?:[^()<>@,;:\\\\\".\\[\\] \\000-\\031]+(?:(?:(?:\\r\\n)?[ \\t])+|\\Z\n|(?=[\\[\"()<>@,;:\\\\\".\\[\\]]))|\\[([^\\[\\]\\r\\\\]|\\\\.)*\\](?:(?:\\r\\n)?[ \\t])*))*\\>(?:(\n?:\\r\\n)?[ \\t])*))*)?;\\s*)\n" }, { "answer_id": 156812, "author": "SchizoDuckie", "author_id": 18077, "author_profile": "https://Stackoverflow.com/users/18077", "pm_score": 0, "selected": false, "text": "var_dump(filter_var('bob@example.com', FILTER_VALIDATE_EMAIL));\n" }, { "answer_id": 167511, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 2, "selected": false, "text": "^[a-zA-Z]([.]?([a-zA-Z0-9_-]+)*)?@([a-zA-Z0-9\\-_]+\\.)+[a-zA-Z]{2,4}$ \n" }, { "answer_id": 1985762, "author": "Nicholas Piasecki", "author_id": 32187, "author_profile": "https://Stackoverflow.com/users/32187", "pm_score": 2, "selected": false, "text": "MailAddress FormatException Address MailAddress MailAddress MailBnfHelper.ReadMailAddress()" }, { "answer_id": 59903872, "author": "Service Objects Engineering", "author_id": 12327828, "author_profile": "https://Stackoverflow.com/users/12327828", "pm_score": 0, "selected": false, "text": "(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\n \\A(?:[a-z0-9!#$%&'*+/=?^_‘{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_‘{|}~-]+)*| \"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])\\z\n {\n \"ValidateEmailInfo\":{\n \"Score\":4,\n \"IsDeliverable\":\"false\",\n \"EmailAddressIn\":\"mickeyMouse@gmail.com\",\n \"EmailAddressOut\":\"mickeyMouse@gmail.com\",\n \"EmailCorrected\":false,\n \"Box\":\"mickeyMouse\",\n \"Domain\":\"gmail.com\",\n \"TopLevelDomain\":\".com\",\n \"TopLevelDomainDescription\":\"commercial\",\n \"IsSMTPServerGood\":\"true\",\n \"IsCatchAllDomain\":\"false\",\n \"IsSMTPMailBoxGood\":\"false\",\n \"WarningCodes\":\"22\",\n \"WarningDescriptions\":\"Email is Bad - Subsequent checks halted.\",\n \"NotesCodes\":\"16\",\n \"NotesDescriptions\":\"TLS\"\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
156,436
<p>It's quite a simple question - how do I sort a collection?</p> <p>I've got a CSV file with rows in a random order. I'd like to sort the rows according to the date in one column. Do I add the rows to a recordset? Can I sort with a Scripting.Dictionary?</p> <p>I've clearly been spoilt with .NET and Linq, and now I find myself back in the land of classic asp, realising I must have known this 7 years ago, and missing generics immensely. I feel like a complete n00b.</p>
[ { "answer_id": 156496, "author": "Wayne", "author_id": 8236, "author_profile": "https://Stackoverflow.com/users/8236", "pm_score": 2, "selected": false, "text": "<%\n\nDim strConnection, conn, rs, strSQL\n\nstrConnection = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\inetpub\\wwwroot\\;Extended Properties='text;HDR=Yes;FMT=Delimited';\"\n\nSet conn = Server.CreateObject(\"ADODB.Connection\")\nconn.Open strConnection\n\nSet rs = Server.CreateObject(\"ADODB.recordset\")\nstrSQL = \"SELECT * FROM test.csv order by date desc\"\nrs.open strSQL, conn, 3,3\n\nWHILE NOT rs.EOF\n Response.Write(rs(\"date\") & \"<br/>\") \n rs.MoveNext\nWEND\n\nrs.Close\nSet rs = Nothing\n\nconn.Close\nSet conn = Nothing\n\n%>\n" }, { "answer_id": 156611, "author": "Michal", "author_id": 21672, "author_profile": "https://Stackoverflow.com/users/21672", "pm_score": 5, "selected": true, "text": "set list = server.createObject(\"System.Collections.Sortedlist\")\nwith list\n .add \"something\", \"YY\"\n .add \"something else\", \"XX\"\nend with\n\nfor i = 0 to list.count - 1\n response.write(list.getKey(i) & \" = \" & list.getByIndex(i))\nnext\n" }, { "answer_id": 10835474, "author": "James Wiseman", "author_id": 144491, "author_profile": "https://Stackoverflow.com/users/144491", "pm_score": 0, "selected": false, "text": "'Simple collection manager class.\n'Performs the opration of adding/setting a collection item.\n'Encapulated off here in order to delegate responsibility away from the collection class.\nClass clsCollectionManager\n Public Sub PopulateCollectionItem(collection, strKey, Value)\n If collection.Exists(strKey) Then\n If (VarType(Value) = vbObject) Then\n Set collection.Item(strKey) = Value\n Else\n collection.Item(strKey) = Value\n End If\n Else\n Call collection.Add(strKey, Value)\n End If\n End Sub\n\n 'take a collection and a new element as input parameters, an spit out a brand new collection \n 'with the new item iserted into the correct location by order\n 'This works on the assumption that the collection it is receiving is already ordered \n '(which it should be if we always use this method to populate the item)\n\n 'This mutates the passed collection, so we highlight this by marking it as byref \n '(this is not strictly necessary as objects are passed by reference anyway)\n Public Sub AddCollectionItemInOrder(byref existingCollection, strNewKey, Value)\n Dim orderedCollection: Set orderedCollection = Server.CreateObject(\"Scripting.Dictionary\")\n Dim strExistingKey\n\n 'If there is something already in our recordset then we need to add it in order.\n\n 'There is no sorting available for a collection (or an array) in VBScript. Therefore we have to do it ourself.\n 'First, iterate over eveything in our current collection. We have to assume that it is itself sorted.\n For Each strExistingKey In existingCollection\n\n 'if the new item doesn't exist AND it occurs after the current item, then add the new item in now \n '(before adding in the current item.)\n If (Not orderedCollection.Exists(strNewKey)) And (strExistingKey > strNewKey) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n Call PopulateCollectionItem(orderedCollection, strExistingKey, existingCollection.item(strExistingKey))\n Next\n\n 'Finally check to see if it still doesn't exist. \n 'It won't if the last place for it is at the very end, or the original collection was empty\n If (Not orderedCollection.Exists(strNewKey)) Then\n Call PopulateCollectionItem(orderedCollection, strNewKey, Value)\n End If\n\n Set existingCollection = orderedCollection\n End Sub\nEnd Class\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5744/" ]
156,438
<p>See title: what does it mean for a C++ function to be inline?</p>
[ { "answer_id": 156453, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "if switch" }, { "answer_id": 156511, "author": "Simon Buchan", "author_id": 20135, "author_profile": "https://Stackoverflow.com/users/20135", "pm_score": 5, "selected": false, "text": "inline // my_thing.h\ninline int do_my_thing(int a, int b) { return a + b; }\n\n// use_my_thing.cpp\n#include \"my_thing.h\"\n...\n set_do_thing(&do_my_thing);\n\n// use_my_thing_again.cpp\n...\n set_other_do_thing(&do_my_thing);\n inline use_my_thing_again.obj : error LNK2005: \"int __cdecl do_my_thing(int,int)\" (?do_my_thing@@YAHHH@Z) already defined in use_my_thing.obj\n<...>\\Scratch.exe : fatal error LNK1169: one or more multiply defined symbols found\n" }, { "answer_id": 157859, "author": "OldMan", "author_id": 23415, "author_profile": "https://Stackoverflow.com/users/23415", "pm_score": 0, "selected": false, "text": "int foo();\ninline int bar();\n int foo(){ int r = bar(); return r; }\n\n\n inline int bar(){ return 5;};\n #include \"inlinetest.h\"\n int main()\n {\n foo();\n //bar();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156438", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7545/" ]
156,457
<p>Is it possible to enumerate all the current errors being displayed through an "Error Provider" without having to access the controls?</p>
[ { "answer_id": 2297261, "author": "Aidan Ryan", "author_id": 1042, "author_profile": "https://Stackoverflow.com/users/1042", "pm_score": 2, "selected": false, "text": "foreach (Control ctrl in errProv.ContainerControl.Controls)\n{\n Console.WriteLine(errProv.GetError(ctrl));\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156457", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4490/" ]
156,467
<p>I've been looking at F# recently, and while I'm not likely to leap the fence any time soon, it definitely highlights some areas where C# (or library support) could make life easier.</p> <p>In particular, I'm thinking about the pattern matching capability of F#, which allows a very rich syntax - much more expressive than the current switch/conditional C# equivalents. I won't try to give a direct example (my F# isn't up to it), but in short it allows:</p> <ul> <li>match by type (with full-coverage checking for discriminated unions) [note this also infers the type for the bound variable, giving member access etc]</li> <li>match by predicate</li> <li>combinations of the above (and possibly some other scenarios I'm not aware of)</li> </ul> <p>While it would be lovely for C# to eventually borrow [ahem] some of this richness, in the interim I've been looking at what can be done at runtime - for example, it is fairly easy to knock together some objects to allow:</p> <pre><code>var getRentPrice = new Switch&lt;Vehicle, int&gt;() .Case&lt;Motorcycle&gt;(bike =&gt; 100 + bike.Cylinders * 10) // "bike" here is typed as Motorcycle .Case&lt;Bicycle&gt;(30) // returns a constant .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Diesel, car =&gt; 220 + car.Doors * 20) .Case&lt;Car&gt;(car =&gt; car.EngineType == EngineType.Gasoline, car =&gt; 200 + car.Doors * 20) .ElseThrow(); // or could use a Default(...) terminator </code></pre> <p>where getRentPrice is a Func&lt;Vehicle,int&gt;.</p> <p>[note - maybe Switch/Case here is the wrong terms... but it shows the idea]</p> <p>To me, this is a lot clearer than the equivalent using repeated if/else, or a composite ternary conditional (which gets very messy for non-trivial expressions - brackets galore). It also avoids a <em>lot</em> of casting, and allows for simple extension (either directly or via extension methods) to more-specific matches, for example an InRange(...) match comparable to the VB Select...Case "x To y" usage.</p> <p><strong>I'm just trying to gauge if people think there is much benefit from constructs like the above (in the absence of language support)?</strong></p> <p>Note additionally that I've been playing with 3 variants of the above:</p> <ul> <li>a Func&lt;TSource,TValue&gt; version for evaluation - comparable to composite ternary conditional statements</li> <li>an Action&lt;TSource&gt; version - comparable to if/else if/else if/else if/else</li> <li>an Expression&lt;Func&lt;TSource,TValue&gt;&gt; version - as the first, but usable by arbitrary LINQ providers</li> </ul> <p>Additionally, using the Expression-based version enables Expression-tree re-writing, essentially inlining all the branches into a single composite conditional Expression, rather than using repeated invocation. I haven't checked recently, but in some early Entity Framework builds I seem to recall this being necessary, as it didn't like InvocationExpression very much. It also allows more efficient usage with LINQ-to-Objects, since it avoids repeated delegate invocations - tests show a match like the above (using the Expression form) performing at the same speed [marginally quicker, in fact] compared to the equivalent C# composite conditional statement. For completeness, the Func&lt;...&gt; based-version took 4 times as long as the C# conditional statement, but is still very quick and is unlikely to be a major bottleneck in most use-cases.</p> <p>I welcome any thoughts / input / critique / etc on the above (or on the possibilities of richer C# language support... here's hoping ;-p).</p>
[ { "answer_id": 156566, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 5, "selected": false, "text": "let getRentPrice (v : Vehicle) = \n match v with\n | :? Motorcycle as bike -> 100 + bike.Cylinders * 10\n | :? Bicycle -> 30\n | :? Car as car when car.EngineType = Diesel -> 220 + car.Doors * 20\n | :? Car as car when car.EngineType = Gasoline -> 200 + car.Doors * 20\n | _ -> failwith \"blah\"\n type Vehicle() = class end\n\ntype Motorcycle(cyl : int) = \n inherit Vehicle()\n member this.Cylinders = cyl\n\ntype Bicycle() = inherit Vehicle()\n\ntype EngineType = Diesel | Gasoline\n\ntype Car(engType : EngineType, doors : int) = \n inherit Vehicle()\n member this.EngineType = engType\n member this.Doors = doors\n" }, { "answer_id": 156837, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "typeof(Motorcycle)" }, { "answer_id": 7301884, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 4, "selected": false, "text": "public class PatternMatcher<Output>\n{\n List<Tuple<Predicate<Object>, Func<Object, Output>>> cases = new List<Tuple<Predicate<object>,Func<object,Output>>>();\n\n public PatternMatcher() { } \n\n public PatternMatcher<Output> Case(Predicate<Object> condition, Func<Object, Output> function)\n {\n cases.Add(new Tuple<Predicate<Object>, Func<Object, Output>>(condition, function));\n return this;\n }\n\n public PatternMatcher<Output> Case<T>(Predicate<T> condition, Func<T, Output> function)\n {\n return Case(\n o => o is T && condition((T)o), \n o => function((T)o));\n }\n\n public PatternMatcher<Output> Case<T>(Func<T, Output> function)\n {\n return Case(\n o => o is T, \n o => function((T)o));\n }\n\n public PatternMatcher<Output> Case<T>(Predicate<T> condition, Output o)\n {\n return Case(condition, x => o);\n }\n\n public PatternMatcher<Output> Case<T>(Output o)\n {\n return Case<T>(x => o);\n }\n\n public PatternMatcher<Output> Default(Func<Object, Output> function)\n {\n return Case(o => true, function);\n }\n\n public PatternMatcher<Output> Default(Output o)\n {\n return Default(x => o);\n }\n\n public Output Match(Object o)\n {\n foreach (var tuple in cases)\n if (tuple.Item1(o))\n return tuple.Item2(o);\n throw new Exception(\"Failed to match\");\n }\n}\n public enum EngineType\n {\n Diesel,\n Gasoline\n }\n\n public class Bicycle\n {\n public int Cylinders;\n }\n\n public class Car\n {\n public EngineType EngineType;\n public int Doors;\n }\n\n public class MotorCycle\n {\n public int Cylinders;\n }\n\n public void Run()\n {\n var getRentPrice = new PatternMatcher<int>()\n .Case<MotorCycle>(bike => 100 + bike.Cylinders * 10) \n .Case<Bicycle>(30) \n .Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)\n .Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)\n .Default(0);\n\n var vehicles = new object[] {\n new Car { EngineType = EngineType.Diesel, Doors = 2 },\n new Car { EngineType = EngineType.Diesel, Doors = 4 },\n new Car { EngineType = EngineType.Gasoline, Doors = 3 },\n new Car { EngineType = EngineType.Gasoline, Doors = 5 },\n new Bicycle(),\n new MotorCycle { Cylinders = 2 },\n new MotorCycle { Cylinders = 3 },\n };\n\n foreach (var v in vehicles)\n {\n Console.WriteLine(\"Vehicle of type {0} costs {1} to rent\", v.GetType(), getRentPrice.Match(v));\n }\n }\n" }, { "answer_id": 46201472, "author": "mcintyre321", "author_id": 2086, "author_profile": "https://Stackoverflow.com/users/2086", "pm_score": 1, "selected": false, "text": "switch if exceptions as control flow OneOf<Motorcycle, Bicycle, Car> vehicle = ... //assign from one of those types\n var getRentPrice = vehicle\n .Match(\n bike => 100 + bike.Cylinders * 10, // \"bike\" here is typed as Motorcycle\n bike => 30, // returns a constant\n car => car.EngineType.Match(\n diesel => 220 + car.Doors * 20\n petrol => 200 + car.Doors * 20\n )\n );\n" }, { "answer_id": 47795205, "author": "Marcus Pierce", "author_id": 5506486, "author_profile": "https://Stackoverflow.com/users/5506486", "pm_score": 6, "selected": true, "text": "switch(shape)\n{\n case Circle c:\n WriteLine($\"circle with radius {c.Radius}\");\n break;\n case Rectangle s when (s.Length == s.Height):\n WriteLine($\"{s.Length} x {s.Height} square\");\n break;\n case Rectangle r:\n WriteLine($\"{r.Length} x {r.Height} rectangle\");\n break;\n default:\n WriteLine(\"<unknown shape>\");\n break;\n case null:\n throw new ArgumentNullException(nameof(shape));\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23354/" ]
156,478
<p>I'm implementing a cache in a class library that i'm using in an asp.net application. </p> <p>I created my cache object as a singleton pattern with a static method to update the cache which is really just loading a member variable/property with a collection of data i need cached (got some locking logic ofcourse). I figured it was a nice way to go since i can just access my data by calling </p> <pre><code>MyCacheObject.Instance.MyDataCollection </code></pre> <p>I'm creating a new cache object to store a pretty big amount of data partitioned by some key. What i'm saying is i'm creating a new cache but this one will not load all of the data at once, but rather store a collection for each key accessed.</p> <pre><code>MyOtherCacheObject.Instance.MyOtherDataCollection(indexkey) </code></pre> <p>This time the question about garbage collection was brought up. Since i'm storing a huge amount of data, wouldn't it be a waste if it got gc'ed all of a sudden? Since it's just a singleton pattern there is nothing ensuring data will stay in cache.</p> <p>So my question is - what is best practice for implemeting a cache to handle this situation? I really don't like a huge complex solution to this, and i know there is caching in System.Web but that seems a bit 'off' since this is just a class library, or what do you think?</p>
[ { "answer_id": 156506, "author": "Sergio Acosta", "author_id": 2954, "author_profile": "https://Stackoverflow.com/users/2954", "pm_score": 4, "selected": true, "text": "public interface ICacheService \n{\n AddItem(...);\n}\n public AspNetBasedCacheService : ICacheService\n{\n AddItem(...)\n {\n // Implementation that uses the HttpContext.Cache object\n }\n }\n public class CacheServiceProvider \n{\n public static ICacheService Instance {get; set;}\n\n}\n Global.asax.cs // inside your class library:\nICacheService cache = CacheServiceProvider.Instance;\ncache.AddItem(...);\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11619/" ]
156,492
<p>I have built a CFC designed to serve as a dynamic, aging cache intended for almost everything worth caching. LDAP queries, function results, arrays, ojects, you name it. Whatever takes time or resources to calculate and is needed more than once. I'd like to be able to do a few things:</p> <ul> <li><strong>share the CFC between applications</strong></li> <li><strong>define the scope of the cache (server / application / session / current request only)</strong></li> <li>use different cache instances at the same time, in the same request</li> <li>be independent from CFCs using the cache component</li> <li>generally adhere to common sense (decoupling, encapsulation, orthogonality, locking)</li> </ul> <p>I would of course be using a different cache instance for every distinct task, but I'd like to be able to use the same CFC across applications. The cache itself is (what else) a Struct, private to the cache instance. How would I properly implement caching and locking when the scope itself is subject to change?</p> <p>For locking, I use named locks (<code>'CacheRead'</code>, <code>'CacheWrite'</code>) currently, this is safe but strikes me as odd. Why would I want a server-wide lock for, say, a session-only operation? (Yes, maybe this <em>is</em> academic, but anyway.)</p> <p>Passing in the APPLICATION scope as a reference when I want application level caching also seems the wrong thing to do. Is there a better way?</p>
[ { "answer_id": 240702, "author": "Adam Tuttle", "author_id": 751, "author_profile": "https://Stackoverflow.com/users/751", "pm_score": 2, "selected": true, "text": "<cfcomponent>\n <cfset variables.cacheScope = \"session\" /><!--- default to session --->\n <cfset variables.cache = \"\"/>\n\n <cfscript>\n function init(scope){\n variables.cacheScope = arguments.scope;\n return this;\n }\n\n function cacheWrite(key, value){\n structInsert(evaluate(variables.cacheScope),arguments.key,arguments.value,true);\n return this;\n }\n\n function cacheRead(key){\n if (not structKeyExists(evaluate(variables.cacheScope), arguments.key)){\n return \"\";\n }else{\n variables.cache = evaluate(variables.cacheScope);\n return variables.cache[arguments.key];\n }\n } \n </cfscript>\n</cfcomponent>\n <!--- clear out any existing session vars --->\n<cfset structClear(session)/>\n<!--- show empty session struct --->\n<cfdump var=\"#session#\" label=\"session vars\">\n<!--- create storage object --->\n<cfset cacher = createObject(\"component\", \"cache\").init(\"session\")/>\n<!--- store a value --->\n<cfset cacher.cacheWrite(\"foo\", \"bar\")/>\n<!--- read stored value --->\n<cfset rtn = cacher.cacheRead(\"foo\")/>\n<!--- show values --->\n<cfdump var=\"#rtn#\">\n<cfdump var=\"#session#\" label=\"session vars\">\n <cfset rtn = createObject(\"component\", \"cache\")\n .init(\"session\")\n .cacheWrite(\"foo\", \"bar\")\n .cacheRead(\"foo\")/>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156492", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18771/" ]
156,503
<p>How can I use JUnit idiomatically to test that some code throws an exception?</p> <p>While I can certainly do something like this:</p> <pre><code>@Test public void testFooThrowsIndexOutOfBoundsException() { boolean thrown = false; try { foo.doStuff(); } catch (IndexOutOfBoundsException e) { thrown = true; } assertTrue(thrown); } </code></pre> <p>I recall that there is an annotation or an Assert.xyz or <em>something</em> that is far less kludgy and far more in-the-spirit of JUnit for these sorts of situations.</p>
[ { "answer_id": 156515, "author": "Johan", "author_id": 11347, "author_profile": "https://Stackoverflow.com/users/11347", "pm_score": 5, "selected": false, "text": "public void testFooThrowsIndexOutOfBoundsException() {\n Throwable e = null;\n\n try {\n foo.doStuff();\n } catch (Throwable ex) {\n e = ex;\n }\n\n assertTrue(e instanceof IndexOutOfBoundsException);\n}\n" }, { "answer_id": 156528, "author": "skaffman", "author_id": 21234, "author_profile": "https://Stackoverflow.com/users/21234", "pm_score": 12, "selected": true, "text": "JUnit <= 4.12 @Test(expected = IndexOutOfBoundsException.class)\n public void testIndexOutOfBoundsException() {\n\n ArrayList emptyList = new ArrayList();\n Object o = emptyList.get(0);\n\n }\n" }, { "answer_id": 156868, "author": "daveb", "author_id": 11858, "author_profile": "https://Stackoverflow.com/users/11858", "pm_score": 9, "selected": false, "text": "try {\n methodThatShouldThrow();\n fail( \"My method didn't throw when I expected it to\" );\n} catch (MyException expectedException) {\n}\n" }, { "answer_id": 2935935, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 10, "selected": false, "text": "Assertions.assertThrows() Assert.assertThrows() ExpectedException public class FooTest {\n @Rule\n public final ExpectedException exception = ExpectedException.none();\n\n @Test\n public void doStuffThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n exception.expect(IndexOutOfBoundsException.class);\n foo.doStuff();\n }\n}\n @Test(expected=IndexOutOfBoundsException.class) IndexOutOfBoundsException foo.doStuff()" }, { "answer_id": 7927418, "author": "rwitzel", "author_id": 998938, "author_profile": "https://Stackoverflow.com/users/998938", "pm_score": 5, "selected": false, "text": "verifyException(foo, IndexOutOfBoundsException.class).doStuff();\n" }, { "answer_id": 12822499, "author": "Hugh Perkins", "author_id": 212731, "author_profile": "https://Stackoverflow.com/users/212731", "pm_score": 4, "selected": false, "text": "public class ExceptionAssertions {\n public static void assertException(BlastContainer blastContainer ) {\n boolean caughtException = false;\n try {\n blastContainer.test();\n } catch( Exception e ) {\n caughtException = true;\n }\n if( !caughtException ) {\n throw new AssertionFailedError(\"exception expected to be thrown, but was not\");\n }\n }\n public static interface BlastContainer {\n public void test() throws Exception;\n }\n}\n assertException(new BlastContainer() {\n @Override\n public void test() throws Exception {\n doSomethingThatShouldExceptHere();\n }\n});\n" }, { "answer_id": 16424903, "author": "John Mikic", "author_id": 1636207, "author_profile": "https://Stackoverflow.com/users/1636207", "pm_score": 5, "selected": false, "text": "@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n try {\n foo.doStuff();\n assert false;\n } catch (IndexOutOfBoundsException e) {\n assert true;\n }\n}\n" }, { "answer_id": 16948961, "author": "Tor P", "author_id": 1218054, "author_profile": "https://Stackoverflow.com/users/1218054", "pm_score": 3, "selected": false, "text": "public class ExceptionMatcher extends BaseMatcher<Throwable> {\n private boolean active = true;\n private Class<? extends Throwable> throwable;\n\n public ExceptionMatcher(Class<? extends Throwable> throwable) {\n this.throwable = throwable;\n }\n\n public void on() {\n this.active = true;\n }\n\n public void off() {\n this.active = false;\n }\n\n @Override\n public boolean matches(Object object) {\n return active && throwable.isAssignableFrom(object.getClass());\n }\n\n @Override\n public void describeTo(Description description) {\n description.appendText(\"not the covered exception type\");\n }\n}\n public ExpectedException exception = ExpectedException.none(); ExceptionMatcher exMatch = new ExceptionMatcher(MyException.class);\nexception.expect(exMatch);\nsomeObject.somethingThatThrowsMyException();\nexMatch.off();\n" }, { "answer_id": 17421500, "author": "Macchiatow", "author_id": 1161494, "author_profile": "https://Stackoverflow.com/users/1161494", "pm_score": 3, "selected": false, "text": "@Test\npublic void testThrowsExceptionWhenWrongSku() {\n\n // Given\n String articleSimpleSku = \"999-999\";\n int amountOfTransactions = 1;\n Exception exception = null;\n\n // When\n try {\n createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);\n } catch (RuntimeException e) {\n exception = e;\n }\n\n // Then\n shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);\n}\n\nprivate void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {\n assertNotNull(e);\n assertTrue(e.getMessage().contains(message));\n}\n" }, { "answer_id": 20008854, "author": "MariuszS", "author_id": 516167, "author_profile": "https://Stackoverflow.com/users/516167", "pm_score": 5, "selected": false, "text": "import static com.googlecode.catchexception.apis.BDDCatchException.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n\n when(() -> foo.doStuff());\n\n then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);\n\n}\n eu.codearte.catch-exception:catch-exception:2.0\n" }, { "answer_id": 24621006, "author": "Rafal Borowiec", "author_id": 718515, "author_profile": "https://Stackoverflow.com/users/718515", "pm_score": 8, "selected": false, "text": "@Test\npublic void verifiesTypeAndMessage() {\n assertThrown(new DummyService()::someMethod)\n .isInstanceOf(RuntimeException.class)\n .hasMessage(\"Runtime exception occurred\")\n .hasMessageStartingWith(\"Runtime\")\n .hasMessageEndingWith(\"occurred\")\n .hasMessageContaining(\"exception\")\n .hasNoCause();\n}\n" }, { "answer_id": 28940773, "author": "Shessuky", "author_id": 1387275, "author_profile": "https://Stackoverflow.com/users/1387275", "pm_score": 3, "selected": false, "text": "try{\n methodThatThrowMyException();\n Assert.fail(\"MyException is not thrown !\");\n} catch (final Exception exception) {\n // Verify if the thrown exception is instance of MyException, otherwise throws an assert failure\n assertTrue(exception instanceof MyException, \"An exception other than MyException is thrown !\");\n // In case of verifying the error message\n MyException myException = (MyException) exception;\n assertEquals(\"EXPECTED ERROR MESSAGE\", myException.getMessage());\n}\n" }, { "answer_id": 28974751, "author": "Alex Collins", "author_id": 1055223, "author_profile": "https://Stackoverflow.com/users/1055223", "pm_score": 4, "selected": false, "text": "// this try block should be as small as possible,\n// as you want to make sure you only catch exceptions from your code\ntry {\n sut.doThing();\n fail(); // fail if this does not throw any exception\n} catch(MyException e) { // only catch the exception you expect,\n // otherwise you may catch an exception for a dependency unexpectedly\n // a strong assertion on the message, \n // in case the exception comes from anywhere an unexpected line of code,\n // especially important if your checking IllegalArgumentExceptions\n assertEquals(\"the message I get\", e.getMessage()); \n}\n assertTrue assertThat(e.getMessage(), containsString(\"the message\");" }, { "answer_id": 30404203, "author": "Srini", "author_id": 3281476, "author_profile": "https://Stackoverflow.com/users/3281476", "pm_score": 3, "selected": false, "text": "@Rule \npublic ExpectedException expectedException;\n\n@Before\npublic void setup()\n{\n expectedException = ExpectedException.none();\n}\n" }, { "answer_id": 31826781, "author": "walsh", "author_id": 4101415, "author_profile": "https://Stackoverflow.com/users/4101415", "pm_score": 8, "selected": false, "text": "assertThrows @Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n Throwable exception = assertThrows(IndexOutOfBoundsException.class, () -> foo.doStuff());\n assertEquals(\"expected messages\", exception.getMessage());\n}\n @Test(expected = IndexOutOfBoundsException.class)\npublic void testFooThrowsIndexOutOfBoundsException() {\n foo.doStuff();\n}\n public class XxxTest {\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Test\n public void testFooThrowsIndexOutOfBoundsException() {\n thrown.expect(IndexOutOfBoundsException.class)\n //you can test the exception message like\n thrown.expectMessage(\"expected messages\");\n foo.doStuff();\n }\n}\n @Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n try {\n foo.doStuff();\n fail(\"expected exception was not occured.\");\n } catch(IndexOutOfBoundsException e) {\n //if execution reaches here, \n //it indicates this exception was occured.\n //so we need not handle it.\n }\n}\n" }, { "answer_id": 34362168, "author": "Mike Nakis", "author_id": 773113, "author_profile": "https://Stackoverflow.com/users/773113", "pm_score": 3, "selected": false, "text": "public final <T extends Throwable> T expectException( Class<T> exceptionClass, Runnable runnable )\n{\n try\n {\n runnable.run();\n }\n catch( Throwable throwable )\n {\n if( throwable instanceof AssertionError && throwable.getCause() != null )\n throwable = throwable.getCause(); //allows testing for \"assert x != null : new IllegalArgumentException();\"\n assert exceptionClass.isInstance( throwable ) : throwable; //exception of the wrong kind was thrown.\n assert throwable.getClass() == exceptionClass : throwable; //exception thrown was a subclass, but not the exact class, expected.\n @SuppressWarnings( \"unchecked\" )\n T result = (T)throwable;\n return result;\n }\n assert false; //expected exception was not thrown.\n return null; //to keep the compiler happy.\n}\n @Test\npublic void testMyFunction()\n{\n RuntimeException e = expectException( RuntimeException.class, () -> \n {\n myFunction();\n } );\n assert e.getMessage().equals( \"I haz fail!\" );\n}\n\npublic void myFunction()\n{\n throw new RuntimeException( \"I haz fail!\" );\n}\n" }, { "answer_id": 35813323, "author": "weston", "author_id": 360211, "author_profile": "https://Stackoverflow.com/users/360211", "pm_score": 5, "selected": false, "text": "import static org.assertj.core.api.Assertions.*;\n\n@Test\npublic void testFooThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n assertThatThrownBy(() -> foo.doStuff())\n .isInstanceOf(IndexOutOfBoundsException.class);\n}\n @Test(expected=IndexOutOfBoundsException.class) assertThatThrownBy(() ->\n {\n throw new Exception(\"boom!\");\n })\n .isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n" }, { "answer_id": 35908056, "author": "Matt Welke", "author_id": 5051165, "author_profile": "https://Stackoverflow.com/users/5051165", "pm_score": -1, "selected": false, "text": "public void testConstructor() {\n boolean expectedExceptionThrown;\n try {\n // Call constructor with bad arguments\n double a = 1;\n double b = 2;\n double c = a + b; // In my example, this is an invalid option for c\n new Triangle(a, b, c);\n expectedExceptionThrown = false; // because it successfully constructed the object\n }\n catch(IllegalArgumentException e) {\n expectedExceptionThrown = true; // because I'm in this catch block\n }\n catch(Exception e) {\n expectedExceptionThrown = false; // because it threw an exception but not the one expected\n }\n assertTrue(expectedExceptionThrown);\n}\n" }, { "answer_id": 38553412, "author": "Daniel Käfer", "author_id": 1079174, "author_profile": "https://Stackoverflow.com/users/1079174", "pm_score": 4, "selected": false, "text": "import static org.junit.jupiter.api.Assertions.assertThrows;\n\n@Test\nvoid testFooThrowsIndexOutOfBoundsException() { \n IndexOutOfBoundsException exception = expectThrows(IndexOutOfBoundsException.class, foo::doStuff);\n \n assertEquals(\"some message\", exception.getMessage());\n}\n" }, { "answer_id": 40317041, "author": "Shirsh Sinha", "author_id": 4840515, "author_profile": "https://Stackoverflow.com/users/4840515", "pm_score": 1, "selected": false, "text": "public int divideByZeroDemo(int a,int b){\n\n return a/b;\n}\n\npublic void exceptionWithMessage(String [] arr){\n\n throw new ArrayIndexOutOfBoundsException(\"Array is out of bound\");\n}\n @Rule\npublic ExpectedException exception=ExpectedException.none();\n\nprivate Demo demo;\n@Before\npublic void setup(){\n\n demo=new Demo();\n}\n@Test(expected=ArithmeticException.class)\npublic void testIfItThrowsAnyException() {\n\n demo.divideByZeroDemo(5, 0);\n\n}\n\n@Test\npublic void testExceptionWithMessage(){\n\n\n exception.expectMessage(\"Array is out of bound\");\n exception.expect(ArrayIndexOutOfBoundsException.class);\n demo.exceptionWithMessage(new String[]{\"This\",\"is\",\"a\",\"demo\"});\n}\n" }, { "answer_id": 41019785, "author": "Brice", "author_id": 48136, "author_profile": "https://Stackoverflow.com/users/48136", "pm_score": 7, "selected": false, "text": "try catch fail() catch try catch @Test(expected = ...) @Rule ExpectedException try catch Assert.fail try @Test(expected = ...) @Test(expected = WantedException.class)\npublic void call2_should_throw_a_WantedException__not_call1() {\n // init tested\n tested.call1(); // may throw a WantedException\n\n // call to be actually tested\n tested.call2(); // the call that is supposed to raise an exception\n}\n ExpectedException ExpectedException @Test @Rule ExpectedException thrown = ExpectedException.none()\n\n@Test\npublic void call2_should_throw_a_WantedException__not_call1() {\n // expectations\n thrown.expect(WantedException.class);\n thrown.expectMessage(\"boom\");\n\n // init tested\n tested.call1(); // may throw a WantedException\n\n // call to be actually tested\n tested.call2(); // the call that is supposed to raise an exception\n}\n ExpectedException // given: an empty list\nList myList = new ArrayList();\n\n// when: we try to get the first element of the list\nwhen(myList).get(1);\n\n// then: we expect an IndexOutOfBoundsException\nthen(caughtException())\n .isInstanceOf(IndexOutOfBoundsException.class)\n .hasMessage(\"Index: 1, Size: 0\") \n .hasNoCause();\n then assertThat(ex).hasNoCause()... inline-mock-maker try catch @Test\npublic void test_exception_approach_1() {\n ...\n assertThatExceptionOfType(IOException.class)\n .isThrownBy(() -> someBadIOOperation())\n .withMessage(\"boom!\"); \n}\n\n@Test\npublic void test_exception_approach_2() {\n ...\n assertThatThrownBy(() -> someBadIOOperation())\n .isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n}\n\n@Test\npublic void test_exception_approach_3() {\n ...\n // when\n Throwable thrown = catchThrowable(() -> someBadIOOperation());\n\n // then\n assertThat(thrown).isInstanceOf(Exception.class)\n .hasMessageContaining(\"boom\");\n}\n assertThrows @Test\n@DisplayName(\"throws EmptyStackException when peeked\")\nvoid throwsExceptionWhenPeeked() {\n Throwable t = assertThrows(EmptyStackException.class, () -> stack.peek());\n\n Assertions.assertEquals(\"...\", t.getMessage());\n}\n assertEquals void Matcher Assert Assertions try catch" }, { "answer_id": 41032596, "author": "Jobin", "author_id": 2893693, "author_profile": "https://Stackoverflow.com/users/2893693", "pm_score": 3, "selected": false, "text": "@Rule\npublic ExpectedException exceptions = ExpectedException.none();\n public class MyTest {\n\n @Rule\n public ExpectedException exceptions = ExpectedException.none();\n\n ClassUnderTest classUnderTest;\n\n @Before\n public void setUp() throws Exception {\n classUnderTest = new ClassUnderTest();\n }\n\n @Test\n public void testAppleisSweetAndRed() throws Exception {\n\n exceptions.expect(Exception.class);\n exceptions.expectMessage(\"this is the exception message\");\n exceptions.expectCause(Matchers.<Throwable>equalTo(exceptionCause));\n\n classUnderTest.methodUnderTest(\"param1\", \"param2\");\n }\n\n}\n" }, { "answer_id": 41559786, "author": "Dilini Rajapaksha", "author_id": 679822, "author_profile": "https://Stackoverflow.com/users/679822", "pm_score": 6, "selected": false, "text": "assertThrows import static org.junit.jupiter.api.Assertions.assertThrows;\n\n@Test\nvoid exceptionTesting() {\n IllegalArgumentException exception = assertThrows(IllegalArgumentException.class, () -> {\n throw new IllegalArgumentException(\"a message\");\n });\n assertEquals(\"a message\", exception.getMessage());\n}\n expected @Test(expected = FileNotFoundException.class) @Test(expected = FileNotFoundException.class) \npublic void testReadFile() { \n myClass.readFile(\"test.txt\");\n}\n try catch public void testReadFile() { \n try {\n myClass.readFile(\"test.txt\");\n fail(\"Expected a FileNotFoundException to be thrown\");\n } catch (FileNotFoundException e) {\n assertThat(e.getMessage(), is(\"The file test.txt does not exist!\"));\n }\n \n}\n ExpectedException @Rule\npublic ExpectedException thrown = ExpectedException.none();\n\n@Test\npublic void testReadFile() throws FileNotFoundException {\n \n thrown.expect(FileNotFoundException.class);\n thrown.expectMessage(startsWith(\"The file test.txt\"));\n myClass.readFile(\"test.txt\");\n}\n" }, { "answer_id": 46512202, "author": "fahrenx", "author_id": 1482358, "author_profile": "https://Stackoverflow.com/users/1482358", "pm_score": 1, "selected": false, "text": "private void expectException(Runnable r, Class<?> clazz) { \n try {\n r.run();\n fail(\"Expected: \" + clazz.getSimpleName() + \" but not thrown\");\n } catch (Exception e) {\n if (!clazz.isInstance(e)) fail(\"Expected: \" + clazz.getSimpleName() + \" but \" + e.getClass().getSimpleName() + \" found\", e);\n }\n }\n expectException(() -> list.sublist(0, 2).get(2), IndexOutOfBoundsException.class);\n" }, { "answer_id": 46514550, "author": "NamshubWriter", "author_id": 95725, "author_profile": "https://Stackoverflow.com/users/95725", "pm_score": 6, "selected": false, "text": "Assertions.assertThrows() Assert.assertThrows() public class FooTest {\n @Test\n public void doStuffThrowsIndexOutOfBoundsException() {\n Foo foo = new Foo();\n\n IndexOutOfBoundsException e = assertThrows(\n IndexOutOfBoundsException.class, foo::doStuff);\n\n assertThat(e).hasMessageThat().contains(\"woops!\");\n }\n}\n throws" }, { "answer_id": 46563308, "author": "heio", "author_id": 4031101, "author_profile": "https://Stackoverflow.com/users/4031101", "pm_score": 0, "selected": false, "text": "public static <T extends Throwable> T assertThrows(Class<T> expected, ThrowingRunnable action) throws Throwable {\n try {\n action.run();\n Assert.fail(\"Did not throw expected \" + expected.getSimpleName());\n return null; // never actually\n } catch (Throwable actual) {\n if (!expected.isAssignableFrom(actual.getClass())) { // runtime '!(actual instanceof expected)'\n System.err.println(\"Threw \" + actual.getClass().getSimpleName() \n + \", which is not a subtype of expected \" \n + expected.getSimpleName());\n throw actual; // throw the unexpected Throwable for maximum transparency\n } else {\n return (T) actual; // return the expected Throwable for further examination\n }\n }\n}\n Runnable throws @FunctionalInterface\npublic interface ThrowingRunnable {\n void run() throws Throwable;\n}\n class CustomException extends Exception {\n public final String message;\n public CustomException(final String message) { this.message = message;}\n}\nCustomException e = assertThrows(CustomException.class, () -> {\n throw new CustomException(\"Lorem Ipsum\");\n});\nassertEquals(\"Lorem Ipsum\", e.message);\n" }, { "answer_id": 47195186, "author": "Mohit ladia", "author_id": 7750672, "author_profile": "https://Stackoverflow.com/users/7750672", "pm_score": 0, "selected": false, "text": "@Test(expected = IndexOutOfBoundsException.class) try{\n}\ncatch(exception to be thrown from method e)\n{\n assertEquals(\"message\", e.getmessage());\n}\n" }, { "answer_id": 48441467, "author": "Dherik", "author_id": 2387977, "author_profile": "https://Stackoverflow.com/users/2387977", "pm_score": 4, "selected": false, "text": "try/catch @Rule package com.mkyong;\n\nimport com.mkyong.examples.CustomerService;\nimport com.mkyong.examples.exception.NameNotFoundException;\nimport org.junit.Rule;\nimport org.junit.Test;\nimport org.junit.rules.ExpectedException;\n\nimport static org.hamcrest.CoreMatchers.containsString;\nimport static org.hamcrest.CoreMatchers.is;\nimport static org.hamcrest.Matchers.hasProperty;\n\npublic class Exception3Test {\n\n @Rule\n public ExpectedException thrown = ExpectedException.none();\n\n @Test\n public void testNameNotFoundException() throws NameNotFoundException {\n\n //test specific type of exception\n thrown.expect(NameNotFoundException.class);\n\n //test message\n thrown.expectMessage(is(\"Name is empty!\"));\n\n //test detail\n thrown.expect(hasProperty(\"errCode\")); //make sure getters n setters are defined.\n thrown.expect(hasProperty(\"errCode\", is(666)));\n\n CustomerService cust = new CustomerService();\n cust.findByName(\"\");\n\n }\n\n}\n" }, { "answer_id": 49696649, "author": "Donatello", "author_id": 1034782, "author_profile": "https://Stackoverflow.com/users/1034782", "pm_score": 2, "selected": false, "text": "public Throwable assertThrows(Class<? extends Throwable> expectedException, java.util.concurrent.Callable<?> funky) {\n try {\n funky.call();\n } catch (Throwable e) {\n if (expectedException.isInstance(e)) {\n return e;\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but was [%s]\", expectedException, e));\n }\n throw new AssertionError(\n String.format(\"Expected [%s] to be thrown, but nothing was thrown.\", expectedException));\n}\n assertThrows(ValidationException.class,\n () -> finalObject.checkSomething(null));\n final @Test(expected = IndexOutOfBoundsException.class)" }, { "answer_id": 51400976, "author": "Piotr Rogowski", "author_id": 3782729, "author_profile": "https://Stackoverflow.com/users/3782729", "pm_score": 2, "selected": false, "text": "assertj-core //given\n\n//when\nThrowable throwable = catchThrowable(() -> anyService.anyMethod(object));\n\n//then\nAnyException anyException = (AnyException) throwable;\nassertThat(anyException.getMessage()).isEqualTo(\"........\");\nassertThat(exception.getCode()).isEqualTo(\".......);\n" }, { "answer_id": 51744696, "author": "Hossam Badri", "author_id": 1807373, "author_profile": "https://Stackoverflow.com/users/1807373", "pm_score": -1, "selected": false, "text": "try {\n my method();\n fail( \"This method must thrwo\" );\n} catch (Exception ex) {\n assertThat(ex.getMessage()).isEqual(myErrormsg);\n}\n" }, { "answer_id": 55708672, "author": "MangduYogii", "author_id": 9491394, "author_profile": "https://Stackoverflow.com/users/9491394", "pm_score": 1, "selected": false, "text": " @Test(expectedException=IndexOutOfBoundsException.class) \n public void testFooThrowsIndexOutOfBoundsException() throws Exception {\n doThrow(IndexOutOfBoundsException.class).when(foo).doStuff(); \n try {\n foo.doStuff(); \n } catch (IndexOutOfBoundsException e) {\n assertEquals(IndexOutOfBoundsException .class, ex.getCause().getClass());\n throw e;\n\n }\n\n }\n" }, { "answer_id": 61762605, "author": "Ilya Serbis", "author_id": 355438, "author_profile": "https://Stackoverflow.com/users/355438", "pm_score": 2, "selected": false, "text": "assertThrows() ArithmeticException exception = assertThrows(ArithmeticException.class, () ->\n calculator.divide(1, 0));\nassertEquals(\"/ by zero\", exception.getMessage());\n org.junit.jupiter.api.Assertions org.junit.Assert org.junit.jupiter:junit-jupiter-api" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1666/" ]
156,504
<p>I'm trying to insert some import lines into a python source file, but i would ideally like to place them right after the initial docstring. Let's say I load the file into the lines variable like this:</p> <pre><code>lines = open('filename.py').readlines() </code></pre> <p>How to find the line number, where the docstring ends?</p>
[ { "answer_id": 156513, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 3, "selected": true, "text": "count = 0\nfor line in lines:\n if line.startswith ('\"\"\"'):\n count += 1\n if count < 3:\n # Before or during end of the docstring\n continue\n # Line is after docstring\n" }, { "answer_id": 156973, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 4, "selected": false, "text": "import tokenize\nf=open(filename)\ninsert_index = None\nfor tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n # Comment\n# \"\"\"Not the real docstring\"\"\"\n' this is the module\\'s \\\ndocstring, containing:\\\n\"\"\" and having code on the same line following it:'; this_is_code=42\n" }, { "answer_id": 40376257, "author": "The Unfun Cat", "author_id": 992687, "author_profile": "https://Stackoverflow.com/users/992687", "pm_score": 0, "selected": false, "text": "def split_docstring_and_code(infile):\n\n import tokenize\n insert_index = None\n f = open(infile)\n for tok, text, (srow, scol), (erow,ecol), l in tokenize.generate_tokens(f.readline):\n if tok == tokenize.COMMENT:\n continue\n elif tok == tokenize.STRING:\n insert_index = erow, ecol\n break\n else:\n break # No docstring found\n\n lines = open(infile).readlines()\n if insert_index is not None:\n erow = insert_index[0]\n return \"\".join(lines[:erow]), \"\".join(lines[erow:])\n else:\n return \"\", \"\".join(lines)\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/985/" ]
156,508
<p>Alright, I have been doing the following (variable names have been changed):</p> <pre><code> FileInputStream fis = null; try { fis = new FileInputStream(file); ... process ... } catch (IOException e) { ... handle error ... } finally { if (fis != null) fis.close(); } </code> </pre> <p>Recently, I started using FindBugs, which suggests that I am not properly closing streams. I decide to see if there's anything that can be done with a finally{} block, and then I see, oh yeah, close() can throw IOException. What are people supposed to do here? The Java libraries throw too many checked exceptions.</p>
[ { "answer_id": 156520, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 5, "selected": false, "text": "FileInputStream fis = null;\ntry\n{\n fis = new FileInputStream(file);\n\n ... process ...\n\n\n}\ncatch (IOException e)\n{\n ... blah blah blah ...\n}\nfinally\n{\n try\n {\n if (fis != null)\n fis.close();\n }\n catch (IOException e)\n {\n }\n}\n" }, { "answer_id": 156526, "author": "squiddle", "author_id": 6554, "author_profile": "https://Stackoverflow.com/users/6554", "pm_score": 2, "selected": false, "text": "public static void closeQuietly(InputStream s) {\n if (null == s) {\n return;\n }\n try {\n s.close();\n } catch (IOException ioe) {\n //ignore exception\n }\n}\n" }, { "answer_id": 156546, "author": "Lars Westergren", "author_id": 15627, "author_profile": "https://Stackoverflow.com/users/15627", "pm_score": 0, "selected": false, "text": " Inputstream s = ....;\n withClosable(s) {\n //your code here\n }\n" }, { "answer_id": 156674, "author": "serg10", "author_id": 1853, "author_profile": "https://Stackoverflow.com/users/1853", "pm_score": 2, "selected": false, "text": "IOException close() public static void closeQuietly(InputStream s) {\n try {\n s.close();\n } catch (IOException ignored) {\n }\n}\n" }, { "answer_id": 156721, "author": "Dave Griffiths", "author_id": 15379, "author_profile": "https://Stackoverflow.com/users/15379", "pm_score": -1, "selected": false, "text": "if (fis != null) OutOfMemoryException" }, { "answer_id": 156889, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 7, "selected": true, "text": "try (InputStream in = new FileInputStream(file)) {\n // TODO: work\n} catch (IOException e) {\n // TODO: handle error\n}\n try {\n InputStream in = new FileInputStream(file);\n try {\n // TODO: work\n } finally {\n in.close();\n }\n } catch (IOException e) {\n // TODO: error handling\n }\n" }, { "answer_id": 157084, "author": "Bruno De Fraine", "author_id": 6918, "author_profile": "https://Stackoverflow.com/users/6918", "pm_score": 2, "selected": false, "text": "final InputStream is = ... // (assuming some construction that can't return null)\ntry {\n // process is\n ...\n} finally {\n is.close();\n}\n FileNotFoundException IOException IOException throws IOException IOException RuntimeException try close finally IOException try IOException close" }, { "answer_id": 6802774, "author": "Olivier Cailloux", "author_id": 859604, "author_profile": "https://Stackoverflow.com/users/859604", "pm_score": 1, "selected": false, "text": "try {\n InputStream in = new FileInputStream(file);\n try {\n // work\n in.close();\n } finally {\n Closeables.closeQuietly(in);\n }\n} catch(IOException exc) {\n // kernel panic\n}\n private void work() throws IOException {\n InputStream in = new FileInputStream(file);\n try {\n // work\n in.close();\n } finally {\n Closeables.closeQuietly(in);\n }\n}\n\npublic void workAndDealWithException() {\n try {\n work();\n } catch(IOException exc) {\n // kernel panic\n }\n}\n" }, { "answer_id": 10644404, "author": "Edwin Dalorzo", "author_id": 697630, "author_profile": "https://Stackoverflow.com/users/697630", "pm_score": 3, "selected": false, "text": "static String readFirstLineFromFile(String path) throws IOException {\n try (BufferedReader br = new BufferedReader(new FileReader(path))) {\n return br.readLine();\n }\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156508", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18049/" ]
156,510
<p>Is there a way to increase the stack size of a Windows application at compile/link time with GCC?</p>
[ { "answer_id": 156730, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 5, "selected": false, "text": "gcc -Wl,--stack,16777216 -o file.exe file.c\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1597/" ]
156,532
<p>I need to import largish (24MB) text files into a MySQL table. Each line looks like this:</p> <pre><code>1 1 0.008 0 0 0 0 0 </code></pre> <p>There are one or more spaces after each field, and the last field is tailed by about 36 spaces before the newline.</p> <p>How do I import such a file into MySQL? From the documentation it seems that LOAD DATA expects all fields to be terminated by exactly the same string. I have tried</p> <pre><code>LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ' '; </code></pre> <p>but MySQL will interpret a sequence of more than one space as delimiting an empty field.</p> <p>Any ideas?</p>
[ { "answer_id": 156550, "author": "Jauco", "author_id": 6874, "author_profile": "https://Stackoverflow.com/users/6874", "pm_score": 4, "selected": true, "text": "sed 's/ \\+/ /g' thefile > thefile.new\n" }, { "answer_id": 156578, "author": "Ian", "author_id": 4396, "author_profile": "https://Stackoverflow.com/users/4396", "pm_score": 0, "selected": false, "text": "<?php\n\n$db = mysql_connect('host', 'user', 'password')\nor die('Failed to connect');\nmysql_select_db('database', $db);\n\n$fileHandle= @fopen(\"import.file\", \"r\");\nif ($fileHandle) {\n while (!feof($fileHandle)) {\n $rawLine = fgets($fileHandle, 4096);\n\n $columns = preg_split(\"/\\s+/\", $rawLine);\n\n //Construct and run an INSERT statement here ... \n\n }\n fclose($fileHandle);\n}\n\n?>\n" }, { "answer_id": 5462898, "author": "Felix", "author_id": 680691, "author_profile": "https://Stackoverflow.com/users/680691", "pm_score": 2, "selected": false, "text": "LOAD DATA INFILE 'filename' INTO TABLE mytable FIELDS TERMINATED BY ','; \n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1428/" ]
156,552
<p>I want to implement a two-pass cache system:</p> <ul> <li><p>The first pass generates a PHP file, with all of the common stuff (e.g. news items), hardcoded. The database then has a cache table to link these with the pages (eg "index.php page=1 style=default"), the database also stores an uptodate field, which if false causes the first pass to rerun the next time the page is viewed.</p></li> <li><p>The second pass fills in the minor details, such as how long ago something(?) was, and mutable items like "You are logged in as...".</p></li> </ul> <p>However I'm not sure on a efficient implementation, that supports both cached and non-cached (e.g., search) pages, without a lot of code and several queries.</p> <p>Right now each time the page is loaded the PHP script is run regenerating the page. For pages like search this is fine, because most searches are different, but for other pages such as the index this is virtually the same for each hit, yet generates a large number of queries and is quite a long script.</p> <p>The problem is some parts of the page do change on a per-user basis, such as the "You are logged in as..." section, so simply saving the generated pages would still result in 10,000's of nearly identical pages.</p> <p>The main concern is with reducing the load on the server, since I'm on shared hosting and at this point can't afford to upgrade, but the site is using a sizeable portion of the servers CPU + putting a fair load on the MySQL server.</p> <p>So basically minimising how much has to be done for each page request, and not regenerating stuff like the news items on the index all the time seems a good start, compared to say search which is a far less static page.</p> <p>I actually considered hard coding the news items as plain HTML, but then that means maintaining them in several places (since they may be used for searches and the comments are on a page dedicated to that news item (i.e. news.php), etc).</p>
[ { "answer_id": 156561, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 1, "selected": false, "text": "if filename exists\n include filename\nelse\n generate results\n render to html (as string)\n write to file\n output string or include file\nendif\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
156,563
<p>How do you setup an asp.net sql membership role/membership provider on a production machine? I'm trying to setup BlogEngine.NET and all the documentation says to use the ASP.NET Website Administration tool from Visual Studio but that isn't available on a production machine. Am I the first BlogEngine user to use it on a non-development box?</p> <p>The SQL server is completely blocked off from everything but the production box, I do have SQL Management Studio on there though.</p> <p>EDIT: I mean, how do you add new users/roles, not how do you create the tables. I've already ran aspnet_regsql to create the schema.</p> <p>EDIT2: MyWSAT doesn't work because it requires an initial user in the database as well. I need an application that will allow me to create new users in the membership database without any authentication, just a connection string.</p>
[ { "answer_id": 158238, "author": "ThatBloke", "author_id": 7050, "author_profile": "https://Stackoverflow.com/users/7050", "pm_score": 4, "selected": true, "text": "\n void Application_Start(object sender, EventArgs e) \n {\n // Code that runs on application startup\n\n // check that the minimal security settings are created\n Security.SetupSecurity();\n }\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17176/" ]
156,575
<p>I'm looking for a good TraceListener for .Net that supports rolling over the log file based on size limits. </p> <p><strong>Constraints</strong></p> <ul> <li>Uses .Net built in Trace logging</li> <li>Independent class or binary that's not part of some gigantic library</li> <li>Allows rolling over a log file based on size</li> </ul>
[ { "answer_id": 36406938, "author": "Ostati", "author_id": 2654100, "author_profile": "https://Stackoverflow.com/users/2654100", "pm_score": 4, "selected": false, "text": "<system.diagnostics>\n <sources>\n <source name=\"System.Net\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n <source name=\"System.Net.Http\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n <source name=\"System.Net.Sockets\">\n <listeners>\n <add name=\"System.Net\"/>\n </listeners>\n </source>\n </sources>\n <switches>\n <add name=\"System.Net\" value=\"Verbose\"/>\n <add name=\"System.Net.Http\" value=\"Verbose\"/>\n <add name=\"System.Net.Sockets\" value=\"Verbose\"/>\n </switches>\n <sharedListeners>\n <add name=\"System.Net\"\n type=\"Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a\"\n traceOutputOptions=\"DateTime,ProcessId,ThreadId\"\n customLocation=\"c:\\temp\"\n location=\"Custom\"\n logFileCreationSchedule=\"Daily\"\n baseFileName=\"NetworkTrace\"/>\n </sharedListeners>\n <trace autoflush=\"true\"/>\n</system.diagnostics>\n <runtime>\n <assemblyBinding xmlns=\"urn:schemas-microsoft-com:asm.v1\">\n <dependentAssembly>\n <assemblyIdentity name=\"Microsoft.VisualBasic\" culture=\"neutral\" publicKeyToken=\"b03f5f7f11d50a3a\"/>\n <codeBase version=\"10.0.0.0\" href=\"file://C:/Program Files (x86)/Reference Assemblies/Microsoft/Framework/.NETFramework/v4.5/Microsoft.VisualBasic.dll\"/>\n </dependentAssembly>\n </assemblyBinding>\n </runtime>\n" }, { "answer_id": 41772876, "author": "Mark Sowul", "author_id": 155892, "author_profile": "https://Stackoverflow.com/users/155892", "pm_score": 2, "selected": false, "text": "try/catch (InvalidOperationException) base.Close FullLogFileName base.Close File.Move(FullLogFileName, newFileWithNumber)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156575", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17222/" ]
156,582
<p>I started using <a href="http://www.codeplex.com/SHFB" rel="noreferrer">Sandcastle</a> some time ago to generate a Documentation Website for one of our projects. It's working quite well but we've always only written documentation for classes, methods, properties (...) in our project and had completely separate documentation for the overall project and project parts/modules/namespaces. It would be nice if I could merge that documentation together and add respective documentation to the generated helper files but I can't figure out how to do it.</p> <p>Just adding comments to the namespace declaration doesn't seem to work (C#):</p> <pre><code>/// &lt;summary&gt; /// My short namespace description /// &lt;/summary&gt; namespace MyNamespace { ... } </code></pre> <p>Does anyone know how to do this? I know it's possible somehow and it would be really nice to have... :)</p>
[ { "answer_id": 156726, "author": "Rinat Abdullin", "author_id": 47366, "author_profile": "https://Stackoverflow.com/users/47366", "pm_score": 3, "selected": false, "text": "<namespaceSummaryItem name=\"System\" isDocumented=\"True\">\n Generic interfaces and helper classes.\n</namespaceSummaryItem>\n" }, { "answer_id": 857062, "author": "Tuinstoelen", "author_id": 106145, "author_profile": "https://Stackoverflow.com/users/106145", "pm_score": 7, "selected": true, "text": "namespace Some.Test\n{\n /// <summary>\n /// The <see cref=\"Some.Test\"/> namespace contains classes for ....\n /// </summary>\n\n [System.Runtime.CompilerServices.CompilerGenerated]\n class NamespaceDoc\n {\n }\n}\n" }, { "answer_id": 23339077, "author": "user1587804", "author_id": 1587804, "author_profile": "https://Stackoverflow.com/users/1587804", "pm_score": 1, "selected": false, "text": "/// <summary>\n /// Concrete implementation of see cref=\"IInterface\" using see cref=\"Concrete\"\n /// </summary>\n class NamespaceDoc\n {\n }" }, { "answer_id": 48572464, "author": "JohnKoz", "author_id": 3368670, "author_profile": "https://Stackoverflow.com/users/3368670", "pm_score": 0, "selected": false, "text": "<doc>\n <assembly/>\n <members>\n <member/>\n </members>\n</doc>\n" }, { "answer_id": 61606330, "author": "B Pete", "author_id": 83781, "author_profile": "https://Stackoverflow.com/users/83781", "pm_score": 0, "selected": false, "text": "Namespace Global.TestNamespace\n ''' <summary>\n ''' The <see cref=\"TestNamespace\"/> namespace contains classes for ....\n ''' </summary>\n <System.Runtime.CompilerServices.CompilerGeneratedAttribute()>\n Class NamespaceDoc\n End Class\nEnd Namespace\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156582", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5005/" ]
156,584
<p>I've seen a few examples on how to do build deployment, however I have something unique that I'd like to do:</p> <ol> <li>Deploy the build to a folder that has the build number (eg. Project\Builds\8423)</li> <li>Alter the version number in the .NET AssmblyInfo.cs to match the build number</li> </ol> <p>Has anyone done this before with .NET projects using NAnt + CruiseControl.net?</p>
[ { "answer_id": 163518, "author": "Mike", "author_id": 2848, "author_profile": "https://Stackoverflow.com/users/2848", "pm_score": 0, "selected": false, "text": "<AssemblyInfo CodeLanguage=\"C#\"\n OutputFile=\"%(YourProjects.RootDir)%(Directory)Properties\\AssemblyInfo.cs\"\n AssemblyVersion=\"$(CCNetLabel)\"\n/>\n" }, { "answer_id": 170239, "author": "scott.caligan", "author_id": 14814, "author_profile": "https://Stackoverflow.com/users/14814", "pm_score": 4, "selected": false, "text": "<target name=\"publish\">\n <if test=\"${not property::exists('CCNetLabel')}\">\n <fail message=\"CCNetLabel property not set, so can't create labelled distribution files\" />\n </if>\n\n <property name=\"publishDirectory\" value=\"D:\\Public\\Project\\Builds\\${CCNetLabel}\" />\n\n <mkdir dir=\"${publishDirectory}\" />\n <copy todir=\"${publishDirectory}\">\n <fileset basedir=\"${buildDirectory}\\bin\">\n <include name=\"*.dll\" />\n </fileset>\n </copy> \n</target>\n <asminfo> <target name=\"version\">\n <property name=\"commonAssemblyInfo\" value=\"${buildDirectory}\\CommonAssemblyInfo.cs\" />\n\n <!-- If build is initiated manually, copy standard CommonAssemblyInfo.cs file. -->\n <if test=\"${not property::exists('CCNetLabel')}\">\n <copy file=\".\\src\\CommonAssemblyInfo.cs\" tofile=\"${commonAssemblyInfo}\" />\n </if>\n\n <!-- If build is initiated by CC.NET, create a custom CommonAssemblyInfo.cs file. -->\n <if test=\"${property::exists('CCNetLabel')}\">\n <asminfo output=\"${commonAssemblyInfo}\" language=\"CSharp\">\n <imports>\n <import namespace=\"System\" />\n <import namespace=\"System.Reflection\" />\n </imports>\n <attributes>\n <attribute type=\"AssemblyCompanyAttribute\" value=\"My Company\" />\n <attribute type=\"AssemblyCopyrightAttribute\" value=\"Copyright © 2008 My Company\" />\n <attribute type=\"AssemblyProductAttribute\" value=\"My Product\" />\n <attribute type=\"AssemblyVersionAttribute\" value=\"1.0.0.${CCNetLabel}\" />\n <attribute type=\"AssemblyInformationalVersionAttribute\" value=\"1.0.0.${CCNetLabel}\" />\n </attributes>\n <references>\n <include name=\"System.dll\" />\n </references>\n </asminfo>\n </if>\n</target>\n\n<target name=\"build-my-project\" depends=\"version\">\n <csc target=\"library\" output=\"${buildDirectory}\\bin\\MyProject.dll\">\n <sources>\n <include name=\".\\src\\MyProject\\*.cs\"/>\n <include name=\".\\src\\MyProject\\**\\*.cs\"/>\n <include name=\"${commonAssemblyInfo}\"/>\n </sources>\n </csc>\n</target>\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17222/" ]
156,585
<p>I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty.</p> <p>Currently I'm doing something like this:</p> <pre><code>IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() &lt; 1) { // can that ever happen? throw new ArgumentException("hostName has no assigned IP-Address"); } TcpClient client = new TcpClient(hostEntry.AddressList[0], 1234); </code></pre> <p>My assumption is that Dns.GetHostEntry either throws an exception if the hostname is not found or otherwise the AddressList is nonempty, but I'm not sure about that.</p>
[ { "answer_id": 156638, "author": "mdb", "author_id": 8562, "author_profile": "https://Stackoverflow.com/users/8562", "pm_score": 2, "selected": true, "text": "InternalGetHostByName(string hostName, bool includeIPv6)" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156585", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21038/" ]
156,586
<p>We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that). When we modify a value in database, we have to reload the web server to display the new value on the web app.</p> <p>Is there any simple way to use the new value without restarting the web server ?</p> <p>(We do <strong>not</strong> want to always look up the value from database but we would like to invalidate the cache, for example by calling a special 'admin' URL)</p> <p>EDIT : We are using JDK 1.4, so I would prefer a solution on that version. :)</p>
[ { "answer_id": 156675, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 3, "selected": false, "text": "getTimeToLive() needsReload()" }, { "answer_id": 55914608, "author": "y.hussain", "author_id": 5874302, "author_profile": "https://Stackoverflow.com/users/5874302", "pm_score": 1, "selected": false, "text": "ReloadableResourceBundleMessageSource getProperties PropertiesHolder" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3122/" ]
156,610
<p>I have a requirement to be able to provide a flex component in English and several asian languages. I have looked at the flex documentation and it seems that I have to build several swf's, which feels wrong. </p> <p>Does anyone know of a straightforward and practical way of bundling string resources in different languages and handling the fonts?</p>
[ { "answer_id": 156631, "author": "Nadav", "author_id": 23094, "author_profile": "https://Stackoverflow.com/users/23094", "pm_score": 0, "selected": false, "text": "ResourceBundle" }, { "answer_id": 156718, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 4, "selected": true, "text": ".properties <Label text=\"{resourceManager.getString('mybundle', 'mystring\")'}/>\n -locale=en_US,sv_SE en_US,sv_SE -source-path+=locale/{locale} {locale} -locale localeChain resourceManager.localeChain = [\"sv_SE\", \"en_US\"];\n" }, { "answer_id": 157927, "author": "Brandon", "author_id": 23133, "author_profile": "https://Stackoverflow.com/users/23133", "pm_score": 0, "selected": false, "text": "copylocale.exe en_US sv_SE\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156610", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24039/" ]
156,641
<p>I have a table of users which has a username column consisting of a six digit number e.g 675381, I need to prepend a zero to each of these usernames e.g. 0675381 would be the final output of the previous example, is there a query that could handle this?</p>
[ { "answer_id": 156656, "author": "daniels", "author_id": 9789, "author_profile": "https://Stackoverflow.com/users/9789", "pm_score": 6, "selected": true, "text": "UPDATE Tablename SET Username = Concat('0', Username);\n" }, { "answer_id": 156657, "author": "f13o", "author_id": 20288, "author_profile": "https://Stackoverflow.com/users/20288", "pm_score": 3, "selected": false, "text": "UPDATE your_table SET column_name=concat('0',column_name);\n" }, { "answer_id": 156664, "author": "Mike Woodhouse", "author_id": 1060, "author_profile": "https://Stackoverflow.com/users/1060", "pm_score": 2, "selected": false, "text": "select LPAD(CONVERT(username, CHAR), 7, '0')\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156641", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13658/" ]
156,650
<p>When reviewing, I sometimes encounter this kind of loop:</p> <pre><code>i = begin while ( i != end ) { // ... do stuff if ( i == end-1 (the one-but-last element) ) { ... do other stuff } increment i } </code></pre> <p>Then I ask the question: would you write this?</p> <pre><code>i = begin mid = ( end - begin ) / 2 // (the middle element) while ( i != end ) { // ... do stuff if ( i &gt; mid ) { ... do other stuff } increment i } </code></pre> <p>In my opinion, this beats the intention of writing a loop: you loop because there is something common to be done for each of the elements. Using this construct, for some of the elements you do something different. So, I conclude, you need a separate loop for those elements:</p> <pre><code>i = begin mid = ( end - begin ) / 2 //(the middle element) while ( i != mid ) { // ... do stuff increment i } while ( i != end ) { // ... do stuff // ... do other stuff increment i } </code></pre> <p>Now I even saw a <a href="https://stackoverflow.com/questions/151046/c-last-loop-iteration-stl-map-iterator">question</a> on SO on how to write the <code>if</code>-clause in a nice way... And I got sad: something isn't right here.</p> <p>Am I wrong? If so, what's so good about cluttering the loop body with special cases, which you are aware of upfront, at coding time?</p>
[ { "answer_id": 156669, "author": "Matthias Winkelmann", "author_id": 4494, "author_profile": "https://Stackoverflow.com/users/4494", "pm_score": 4, "selected": false, "text": "for(i=0;i<elements.size;i++) {\n if (i>0) {\n string += ','\n }\n string += elements[i]\n}\n string = elements.join(',')\n" }, { "answer_id": 156678, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 2, "selected": false, "text": "for (i=0; i<5; i++)\n{\n switch(i)\n {\n case 0:\n // something\n break;\n case 1:\n // something else\n break;\n // etc...\n }\n}\n" }, { "answer_id": 156790, "author": "Swanand", "author_id": 18768, "author_profile": "https://Stackoverflow.com/users/18768", "pm_score": 3, "selected": false, "text": "i = begin\nmid = ( end - begin ) / 2 //(the middle element)\nwhile ( i != mid ) { \n // ... do stuff\n increment i\n}\n\nwhile ( i != end ) {\n // ... do other stuff\n increment i\n}\n" }, { "answer_id": 156932, "author": "Jonathan C Dickinson", "author_id": 24064, "author_profile": "https://Stackoverflow.com/users/24064", "pm_score": 3, "selected": false, "text": "if(items == null)\n return null;\n\nStringBuilder result = new StringBuilder();\nif(items.Length != 0)\n{\n result.Append(items[0]); // Special case outside loop.\n for(int i = 1; i < items.Length; i++) // Note: we start at element one.\n {\n result.Append(\";\");\n result.Append(items[i]);\n }\n}\nreturn result.ToString();\n" }, { "answer_id": 15847571, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 2, "selected": false, "text": "i = begin\nwhile ( i != end -1 ) { \n // ... do stuff for element from begn to second last element\n increment i\n}\n\nif(given_array(end -1) != ''){\n // do stuff for the EOF element in the array\n}\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6610/" ]
156,683
<p>I would like to know what of the many XSLT engines out there works well with Perl.</p> <p>I will use Apache (2.0) and Perl, and I want to obtain PDFs and XHTMLs.</p> <p>I'm new to this kind of projects so any comment or suggestion will be welcome.</p> <p>Thanks.</p> <hr> <p>Doing a simple search on Google I found a lot and I suppose that there are to many more.</p> <ul> <li><a href="http://www.mod-xslt2.com/" rel="noreferrer">http://www.mod-xslt2.com/</a></li> <li><a href="http://xml.apache.org/xalan-j/" rel="noreferrer">http://xml.apache.org/xalan-j/</a></li> <li><a href="http://saxon.sourceforge.net/" rel="noreferrer">http://saxon.sourceforge.net/</a></li> <li><a href="http://www.dopscripts.com/xslt_parser.html" rel="noreferrer">http://www.dopscripts.com/xslt_parser.html</a></li> </ul> <p>Any comment on your experiences will be welcome.</p>
[ { "answer_id": 156870, "author": "Penfold", "author_id": 11952, "author_profile": "https://Stackoverflow.com/users/11952", "pm_score": 6, "selected": true, "text": " use XML::LibXSLT;\n use XML::LibXML;\n\n my $parser = XML::LibXML->new();\n my $xslt = XML::LibXSLT->new();\n\n my $source = $parser->parse_file('foo.xml');\n my $style_doc = $parser->parse_file('bar.xsl');\n\n my $stylesheet = $xslt->parse_stylesheet($style_doc);\n\n my $results = $stylesheet->transform($source);\n\n print $stylesheet->output_string($results);\n #create output file\nopen(my $output_xml_file_name, '>', 'test.xml');\nprint $output_xml_file_name \"$results\";\n use XML::LibXSLT::Easy;\n\n my $p = XML::LibXSLT::Easy->new;\n\n my $output = $p->process( xml => \"foo.xml\", xsl => \"foo.xsl\" );\n" } ]
2008/10/01
[ "https://Stackoverflow.com/questions/156683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19689/" ]