qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
296,025
<p>I am preparing a project proposal for a client who wants to publish video in his website. I need to define which video formats will be allowed, which video sizes, as well as the necessary tools for conversion and preparation. </p> <p>I have no experience with embedding video in websites so which markup do I need to play video online?</p>
[ { "answer_id": 296098, "author": "rich", "author_id": 25502, "author_profile": "https://Stackoverflow.com/users/25502", "pm_score": 0, "selected": false, "text": "<embed src=\"http://aaa/bbb/ccc/myVideo.wmv\" type=\"application/x-mplayer2\" pluginspage=\"http://www.microsoft.com/Windows/MediaPlayer/\" name=\"MediaPlayer\" autostart=\"1\" showcontrols=\"1\" showstatusbar=\"0\" autorewind=\"1\" showdisplay=\"0\" height=\"256\" width=\"320\">" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2138/" ]
296,036
<p>If a large module is loaded by some submodule of your code, is there any benefit to referencing the module from that namespace instead of importing it again?</p> <p>For example: I have a module MyLib, which makes extensive use of ReallyBigLib. If I have code that imports MyLib, should I dig the module out like so</p> <pre><code>import MyLib ReallyBigLib = MyLib.SomeModule.ReallyBigLib </code></pre> <p>or just</p> <pre><code>import MyLib import ReallyBigLib </code></pre>
[ { "answer_id": 296062, "author": "Toni Ruža", "author_id": 6267, "author_profile": "https://Stackoverflow.com/users/6267", "pm_score": 7, "selected": true, "text": "import MyLib\nimport ReallyBigLib\n" }, { "answer_id": 298106, "author": "Charles Merriam", "author_id": 1320510, "author_profile": "https://Stackoverflow.com/users/1320510", "pm_score": 5, "selected": false, "text": " # module/file a.py\n print \"Hello from a.py!\"\n import b\n\n # module/file b.py\n print \"Hello from b.py!\"\n import a\n >>> import b\nHello from b.py!\nHello from a.py!\n>>> import a\n>>>\n" }, { "answer_id": 301344, "author": "babbageclunk", "author_id": 38851, "author_profile": "https://Stackoverflow.com/users/38851", "pm_score": 2, "selected": false, "text": "sys.modules sys.modules" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296036", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32880/" ]
296,055
<p>Let's say I want to create the alias %xed for %edit -x. How would I do it?</p>
[ { "answer_id": 296334, "author": "Igal Serban", "author_id": 25737, "author_profile": "https://Stackoverflow.com/users/25737", "pm_score": 3, "selected": true, "text": "def ed_xed(self,arg):\n ip = self.api\n return ip.magic.im_class.magic_edit(ip.IP,\" -x %s \"%arg)\n\nip.expose_magic('xed',ed_xed)\n In [5]: %edit -x\nIn [6]: macro xed 5\nIn [7]: store xed\nIn [8]: xed\n" }, { "answer_id": 11827866, "author": "Carl Smith", "author_id": 1253428, "author_profile": "https://Stackoverflow.com/users/1253428", "pm_score": 2, "selected": false, "text": "get_ipython().expose_magic" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
296,090
<p>I am using C# and DSL Tools for VS2005. </p> <p>I need to create Transactions to change some data but i want them to be hidden from the user, that means, to not show in the UNDO list in VS2005.</p> <p>I tried by disabling the UndoManager</p> <pre><code>store.UndoManager.UndoState = UndoState.Disabled; </code></pre> <p>But by disabling it all existing previous actions in the undo list are cleared.</p> <p>Transactions have a property called "isHidden" but it's readonly i don't know how i can set the to hidden. I also tried to create a new UndoManager but it's also a readonly property...</p> <p>How can i create a transaction that does not appear in the undo list?</p> <p>I'd be glad to write some more details in order to clarify any doubts, Thank you very much, Luís Filipe</p> <p>[added]</p> <p>i paint every shape's background based on a property value. E.g, green if true, red if false. I need to open a transaction to paint the shape's background but for me it behaves as a calculated (read-only) property.</p>
[ { "answer_id": 412905, "author": "Apóstolo", "author_id": 24099, "author_profile": "https://Stackoverflow.com/users/24099", "pm_score": 2, "selected": true, "text": "store.UndoManager.UndoState = UndoState.Disabled store.UndoManager.UndoState = UndoState.DisabledNoFlush;" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296090", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20335/" ]
296,096
<p>I'm writing code in Java, using the NetBeans IDE. I keep getting a couple of "Incompatible Type" errors. I declare a variable as String and then assign to it the value from a method that returns a String too. The error says that there was expected a type of "String" but instead found "..." where "..." the name of the method I call.</p> <p>For example, this is a line that gives me the error:</p> <pre> incompatible types found: encode_monoalphabetic_engine required: java.lang.String encoded = encode_monoalphabetic_engine(string); </pre>
[ { "answer_id": 296106, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 0, "selected": false, "text": "string java.lang.String" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,097
<p>we're dealing with a very slow update statement in an Oracle project.</p> <p>Here's a little script to replciate the issue:</p> <pre><code>drop table j_test; CREATE TABLE J_TEST ( ID NUMBER(10) PRIMARY KEY, C1 VARCHAR2(50 BYTE), C2 VARCHAR2(250 BYTE), C3 NUMBER(5), C4 NUMBER(10) ); -- just insert a bunch of rows insert into j_test (id) select rownum from &lt;dummy_table&gt; where rownum &lt; 100000; -- this is the statement that runs forever (longer than my patience allows) update j_test set C3 = 1, C1 = 'NEU'; </code></pre> <p>There are some environments where the Update-Statement takes just about 20 seconds, some where the statement runs for a few minutes. When using more rows, the problem gets even worse.</p> <p>We have no idea what is causing this behavior, and would like to have an understanding of what is going on before proposing a solution.</p> <p>Any ideas and suggestions? Thanks Thorsten</p>
[ { "answer_id": 296123, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 2, "selected": false, "text": "insert into j_test (id, C3, C4)\nselect rownum, 1, 'NEU'\nfrom <dummy_table>\nwhere rownum < 100000;\n" }, { "answer_id": 296171, "author": "user34850", "author_id": 34850, "author_profile": "https://Stackoverflow.com/users/34850", "pm_score": 2, "selected": false, "text": "UPDATE j_test\n SET c3 = 3\n WHERE c1 = 'NEU'\n" }, { "answer_id": 296188, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 5, "selected": true, "text": "CREATE TABLE J_TEST\n(\n ID NUMBER(10) PRIMARY KEY,\n C1 VARCHAR2(50 BYTE),\n C2 VARCHAR2(250 BYTE),\n C3 NUMBER(5),\n C4 NUMBER(10)\n) PCTFREE 40;\n SQL> CREATE TABLE J_TEST\n 2 (\n 3 ID NUMBER(10) PRIMARY KEY,\n 4 C1 VARCHAR2(50 BYTE),\n 5 C2 VARCHAR2(250 BYTE),\n 6 C3 NUMBER(5),\n 7 C4 NUMBER(10)\n 8 );\n\nTable created.\n\nSQL> insert into j_test (id)\n 2 select rownum \n 3 from transactions\n 4 where rownum < 100000;\n\n99999 rows created.\n\nSQL> update j_test\n 2 set C3 = 1,\n 3 C2 = 'NEU'\n 4 /\n\n99999 rows updated.\n\nElapsed: 00:01:41.60\n\nSQL> analyze table j_test compute statistics;\n\nTable analyzed.\n\nSQL> select blocks, chain_cnt from user_tables where table_name='J_TEST';\n\n BLOCKS CHAIN_CNT\n---------- ----------\n 694 82034\n\nSQL> drop table j_test;\n\nTable dropped.\n\nSQL> CREATE TABLE J_TEST\n 2 (\n 3 ID NUMBER(10) PRIMARY KEY,\n 4 C1 VARCHAR2(50 BYTE),\n 5 C2 VARCHAR2(250 BYTE),\n 6 C3 NUMBER(5),\n 7 C4 NUMBER(10)\n 8 ) PCTFREE 40;\n\nTable created.\n\nSQL> insert into j_test (id)\n 2 select rownum \n 3 from transactions\n 4 where rownum < 100000;\n\n99999 rows created.\n\nSQL> update j_test\n 2 set C3 = 1,\n 3 C2 = 'NEU'\n 4 /\n\n99999 rows updated.\n\nElapsed: 00:00:27.74\n\nSQL> analyze table j_test compute statistics;\n\nTable analyzed.\n\nSQL> select blocks, chain_cnt from user_tables where table_name='J_TEST';\n\n BLOCKS CHAIN_CNT\n---------- ----------\n 232 0\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296097", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25320/" ]
296,116
<p>I am implementing web services for a PHP application and am trying to understand what both standard web services and RESTful web services have to offer. My intent is to write wrapper code to abstract away the web service details so that developers can just "instantiate remote objects" and use them. Here are my thoughts, perhaps some of you could add your experience and expand this:</p> <p><strong>RESTful Web Servcies</strong></p> <p>are basically just "XML feeds on demand", so e.g. you could write wrapper code for a client application so it could query the server application in this way:</p> <pre><code>$users = Users::getUsers("state = 'CO'"); </code></pre> <ul> <li>this would in turn get an XML feed form a remote URL</li> <li>$users could be made into a collection of full User objects, or</li> <li>left as XML, or</li> <li>turned into an array, etc.</li> <li>the query script ("state = 'CO'") would be translated into SQL on the server side</li> <li><p>RESTful Web Services are in general read-only from the view of the client, although you could write code which could use POST or GET to make changes on the server, e.g. passing an encrypted token for security, e.g.:</p> <p>$users = Users::addUser($encryptedTrustToken, 'jim',$encryptedPassword, 'James', 'Taylor');</p></li> </ul> <p>and this would create a new user on the server application.</p> <p><strong>Standard Web Services</strong></p> <p>Standard Web Servcies in the end basically do the same thing. The one advantage they have is that client can discover their details via WSDL. But other than that, if I want to write wrapper code which allows a developer to instantiate, edit and save objects remotely, I still need to implement the wrapper code. SOAP doesn't do any of that for me, it can do this:</p> <pre><code>$soap = new nusoap_client('http://localhost/test/webservice_user.php?wsdl', true); $user = $soap-&gt;getProxy(); $lastName = $user-&gt;lastName(); </code></pre> <p>but if I want to edit and save:</p> <pre><code>$user-&gt;setLastName('Jones'); $user-&gt;save(); </code></pre> <p>then I need to e.g. handle all of the state on the server side, SOAP doesn't seem to hold that object on the server side for each client. </p> <p>Perhaps there are limitations in the PHP SOAP implementation I am using (nusoap). Perhaps Java and .NET implementations do much more.</p> <p>Will enjoy hearing your feedback to clear up some of these clouds.</p>
[ { "answer_id": 296170, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "var someResult = proxy.SubmitOrder(...);\n var qry = from user in ctx.Users\n where user.State == 'CO'\n select user;\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296116", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4639/" ]
296,133
<p>I'm astonished that the <a href="http://commons.apache.org/collections/" rel="nofollow noreferrer">Apache Commons Collections</a> project still hasn't got around to making their library generics-aware. I really like the features provided by this library, but the lack of support for generics is a big turn-off. There is a <a href="http://larvalabs.com/collections/index.html" rel="nofollow noreferrer">Lavalabs fork of Commons Collections which does support generics</a>, which seems to claim backward compatibility, but when I tried updating to this version, my web application failed to start (in JBoss).</p> <p>My questions are:</p> <ul> <li>Whether anyone has successfully updated from Commons Collections to the fork mentioned above</li> <li>If Commons Collections has any plans to add support for generics</li> </ul> <p>BTW, I'm aware of Google collections, but am reluctant to use it until the API stabilises.</p> <p>Cheers, Don</p>
[ { "answer_id": 4647248, "author": "linuxbuild", "author_id": 241776, "author_profile": "https://Stackoverflow.com/users/241776", "pm_score": 1, "selected": false, "text": "org.apache.commons.collections org.apache.commons.collections15 commons-collections-3.2.1.jar collections-generic-4.01.jar" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
296,146
<p>I am sure making a silly mistake but I can't figure what:</p> <p>In SQL Server 2005 I am trying select all customers except those who have made a reservation before 2 AM.</p> <p>When I run this query:</p> <pre><code>SELECT idCustomer FROM reservations WHERE idCustomer NOT IN (SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) &lt; 2) </code></pre> <p>I get 0 results.</p> <p>But </p> <pre><code>SELECT idCustomer FROM reservations </code></pre> <p>returns 152.000 results and the "NOT IN" part:</p> <pre><code>SELECT distinct idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) &lt; 2 </code></pre> <p>returns only 284 rows</p>
[ { "answer_id": 296158, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 7, "selected": true, "text": "SELECT distinct idCustomer FROM reservations\nWHERE DATEPART ( hour, insertDate) < 2\n and idCustomer is not null\n WHERE field1 NOT IN (1, 2, 3, null)\n WHERE NOT (field1 = 1 OR field1 = 2 OR field1 = 3 OR field1 = null)\n" }, { "answer_id": 296200, "author": "jerryhung", "author_id": 37568, "author_profile": "https://Stackoverflow.com/users/37568", "pm_score": 2, "selected": false, "text": "SELECT idCustomer FROM reservations \nEXCEPT\nSELECT idCustomer FROM reservations WHERE DATEPART ( hour, insertDate) < 2\n" }, { "answer_id": 296224, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 0, "selected": false, "text": "SELECT Reservations.idCustomer FROM Reservations (nolock)\nLEFT OUTER JOIN @reservations ExcludedReservations (nolock) ON Reservations.idCustomer=ExcludedReservations.idCustomer AND DATEPART(hour, ExcludedReservations.insertDate) < 2\nWHERE ExcludedReservations.idCustomer IS NULL AND Reservations.idCustomer IS NOT NULL\nGROUP BY Reservations.idCustomer\n" }, { "answer_id": 296228, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "SELECT distinct idCustomer FROM reservations \nWHERE DATEPART(hour, insertDate) >= 2\n" }, { "answer_id": 296453, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 3, "selected": false, "text": "NULL IN IN NOT IN IF 1 NOT IN (1, 2, 3, NULL) PRINT '1 NOT IN (1, 2, 3, NULL)'\nIF 1 NOT IN (2, 3, NULL) PRINT '1 NOT IN (2, 3, NULL)'\nIF 1 NOT IN (2, 3) PRINT '1 NOT IN (2, 3)' -- Prints\nIF 1 IN (1, 2, 3, NULL) PRINT '1 IN (1, 2, 3, NULL)' -- Prints\nIF 1 IN (2, 3, NULL) PRINT '1 IN (2, 3, NULL)'\nIF 1 IN (2, 3) PRINT '1 IN (2, 3)'\n" }, { "answer_id": 41734614, "author": "Akash Pawar", "author_id": 7439129, "author_profile": "https://Stackoverflow.com/users/7439129", "pm_score": -1, "selected": false, "text": "SELECT MIN(A.maxsal) secondhigh\nFROM (\n SELECT TOP 2 MAX(EmployeeBasic) maxsal\n FROM M_Salary\n GROUP BY EmployeeBasic\n ORDER BY EmployeeBasic DESC\n ) A\n" }, { "answer_id": 44899349, "author": "santhosh", "author_id": 6274381, "author_profile": "https://Stackoverflow.com/users/6274381", "pm_score": -1, "selected": false, "text": "select * from table_name where id=5 and column_name not in ('sandy,'pandy');\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4264/" ]
296,147
<p>I have a web service class that the rest of the framework depends on to grab its data, but the web service class needs to have different method attributes depending on what environment it's in. For instance...</p> <pre><code>[SoapDocumentMethodAttribute("https://example",...)] public string Test() { //doSomething } </code></pre> <p>See that "<a href="https://example" rel="nofollow noreferrer">https://example</a>"? That needs to change depending on the environment. AFAIK you can't make that string dynamic for runtime, it has to be compiled that way. So I'm trying to get it so that I have multiple CS files for this web service that have the different attribute URLs hardcoded in them, and MSBuild swaps them on precompile. So I'd have a base "Service.cs" for testing, "Service.cs.production" for the production environment, and so on.</p> <ul> <li>Is this the best way to do this, or am I missing something where I can have one CS that handles the environment on its own?</li> <li>To preserve having the same class name and IntelliSense not thinking things are ambiguous, I'm mucking up the file extensions ("Service.cs" versus "Service.cs.production"). Is that the only way to do it?</li> <li>Considering all the above is OK, and I'm compiling against a "Production" configuration, can it compile Service.cs.production <strong>instead of</strong> Service.cs and everything goes hunky-dorey?</li> </ul> <p>Thanks!</p>
[ { "answer_id": 296185, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "#if TESTING\n [SoapDocumentMethodAttribute(something)]\n#else\n [SoapDocumentMethodAttribute(someotherthing)]\n#endif\n <DefineConstants>TESTING</DefineConstants>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296147", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1212/" ]
296,148
<p>I have the following div layout:</p> <img src="https://i.stack.imgur.com/bZSnA.jpg"> <p>Everything is fine when I put normal txt elements in both the blue and the orange div. However, when I place an image in the orange div (which is 31px), the elements in the blue div get pushed down by about half the height of the blue div.</p> <p>(additional info, when hovering over the html for the orange div in firebug, it seems like only half of the image is contained within it, even though to the naked eye it appears fine).</p> <p>Would appreciate any help, I'm still a bit rusty on the box model. Thanks.</p>
[ { "answer_id": 296166, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 0, "selected": false, "text": "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n" }, { "answer_id": 296237, "author": "Ola Tuvesson", "author_id": 6903, "author_profile": "https://Stackoverflow.com/users/6903", "pm_score": 3, "selected": true, "text": "<style>\ndiv {\nposition: absolute;\nborder: 1px solid blue;\n}\ndiv img {\nheight: 31px;\nwidth: 50px;\nfloat: left;\n}\n</style>\n\n<div>\n <img src=\"myImage.gif\">\n <p>Lorem ipsum dolor sit amet...</p>\n</div>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28871/" ]
296,150
<p>Many times I saw logging of errors like these:</p> <pre><code>System.out.println("Method aMethod with parameters a:"+a+" b: "+b); print("Error in line 88"); </code></pre> <p>so.. What are the best practices to log an error?</p> <p><strong>EDIT:</strong></p> <p>This is java but could be C/C++, basic, etc.</p>
[ { "answer_id": 296194, "author": "adam", "author_id": 33604, "author_profile": "https://Stackoverflow.com/users/33604", "pm_score": 2, "selected": false, "text": "log.warning(\"..\");\nlog.fine(\"..\");\nlog.finer(\"..\");\nlog.finest(\"..\");\n log.log(Level.WARNING, \"blah blah blah\", e);\n handlers = java.util.logging.ConsoleHandler\n\n.level = WARNING\n\njava.util.logging.ConsoleHandler.level = ALL\n\ncom.example.blah = FINE\ncom.example.testcomponents = FINEST\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24639/" ]
296,173
<p>I'd like to copy the files that have a specific file extension to a new folder. I have an idea how to use <code>os.walk</code> but specifically how would I go about using that? I'm searching for the files with a specific file extension in only one folder (this folder has 2 subdirectories but the files I'm looking for will never be found in these 2 subdirectories so I don't need to search in these subdirectories). Thanks in advance.</p>
[ { "answer_id": 296184, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 6, "selected": true, "text": "import glob, os, shutil\n\nfiles = glob.iglob(os.path.join(source_dir, \"*.ext\"))\nfor file in files:\n if os.path.isfile(file):\n shutil.copy2(file, dest_dir)\n" }, { "answer_id": 296620, "author": "Deon", "author_id": 37056, "author_profile": "https://Stackoverflow.com/users/37056", "pm_score": 2, "selected": false, "text": "for root, dirs, files in os.walk(srcDir):\n for file in files:\n if file[-4:].lower() == '.jpg':\n shutil.copy(os.path.join(root, file), os.path.join(dest, file))\n" }, { "answer_id": 296621, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 3, "selected": false, "text": "import os, shutil\n\nfor basename in os.listdir(srcdir):\n if basename.endswith('.ext'):\n pathname = os.path.join(srcdir, basename)\n if os.path.isfile(pathname):\n shutil.copy2(pathname, dstdir)\n" }, { "answer_id": 299685, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "os.walk import fnmatch, os, shutil\n\ndef copyfiles(srcdir, dstdir, filepattern):\n def failed(exc):\n raise exc\n\n for dirpath, dirs, files in os.walk(srcdir, topdown=True, onerror=failed):\n for file in fnmatch.filter(files, filepattern):\n shutil.copy2(os.path.join(dirpath, file), dstdir)\n break # no recursion\n copyfiles(\".\", \"test\", \"*.ext\")\n" }, { "answer_id": 14833938, "author": "Mihai", "author_id": 2064949, "author_profile": "https://Stackoverflow.com/users/2064949", "pm_score": 1, "selected": false, "text": "import os, shutil, sys\n\nsrcDir = sys.argv[1] \ndstDir = sys.argv[2]\nextension = sys.argv[3]\n\nprint \"Source Dir: \", srcDir, \"\\n\", \"Destination Dir: \",dstDir, \"\\n\", \"Extension: \", extension\n\nfor root, dirs, files in os.walk(srcDir):\n for file_ in files:\n if file_.endswith(extension):\n shutil.copy(os.path.join(root, file_), os.path.join(dstDir, file_))\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
296,182
<p>In the standard PrintDialog there are four values associated with a selected printer: Status, Type, Where, and Comment.</p> <p>If I know a printer's name, how can I get these values in C# 2.0?</p>
[ { "answer_id": 296298, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 5, "selected": false, "text": "using System.Drawing.Printing;\n PrinterSettings ps = new PrinterSettings();\nps.PrinterName = \"The printer name\"; // Load the appropriate printer's setting\n ps.isValid()" }, { "answer_id": 296375, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 7, "selected": true, "text": "using System.Management;\n string printerName = \"YourPrinterName\";\nstring query = string.Format(\"SELECT * from Win32_Printer WHERE Name LIKE '%{0}'\", printerName);\n\nusing (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))\nusing (ManagementObjectCollection coll = searcher.Get())\n{\n try\n {\n foreach (ManagementObject printer in coll)\n {\n foreach (PropertyData property in printer.Properties)\n {\n Console.WriteLine(string.Format(\"{0}: {1}\", property.Name, property.Value));\n }\n }\n }\n catch (ManagementException ex)\n {\n Console.WriteLine(ex.Message);\n }\n}\n" }, { "answer_id": 7059300, "author": "itsho", "author_id": 426315, "author_profile": "https://Stackoverflow.com/users/426315", "pm_score": 2, "selected": false, "text": "string[] arrExtendedPrinterStatus = { \n \"\",\"Other\", \"Unknown\", \"Idle\", \"Printing\", \"Warming Up\",\n \"Stopped Printing\", \"Offline\", \"Paused\", \"Error\", \"Busy\",\n \"Not Available\", \"Waiting\", \"Processing\", \"Initialization\",\n \"Power Save\", \"Pending Deletion\", \"I/O Active\", \"Manual Feed\"\n};\n string[] arrErrorState = {\n \"Unknown\", \"Other\", \"No Error\", \"Low Paper\", \"No Paper\", \"Low Toner\",\n \"No Toner\", \"Door Open\", \"Jammed\", \"Offline\", \"Service Requested\",\n \"Output Bin Full\"\n};\n" }, { "answer_id": 8857520, "author": "David", "author_id": 1148554, "author_profile": "https://Stackoverflow.com/users/1148554", "pm_score": 2, "selected": false, "text": "usage: printer.Properties[\"PropName\"].Value\n" }, { "answer_id": 26738414, "author": "stoj", "author_id": 227110, "author_profile": "https://Stackoverflow.com/users/227110", "pm_score": 2, "selected": false, "text": "var queue = new LocalPrintServer().GetPrintQueue(\"Printer Name\");\nvar queueStatus = queue.QueueStatus;\nvar jobStatus = queue.GetPrintJobInfoCollection().FirstOrDefault().JobStatus\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38258/" ]
296,199
<p>I looked at the different options for plotting functions (or other types of graphs) in an interactive window. I mostly use wxWidgets but I'd be open to any other "interfaces". </p> <h2><strong>Looking at what is available, here is what I've found</strong>:</h2> <p><strong>wxPlot</strong>: Not updated since 2006. But it would be a good candidate if it was...</p> <p><strong>wxMathPlot</strong>: Very new, not mature, few features (still active?)</p> <p><strong>libgraph</strong>: Outdated, not rebust, 2D only and outputs images only.</p> <p><strong>koolplot</strong>: Too basic, no control over the created window.</p> <p><strong>EasyBMP</strong>: Very basic, only images output.</p> <p><strong>plotutils</strong>: Command line only.</p> <p><strong>plplot</strong>: C and C++ API are barely maintained. It is in fact on this that wxPlot is based. Could be a could candidate also if C and C++ interface we're updated.</p> <p>Any comments? Ideas?</p> <p>Thanks!</p>
[ { "answer_id": 391215, "author": "Gant", "author_id": 12460, "author_profile": "https://Stackoverflow.com/users/12460", "pm_score": 3, "selected": false, "text": "system()" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296199", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38290/" ]
296,230
<p>In javascript, I've got a block of HTML like this:</p> <pre><code>&lt;h2&gt;{title}&lt;/h2&gt; &lt;p&gt;&lt;a href="{url}"&gt;{content}&lt;/a&gt;&lt;/p&gt; </code></pre> <p>And I'm trying use regex "match" to spit out an array of all the {item}'s. So my output should look like:</p> <pre><code>['title', 'url', 'content'] </code></pre> <p>I've gotten as far as:</p> <pre><code>var pattern = new RegExp("\{[a-zA-Z]+\}+"); var match = pattern.exec("{Sample} bob {text}"); </code></pre> <p>But it's only returning the first tag. </p> <p>This is just beyond my regex skills. Can anyone help?</p> <p>Cheers!</p>
[ { "answer_id": 296235, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 2, "selected": false, "text": "var pattern = new RegExp(\"\\{[a-zA-Z]+\\}+\", \"g\");\n" }, { "answer_id": 296266, "author": "Jan Goyvaerts", "author_id": 33358, "author_profile": "https://Stackoverflow.com/users/33358", "pm_score": 4, "selected": true, "text": "var pattern = new RegExp(\"\\{[a-zA-Z]+\\}\", \"g\");\n var pattern = /\\{[a-zA-Z]+\\}/g;\n var matches = \"{Sample} bob {text}\".match(pattern);\n" }, { "answer_id": 296295, "author": "Corey", "author_id": 38241, "author_profile": "https://Stackoverflow.com/users/38241", "pm_score": 0, "selected": false, "text": "exec" }, { "answer_id": 296313, "author": "dlamblin", "author_id": 459, "author_profile": "https://Stackoverflow.com/users/459", "pm_score": 1, "selected": false, "text": "String.prototype.template = function (obj) {\n return this.replace(/{([^{}]+)}/g,\n function (full, word) {\n return((typeof obj[word]==='string'||typeof obj[word]==='number')?obj[word]:full);\n }\n );\n};\n\n\"The {adj1} {adj2} {noun}.\".template({adj1: 'lazy',adj2: 'brown', noun: 'dog'})\n==> \"The lazy brown dog.\"\n" }, { "answer_id": 296345, "author": "Kristof Neirynck", "author_id": 11451, "author_profile": "https://Stackoverflow.com/users/11451", "pm_score": 1, "selected": false, "text": "<script>\nvar text = '<h2>{title}</h2>\\n<p><a href=\"{url}\">{content}</a></p>';\nvar regex = /\\{[a-z]+\\}/ig;\nvar result = text.match(regex);\nfor (var i = 0; i < result.length; i++) {\n console.debug(i + \". \" + result[i]);\n}\n/*\ngives:\n0. {title}\n1. {test}\n2. {url}\n3. {content}\n*/\n</script>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38241/" ]
296,251
<p>I have a set of classes, each one is a different <a href="http://en.wikipedia.org/wiki/Strategy_pattern" rel="noreferrer">strategy</a> to do the same work. </p> <pre><code>namespace BigCorp.SuperApp { public class BaseClass { } public class ClassA : BaseClass { } public class ClassB : BaseClass { } } </code></pre> <p>The choice of which strategy to use is configurable. I want to configure only the class name 'ClassB' instead of the full type name 'BigCorp.SuperApp.ClassB' in the app.config file.</p> <pre><code>&lt;appConfig&gt; &lt;SuperAppConfig&gt; &lt;Handler name="ClassB" /&gt; &lt;/SuperAppConfig&gt; &lt;/appConfig&gt; </code></pre> <p>However, the reflection calls fail because they expect the full type name, particularly</p> <pre><code>Type t = Type.GetType("ClassB"); // results in t == null BaseClass c = Activator.CreateInstance(t) as BaseClass; // fails </code></pre> <p>How can I get this to work while configuring only the class name? Concatenate the namespace to the class name for full type name? Is there another reflection call that works?</p> <p>If you think this is useless and I should expect the configuration to contain the full type name, I am open to that solution! Just provide rationale to convince me.</p> <p>(I will not be loading a type from outside this assembly/namespace)</p>
[ { "answer_id": 296260, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "Assembly.GetType(name) Assembly assembly = typeof(SomeKnownType).Assembly; // in the same assembly!\nType type = assembly.GetType(name); // full name - i.e. with namespace (perhaps concatenate)\nobject obj = Activator.CreateInstance(type);\n Type.GetType(string)" }, { "answer_id": 296302, "author": "Kyle Trauberman", "author_id": 21461, "author_profile": "https://Stackoverflow.com/users/21461", "pm_score": 3, "selected": false, "text": "Type t = Type.GetType(\"Namespace.\" + className); \nBaseClass c = Activator.CreateInstance(t) as BaseClass; \n" }, { "answer_id": 296406, "author": "Bryan Watts", "author_id": 37815, "author_profile": "https://Stackoverflow.com/users/37815", "pm_score": 4, "selected": true, "text": "<appConfig>\n <SuperAppConfig handlerNamespace=\"BigCorp.SuperApp\">\n <Handler class=\"ClassB\" />\n </SuperAppConfig>\n</appConfig>\n" }, { "answer_id": 298992, "author": "Anthony Mastrean", "author_id": 3619, "author_profile": "https://Stackoverflow.com/users/3619", "pm_score": 2, "selected": false, "text": "<SuperAppConfig>\n <ObjectConfig provider=\"BigCorp.SuperApp.ClassA\">\n <add name=\"one\" />\n <add name=\"two\" />\n </ObjectConfig>\n</SuperAppConfig>\n private static Assembly a = typeof(IFactoryObject).Assembly;\npublic static IFactoryObject CreateObject(String providerName)\n{\n Type t = a.GetType(providerName)\n IFactoryObject o = Activator.CreateInstance(t) as IFactoryObject;\n return o;\n}\n" }, { "answer_id": 7545097, "author": "citronas", "author_id": 225808, "author_profile": "https://Stackoverflow.com/users/225808", "pm_score": 1, "selected": false, "text": "BaseClass c = Activator.CreateInstance(t) as BaseClass; // fails\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3619/" ]
296,256
<p>I am looking for a Windows based library which can be used for parsing a bunch of C files to list global and local variables. The global and local variables may be declared using typedef. The output (i.e. list of global and local variables) can then be used for post processing (e.g. replacing the variable names with a new name).</p> <p>Is such a library available?</p>
[ { "answer_id": 296965, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 0, "selected": false, "text": "lex yacc" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296256", "https://Stackoverflow.com", "https://Stackoverflow.com/users/30289/" ]
296,261
<p>When I try using a <code>Name="id"</code> and\or <code>x:name="id"</code> I get a compiler error:</p> <pre><code>The Type 'MyName' was not found. Verify that you are not missing an assembly reference and that all referenced assemblies have been built. </code></pre> <p>When I don't have this specified my control runs just fine. Any suggestions?</p>
[ { "answer_id": 296296, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 0, "selected": false, "text": "ContentControl" }, { "answer_id": 343452, "author": "Miral", "author_id": 43534, "author_profile": "https://Stackoverflow.com/users/43534", "pm_score": 3, "selected": true, "text": "x:Name Name x:Class" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/805/" ]
296,263
<p>What is the <code>@</code> symbol mean in <a href="/questions/tagged/oracle" class="post-tag" title="show questions tagged &#39;oracle&#39;" rel="tag">oracle</a>? </p> <p>For example:</p> <pre><code>select * from question_answer@abcd where id = '45' </code></pre>
[ { "answer_id": 296331, "author": "a2800276", "author_id": 27408, "author_profile": "https://Stackoverflow.com/users/27408", "pm_score": 6, "selected": true, "text": "select * from question_answer@abcd where id = '45'\n question_answer abcd dblink" }, { "answer_id": 296332, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 4, "selected": false, "text": "SELECT * FROM all_db_links;\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,264
<p>In EL expressions, used in a jsp page, strings are taken literally. For example, in the following code snippet</p> <pre><code>&lt;c:when test="${myvar == 'prefix.*'}"&gt; </code></pre> <p>test does not evaluate to true if the value of myvar is 'prefixxxxx.' Does anyone know if there is a way to have the string interpreted as a regex instead? Does EL have something similar to awk's tilde ~ operator?</p>
[ { "answer_id": 296324, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 3, "selected": false, "text": "<c:when test=\"${fn:startsWith(myVar, 'prefix')}\">\n" }, { "answer_id": 296712, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "fn:startsWith import java.util.regex.Pattern;\n\npublic class Regexp {\n\n public static boolean matches(String pattern, CharSequence str) {\n return Pattern.compile(pattern).matcher(str).matches();\n }\n\n}\n <taglib xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd\" version=\"2.0\">\n <tlib-version>1.0</tlib-version>\n <short-name>x-c</short-name>\n <uri>http://dev.x.com/taglib/core/1.0</uri>\n <function>\n <description>Test whether a string matches a regular expression.</description>\n <display-name>Matches</display-name>\n <name>matches</name>\n <function-class>com.x.taglib.core.Regexp</function-class>\n <function-signature>boolean matches(java.lang.String, java.lang.CharSequence)</function-signature>\n </function>\n</taglib>\n" }, { "answer_id": 19530877, "author": "abualy", "author_id": 2909350, "author_profile": "https://Stackoverflow.com/users/2909350", "pm_score": 3, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>\n<taglib version=\"2.1\"\n xmlns=\"http://java.sun.com/xml/ns/javaee\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee\n http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd\">\n\n <display-name>Acme tags</display-name>\n <short-name>custom</short-name>\n <uri>http://www.acme.com.au</uri>\n <function>\n <name>matches</name>\n <function-class>java.util.regex.Pattern</function-class>\n <function-signature>\n boolean matches(java.lang.String, java.lang.CharSequence)\n </function-signature>\n </function>\n</taglib>\n <%@taglib uri=\"http://www.acme.com.au\" prefix=\"custom\"%>\ncustom:matches('aaa.+', someVar) }\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1094969/" ]
296,268
<p>I'm thinking about starting work on a fairly large scale .NET or ASP.NET project (I haven't decided yet, but it is likely that, eventually, it will be accessible from both a desktop application written in .NET as well as an ASP.NET web application). However, I'm not sure if there's a conventional way to structure the project.</p> <p>The project itself is a resource/knowledge management tool that tracks a number of knowledge sources - people, publications (books, journals, magazines), web resources, digital documents (including PDF, Word documents, ODF documents, MP3s and more) and others as I see fit. Of course, because its so large, I want to be able to implement and test one section at a time, but have them integrated into a single system.</p> <p>Once I have a section or two done and tested, I want to release this as an open-source tool. However, if others are going to be working on this, I want to present them with an easy to understand structure. However, I have never worked on an ASP.NET project and I haven't touched .NET since when the 2.0 framework was new. I'm looking for any conventions that exist within the .NET community as well as any general conventions as to how such a large scale project can be structured to make design, development, testing, use, and maintenance as easy and painless as possible for anyone who uses or works on this project.</p> <p><strong>EDIT 1:</strong> I'm not only looking for patterns (like what Toran Billups pointed out), but also directory structures, project structures (as in the VisualStudio project), and documentation structures.</p>
[ { "answer_id": 309827, "author": "Keith G", "author_id": 5208, "author_profile": "https://Stackoverflow.com/users/5208", "pm_score": 1, "selected": false, "text": "projectname/\n /source/\n /source/projectname.sln\n /source/DataAccess/\n /source/DataAccess/DataAccess.csproj\n /database/schema/\n /database/schema/something.sql\n /database/testdata/\n /database/refdata/\n /tools/\n /COTS/\n /COTS/vendorname/\n /COTS/vendorname/somelib.dll\n /doc/\n /build/\n /installer/\n /projectname.build\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/572/" ]
296,270
<p>I apologize in advance if this question seems remedial.</p> <p>Which would be considered more efficient in Python:</p> <p><strong>Standard import</strong></p> <pre><code>import logging try: ...some code... exception Exception, e: logging.error(e) </code></pre> <p>...or...</p> <p><strong>Contextual import</strong></p> <pre><code>try: ...some code... exception Exception, e: import logging logging.error(e) </code></pre>
[ { "answer_id": 296292, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "import" }, { "answer_id": 296380, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "import if if someConfig:\n import this as bigDeal\nelse:\n import that as bigDeal\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296270", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10040/" ]
296,283
<p>The "ATL simple object" wizard doesn't provide a way to specify that a new class is derived from an existing coclass and its interface. In Visual Studio 2008, how do I make a new ATL COM class derived from an existing one (i.e. <code>Base</code> implements <code>IBase</code>, and I want to make a new <code>Derived</code> class derived from <code>Base</code> that implements <code>IDerived</code>, where <code>IDerived</code> is derived from <code>IBase</code>.)</p> <p>Update: it sounds simple, but a wizard-generated ATL class has up to six base classes, a COM map and a connection point map. Which of these base classes and maps should be repeated in the derived class? If maps are repeated in the derived class should they contain the contents of the base class map or just the additional items? Does the order of base classes matter? What about <code>FinalConstruct()</code> and <code>FinalRelease()</code>? Should <code>DECLARE_PROTECT_FINAL_CONSTRUCT</code> and <code>DECLARE_REGISTRY_RESOURCEID</code> be repeated in the derived class?</p> <p>Here's a sample base class that is empty except for all the boilerplate. Now what should the derived class look like?</p> <pre><code>class ATL_NO_VTABLE CBase : public CComObjectRootEx&lt;CComSingleThreadModel&gt;, public CComCoClass&lt;CBase, &amp;CLSID_Base&gt;, public ISupportErrorInfo, public IConnectionPointContainerImpl&lt;CBase&gt;, public CProxy_IBaseEvents&lt;CBase&gt;, public IDispatchImpl&lt;IBase, &amp;IID_IBase, &amp;LIBID_ExampleLib, /*wMajor =*/ 1, /*wMinor =*/ 0&gt; { public: CBase() { } DECLARE_REGISTRY_RESOURCEID(IDR_Base) BEGIN_COM_MAP(CBase) COM_INTERFACE_ENTRY(IBase) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IConnectionPointContainer) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(CBase) CONNECTION_POINT_ENTRY(__uuidof(_IBaseEvents)) END_CONNECTION_POINT_MAP() // ISupportsErrorInfo STDMETHOD(InterfaceSupportsErrorInfo)(REFIID riid); DECLARE_PROTECT_FINAL_CONSTRUCT() HRESULT FinalConstruct() { return S_OK; } void FinalRelease() { } }; OBJECT_ENTRY_AUTO(__uuidof(Base), CBase) </code></pre>
[ { "answer_id": 375067, "author": "computinglife", "author_id": 17224, "author_profile": "https://Stackoverflow.com/users/17224", "pm_score": 1, "selected": false, "text": "CBaseLogic : IBase\n\nclass ATL_NO_VTABLE CBase :\n public CComObjectRootEx<CComSingleThreadModel>,\n public CComCoClass<CBase, &CLSID_Base>,\n public ISupportErrorInfo,\n public IConnectionPointContainerImpl<CBase>,\n public CProxy_IBaseEvents<CBase>,\n public IDispatchImpl<IBase, &IID_IBase, &LIBID_ExampleLib\n{\nCBaseLogic m_LogicObj; /* Method calls are simply forwarded to this member */\n};\n\n\nCDerivedLogic : public CBaseLogic\n\nclass ATL_NO_VTABLE CDerived :\n public CComObjectRootEx<CComSingleThreadModel>,\n public CComCoClass<CDerived, &CLSID_Base>,\n public ISupportErrorInfo,\n public IConnectionPointContainerImpl<CDerived>,\n public CProxy_IBaseEvents<CDerived>,\n public IDispatchImpl<IBase, &IID_IBase, &LIBID_ExampleLib\n{\nCDerivedLogic m_LogicObj;\n};\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296283", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22820/" ]
296,284
<p>I would like to create dynamic urls that route to controller actions with an Id value. I've created the following route using a catch-all parameter</p> <pre><code>routes.MapRoute( "RouteName", "{id}/{*Url}", new { controller = "Controller", action = "Action", id = "" } ); </code></pre> <p>This works as expected and allows me to use the following Urls:</p> <p>"<a href="http://website.com/1/fake/url/path" rel="nofollow noreferrer">http://website.com/1/fake/url/path</a>" (1 being the id that gets passed to the action method)</p> <p>Does anyone know a way to achieve it this way instead without creating my own http module?:</p> <p>"<a href="http://website.com/fake/url/path/1" rel="nofollow noreferrer">http://website.com/fake/url/path/1</a>"</p> <p>Thanks - Mark</p>
[ { "answer_id": 300635, "author": "Doug Wilson", "author_id": 32588, "author_profile": "https://Stackoverflow.com/users/32588", "pm_score": 1, "selected": false, "text": "routes.MapRoute(\"Default\", \"{*token}\", \n new { controller = \"Home\", action = \"Index\", token = 0 });\n [HandleError]\npublic class HomeController : Controller\n{\n public ActionResult Index([ModelBinder(typeof(IndexReqquestBinder))] IndexRequest request)\n {\n ViewData[\"Title\"] = \"Home Page\";\n ViewData[\"Message\"] = String.Format(\"We're looking at ID: {0}\", request.ID);\n\n return View();\n }\n}\n\npublic class IndexRequest\n{\n public Int32 ID { get; set; }\n public IndexRequest(Int32 id)\n {\n this.ID = id;\n }\n}\n\npublic class IndexReqquestBinder : IModelBinder\n{\n public ModelBinderResult BindModel(ModelBindingContext bindingContext)\n {\n if ( null != bindingContext.RouteData.Values[\"token\"] ) {\n foreach ( String v in bindingContext.RouteData.Values[\"token\"].ToString().Split('/') ) {\n Int32 id = 0;\n if ( Int32.TryParse(v, out id) ) {\n return new ModelBinderResult(new IndexRequest(id));\n }\n }\n\n }\n return new ModelBinderResult(new IndexRequest(0));\n }\n}\n" }, { "answer_id": 1270739, "author": "Andrej Kaurin", "author_id": 155639, "author_profile": "https://Stackoverflow.com/users/155639", "pm_score": 0, "selected": false, "text": "> public class CustomControllerFactory : DefaultControllerFactory\n> {\n> public override IController\n> CreateController(System.Web.Routing.RequestContext\n> requestContext, string controllerName)\n> {\n> try\n> {\n> return base.CreateController(requestContext,\n> controllerName);\n> }\n> catch (Exception exception)\n> {\n> // collect route data\n> string id = (string)requestContext.RouteData.Values[\"id\"];\n> string action = (string)requestContext.RouteData.Values[\"action\"];\n> // set full path as routing \"page\" parameter\n> VirtualPathData path = requestContext.RouteData.Route.GetVirtualPath(requestContext,\n> requestContext.RouteData.Values);\n> requestContext.RouteData.Values[\"id\"]\n> = path.VirtualPath; // or anything you need\n> // use controller page by default\n> controllerName = \"MyController\";\n> // set basuc routing data\n> requestContext.RouteData.Values[\"controller\"]\n> = controllerName;\n> requestContext.RouteData.Values[\"action\"]\n> = \"index\";\n> // call base method to create controller\n> return base.CreateController(requestContext,\n> controllerName);\n> }\n> }\n>}\n protected void Application_Start()\n {\n ControllerBuilder.Current.SetControllerFactory(new MyNameSpace.CustomControllerFactory ());\n RegisterRoutes(RouteTable.Routes); // this already exists by default\n }\n" }, { "answer_id": 26989351, "author": "Sonu", "author_id": 4264466, "author_profile": "https://Stackoverflow.com/users/4264466", "pm_score": 1, "selected": false, "text": "RouteCollection routes = RouteTable.Routes;\n if (routes[\"rname\"] != null)\n {\n RouteTable.Routes.Remove(routes[\"rname\"]);\n }\n routes.Remove(routes[\"Default\"]); \n routes.MapRoute(\n name: \"newname\",\n url: url + \"/{customId}\",\n defaults: new { controller = \"Search\", action = \"Index\", customId = UrlParameter.Optional }\n );\n\n //default route value\n routes.MapRoute(\n name: \"Default\",\n url: \"{controller}/{action}/{id}\",\n defaults: new { controller = \"Home\", action = \"Index\", id = UrlParameter.Optional }\n );\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,294
<p>How do I install a specific package, like derbytools, with Maven without specifying it as a dependency of project?</p>
[ { "answer_id": 296315, "author": "rich", "author_id": 25502, "author_profile": "https://Stackoverflow.com/users/25502", "pm_score": 2, "selected": false, "text": "mvn install mvn install:install-file -DgroupId=%DERBYTOOLS_GROUP_ID% \\ \n -DartifactId=%DERBYTOOLS_ARTIFACT_ID% \\\n -Dversion=%DERBYTOOLS_VERSION% \\\n -Dpackaging=jar \\\n -Dfile=%DERBYTOOLS_FILE_PATH%\n" }, { "answer_id": 1449765, "author": "Rich Seller", "author_id": 123582, "author_profile": "https://Stackoverflow.com/users/123582", "pm_score": 1, "selected": false, "text": "<dependency>\n <groupId>org.apache.derby</groupId>\n <artifactId>derbytools</artifactId>\n <version>10.4.2.0</version>\n</dependency>\n system <dependency>\n <groupId>org.apache.derby</groupId>\n <artifactId>derbytools</artifactId>\n <version>10.4.2.0</version>\n <scope>system</scope>\n <systemPath>/path/to/derbytools.jar</systemPath>\n</dependency>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6068/" ]
296,309
<p>The following code is just a simplified example to demonstrate my problem:</p> <pre><code>using System; using System.IO; using System.Diagnostics; using System.Threading; namespace ConsoleApplication5 { class Program { static string LogFile = @"C:\test.log"; static void Main(string[] args) { for (int i = 0;i&lt;10;i++) { new Thread(new ParameterizedThreadStart(DoWork)).Start(i); } Console.ReadKey(); } static void DoWork(object param) { int count = (int)param; try { using (FileStream fs = new FileStream(LogFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite)) using (StreamWriter sw = new StreamWriter(fs)) { sw.WriteLine(DateTime.Now + " - Start " + count.ToString()); Thread.Sleep(2000); // simulate doing some work sw.WriteLine(DateTime.Now + " - End " + count.ToString()); } } catch (Exception e) { Console.WriteLine(count.ToString() + ": " + e.Message); return; } Console.WriteLine(count.ToString() + ": Done."); } } } </code></pre> <p>The problem here is that typically only one entry makes it into the file, even though I call the method 10 times. The file should be open to allow sharing. As far as I can tell no exceptions are thrown. What's going on?</p> <p>In the real code that this example shadows, each call to DoWork is actually in a separate process, though testing shows that the results are the same-- if I can fix it here I can fix it there.</p>
[ { "answer_id": 10818164, "author": "William", "author_id": 1426251, "author_profile": "https://Stackoverflow.com/users/1426251", "pm_score": 1, "selected": false, "text": "SyncLock queue" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296309", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
296,312
<p>I'm using Spring's dependency injection but I'm running into difficulty loading a resource in my Spring config file. </p> <p>The resource is an XML file and is in a JAR file on my classpath. I try to access it as follows:</p> <pre><code>&lt;import resource="classpath:com/config/resources.xml" /&gt; </code></pre> <p>however I keep getting encountering the following error:</p> <blockquote> <p>Failed to import bean definitions from URL location [classpath:com/config/resources.xml]</p> </blockquote> <p>The JAR file is on the classpath of a Java project, which is in turn used by my web app. Should I really be doing my Spring configuration in the web project as opposed the Java project, or does that matter?</p>
[ { "answer_id": 296357, "author": "toolkit", "author_id": 3295, "author_profile": "https://Stackoverflow.com/users/3295", "pm_score": 4, "selected": true, "text": "<listener>\n <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>\n</listener>\n\n<context-param>\n <param-name>contextConfigLocation</param-name>\n <param-value>classpath:/com/config/resources.xml</param-value>\n</context-param>\n WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());\n" }, { "answer_id": 299815, "author": "Chochos", "author_id": 10165, "author_profile": "https://Stackoverflow.com/users/10165", "pm_score": 0, "selected": false, "text": "<import> classpath: <import resource=\"config/resources.xml\" /> contextConfigLocation" }, { "answer_id": 2480119, "author": "Paul Gregoire", "author_id": 127938, "author_profile": "https://Stackoverflow.com/users/127938", "pm_score": 1, "selected": false, "text": "try {\n subContext = new FileSystemXmlApplicationContext(new String[] { \"classpath*:/myconfig.xml\" }, true, context);\n} catch (Exception fnfe) {\n subContext = new FileSystemXmlApplicationContext(new String[] { \"plugins/myconfig.xml\" }, true, context);\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
296,325
<p>I'm teaching Java EE at the university, and this was a question a student asked. I said "no", but I wasn't really sure, so I thought I might ask you mighty developers. :)</p> <p>Basically, what I'd like to do is to use entities if they were in my context: cat getters, setters, etc, so like normal POJOs. if I use an EJB using its remote inferface, the entities gets decoupled from the core infrastructure, so that's a no-go.</p> <p>I thought about writing a layer such as this in my MSc thesis. If it's a dead idea, feel free to tell me. If it's not, tell me if you'd like one.</p> <p>Or if there is such a tool out there, let me know!</p>
[ { "answer_id": 301673, "author": "jamesh", "author_id": 4737, "author_profile": "https://Stackoverflow.com/users/4737", "pm_score": -1, "selected": false, "text": "map.get()" }, { "answer_id": 303388, "author": "Varun Mehta", "author_id": 31537, "author_profile": "https://Stackoverflow.com/users/31537", "pm_score": 3, "selected": true, "text": "+--------------------+\n| Presentation |\n+--------------------+\n| Controller/Actions |\n+--------------------+\n| Business Delegate |\n| (Service) |\n+--------------------+\n| Data Access Layer |\n+--------------------+\n| Database |\n+--------------------+\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296325", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,333
<p>I have an importer process which is running as a windows service (debug mode as an application) and it processes various xml documents and csv's and imports into an SQL database. All has been well until I have have had to process a large amount of data (120k rows) from another table (as I do the xml documents).</p> <p>I am now finding that the SQL server's memory usage is hitting a point where it just hangs. My application never receives a time out from the server and everything just goes STOP. </p> <p>I am still able to make calls to the database server separately but that application thread is just stuck with no obvious thread in SQL Activity Monitor and no activity in Profiler.</p> <p>Any ideas on where to begin solving this problem would be greatly appreciated as we have been struggling with it for over a week now.</p> <p>The basic architecture is c# 2.0 using NHibernate as an ORM data is being pulled into the actual c# logic and processed then spat back into the same database along with logs into other tables.</p> <hr> <p>The only other prob which sometimes happens instead is that for some reason a cursor is being opening on this massive table, which I can only assume is being generated from ADO.net the statement like exec sp_cursorfetch 180153005,16,113602,100 is being called thousands of times according to Profiler</p>
[ { "answer_id": 297367, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "COMMIT INSERT SELECT" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/258/" ]
296,366
<p>I have a directory full of files and I need to pull the headers and footers off of them. They are all variable length so using head or tail isn't going to work. Each file does have a line I can search for, but I don't want to include the line in the results.</p> <p>It's usually </p> <pre><code>*** Start (more text here) </code></pre> <p>And ends with </p> <pre><code>*** Finish (more text here) </code></pre> <p>I want the file names to stay the same, so I need to overwrite the originals, or write to a different directory and I'll overwrite them myself.</p> <p>Oh yeah, it's on a linux server of course, so I have Perl, sed, awk, grep, etc.</p>
[ { "answer_id": 296385, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 0, "selected": false, "text": "$ sed -i '/^\\*\\*\\* Start/,/^\\*\\*\\* Finish/d!' *\n $ sed -i -e '/./,/^\\*\\*\\* Start/d' -e '/^\\*\\*\\* Finish/,/./d' *\n d! sed" }, { "answer_id": 296404, "author": "Drakosha", "author_id": 19868, "author_profile": "https://Stackoverflow.com/users/19868", "pm_score": 1, "selected": false, "text": "cat yourFileHere | awk '{if (d > 0) print $0} /.*Start.*/ {d = 1}'\n cat yourFileHere | awk '/.*Finish.*/ {d = 1} {if (d < 1) print $0}'\n cat yourFileHere | awk '/.*Start.*/ {d = 1; next} /.*Finish.*/ {d = 0; next} {if (d > 0) print $0}'\n csplit yourFileHere /Start/ /Finish/\n" }, { "answer_id": 296432, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl -w\nuse strict;\nuse Tie::File;\nmy $Filename=shift; \ntie my @File, 'Tie::File', $Filename or die \"could not access $Filename.\\n\"; \nwhile (shift @File !~ /^\\*\\*\\* Start/) {}; \nwhile (pop @File !~ /^\\*\\*\\* Finish/) {}; \nuntie @File; \n" }, { "answer_id": 296617, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 0, "selected": false, "text": "#!/usr/bin/perl -ni\nif(my $num = /^\\*\\*\\* Start/ .. /^\\*\\*\\* Finish/) {\n print if $num != 1 and $num + 0 eq $num;\n}\n" }, { "answer_id": 296672, "author": "draegtun", "author_id": 12195, "author_profile": "https://Stackoverflow.com/users/12195", "pm_score": 3, "selected": true, "text": "# flip-flop.pl\nuse strict;\nuse warnings;\n\nmy $start = qr/^\\*\\*\\* Start/;\nmy $finish = qr/^\\*\\*\\* Finish/;\n\nwhile ( <> ) {\n if ( /$start/ .. /$finish/ ) {\n next if /$start/ or /$finish/;\n print $_;\n }\n}\n $ perl -i'copy_*' flip-flop.pl data.txt \n" }, { "answer_id": 297344, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 2, "selected": false, "text": "csplit inputfile %^\\*\\*\\* Start%1 /^\\*\\*\\* Finish/ %% {*}\n xx00 --prefix --suffix --digits csplit csplit $1 %^\\*\\*\\* Start%1 /^\\*\\*\\* Finish/ %% {*}\nmv -f xx00 $1\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13704/" ]
296,398
<p>I have a List of beans, each of which has a property which itself is a List of email addresses.</p> <pre><code>&lt;c:forEach items="${upcomingSchedule}" var="conf"&gt; &lt;div class='scheduled' title="${conf.subject}" id="scheduled&lt;c:out value="${conf.id}"/&gt;"&gt; ... &lt;/div&gt; &lt;/c:forEach&gt; </code></pre> <p>This renders one <code>&lt;div&gt;</code> per bean in the List.</p> <p>For the sublist, what I'd like to be able to do is to concatenate each of the entries in the list to form a single String, to be displayed as a part of the <code>&lt;div&gt;</code>'s <code>title</code> attribute. Why? Because we are using a javascript library (mootools) to turn this <code>&lt;div&gt;</code> into a floating tool tip, and the library turns the <code>title</code> into the text of the tooltip.</p> <p>So, if <code>${conf.subject}</code> was "Subject", ultimately I'd like the <code>title</code> of the <code>&lt;div&gt;</code> to be "Subject: blah@blah.com, blah2@blah2.com, etc.", containing all of the email addresses of the sub-list.</p> <p>How can I do this using JSP EL? I'm trying to stay away from putting scriptlet blocks in the jsp file.</p>
[ { "answer_id": 296430, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 4, "selected": true, "text": "<c:forEach items=\"${upcomingSchedule}\" var=\"conf\">\n <c:set var=\"title\" value=\"${conf.subject}: \"/>\n <c:forEach items=\"${conf.invitees}\" var=\"invitee\">\n <c:set var=\"title\" value=\"${title} ${invitee}, \"/>\n </c:forEach>\n <div class='scheduled' title=\"${title}\" id=\"scheduled<c:out value=\"${conf.id}\"/>\">\n ...\n </div>\n</c:forEach>\n <c:set>" }, { "answer_id": 296437, "author": "lucas", "author_id": 31172, "author_profile": "https://Stackoverflow.com/users/31172", "pm_score": 2, "selected": false, "text": "${fn:join(array, \";\")}\n" }, { "answer_id": 296478, "author": "alexmeia", "author_id": 36587, "author_profile": "https://Stackoverflow.com/users/36587", "pm_score": 1, "selected": false, "text": "<div class='scheduled' title=\"${conf.subject}: ${conf.invitees}\" id=\"scheduled${conf.id}\">\n" }, { "answer_id": 296752, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": false, "text": "join Collection package com.x.taglib.core;\n\npublic class StringUtil {\n\n public static String join(Iterable<?> elements, CharSequence separator) {\n StringBuilder buf = new StringBuilder();\n if (elements != null) {\n if (separator == null)\n separator = \" \";\n for (Object o : elements) {\n if (buf.length() > 0)\n buf.append(separator);\n buf.append(o);\n }\n }\n return buf.toString();\n }\n\n}\n <taglib xmlns=\"http://java.sun.com/xml/ns/j2ee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd\" version=\"2.0\">\n <tlib-version>1.0</tlib-version>\n <short-name>x-c</short-name>\n <uri>http://dev.x.com/taglib/core/1.0</uri>\n <function>\n <description>Join elements of an Iterable into a string.</description>\n <display-name>Join</display-name>\n <name>join</name>\n <function-class>com.x.taglib.core.StringUtil</function-class>\n <function-signature>java.lang.String join(java.lang.Iterable, java.lang.CharSequence)</function-signature>\n </function>\n</taglib>\n StringUtil" }, { "answer_id": 2121450, "author": "Spanky Quigman", "author_id": 165462, "author_profile": "https://Stackoverflow.com/users/165462", "pm_score": 0, "selected": false, "text": "<c:forEach var=\"tab\" items=\"${tabs}\">\n <c:set var=\"tabAttrs\" value='${tabAttrs} ${tab.key}=\"${tab.value}\"'/>\n</c:forEach>\n" }, { "answer_id": 14550381, "author": "Sandro", "author_id": 2016004, "author_profile": "https://Stackoverflow.com/users/2016004", "pm_score": 0, "selected": false, "text": "<c:forEach items=\"${upcomingSchedule}\" var=\"conf\">\n <div class='scheduled' title=\"${conf.subject}\" \n\n id=\"scheduled${conf.id}\">\n\n ...\n </div>\n</c:forEach>\n" }, { "answer_id": 21184534, "author": "Tim B", "author_id": 3049628, "author_profile": "https://Stackoverflow.com/users/3049628", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<taglib version=\"2.1\" xmlns=\"http://java.sun.com/xml/ns/javaee\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-jsptaglibrary_2_1.xsd\">\n <tlib-version>1.0</tlib-version>\n <short-name>string_util</short-name>\n <uri>/WEB-INF/tlds/string_util</uri>\n <info>String Utilities</info>\n <tag>\n <name>join</name>\n <info>Join the contents of any iterable using a separator</info>\n <tag-class>XXX.taglib.JoinObjects</tag-class>\n <body-content>tagdependent</body-content>\n <attribute>\n <name>iterable</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <type>java.lang.Iterable</type>\n </attribute>\n <attribute>\n <name>separator</name>\n <required>false</required>\n <rtexprvalue>false</rtexprvalue>\n <type>java.lang.String</type>\n </attribute>\n </tag>\n\n <tag>\n <name>joinints</name>\n <info>Join the contents of an integer array using a separator</info>\n <tag-class>XXX.taglib.JoinInts</tag-class>\n <body-content>tagdependent</body-content>\n <attribute>\n <name>integers</name>\n <required>true</required>\n <rtexprvalue>true</rtexprvalue>\n <type>java.lang.Integer[]</type>\n </attribute>\n <attribute>\n <name>separator</name>\n <required>false</required>\n <rtexprvalue>false</rtexprvalue>\n <type>java.lang.String</type>\n </attribute>\n </tag>\n</taglib>\n public class JoinInts extends TagSupport {\n\n int[] integers;\n String separator = \",\";\n\n @Override\n public int doStartTag() throws JspException {\n if (integers != null) {\n StringBuilder buf = new StringBuilder();\n if (separator == null) {\n separator = \" \";\n }\n for (int i: integers) {\n if (buf.length() > 0) {\n buf.append(separator);\n }\n buf.append(i);\n }\n try {\n pageContext.getOut().print(buf);\n } catch (IOException ex) {\n Logger.getLogger(JoinInts.class.getName()).log(Level.SEVERE, null, ex);\n }\n }\n return SKIP_BODY;\n }\n\n @Override\n public int doEndTag() throws JspException {\n return EVAL_PAGE;\n }\n\n public int[] getIntegers() {\n return integers;\n }\n\n public void setIntegers(int[] integers) {\n this.integers = integers;\n }\n\n public String getSeparator() {\n return separator;\n }\n\n public void setSeparator(String separator) {\n this.separator = separator;\n }\n}\n <%@ taglib prefix=\"su\" uri=\"/WEB-INF/tlds/string_util.tld\" %>\n\n[new Date(${row.key}), <su:joinints integers=\"${row.value}\" separator=\",\" />],\n" }, { "answer_id": 46321425, "author": "Georgios Syngouroglou", "author_id": 1123501, "author_profile": "https://Stackoverflow.com/users/1123501", "pm_score": 0, "selected": false, "text": "<div>${stringList.stream().reduce(\",\", (n,p)->p.concat(n))}</div>\n <div>${personList.stream().map(p->p.getFirstName()).reduce(\",\", (n,p)->p.concat(n))}</div>\n <c:forEach items=\"${upcomingSchedule}\" var=\"conf\">\n <c:set var=\"separator\" value=\",\"/>\n <c:set var=\"titleFront\" value=\"${conf.subject}: \"/>\n <c:set var=\"titleEnd\" value=\"${conf.invitees.stream().reduce(separator, (n,p)->p.concat(n))}\"/>\n <div class='scheduled' title=\"${titleFront} ${titleEnd.isEmpty() ? \"\" : titleEnd.substring(0, titleEnd.length()-1)}\" id=\"scheduled<c:out value=\"${conf.id}\"/>\">\n ...\n </div>\n</c:forEach>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4249/" ]
296,405
<p>I am writing an algorithm to find the dominating set of a tournament graph. Is the minimum spanning tree of a directed graph equivalent to the dominating set of the graph? In other words, if I find the smallest MST for the tournament graph (by iterating through all of the vertices), can I then say this is equivalent to the dominating set of the graph?</p>
[ { "answer_id": 296445, "author": "DanJ", "author_id": 4697, "author_profile": "https://Stackoverflow.com/users/4697", "pm_score": 1, "selected": false, "text": "_ _" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296405", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27884/" ]
296,414
<p>I'm trying to unit test a page in my ASP.NET MVC application that, when posted to, will delete a user's item. I want to restrict this page so that it can only be posted to by the owner of said item. Originally, I wanted to just stick a quick check in the controller that checked if the HttpContext.Current.User.Identity.Name is equal to the owner of the item, but I quickly realized that unit testing this would be difficult.</p> <p>Should I create an interface that provides a way to access the current logged-in user's name?</p>
[ { "answer_id": 296484, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 3, "selected": true, "text": "HttpContext.Current.User IPrincipal HttpContext.Current.User.Identity IIdentity" }, { "answer_id": 6752922, "author": "Sly", "author_id": 72174, "author_profile": "https://Stackoverflow.com/users/72174", "pm_score": 3, "selected": false, "text": "Controller CreateControllerAs(string userName) {\n\n var mock = new Mock<ControllerContext>();\n mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);\n mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);\n\n var controller = new SomeController();\n controller.ControllerContext = mock.Object;\n\n return controller;\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296414", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
296,418
<p>I have a datagridview where the users can select which subset of columns to view. The problem I am having is that when I change the columns being displayed, the column widths are only being determined by the width of the Header Cells, not the data in it. I do have each column set to AutoSizeMode = AllCells.</p> <p>If a new row is added, the columns become the correct width. But when the set of columns is changed, the widths are wrong.</p>
[ { "answer_id": 296425, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.None;\ndgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296418", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4779/" ]
296,455
<p>Is there a quick-and-dirty way to tell programmatically, in shell script or in Perl, whether a path is located on a remote filesystem (nfs or the like) or a local one? Or is the only way to do this to parse /etc/fstab and check the filesystem type?</p>
[ { "answer_id": 296507, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 2, "selected": false, "text": "df -T $dir | tail -1 | awk '{print $2;}'\n" }, { "answer_id": 296542, "author": "Chris Dodd", "author_id": 29759, "author_profile": "https://Stackoverflow.com/users/29759", "pm_score": 5, "selected": true, "text": "stat -f -c %T <filename> -l" }, { "answer_id": 296655, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 0, "selected": false, "text": "print \"remote\" if (stat($filename))[0] < 0\n" }, { "answer_id": 296745, "author": "Svante", "author_id": 31615, "author_profile": "https://Stackoverflow.com/users/31615", "pm_score": 2, "selected": false, "text": "df df .\n df . | tail -1 | awk '{print $1}'\n" }, { "answer_id": 3558849, "author": "Vagnerr", "author_id": 3720, "author_profile": "https://Stackoverflow.com/users/3720", "pm_score": 1, "selected": false, "text": "/bin/df -g <filename> | tail -2 | head -1 | awk '{print $1}'\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296455", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12204/" ]
296,458
<p>In the .xsd file for a typed DataSet in .NET, there's a <code>&lt;Connections&gt;</code> section that contains a list of any data connections I've used to set up the DataTables and TableAdapters.</p> <p>There are times when I'd prefer not to have those there. For instance, sometimes I prefer to pass in a connection string to a custom constructor and use that rather than look for one in settings, .config, etc.</p> <p>But it seems like if I remove the connection strings from that section (leaving it empty), or remove the section entirely, the DataSet code-generation tool freaks out. Whereas if I <em>don't</em> remove them, the DataSet gripes when I put it in a different project because it can't find the settings for those connection strings.</p> <p>Is there any way I can tell a typed DataSet not to worry about any connections? (Obviously I'll have to give it a connection if I change any TableAdapter SQL or stored procs, but that should be <em>my</em> problem.)</p>
[ { "answer_id": 859682, "author": "Ole Lynge", "author_id": 41094, "author_profile": "https://Stackoverflow.com/users/41094", "pm_score": 2, "selected": false, "text": "public internal public sealed partial class Settings\n{\n [...]\n [global::System.Configuration.DefaultSettingValueAttribute\n (\"Data Source=.;Initial Catalog=MyDb;Integrated Security=True;\")]\n public string MyConnectionString\n {\n get\n {\n return ((string)(this[\"MyConnectionString\"]));\n }\n }\n}\n public string MyConnectionString\n{\n get\n {\n return ((string)(this[\"MyConnectionString\"]));\n }\n set\n {\n this[\"MyConnectionString\"] = value;\n }\n}\n MyDataAccessLibrary.Properties.Settings.Default.MyConnectionString = ...\n" }, { "answer_id": 859866, "author": "this. __curious_geek", "author_id": 89556, "author_profile": "https://Stackoverflow.com/users/89556", "pm_score": 0, "selected": false, "text": "<connections> <connections>" }, { "answer_id": 2909301, "author": "Carter Medlin", "author_id": 324479, "author_profile": "https://Stackoverflow.com/users/324479", "pm_score": 1, "selected": false, "text": "<add name=\"MyConnectionString\" connectionString=\"data source=.;Integrated Security=SSPI\" providerName=\"System.Data.SqlClient\" />\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296458", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
296,490
<p>I would like to remove two files from a folder at the conclusion of my script. Do I need to create a function responsible for removing these two specific files? I would like to know in some detail how to use os.remove (if that is what I should use) properly. These two files will always be discarded at the conclusion of my script (which packages a series of files together in a zip format). Thanks in advance. </p>
[ { "answer_id": 296495, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": -1, "selected": true, "text": "os.remove(\"path/to/file\") .emacs os.remove(\".emacs\")\n str" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
296,499
<p>Once I have all the files I require in a particular folder, I would like my python script to zip the folder contents. </p> <p>Is this possible? </p> <p>And how could I go about doing it?</p>
[ { "answer_id": 296565, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 3, "selected": false, "text": "def zipfolder(path, relname, archive):\n paths = os.listdir(path)\n for p in paths:\n p1 = os.path.join(path, p) \n p2 = os.path.join(relname, p)\n if os.path.isdir(p1): \n zipfolder(p1, p2, archive)\n else:\n archive.write(p1, p2) \n\ndef create_zip(path, relname, archname):\n archive = zipfile.ZipFile(archname, \"w\", zipfile.ZIP_DEFLATED)\n if os.path.isdir(path):\n zipfolder(path, relname, archive)\n else:\n archive.write(path, relname)\n archive.close()\n" }, { "answer_id": 296722, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 6, "selected": true, "text": "#!/usr/bin/env python\nfrom __future__ import with_statement\nfrom contextlib import closing\nfrom zipfile import ZipFile, ZIP_DEFLATED\nimport os\n\ndef zipdir(basedir, archivename):\n assert os.path.isdir(basedir)\n with closing(ZipFile(archivename, \"w\", ZIP_DEFLATED)) as z:\n for root, dirs, files in os.walk(basedir):\n #NOTE: ignore empty directories\n for fn in files:\n absfn = os.path.join(root, fn)\n zfn = absfn[len(basedir)+len(os.sep):] #XXX: relative path\n z.write(absfn, zfn)\n\nif __name__ == '__main__':\n import sys\n basedir = sys.argv[1]\n archivename = sys.argv[2]\n zipdir(basedir, archivename)\n C:\\zipdir> python -mzipdir c:\\tmp\\test test.zip\n 'C:\\zipdir\\test.zip' 'c:\\tmp\\test'" }, { "answer_id": 11880001, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 5, "selected": false, "text": " shutil.make_archive(target_file, format=\"bztar\", root_dir=compress_me) \n" }, { "answer_id": 69454333, "author": "rob_7cc", "author_id": 6100445, "author_profile": "https://Stackoverflow.com/users/6100445", "pm_score": 0, "selected": false, "text": "ZipFile.write() add_folder_to_zip() import zipfile\nimport os\n\ndef add_folder_to_zip(src_folder_name, dst_zip_archive):\n \"\"\" Adds a folder and its contents to a zip archive\n\n Args:\n src_folder_name (str): Source folder name to add to the archive\n dst_zip_archive (ZipFile): Destination zip archive\n\n Returns:\n None\n \"\"\"\n for walk_item in os.walk(src_folder_name):\n for file_item in walk_item[2]:\n # walk_item[2] is a list of files in the folder entry\n # walk_item[0] is the folder entry full path \n fn_to_add = os.path.join(walk_item[0], file_item)\n dst_zip_archive.write(fn_to_add)\n\nif __name__ == '__main__':\n zf = zipfile.ZipFile('myzip.zip', mode='w')\n add_folder_to_zip('zip_this_folder', zf)\n zf.close()\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37804/" ]
296,501
<p>I am overriding a Grid, adding some customer features. One of the features is a drop-down to adjust page size. I am extending the grid using a customer server control, which works great for what I've done so far. Now, however I am having a bit of trouble getting the dynamically added control to do a postback. The javascript to initiate the postback is not present.</p> <pre><code>Protected Overrides Sub OnPreRender(ByVal e As System.EventArgs) Dim pageSizePanel As New Panel ... Dim countList As List(Of String) = GetCountList() Dim pageSizeDropdown As New DropDownList() pageSizeDropdown.ID = "pageSizeDropdown" pageSizeDropdown.DataSource = countList pageSizeDropdown.DataBind() AddHandler pageSizeDropdown.SelectedIndexChanged, _ AddressOf HandlePageSizeChange pageSizePanel.Controls.Add(pageSizeDropdown) ... MyBase.Controls.AddAt(0, pageSizePanel) MyBase.OnPreRender(e) End Sub </code></pre> <p>The HTML is</p> <pre><code>&lt;select name="tab$grid1Tab$RadGrid1$pageSizeDropdown" id="tab_grid1Tab_RadGrid1_pageSizeDropdown"&gt; &lt;option selected="selected" value="10"&gt;10&lt;/option&gt; &lt;option value="20"&gt;20&lt;/option&gt; &lt;option value="40"&gt;40&lt;/option&gt; &lt;option value="80"&gt;80&lt;/option&gt; &lt;option value="All"&gt;All&lt;/option&gt; &lt;/select&gt; </code></pre> <p>So, does this have to do with when I'm 'injecting' the controls? Does it have to do with dynamic addition of the controls?</p>
[ { "answer_id": 296509, "author": "John", "author_id": 30006, "author_profile": "https://Stackoverflow.com/users/30006", "pm_score": 3, "selected": true, "text": "pageSizeDropdown.AutoPostBack = true\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296501", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
296,503
<p>I have a user control where the XAML of the control can bind to the appropriate properties from the parent's data context like normal (the data context propagates in xaml). </p> <p>For example, I have a window whose DataContext I am setting to ObjectA for example. My user control within the window is then try to access the properties within the dataContext</p> <p>So my window's xaml and code behind can both see a non-null DataContext. </p> <p>My control that DataContext propagates to can see a non-null DataContext in the Xaml but not in the code behind.</p> <p>What is the proper way of handling this?</p>
[ { "answer_id": 296614, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": 4, "selected": false, "text": "public partial class UserControl1\n{\n public UserControl1()\n {\n this.InitializeComponent();\n\n //DataContext will be null here \n this.Loaded += new RoutedEventHandler(UserControl1_Loaded);\n }\n\n void UserControl1_Loaded(object sender, RoutedEventArgs e)\n {\n //Check DataContext Property here - Value is not null\n }\n}\n" }, { "answer_id": 299247, "author": "Bijington", "author_id": 32348, "author_profile": "https://Stackoverflow.com/users/32348", "pm_score": 6, "selected": true, "text": "public partial class UserControl1 : UserControl\n{\n public UserControl1()\n {\n InitializeComponent();\n\n DataContextChanged += new DependencyPropertyChangedEventHandler(UserControl1_DataContextChanged);\n }\n\n void UserControl1_DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)\n {\n // You can also validate the data going into the DataContext using the event args\n }\n}\n" }, { "answer_id": 554785, "author": "hughdbrown", "author_id": 10293, "author_profile": "https://Stackoverflow.com/users/10293", "pm_score": 4, "selected": false, "text": "xmlns:debug=\"clr-namespace:System.Diagnostics;assembly=System\"\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9401/" ]
296,517
<p>I need to pass an array from JavaScript to a page method in C#. I have tried using a parameter in the C# method of IList and also a string[] array. Both ways throw an exception "cannot convert an object of type system.string to xxx", where xxx is the parameter type in the C# method. I am passing the object from jQuery as a json object, and looks like it is coming through properly. Here is what it looks like:</p> <pre><code>{"testNumbers":"5555555555,3333333333,4444444444"} </code></pre> <p>What am I doing wrong here?</p> <p>EDIT: C# Code:</p> <pre><code>[WebMethod()] public static void ProcessAction(string[] testNumbers) { var dataProvider = new DataProvider(); dataProvider.ProcessAction(testNumbers); } </code></pre>
[ { "answer_id": 296564, "author": "Powerlord", "author_id": 15880, "author_profile": "https://Stackoverflow.com/users/15880", "pm_score": 4, "selected": true, "text": "{\"testNumbers\": [5555555555,3333333333,4444444444]}\n" }, { "answer_id": 296574, "author": "PhilHoy", "author_id": 29547, "author_profile": "https://Stackoverflow.com/users/29547", "pm_score": 0, "selected": false, "text": "{\"testNumbers\":[\"5555555555\",\"3333333333\",\"4444444444\"]} \n http://www.json.org/" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296517", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1284/" ]
296,519
<p>I have shell script which starts with:</p> <pre><code>sdir=`dirname $0` sdir=`(cd "$sdir/"; pwd)` </code></pre> <p>And this usually gets expanded (with 'sh -h') into </p> <pre><code>++ dirname /opt/foo/bin/bar + sdir=/opt/foo/bin ++ cd /opt/foo/bin/ ++ pwd + sdir=/opt/foo/bin </code></pre> <p>but for single user for single combination of parameters in expands into (note two lines at the result sbin value)</p> <pre><code>++ dirname bin/foo + sdir=bin ++ cd bin/ ++ pwd + sdir='/opt/foo/bin /opt/foo/bin' </code></pre> <p>I tried different combinations but was not able to reproduce this behavior. With different input parameters for that user it started producing correct single line result. I am new to shell scripting, so please advice when such <code>(cd X; pwd)</code> can return two line. it was observed on CentOS, but not sure it that matters. Please advice.</p>
[ { "answer_id": 296585, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "sdir=`dirname $0`\nsdir=`(cd \"$sdir/\" >/dev/null; pwd)`\n" }, { "answer_id": 906069, "author": "Aaron Digulla", "author_id": 34088, "author_profile": "https://Stackoverflow.com/users/34088", "pm_score": 0, "selected": false, "text": "sdir=$( cd $(dirname \"$0\") > /dev/null && pwd )\n /" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296519", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,520
<p>I have a Win32 console application which is doing some computations, compiled in Compaq Visual Fortran (which probably doesn't matter). </p> <p>I need to run a lot of them simultaneously.</p> <p>In XP, they take around 90-100% CPU together, work very fast. In Vista, no matter how many of them I run, they take no more than 10% of CPU (together), and work very slow respectively.</p> <p>There is quite a bit of console output going on, but now VERY much. I can minimize all the windows, it does not help. CPU is basically doing nothing...</p> <p>Any ideas?</p> <p><strong>Update:</strong></p> <p>No, these are different machines, but they run relatively the same hardware. 2. Threads are not used, this is a VERY OLD (20 yrs) plain app for DOS, compiled in win32. It is supposed to compute iterations until they meet, consume all it has. My impression - VISTA just does NOT GIVE IT MORE CPU</p>
[ { "answer_id": 296691, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": false, "text": "c:\\temp> dir > output.log\n nul c:\\temp> dir > nul\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296520", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38325/" ]
296,525
<h1>Example</h1> <p>There is an application that measures temperature in each town of the world. Each measurement is taken every 5 minutes and written in to the Measurement table.</p> <pre><code>CREATE TABLE [dbo].[Measurement]( [MeasurementID] [int] IDENTITY(1,1) NOT NULL, [Town] [varchar](50) NOT NULL, [Date] [datetime] NOT NULL, [Temp] [int] NOT NULL, CONSTRAINT [PK_Measurement] PRIMARY KEY CLUSTERED ( [MeasurementID] ASC )) ON [PRIMARY] </code></pre> <h1>Question</h1> <p>What is the most efficient query to get a list of the towns and their current temperature?</p> <p>Assume there are 100k towns and 10 million records</p> <p><em>NOTE: I have added a couple of possible answers, but there are probably other options.</em></p>
[ { "answer_id": 296531, "author": "Andrew Rimmer", "author_id": 1982, "author_profile": "https://Stackoverflow.com/users/1982", "pm_score": 0, "selected": false, "text": "select s.*\nfrom Measurement s\nwhere exists ( \n select 1\n from Measurement s1\n where s.Town = s1.Town\n group by s1.Town\n having max( s1.Date )= s.Date)\n order by s.Town\n" }, { "answer_id": 296532, "author": "Andrew Rimmer", "author_id": 1982, "author_profile": "https://Stackoverflow.com/users/1982", "pm_score": 1, "selected": false, "text": "select *\nfrom\n(\n select distinct *, --Keyword,Total,CreatedOn,EngineInstanceID,\n Rank() over (PARTITION by Town order by Date DESC) as DateOrder\n from Measurement\n where Town is not null\n) CurrentMeasurement\nwhere DateOrder = 1\n" }, { "answer_id": 296588, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 0, "selected": false, "text": "select m.town, m.temperature, m.date\nfrom Measurement m\nwhere m.date = (select max(m2.date) from Measurement m2 where m2.town = m.town)\norder by 1\n" }, { "answer_id": 297222, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "WITH LastMeasurements AS (\n SELECT [Town], MAX([Date]) AS LastMeasurementDate\n FROM [Measurement]\n GROUP BY [Town]\n)\nSELECT [Measurement].Town, [Measurement].[Date], [Measurement].Temp\nFROM [Measurement]\nINNER JOIN LastMeasurements\n ON [Measurement].[Town] = LastMeasurements.[Town]\n AND [Measurement].[Date] = LastMeasurements.LastMeasurementDate\n GROUP BY" }, { "answer_id": 9245307, "author": "ErikE", "author_id": 57611, "author_profile": "https://Stackoverflow.com/users/57611", "pm_score": 0, "selected": false, "text": "SELECT\n M.*\nFROM\n Towns T\n OUTER APPLY (\n SELECT TOP 1 * -- add 'WITH TIES' to the 'TOP 1' if you have/want ties on date.\n FROM Measurement M\n WHERE T.Town = M.Town\n ORDER BY M.Date DESC\n ) M\n SELECT\n M.*\nFROM\n (SELECT DISTINCT Town FROM Towns) T\n OUTER APPLY (\n SELECT TOP 1 *\n FROM Measurement M\n WHERE T.Town = M.Town\n ORDER BY M.Date DESC\n ) M\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296525", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1982/" ]
296,533
<p>I have a Windows Forms app, that has a single ElementHost containing a WPF UserControl... in my WPF, I have a VERY simple ListView:</p> <pre><code>&lt;ListView Margin="4" ItemsSource="{Binding Notifications}"&gt; &lt;ListView.View&gt; &lt;GridView&gt; &lt;GridViewColumn Header="FirstName" DisplayMemberBinding="{Binding FirstName}" /&gt; &lt;GridViewColumn Header="LastName" DisplayMemberBinding="{Binding LastName}" /&gt; &lt;GridViewColumn Header="Address" DisplayMemberBinding="{Binding Address}" /&gt; &lt;GridViewColumn Header="City" DisplayMemberBinding="{Binding City}" /&gt; &lt;GridViewColumn Header="State" DisplayMemberBinding="{Binding State}" /&gt; &lt;GridViewColumn Header="Zip" DisplayMemberBinding="{Binding Zip}" /&gt; &lt;/GridView&gt; &lt;/ListView.View&gt; &lt;/ListView&gt; </code></pre> <p>If my source has 10 items, the form loads in less than one second. If my source has 1000 items, it takes 7 seconds!!! My timer is ONLY taking the loading into account (not how much time it takes to get the items).</p> <p>So my question is:</p> <p>Is using an ElementHost a performance nightmare?</p> <p>Is WPF DataBinding a performance nightmare?</p> <p>Is the ListView a piece of crap? (btw, same results with the WPFToolkit's DataGrid)?</p>
[ { "answer_id": 296606, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<ListView ItemsSource=\"{BindingNames}\"Name=\"lv\">\n <ListView.ItemsPanel>\n <ItemsPanelTemplate>\n <!--<StackPanel/>\n If StackPanel was used, the memory consumed was over 2GB and dead slow.\n -->\n <VirtualizingStackPanel>\n <!--Memory footprint is only 200 mb-->\n </VirtualizingStackPanel>\n </ItemsPanelTemplate>\n </ListView.ItemsPanel>\n <ListView.ItemTemplate>\n <DataTemplate>\n <TextBlock Text=\"{Binding}\"/>\n </DataTemplate>\n </ListView.ItemTemplate>\n </ListView> \n" }, { "answer_id": 54212701, "author": "Simon Voggeneder", "author_id": 720425, "author_profile": "https://Stackoverflow.com/users/720425", "pm_score": 2, "selected": false, "text": "MaxHeight ListView" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11917/" ]
296,536
<p>I am trying to write a bash script for testing that takes a parameter and sends it through curl to web site. I need to url encode the value to make sure that special characters are processed properly. What is the best way to do this? </p> <p>Here is my basic script so far:</p> <pre><code>#!/bin/bash host=${1:?'bad host'} value=$2 shift shift curl -v -d "param=${value}" http://${host}/somepath $@ </code></pre>
[ { "answer_id": 296630, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 3, "selected": false, "text": "urlencode.sed s/%/%25/g\ns/ /%20/g\ns/ /%09/g\ns/!/%21/g\ns/\"/%22/g\ns/#/%23/g\ns/\\$/%24/g\ns/\\&/%26/g\ns/'\\''/%27/g\ns/(/%28/g\ns/)/%29/g\ns/\\*/%2a/g\ns/+/%2b/g\ns/,/%2c/g\ns/-/%2d/g\ns/\\./%2e/g\ns/\\//%2f/g\ns/:/%3a/g\ns/;/%3b/g\ns//%3e/g\ns/?/%3f/g\ns/@/%40/g\ns/\\[/%5b/g\ns/\\\\/%5c/g\ns/\\]/%5d/g\ns/\\^/%5e/g\ns/_/%5f/g\ns/`/%60/g\ns/{/%7b/g\ns/|/%7c/g\ns/}/%7d/g\ns/~/%7e/g\ns/ /%09/g\n STR1=$(echo \"https://www.example.com/change&$ ^this to?%checkthe@-functionality\" | cut -d\\? -f1)\nSTR2=$(echo \"https://www.example.com/change&$ ^this to?%checkthe@-functionality\" | cut -d\\? -f2)\nOUT2=$(echo \"$STR2\" | sed -f urlencode.sed)\necho \"$STR1?$OUT2\"\n urlencode https://www.exxample.com?isThisFun=HellNo\n" }, { "answer_id": 298258, "author": "dubek", "author_id": 884, "author_profile": "https://Stackoverflow.com/users/884", "pm_score": 7, "selected": false, "text": "URI::Escape uri_escape ...\n\nvalue=\"$(perl -MURI::Escape -e 'print uri_escape($ARGV[0]);' \"$2\")\"\n...\n" }, { "answer_id": 329421, "author": "MatthieuP", "author_id": 41469, "author_profile": "https://Stackoverflow.com/users/41469", "pm_score": 4, "selected": false, "text": ":\n##########################################################################\n# Title : urlencode - encode URL data\n# Author : Heiner Steven (heiner.steven@odn.de)\n# Date : 2000-03-15\n# Requires : awk\n# Categories : File Conversion, WWW, CGI\n# SCCS-Id. : @(#) urlencode 1.4 06/10/29\n##########################################################################\n# Description\n# Encode data according to\n# RFC 1738: \"Uniform Resource Locators (URL)\" and\n# RFC 1866: \"Hypertext Markup Language - 2.0\" (HTML)\n#\n# This encoding is used i.e. for the MIME type\n# \"application/x-www-form-urlencoded\"\n#\n# Notes\n# o The default behaviour is not to encode the line endings. This\n# may not be what was intended, because the result will be\n# multiple lines of output (which cannot be used in an URL or a\n# HTTP \"POST\" request). If the desired output should be one\n# line, use the \"-l\" option.\n#\n# o The \"-l\" option assumes, that the end-of-line is denoted by\n# the character LF (ASCII 10). This is not true for Windows or\n# Mac systems, where the end of a line is denoted by the two\n# characters CR LF (ASCII 13 10).\n# We use this for symmetry; data processed in the following way:\n# cat | urlencode -l | urldecode -l\n# should (and will) result in the original data\n#\n# o Large lines (or binary files) will break many AWK\n# implementations. If you get the message\n# awk: record `...' too long\n# record number xxx\n# consider using GNU AWK (gawk).\n#\n# o urlencode will always terminate it's output with an EOL\n# character\n#\n# Thanks to Stefan Brozinski for pointing out a bug related to non-standard\n# locales.\n#\n# See also\n# urldecode\n##########################################################################\n\nPN=`basename \"$0\"` # Program name\nVER='1.4'\n\n: ${AWK=awk}\n\nUsage () {\n echo >&2 \"$PN - encode URL data, $VER\nusage: $PN [-l] [file ...]\n -l: encode line endings (result will be one line of output)\n\nThe default is to encode each input line on its own.\"\n exit 1\n}\n\nMsg () {\n for MsgLine\n do echo \"$PN: $MsgLine\" >&2\n done\n}\n\nFatal () { Msg \"$@\"; exit 1; }\n\nset -- `getopt hl \"$@\" 2>/dev/null` || Usage\n[ $# -lt 1 ] && Usage # \"getopt\" detected an error\n\nEncodeEOL=no\nwhile [ $# -gt 0 ]\ndo\n case \"$1\" in\n -l) EncodeEOL=yes;;\n --) shift; break;;\n -h) Usage;;\n -*) Usage;;\n *) break;; # First file name\n esac\n shift\ndone\n\nLANG=C export LANG\n$AWK '\n BEGIN {\n # We assume an awk implementation that is just plain dumb.\n # We will convert an character to its ASCII value with the\n # table ord[], and produce two-digit hexadecimal output\n # without the printf(\"%02X\") feature.\n\n EOL = \"%0A\" # \"end of line\" string (encoded)\n split (\"1 2 3 4 5 6 7 8 9 A B C D E F\", hextab, \" \")\n hextab [0] = 0\n for ( i=1; i<=255; ++i ) ord [ sprintf (\"%c\", i) \"\" ] = i + 0\n if (\"'\"$EncodeEOL\"'\" == \"yes\") EncodeEOL = 1; else EncodeEOL = 0\n }\n {\n encoded = \"\"\n for ( i=1; i<=length ($0); ++i ) {\n c = substr ($0, i, 1)\n if ( c ~ /[a-zA-Z0-9.-]/ ) {\n encoded = encoded c # safe character\n } else if ( c == \" \" ) {\n encoded = encoded \"+\" # special handling\n } else {\n # unsafe character, encode it as a two-digit hex-number\n lo = ord [c] % 16\n hi = int (ord [c] / 16);\n encoded = encoded \"%\" hextab [hi] hextab [lo]\n }\n }\n if ( EncodeEOL ) {\n printf (\"%s\", encoded EOL)\n } else {\n print encoded\n }\n }\n END {\n #if ( EncodeEOL ) print \"\"\n }\n' \"$@\"\n" }, { "answer_id": 1710689, "author": "blueyed", "author_id": 15690, "author_profile": "https://Stackoverflow.com/users/15690", "pm_score": 5, "selected": false, "text": "perl -p -e 's/([^A-Za-z0-9])/sprintf(\"%%%02X\", ord($1))/seg'\n" }, { "answer_id": 2027690, "author": "Jacob Rask", "author_id": 114168, "author_profile": "https://Stackoverflow.com/users/114168", "pm_score": 10, "selected": true, "text": "curl --data-urlencode man curl --data <data> curl \\\n --data-urlencode \"paramName=value\" \\\n --data-urlencode \"secondParam=value\" \\\n http://example.com\n curl -V curl --get \\\n --data-urlencode \"p1=value 1\" \\\n --data-urlencode \"p2=value 2\" \\\n http://example.com\n # http://example.com?p1=value%201&p2=value%202\n" }, { "answer_id": 2236014, "author": "sandro", "author_id": 270188, "author_profile": "https://Stackoverflow.com/users/270188", "pm_score": 6, "selected": false, "text": "encoded_value=$(python3 -c \"import urllib.parse; print urllib.parse.quote('''$value''')\")\n \"http://www.rai.it/dl/audio/\" \"1264165523944Ho servito il re d'Inghilterra - Puntata 7\n" }, { "answer_id": 3077738, "author": "Louis Marascio", "author_id": 174430, "author_profile": "https://Stackoverflow.com/users/174430", "pm_score": 3, "selected": false, "text": "url_encode() {\n [ $# -lt 1 ] && { return; }\n\n encodedurl=\"$1\";\n\n # make sure hexdump exists, if not, just give back the url\n [ ! -x \"/usr/bin/hexdump\" ] && { return; }\n\n encodedurl=`\n echo $encodedurl | hexdump -v -e '1/1 \"%02x\\t\"' -e '1/1 \"%_c\\n\"' |\n LANG=C awk '\n $1 == \"20\" { printf(\"%s\", \"+\"); next } # space becomes plus\n $1 ~ /0[adAD]/ { next } # strip newlines\n $2 ~ /^[a-zA-Z0-9.*()\\/-]$/ { printf(\"%s\", $2); next } # pass through what we can\n { printf(\"%%%s\", $1) } # take hex value of everything else\n '`\n}\n" }, { "answer_id": 4657796, "author": "manoflinux", "author_id": 571272, "author_profile": "https://Stackoverflow.com/users/571272", "pm_score": 3, "selected": false, "text": "url=$(echo \"$1\" | sed -e 's/%/%25/g' -e 's/ /%20/g' -e 's/!/%21/g' -e 's/\"/%22/g' -e 's/#/%23/g' -e 's/\\$/%24/g' -e 's/\\&/%26/g' -e 's/'\\''/%27/g' -e 's/(/%28/g' -e 's/)/%29/g' -e 's/\\*/%2a/g' -e 's/+/%2b/g' -e 's/,/%2c/g' -e 's/-/%2d/g' -e 's/\\./%2e/g' -e 's/\\//%2f/g' -e 's/:/%3a/g' -e 's/;/%3b/g' -e 's//%3e/g' -e 's/?/%3f/g' -e 's/@/%40/g' -e 's/\\[/%5b/g' -e 's/\\\\/%5c/g' -e 's/\\]/%5d/g' -e 's/\\^/%5e/g' -e 's/_/%5f/g' -e 's/`/%60/g' -e 's/{/%7b/g' -e 's/|/%7c/g' -e 's/}/%7d/g' -e 's/~/%7e/g')\n" }, { "answer_id": 5117285, "author": "Piotr Czapla", "author_id": 80869, "author_profile": "https://Stackoverflow.com/users/80869", "pm_score": 5, "selected": false, "text": "GET --get curl -v --get --data-urlencode \"access_token=$(cat .fb_access_token)\" https://graph.facebook.com/me/feed\n" }, { "answer_id": 5835915, "author": "Stuart P. Bentley", "author_id": 34799, "author_profile": "https://Stackoverflow.com/users/34799", "pm_score": 2, "selected": false, "text": "url=$(echo 'print((arg[1]:gsub(\"([^%w%-%.%_%~])\",function(c)return(\"%%%02X\"):format(c:byte())end)))' | lua - \"$1\")\n gsub(\"\\r?\\n\", \"\\r\\n\") url=$(echo 'print((arg[1]:gsub(\"\\r?\\n\", \"\\r\\n\"):gsub(\"([^%w%-%.%_%~ ]))\",function(c)return(\"%%%02X\"):format(c:byte())end):gsub(\" \",\"+\"))' | lua - \"$1\")\n" }, { "answer_id": 7506695, "author": "josch", "author_id": 784669, "author_profile": "https://Stackoverflow.com/users/784669", "pm_score": 6, "selected": false, "text": "sed awk echo -ne 'some random\\nbytes' | xxd -plain | tr -d '\\n' | sed 's/\\(..\\)/%\\1/g'\n hexdump hexdump xxd tr echo -ne 'some random\\nbytes' | hexdump -v -e '/1 \"%02x\"' | sed 's/\\(..\\)/%\\1/g'\n" }, { "answer_id": 9088459, "author": "Darren Weber", "author_id": 1172685, "author_profile": "https://Stackoverflow.com/users/1172685", "pm_score": 3, "selected": false, "text": "value=\"http://www.google.com\"\nencoded=$(php -r \"echo rawurlencode('$value');\")\n# encoded = \"http%3A%2F%2Fwww.google.com\"\necho $(php -r \"echo rawurldecode('$encoded');\")\n# returns: \"http://www.google.com\"\n" }, { "answer_id": 10660730, "author": "Orwellophile", "author_id": 912236, "author_profile": "https://Stackoverflow.com/users/912236", "pm_score": 8, "selected": false, "text": "rawurlencode() {\n local string=\"${1}\"\n local strlen=${#string}\n local encoded=\"\"\n local pos c o\n\n for (( pos=0 ; pos<strlen ; pos++ )); do\n c=${string:$pos:1}\n case \"$c\" in\n [-_.~a-zA-Z0-9] ) o=\"${c}\" ;;\n * ) printf -v o '%%%02x' \"'$c\"\n esac\n encoded+=\"${o}\"\n done\n echo \"${encoded}\" # You can either set a return variable (FASTER) \n REPLY=\"${encoded}\" #+or echo the result (EASIER)... or both... :p\n}\n easier: echo http://url/q?=$( rawurlencode \"$args\" )\nfaster: rawurlencode \"$args\"; echo http://url/q?${REPLY}\n # Returns a string in which the sequences with percent (%) signs followed by\n# two hex digits have been replaced with literal characters.\nrawurldecode() {\n\n # This is perhaps a risky gambit, but since all escape characters must be\n # encoded, we can replace %NN with \\xNN and pass the lot to printf -b, which\n # will decode hex for us\n\n printf -v REPLY '%b' \"${1//%/\\\\x}\" # You can either set a return variable (FASTER)\n\n echo \"${REPLY}\" #+or echo the result (EASIER)... or both... :p\n}\n $ diff rawurlencode.inc.sh \\\n <( rawurldecode \"$( rawurlencode \"$( cat rawurlencode.inc.sh )\" )\" ) \\\n && echo Matched\n\nOutput: Matched\n replace_value=$(echo $replace_value | sed -f /usr/lib/ddns/url_escape.sed)\n # sed url escaping\ns:%:%25:g\ns: :%20:g\ns:<:%3C:g\ns:>:%3E:g\ns:#:%23:g\ns:{:%7B:g\ns:}:%7D:g\ns:|:%7C:g\ns:\\\\:%5C:g\ns:\\^:%5E:g\ns:~:%7E:g\ns:\\[:%5B:g\ns:\\]:%5D:g\ns:`:%60:g\ns:;:%3B:g\ns:/:%2F:g\ns:?:%3F:g\ns^:^%3A^g\ns:@:%40:g\ns:=:%3D:g\ns:&:%26:g\ns:\\$:%24:g\ns:\\!:%21:g\ns:\\*:%2A:g\n xxd" }, { "answer_id": 10797966, "author": "Sergey", "author_id": 1423482, "author_profile": "https://Stackoverflow.com/users/1423482", "pm_score": 6, "selected": false, "text": "urlencode() {\n local data\n if [[ $# != 1 ]]; then\n echo \"Usage: $0 string-to-urlencode\"\n return 1\n fi\n data=\"$(curl -s -o /dev/null -w %{url_effective} --get --data-urlencode \"$1\" \"\")\"\n if [[ $? != 3 ]]; then\n echo \"Unexpected error\" 1>&2\n return 2\n fi\n echo \"${data##/?}\"\n return 0\n}\n date | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- \"\" | cut -c 3-\n\n# If you experience the trailing %0A, use\ndate | curl -Gso /dev/null -w %{url_effective} --data-urlencode @- \"\" | sed -E 's/..(.*).../\\1/'\n" }, { "answer_id": 11111040, "author": "k107", "author_id": 594496, "author_profile": "https://Stackoverflow.com/users/594496", "pm_score": 2, "selected": false, "text": "value=\"$(ruby -r cgi -e 'puts CGI.escape(ARGV[0])' \"$2\")\"\n" }, { "answer_id": 13561353, "author": "kev", "author_id": 348785, "author_profile": "https://Stackoverflow.com/users/348785", "pm_score": 3, "selected": false, "text": "$ echo -ne '你好世界' | uni2ascii -aJ\n%E4%BD%A0%E5%A5%BD%E4%B8%96%E7%95%8C\n" }, { "answer_id": 17989856, "author": "chenzhiwei", "author_id": 1536735, "author_profile": "https://Stackoverflow.com/users/1536735", "pm_score": 4, "selected": false, "text": "after=$(echo -e \"$before\" | od -An -tx1 | tr ' ' % | xargs printf \"%s\")\n" }, { "answer_id": 18252264, "author": "ajaest", "author_id": 747616, "author_profile": "https://Stackoverflow.com/users/747616", "pm_score": 1, "selected": false, "text": "URL_ENCODED_DATA=`php -r \"echo urlencode('$DATA');\"`\n" }, { "answer_id": 20653858, "author": "jan halfar", "author_id": 1044649, "author_profile": "https://Stackoverflow.com/users/1044649", "pm_score": 2, "selected": false, "text": "echo \"encode me\" | php -r \"echo urlencode(file_get_contents('php://stdin'));\"\n" }, { "answer_id": 20773604, "author": "Ray Burgemeestre", "author_id": 1958831, "author_profile": "https://Stackoverflow.com/users/1958831", "pm_score": 1, "selected": false, "text": "#!/bin/ksh93\n\nfunction rawurlencode\n{\n typeset string=\"${1}\"\n typeset strlen=${#string}\n typeset encoded=\"\"\n\n for (( pos=0 ; pos<strlen ; pos++ )); do\n c=${string:$pos:1}\n case \"$c\" in\n [-_.~a-zA-Z0-9] ) o=\"${c}\" ;;\n * ) o=$(printf '%%%02x' \"'$c\")\n esac\n encoded+=\"${o}\"\n done\n print \"${encoded}\"\n}\n\nfunction rawurldecode\n{\n printf $(printf '%b' \"${1//%/\\\\x}\")\n}\n\nprint $(rawurlencode \"C++\") # --> C%2b%2b\nprint $(rawurldecode \"C%2b%2b\") # --> C++\n" }, { "answer_id": 24601480, "author": "davidchambers", "author_id": 312785, "author_profile": "https://Stackoverflow.com/users/312785", "pm_score": 3, "selected": false, "text": "uriencode() {\n node -p \"encodeURIComponent('${1//\\'/\\\\\\'}')\"\n}\n" }, { "answer_id": 26929482, "author": "Dylan", "author_id": 3102549, "author_profile": "https://Stackoverflow.com/users/3102549", "pm_score": 3, "selected": false, "text": "value=$(urlencode \"${2}\")\n sudo apt install gridsite-clients\n" }, { "answer_id": 28055173, "author": "Klaus", "author_id": 420726, "author_profile": "https://Stackoverflow.com/users/420726", "pm_score": 3, "selected": false, "text": "encodeURIComponent perl -pe 's/([^a-zA-Z0-9_.!~*()'\\''-])/sprintf(\"%%%02X\", ord($1))/ge'\n .bash_profile alias encodeURIComponent='perl -pe '\\''s/([^a-zA-Z0-9_.!~*()'\\''\\'\\'''\\''-])/sprintf(\"%%%02X\",ord($1))/ge'\\'\n encodeURIComponent $ echo -n 'hèllo wôrld!' | encodeURIComponent\nh%C3%A8llo%20w%C3%B4rld!\n" }, { "answer_id": 28734597, "author": "Ryan", "author_id": 563394, "author_profile": "https://Stackoverflow.com/users/563394", "pm_score": 3, "selected": false, "text": "echo 'part-that-needs-encoding' | php -R 'echo urlencode($argn);'\n" }, { "answer_id": 34407620, "author": "nisetama", "author_id": 4669748, "author_profile": "https://Stackoverflow.com/users/4669748", "pm_score": 8, "selected": false, "text": "jq $ printf %s 'input text'|jq -sRr @uri\ninput%20text\n$ jq -rn --arg x 'input text' '$x|@uri'\ninput%20text\n -r --raw-output -n --null-input -R --raw-input -sR --slurp --raw-input -sRr -Rr %0A $ printf %s\\\\n multiple\\ lines of\\ text|jq -Rr @uri\nmultiple%20lines\nof%20text\n$ printf %s\\\\n multiple\\ lines of\\ text|jq -sRr @uri\nmultiple%20lines%0Aof%20text%0A\n xxd -p|tr -d \\\\n|sed 's/../%&/g'\n" }, { "answer_id": 41405682, "author": "Zombo", "author_id": 1002260, "author_profile": "https://Stackoverflow.com/users/1002260", "pm_score": 3, "selected": false, "text": "url_encode() {\n awk 'BEGIN {\n for (n = 0; n < 125; n++) {\n m[sprintf(\"%c\", n)] = n\n }\n n = 1\n while (1) {\n s = substr(ARGV[1], n, 1)\n if (s == \"\") {\n break\n }\n t = s ~ /[[:alnum:]_.!~*\\47()-]/ ? t s : t sprintf(\"%%%02X\", m[s])\n n++\n }\n print t\n }' \"$1\"\n}\n value=$(url_encode \"$2\")\n" }, { "answer_id": 41413026, "author": "davidchambers", "author_id": 312785, "author_profile": "https://Stackoverflow.com/users/312785", "pm_score": 4, "selected": false, "text": "uriencode() {\n s=\"${1//'%'/%25}\"\n s=\"${s//' '/%20}\"\n s=\"${s//'\"'/%22}\"\n s=\"${s//'#'/%23}\"\n s=\"${s//'$'/%24}\"\n s=\"${s//'&'/%26}\"\n s=\"${s//'+'/%2B}\"\n s=\"${s//','/%2C}\"\n s=\"${s//'/'/%2F}\"\n s=\"${s//':'/%3A}\"\n s=\"${s//';'/%3B}\"\n s=\"${s//'='/%3D}\"\n s=\"${s//'?'/%3F}\"\n s=\"${s//'@'/%40}\"\n s=\"${s//'['/%5B}\"\n s=\"${s//']'/%5D}\"\n printf %s \"$s\"\n}\n" }, { "answer_id": 41955579, "author": "nulleight", "author_id": 789371, "author_profile": "https://Stackoverflow.com/users/789371", "pm_score": 2, "selected": false, "text": "urlencode()\n{\n local S=\"${1}\"\n local encoded=\"\"\n local ch\n local o\n for i in $(seq 0 $((${#S} - 1)) )\n do\n ch=${S:$i:1}\n case \"${ch}\" in\n [-_.~a-zA-Z0-9]) \n o=\"${ch}\"\n ;;\n *) \n o=$(printf '%%%02x' \"'$ch\") \n ;;\n esac\n encoded=\"${encoded}${o}\"\n done\n echo ${encoded}\n}\n\nurldecode() \n{\n # urldecode <string>\n local url_encoded=\"${1//+/ }\"\n printf '%b' \"${url_encoded//%/\\\\x}\"\n}\n" }, { "answer_id": 43376248, "author": "Nestor Urquiza", "author_id": 399959, "author_profile": "https://Stackoverflow.com/users/399959", "pm_score": 3, "selected": false, "text": "node -p \"encodeURIComponent('$url')\"\n" }, { "answer_id": 48071404, "author": "Per Bothner", "author_id": 6883790, "author_profile": "https://Stackoverflow.com/users/6883790", "pm_score": 0, "selected": false, "text": "print_path_url() {\n local LC_ALL=C\n local string=\"$PWD\"\n local strlen=${#string}\n local encoded=\"\"\n local pos c o\n\n for (( pos=0 ; pos<strlen ; pos++ )); do\n c=${string:$pos:1}\n case \"$c\" in\n [-_.~a-zA-Z0-9/] ) o=\"${c}\" ;;\n * ) printf -v o '%%%02x' \"'$c\"\n esac\n encoded+=\"${o}\"\n done\n printf \"\\033]7;file://%s%s\\007\" \"${HOSTNAME:-}\" \"${encoded}\"\n}\n" }, { "answer_id": 56778195, "author": "Bruno Bronosky", "author_id": 117471, "author_profile": "https://Stackoverflow.com/users/117471", "pm_score": 0, "selected": false, "text": "url $ urlencode(){ node -e \"console.log(require('url').parse(process.argv.slice(1).join('+')).href)\" \"$@\"; }\n\n$ urlencode \"https://example.com?my_database_has=these 'nasty' query strings in it\"\nhttps://example.com/?my_database_has=these%20%27nasty%27%20query%20strings%20in%20it\n" }, { "answer_id": 62619806, "author": "dash-o", "author_id": 12098405, "author_profile": "https://Stackoverflow.com/users/12098405", "pm_score": 0, "selected": false, "text": "url_encode()\n{\n local key=\"${1}\" varname=\"${2:-_rval}\" prefix=\"${3:-_ENCKEY_}\"\n local unsafe=${key//[-_.~a-zA-Z0-9 ]/} \n local -i key_len=${#unsafe}\n local ch ch1 ch0\n\n while [ \"$unsafe\" ] ;do\n ch=${unsafe:0:1}\n ch0=\"\\\\$ch\"\n printf -v ch1 '%%%02x' \"'$ch'\" \n key=${key//$ch0/\"$ch1\"}\n unsafe=${unsafe//\"$ch0\"}\n done\n key=${key// /+} \n\n REPLY=\"$key\"\n # printf \"%s\" \"$REPLY\"\n return 0\n}\n\n function t {\n local key\n for (( i=1 ; i<=$1 ; i++ )) do url_encode \"$2\" kkk2 ; done\n echo \"K=$REPLY\"\n}\n\nt 1000 \"https://stackoverflow.com/questions/296536/how-to-urlencode-data-for-curl-command\"\n\n" }, { "answer_id": 62788692, "author": "Wolfgang Fahl", "author_id": 1497139, "author_profile": "https://Stackoverflow.com/users/1497139", "pm_score": 3, "selected": false, "text": "echo \"Test & /me\" | python -c \"import urllib.parse;print (urllib.parse.quote(input()))\"\n" }, { "answer_id": 66158943, "author": "masterxilo", "author_id": 524504, "author_profile": "https://Stackoverflow.com/users/524504", "pm_score": 3, "selected": false, "text": "uriencode_stdin() {\n node -p 'encodeURIComponent(require(\"fs\").readFileSync(0))'\n}\n\necho -n $'hello\\nwörld' | uriencode_stdin\nhello%0Aw%C3%B6rld\n\n" }, { "answer_id": 67448946, "author": "Darkman", "author_id": 10534012, "author_profile": "https://Stackoverflow.com/users/10534012", "pm_score": 0, "selected": false, "text": "#!/bin/dash\n\nreplaceUnicodes () { # $1=input/output file\n if ! mv -f \"$1\" \"$1\".tmp 2>/dev/null; then return 1; fi\n output=\"$1\" awk '\n function hexValue(chr) {\n if(chr==\"0\") return 0; if(chr==\"1\") return 1; if(chr==\"2\") return 2; if(chr==\"3\") return 3; if(chr==\"4\") return 4; if(chr==\"5\") return 5;\n if(chr==\"6\") return 6; if(chr==\"7\") return 7; if(chr==\"8\") return 8; if(chr==\"9\") return 9; if(chr==\"A\") return 10;\n if(chr==\"B\") return 11; if(chr==\"C\") return 12; if(chr==\"D\") return 13; if(chr==\"E\") return 14; return 15 }\n function hexToDecimal(str, value,i,inc) {\n str=toupper(str); value=and(hexValue(substr(str,length(str),1)),15); inc=1;\n for(i=length(str)-1;i>0;i--) {\n value+=lshift(hexValue(substr(str,i,1)),4*inc++)\n } return value }\n function toDecimal(str, value,i) {\n for(i=1;i<=length(str);i++) {\n value=(value*10)+substr(str,i,1)\n } return value }\n function to32BE(high,low) {\n # return 0x10000+((high-0xD800)*0x400)+(low-0xDC00) }\n return lshift((high-0xD800),10)+(low-0xDC00)+0x10000 }\n function toUTF8(value) {\n if(value<0x80) { \n return sprintf(\"%%%02X\",value)\n } else if(value>0xFFFF) {\n return sprintf(\"%%%02X%%%02X%%%02X%%%02X\",or(0xF0,and(rshift(value,18),0x07)),or(0x80,and(rshift(value,12),0x3F)),or(0x80,and(rshift(value,6),0x3F)),or(0x80,and(rshift(value,0),0x3F)))\n } else if(value>0x07FF) {\n return sprintf(\"%%%02X%%%02X%%%02X\",or(0xE0,and(rshift(value,12),0x0F)),or(0x80,and(rshift(value,6),0x3F)),or(0x80,and(rshift(value,0),0x3F)))\n } else { return sprintf(\"%%%02X%%%02X\",or(0xC0,and(rshift(value,6),0x1F)),or(0x80,and(rshift(value,0),0x3F))) }\n }\n function trap(str) { sub(/^\\\\+/,\"\\\\\",str); return str }\n function esc(str) { gsub(/\\\\/,\"\\\\\\\\\",str); return str }\n BEGIN { output=ENVIRON[\"output\"] }\n {\n finalStr=\"\"; while(match($0,/[\\\\]+u[0-9a-fA-F]{4}/)) {\n p=substr($0,RSTART,RLENGTH); num=hexToDecimal(substr(p,RLENGTH-3,4));\n bfrStr=substr($0,1,RSTART-1); $0=substr($0,RSTART+RLENGTH,length($0)-(RSTART+RLENGTH-1));\n if(surrogate) {\n surrogate=0;\n if(RSTART!=1 || num<0xD800 || (num>0xDBFF && num<0xDC00) || num>0xDFFF) {\n finalStr=sprintf(\"%s%s%s%s\",finalStr,trap(highP),bfrStr,toUTF8(num))\n } else if(num>0xD7FF && num<0xDC00) {\n surrogate=1; high=num; finalStr=sprintf(\"%s%s\",finalStr,trap(highP))\n } else { finalStr=sprintf(\"%s%s\",finalStr,toUTF8(to32BE(high,num))) }\n } else if(num>0xD7FF && num<0xDC00) {\n surrogate=1; highP=p; high=num; finalStr=sprintf(\"%s%s\",finalStr,bfrStr)\n } else { finalStr=sprintf(\"%s%s%s\",finalStr,bfrStr,toUTF8(num)) }\n } finalStr=sprintf(\"%s%s\",finalStr,$0); $0=finalStr\n\n while(match($0,/[\\\\]+U[0-9a-fA-F]{8}/)) {\n str=substr($0,RSTART,RLENGTH); gsub(esc(str),toUTF8(hexToDecimal(substr(str,RLENGTH-7,8))),$0)\n }\n while(match($0,/[\\\\]*&#[xX][0-9a-fA-F]{1,8};/)) {\n str=substr($0,RSTART,RLENGTH); idx=index(str,\"#\");\n gsub(esc(str),toUTF8(hexToDecimal(substr(str,idx+2,RLENGTH-idx-2))),$0)\n }\n while(match($0,/[\\\\]*&#[0-9]{1,10};/)) {\n str=substr($0,RSTART,RLENGTH); idx=index(str,\"#\");\n gsub(esc(str),toUTF8(toDecimal(substr(str,idx+1,RLENGTH-idx-1))),$0)\n }\n printf(\"%s\\n\",$0) > output\n }' \"$1\".tmp\n rm -f \"$1\".tmp\n}\n\nreplaceHtmlEntities () { # $1=input/output file\n if ! mv -f \"$1\" \"$1\".tmp 2>/dev/null; then return 1; fi\n sed 's/%3[aA]/:/g; s/%2[fF]/\\//g; s/&quot;/%22/g; s/&lt;/%3C/g; s/&gt;/%3E/g; s/&nbsp;/%A0/g; s/&cent;/%A2/g; s/&pound;/%A3/g; s/&yen;/%A5/g; s/&copy;/%A9/g; s/&reg;/%AE/g; s/&amp;/\\&/g; s/\\\\*\\//\\//g' \"$1\".tmp > \"$1\"\n rm -f \"$1\".tmp\n}\n\n\n# \"od -v -A n -t u1 -w99999999\"\n# \"hexdump -v -e \\47/1 \\42%d \\42\\47\"\n# Reminder :: Do not encode (, ), [, and ].\ntoUTF8Encoded () { # $1=input/output file\n if ! mv -f \"$1\" \"$1\".tmp 2>/dev/null; then return 1; fi\n if [ -s \"$1\".tmp ]; then\n # od -A n -t u1 -w99999999 \"$1\".tmp | \\\n hexdump -v -e '/1 \"%d \"' \"$1\".tmp | \\\n output=\"$1\" awk 'function hexDigit(chr) { if((chr>47 && chr<58) || (chr>64 && chr<71) || (chr>96 && chr<103)) return 1; return 0 }\n BEGIN { output=ENVIRON[\"output\"] }\n { for(i=1;i<=NF;i++) {\n flushed=0; c=$(i);\n if(c==13) { if($(i+1)==10) i++; printf(\"%s\\n\",url) > output; url=\"\"; flushed=1\n } else if(c==10) { printf(\"%s\\n\",url) > output; url=\"\"; flushed=1\n } else if(c==37) {\n if(hexDigit($(i+1)) && hexDigit($(i+2))) {\n url=sprintf(\"%s%%%c%c\",url,$(i+1),$(i+2)); i+=2\n } else { url=sprintf(\"%s%%25\",url) }\n } else if(c>32 && c<127 && c!=34 && c!=39 && c!=96 && c!=60 && c!=62) {\n url=sprintf(\"%s%c\",url,c)\n } else { url=sprintf(\"%s%%%02X\",url,c) }\n } if(!flushed) printf(\"%s\\n\",url) > output\n }'\n fi\n rm -f \"$1\".tmp\n}\n replaceUnicodes() replaceHtmlEntities() toUTF8Encoded()" }, { "answer_id": 69586585, "author": "sthames42", "author_id": 2245849, "author_profile": "https://Stackoverflow.com/users/2245849", "pm_score": 1, "selected": false, "text": "url_encode()\n {\n echo -n \"$1\" | perl -pe 's/[^a-zA-Z0-9\\/_.~-]/sprintf \"%%%02x\", ord($&)/ge'\n }\n" }, { "answer_id": 74364443, "author": "CSTobey", "author_id": 1344599, "author_profile": "https://Stackoverflow.com/users/1344599", "pm_score": 0, "selected": false, "text": "${#str} ${str:$i:1} while IFS='' read -n 1 c ; do [[ \"$c\" =~ [A-Za-z0-9.~_-] ]] && printf \"$c\" || printf '%%%02X' \"'$c\" ; done\n function urlen_stdin {\n while IFS='' read -n 1 c ; do [[ \"$c\" =~ [A-Za-z0-9.~_-] ]] && printf \"$c\" || printf '%%%02X' \"'$c\" ; done\n}\nfunction urlen_param {\n printf '%s' \"$1\" | while IFS='' read -n 1 c ; do [[ \"$c\" =~ [A-Za-z0-9.~_-] ]] && printf \"$c\" || printf '%%%02X' \"'$c\" ; done\n}\nfunction urlen_here {\n while IFS='' read -n 1 c ; do [[ \"$c\" =~ [A-Za-z0-9.~_-] ]] && printf \"$c\" || printf '%%%02X' \"'$c\" ; done <<< \"$1\"\n}\n\n#usage: \necho -n 'hello !@#$%^&*()[]:;{}\\/|-_=+.,? world' | urlen_stdin\nurlen_param 'hello !@#$%^&*()[]:;{}\\/|-_=+.,? world'\nurlen_here 'hello !@#$%^&*()[]:;{}\\/|-_=+.,? world'\n# all methods render:\nhello%20%21%40%23%24%25%5E%26%2A%28%29%5B%5D%3A%3B%7B%7D%2F%7C-_%3D%2B.%2C%3F%20world\n IFS='' read -n 1 [[ =~ ]] && || printf '%%%02X' %" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19130/" ]
296,538
<p>I'm working for the first time with Forms Authentication, I'm using an example from the web to learn, I included in my web.config</p> <pre><code> &lt;authentication mode="Forms"&gt; &lt;forms name="MYWEBAPP.ASPXAUTH" loginUrl="Login.aspx" protection="All" path="/"/&gt; &lt;/authentication&gt; &lt;authorization&gt; &lt;deny users="?"/&gt; &lt;/authorization&gt; </code></pre> <p>Then I created a page for logging in "login.aspx", and coded this on a button, just to start;</p> <pre><code>private void btnLogin_Click(Object sender, EventArgs e) { // Initialize FormsAuthentication FormsAuthentication.Initialize(); // Create a new ticket used for authentication FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, // Ticket version Username.Value, // Username associated with ticket DateTime.Now, // Date/time issued DateTime.Now.AddMinutes(30), // Date/time to expire true, // "true" for a persistent user cookie "accountants, seekers, copiers, typers", // User-data, in this case the roles FormsAuthentication.FormsCookiePath);// Path cookie valid for // Encrypt the cookie using the machine key for secure transport string hash = FormsAuthentication.Encrypt(ticket); HttpCookie cookie = new HttpCookie( FormsAuthentication.FormsCookieName, // Name of auth cookie hash); // Hashed ticket // Set the cookie's expiration time to the tickets expiration time if (ticket.IsPersistent) cookie.Expires = ticket.Expiration; // Add the cookie to the list for outgoing response Response.Cookies.Add(cookie); } </code></pre> <p>Also I coded in Global.asax;</p> <pre><code>protected void Application_AuthenticateRequest(object sender, EventArgs e) { if(HttpContext.Current.User != null) { if(HttpContext.Current.User.Identity.IsAuthenticated) { if (HttpContext.Current.User.Identity is FormsIdentity) { FormsIdentity id = (FormsIdentity)HttpContext.Current.User.Identity; FormsAuthenticationTicket ticket = id.Ticket; // Get the stored user-data, in this case, our roles string userData = ticket.UserData; string[] roles = userData.Split(','); HttpContext.Current.User = new GenericPrincipal(id, roles); } } } } </code></pre> <p>And finally in another page I tried to confirm the roles aquired;</p> <pre><code>protected void Page_Load(object sender, EventArgs e) { string str = null; if (User.IsInRole("seekers")) { str += " seekers "; } if (User.IsInRole("accountants")) { str += " accountants "; } if (User.IsInRole("copiers")) { str += "copiers"; } Response.Write(str); } </code></pre> <p>But something strange happens cause it only writes "accountants" (note that "accountants" is the firts element in the delimited comma string) and not the other roles, which were supposed to be showed. I changed the order of the role list in the btnlogin click event writing "copiers" as the first element and it's written only "copiers" in the page. </p> <p>I've tried with different combinations and always is printed the first element of the delimited comma string.</p> <p>Sorry by my ignorance but what is happening here, are all the roles there or not? is normal? or there's something I'm forgetting here?</p> <p>Thanks in advance.</p>
[ { "answer_id": 296546, "author": "Jonas Kongslund", "author_id": 37548, "author_profile": "https://Stackoverflow.com/users/37548", "pm_score": 3, "selected": true, "text": "\"accountants, seekers, copiers, typers\"\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
296,550
<p>I understand how Lucene.net can work for text indexing. Will I be able to efficiently search for documents based on a given date range? Or will Lucene.net just use text matching to match the dates?</p>
[ { "answer_id": 304964, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 4, "selected": true, "text": " public static string Serialize(DateTime dateTime)\n {\n return dateTime.ToString(\"yyyyMMddHHmmss\", CultureInfo.InvariantCulture);\n }\n\n public static DateTime Deserialize(string str)\n {\n return DateTime.ParseExact(str, \"yyyyMMddHHmmss\", CultureInfo.InvariantCulture);\n }\n" }, { "answer_id": 3473829, "author": "Malay", "author_id": 419168, "author_profile": "https://Stackoverflow.com/users/419168", "pm_score": 1, "selected": false, "text": "yyyymmddHHmmssff yyyymmdd HHmmss Sort[]" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296550", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
296,560
<p>I am looking for a way to mount\unmount a USB flash drive using VBScript. This is the closest I was able to get.</p> <pre><code>Sub EjectDrive(strDrive) On Error Resume Next CONST SSF_DRIVES = 17 Set objShell = CreateObject("Shell.Application") Set objDrive = objShell.Namespace(SSF_DRIVES).ParseName(strDrive) objDrive.InvokeVerb "E&amp;ject" End Sub </code></pre>
[ { "answer_id": 297352, "author": "aphoria", "author_id": 2441, "author_profile": "https://Stackoverflow.com/users/2441", "pm_score": 2, "selected": false, "text": "strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n & \"{impersonationLevel=impersonate}!\\\\\" & strComputer & \"\\root\\cimv2\")\n\nSet colItems = objWMIService.ExecQuery _\n (\"Select * From Win32_Volume Where Name = 'E:\\\\'\")\n\nFor Each objItem in colItems\n objItem.Dismount(True, True)\nNext\n" }, { "answer_id": 300798, "author": "Zoredache", "author_id": 20267, "author_profile": "https://Stackoverflow.com/users/20267", "pm_score": 0, "selected": false, "text": "Set WshShell = WScript.CreateObject(\"WScript.Shell\")\nintReturn = WshShell.Run(\"RunDll32.exe shell32.dll,Control_RunDLL hotplug.dll\", 1, TRUE)\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,584
<p><strong>In C#, is there a way to instantiate an instance of a class without invoking its constructor?</strong></p> <p>Assume the class is public and is defined in a 3rd party library and the constructor is internal. The reasons I want to do this are complicated but it would be helpful to know if it's possible using some kind of C# hackery.</p> <p>NOTE: I specifically <strong>do not want to call any constructor</strong> so using reflection to access the internal constructor is not an option.</p>
[ { "answer_id": 296611, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 0, "selected": false, "text": "using System.Reflection;\n\n// If the constructor takes arguments, otherwise pass these as null\nType[] pTypes = new Type[1];\npTypes[0] = typeof(object); \nobject[] argList = new object[1];\nargList[0] = constructorArgs;\n\nConstructorInfo c = typeof(Foo).GetConstructor\n (BindingFlags.NonPublic |\n BindingFlags.Instance,\n null,\n pTypes,\n null);\n\nFoo foo = \n (Foo) c.Invoke(BindingFlags.NonPublic,\n null, \n argList, \n Application.CurrentCulture);\n" }, { "answer_id": 296720, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": -1, "selected": false, "text": "byte[] fakeObject = new byte[sizeof(myStruct)];\n" }, { "answer_id": 74641011, "author": "Warty", "author_id": 273085, "author_profile": "https://Stackoverflow.com/users/273085", "pm_score": 0, "selected": false, "text": "RuntimeHelpers.GetUninitializedObject(Type) FormatterServices.GetUninitializedObject(Type)" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296584", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2069/" ]
296,587
<p>I have a single user java program that I would like to have store data in a light weight database such as Derby or Sqlite. I would like to use a data abstraction layer in my program. Hibernate appears to require a lot of configuration and is overkill for what I need. What are light weight alternatives to Hibernate?</p>
[ { "answer_id": 4655996, "author": "Somatik", "author_id": 42198, "author_profile": "https://Stackoverflow.com/users/42198", "pm_score": 3, "selected": false, "text": "// Define the query\nDBCommand cmd = db.createCommand();\nDBColumnExpr EMPLOYEE_FULLNAME= db.EMPLOYEES.LASTNAME.append(\", \")\n .append(db.EMPLOYEES.FIRSTNAME).as(\"FULL_NAME\");\n// Select required columns\ncmd.select(db.EMPLOYEES.EMPLOYEE_ID, EMPLOYEE_FULLNAME);\ncmd.select(db.EMPLOYEES.GENDER, db.EMPLOYEES.PHONE_NUMBER);\ncmd.select(db.DEPARTMENTS.NAME.as(\"DEPARTMENT\"));\ncmd.select(db.DEPARTMENTS.BUSINESS_UNIT);\n// Set Joins\ncmd.join(db.EMPLOYEES.DEPARTMENT_ID, db.DEPARTMENTS.DEPARTMENT_ID);\n// Set contraints and order\ncmd.where(EMP.LASTNAME.length().isGreaterThan(0));\ncmd.orderBy(EMP.LASTNAME);;\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296587", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
296,603
<p>I'm working on an anti-spam project (<a href="http://centmail.net" rel="nofollow noreferrer">centmail</a>) that involves having the sender use a client plugin that adds a custom header (as well as a signature, but that part's <a href="https://stackoverflow.com/questions/142319">easier</a>). The general problem is to add an email header to your outgoing mail where the contents of the header field is determined dynamically for each message.</p> <p>Surprisingly, this does not seem to be possible in Pine/Alpine. Pine lets you specify a filter script for outgoing mail but only the body and not the headers get passed through it. You can of course define custom headers in the Pine settings but I see no way to dynamically change the contents of them.</p> <p>I'd be grateful to hear how to do this in other email clients (Thunderbird, Outlook, Evolution, Mutt, etc). And of course if I'm wrong about Pine.</p>
[ { "answer_id": 482698, "author": "Keltia", "author_id": 16143, "author_profile": "https://Stackoverflow.com/users/16143", "pm_score": 0, "selected": false, "text": "edit_headers my_hdr" }, { "answer_id": 482980, "author": "Sébastien RoccaSerra", "author_id": 2797, "author_profile": "https://Stackoverflow.com/users/2797", "pm_score": 2, "selected": false, "text": "get-buffer-create mail-send mail-interactive nil mail-send From: \"Toto\" <toto@toto.net>\nTo: somebody@somewhere.net\nSubject: Something\nBCC: sebastien.rocca-serra@f4-group.com\n--text follows this line--\n\nHello, how are you?\n mail-send-hook" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296603", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4234/" ]
296,609
<p>I'm trying to avoid a composite control or using and ASCX by extending an existing control. However, I'm having trouble with getting the controls added to the inherited control and keep their view-state/post-back integrity. Whenever I add the controls during pre-render, the controls show up, but the post-back throws a viewstate exception. I tried adding them both there and during LoadViewState (which of course was a long-shot silly). Init is not available from the control which I'm extending.</p> <blockquote> <p>The exception is Sys.WebForms.PageRequestManagerServerErrorException: Failed to load viewsstate. The control tree into which viewstate is being loaded must match the control tree that was used to save viewstate during the previous request. For example, when adding controls dynamically, the controls added during a post-back must match the type and position of the controls added during the initial request</p> </blockquote>
[ { "answer_id": 296623, "author": "Zachary Yates", "author_id": 8360, "author_profile": "https://Stackoverflow.com/users/8360", "pm_score": 3, "selected": true, "text": "protected override void CreateChildControls(){\n Controls.Add(someControl);\n base.CreateChildControls();\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296609", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2017/" ]
296,615
<p>Greetings!</p> <p>I'm scratching my head, wondering why when I do the following:</p> <pre><code>Response.Redirect(@"http://www.example.com/file.exe?id=12345"); </code></pre> <p>Both IE6 and IE7 will download the file as "file" (with no extension), but Firefox, Opera, Google Chrome and Safari have no problems at all downloading the file as "file.exe".</p> <p>Any idea what IE6/7's problem is and how can I fix this?</p>
[ { "answer_id": 296631, "author": "Falco Foxburr", "author_id": 37266, "author_profile": "https://Stackoverflow.com/users/37266", "pm_score": 2, "selected": false, "text": "Content-Type: application/octet-stream\nContent-Disposition: attachment; filename=\"file.exe\"\n" }, { "answer_id": 300884, "author": "Nathan", "author_id": 24954, "author_profile": "https://Stackoverflow.com/users/24954", "pm_score": 0, "selected": false, "text": "Response.Clear(); //In case your .aspx page has already written some html content\nResponse.AddHeader(\"Content-Type\", \"application/octet-stream\");\nstring disp = String.Format(\"attachment; filename={0}\", fileName); // fileName = file.exe\nResponse.AddHeader(\"Content-Disposition\", disp);\n\nServer.Transfer(@\"http://www.example.com/file.exe?id=12345\");\n Response.Clear(); //In case your .aspx page has already written some html content\nbyte[] exeContent = ... //read the content of the .exe into a byte[]\n\nResponse.AddHeader(\"Content-Type\", \"application/octet-stream\");\nstring disp = String.Format(\"attachment; filename={0}\", fileName); // fileName = file.exe\nResponse.AddHeader(\"Content-Disposition\", disp);\n\nResponse.BinaryWrite(exeContent);\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
296,619
<p>FreeMarker templates support an if-statement with the following syntax</p> <pre><code>&lt;#if hot&gt; It's hot. &lt;/#if&gt; </code></pre> <p>I've looked in the documentation and can't find any support for an if-else statement. Of course, I could achieve the same result with:</p> <pre><code>&lt;#if hot&gt; It's hot. &lt;/#if&gt; &lt;#if !hot&gt; It's not hot. &lt;/#if&gt; </code></pre> <p>Is there support for if-else in FreeMarker?</p>
[ { "answer_id": 296627, "author": "Ulf Lindback", "author_id": 30354, "author_profile": "https://Stackoverflow.com/users/30354", "pm_score": 6, "selected": true, "text": "<#if hot>\nit's hot\n<#else>\nit's not\n</#if>\n" }, { "answer_id": 299243, "author": "iberck", "author_id": 34768, "author_profile": "https://Stackoverflow.com/users/34768", "pm_score": 4, "selected": false, "text": "<#if condition> ... <#elseif condition2> ... <#elseif condition3> ... <#else> ... <#/if>" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296619", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2648/" ]
296,632
<p>I'm trying to configure Apache to allow read only access and ask for user to write to a SVN repository when you are coming from the local network (10.*) but not allow any access unless logged in when coming from external network.</p> <p>I sort of understand how the Order, Deny, Allow, and Limit directives work but I do not know if it is possible/how to combine them to achieve the desired result.</p> <pre><code>&lt;Location /svn&gt; # Set mod_dav_svn settings DAV svn SVNListParentPath on SVNParentPath /mnt/svn AuthzSVNAccessFile /mnt/svn/.authz # Set Authentication AuthType Basic AuthName "Auth Realm" AuthUserFile /mnt/svn/.htpasswd Order Deny,Allow Deny from all Allow from 127.0.0.1 10.0.0.0/8 &lt;LimitExcept GET PROPFIND OPTIONS REPORT&gt; Require valid-user &lt;/LimitExcept&gt; Satisfy Any &lt;/Location&gt; </code></pre> <p>I know this will allow all access to any local traffic but ask for login when trying to write from external traffic. This is close to what I want. Any help or suggestions on what to read are greatly appreciated.</p>
[ { "answer_id": 296627, "author": "Ulf Lindback", "author_id": 30354, "author_profile": "https://Stackoverflow.com/users/30354", "pm_score": 6, "selected": true, "text": "<#if hot>\nit's hot\n<#else>\nit's not\n</#if>\n" }, { "answer_id": 299243, "author": "iberck", "author_id": 34768, "author_profile": "https://Stackoverflow.com/users/34768", "pm_score": 4, "selected": false, "text": "<#if condition> ... <#elseif condition2> ... <#elseif condition3> ... <#else> ... <#/if>" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296632", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32465/" ]
296,657
<p>Recently, when porting some STL code to VS2008 I wanted to disable warnings generated by <code>std::copy</code> by defining the new <code>_SCL_SECURE_NO_WARNINGS</code> flag. You can do this in two ways:</p> <ul> <li>Using the <strong>/D</strong> compiler switch, which can be specified in the project properties. You need to ensure it is defined for both Release and Debug builds, which I often forget to do.</li> <li><p>By defining it macro style before you include the relevant STL headers, or, for total coverage, in stdafx.h:</p> <p><code>#define _SCL_SECURE_NO_WARNINGS</code></p></li> </ul> <p>Both of these methods work fine but I wondered if there was any argument for favouring one over the other?</p>
[ { "answer_id": 297147, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 1, "selected": false, "text": "#ifdef _MSC_VER\n#define _SCL_SECURE_NO_WARNINGS\n#endif\n" }, { "answer_id": 1640134, "author": "blak3r", "author_id": 67268, "author_profile": "https://Stackoverflow.com/users/67268", "pm_score": 1, "selected": false, "text": "/p:DefineConstants=\"MY_MACRO1;MY_MACRO2\"\n Target CoreCompile:\n C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\Csc.exe /define:MY_MACRO1;MY_MACRO2 ...\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
296,658
<p>I am creating a joomla plugin and want to load an array of images after the page has loaded. To do that, I'm currently using mootools.js to call myserver URL, obtain the JSON response and parse the response into javascript variables that represent each image url. It works great, but mootools.js is appropriately named since it is a real heffer in the size department. </p> <p>Is there a lightweight script out there that will make the ajax call and parse the JSON object? The smaller the better. </p>
[ { "answer_id": 296939, "author": "jishi", "author_id": 33663, "author_profile": "https://Stackoverflow.com/users/33663", "pm_score": 1, "selected": false, "text": "eval var json = eval('(' + xhr.responseText + ')');\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38339/" ]
296,667
<p>I have a function, <code>a()</code>, that I want to override, but also have the original <code>a()</code> be performed in an order depending on the context. For example, sometimes when I'm generating a page I'll want to override like this:</p> <pre><code>function a() { new_code(); original_a(); } </code></pre> <p>and sometimes like this:</p> <pre><code>function a() { original_a(); other_new_code(); } </code></pre> <p>How do I get that <code>original_a()</code> from within the over-riding <code>a()</code>? Is it even possible?</p> <p>Please don't suggest alternatives to over-riding in this way, I know of many. I'm asking about this way specifically.</p>
[ { "answer_id": 296706, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 9, "selected": true, "text": "var a = (function() {\n var original_a = a;\n\n if (condition) {\n return function() {\n new_code();\n original_a();\n }\n } else {\n return function() {\n original_a();\n other_new_code();\n }\n }\n})();\n original_a () a a" }, { "answer_id": 296713, "author": "PhilHoy", "author_id": 29547, "author_profile": "https://Stackoverflow.com/users/29547", "pm_score": 7, "selected": false, "text": "(function() {\n // log all calls to setArray\n var proxied = jQuery.fn.setArray;\n jQuery.fn.setArray = function() {\n console.log( this, arguments );\n return proxied.apply( this, arguments );\n };\n})();\n" }, { "answer_id": 1740510, "author": "Naresh S", "author_id": 211832, "author_profile": "https://Stackoverflow.com/users/211832", "pm_score": 5, "selected": false, "text": "//Saving the original func\nvar org_foo = window.foo;\n\n//Assigning proxy fucnc\nwindow.foo = function(args){\n //Performing checks\n if(checkCondition(args)){\n //Calling original funcs\n org_foo(args);\n }\n};\n" }, { "answer_id": 2170673, "author": "Hai Phan", "author_id": 262788, "author_profile": "https://Stackoverflow.com/users/262788", "pm_score": 4, "selected": false, "text": "function override(f, g) {\n return function() {\n return g(f);\n };\n}\n a = override(a, function(original_a) {\n if (condition) { new_code(); original_a(); }\n else { original_a(); other_new_code(); }\n });\n" }, { "answer_id": 9084014, "author": "Edric Garran", "author_id": 1180919, "author_profile": "https://Stackoverflow.com/users/1180919", "pm_score": 2, "selected": false, "text": "a = override(a, function(original_a) {\n if (condition) { new_code(); original_a.apply(this, arguments) ; }\n else { original_a.apply(this, arguments); other_new_code(); }\n});\n" }, { "answer_id": 12487565, "author": "nevf", "author_id": 91300, "author_profile": "https://Stackoverflow.com/users/91300", "pm_score": 2, "selected": false, "text": "this arguments this arguments" }, { "answer_id": 33857893, "author": "Sagar Sodah", "author_id": 2007205, "author_profile": "https://Stackoverflow.com/users/2007205", "pm_score": 0, "selected": false, "text": "if (typeof originalFunction === \"undefined\") {\n originalFunction = targetFunction;\n targetFunction = function(x, y) {\n //Your code\n originalFunction(a, b);\n //Your Code\n }; \n}\n" }, { "answer_id": 33912606, "author": "Zoltán Tamási", "author_id": 1323504, "author_profile": "https://Stackoverflow.com/users/1323504", "pm_score": 0, "selected": false, "text": "function overrideFunction(namespace, baseFuncName, func) {\n var originalFn = namespace[baseFuncName];\n namespace[baseFuncName] = function () {\n return func.apply(this, [originalFn.bind(this)].concat(Array.prototype.slice.call(arguments, 0)));\n };\n}\n overrideFunction($.fn.popover.Constructor.prototype, 'leave', function(baseFn, obj) {\n // ... do stuff before base call\n baseFn(obj);\n // ... do stuff after base call\n});\n" }, { "answer_id": 39442366, "author": "James L.", "author_id": 4180797, "author_profile": "https://Stackoverflow.com/users/4180797", "pm_score": 2, "selected": false, "text": "const orginial = someObject.foo;\nsomeObject.foo = function() {\n if (condition) orginial.bind(this)(...arguments);\n};\n" }, { "answer_id": 40655375, "author": "Rodrigo Hernandez", "author_id": 1759808, "author_profile": "https://Stackoverflow.com/users/1759808", "pm_score": 2, "selected": false, "text": " var a = (function(original_a) {\n if (condition) {\n return function() {\n new_code();\n original_a();\n }\n } else {\n return function() {\n original_a();\n other_new_code();\n }\n }\n })(a);\n" }, { "answer_id": 52090343, "author": "SteckDEV", "author_id": 1771899, "author_profile": "https://Stackoverflow.com/users/1771899", "pm_score": 0, "selected": false, "text": "this.viewer = new Autodesk.Viewing.Private.GuiViewer3D(\n this.viewerContainer)\nvar viewer = this.viewer;\nviewer.updateToolbarButtons = this.updateToolbarButtons(viewer);\n updateToolbarButtons = function(viewer) {\n var _viewer = viewer;\n return function(width, height){ \nblah blah black sheep I can refer to this.anything();\n}\n};\n" }, { "answer_id": 62224638, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 0, "selected": false, "text": "describe describe function describe( name, callback ) {\n if ( name.includes( \"skip\" ) )\n return this.describe.skip( name, callback );\n else\n return this.describe( name, callback );\n}\n () => this this this.describe this.describe.skip describe describe.skip" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16777/" ]
296,674
<p>One thing that bugs me about IE is that when it goes to load a page with an iframe it will wait until the iframe has finished loading before it will render the page. Firefox by contrast will render all the other page elements while the iframe is loading which is really nice if the iframe takes a long time to load because it gives the user some feedback that the page is progressing. It also allows you to do things like display a "iframe loading" messege while the frame loads and swap it out onload of the iframe.</p> <p>So, I am wondering if anyone has found a workaround for this. Ideally, I'd like to see a cross browser solution that shows a progess bar as an iframe loads on the page. Short of that I'd take a method of implementing an iframe that forces IE to first render the page then load the iframe.</p> <p>I have seen a couple of interesting jquery progress bars like: <a href="http://plugins.jquery.com/project/jQueryProgressBar" rel="nofollow noreferrer">http://plugins.jquery.com/project/jQueryProgressBar</a></p> <p>But...(and correct me if I'm wrong here cause my understanding is shaky)...it seems to me the jquery bars only render after the DOM has loaded. In IE the iframe content is not shown until after the DOM is loaded so showing a progress bar at that point is irrelevant.</p> <p>I've also tried setting the iframe src to loading.htm and then onload switch the src to the content I want. Sadly IE still will not render the page until the final content page comes up (seems strange to me).</p> <p>Help me stackoverflow, you're my only hope.</p>
[ { "answer_id": 296731, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": true, "text": "<!-- jQuery example: -->\n\n<div id='content'>Loading...</div>\n\n<script type='text/javascript'>\n$(\"#content\").load(url);\n</script>\n" }, { "answer_id": 296774, "author": "Benry", "author_id": 28408, "author_profile": "https://Stackoverflow.com/users/28408", "pm_score": 1, "selected": false, "text": "<body onload=\"document.getElementById('myIframe').location='someurl';\">\n <iframe id=\"myIframe\">\n</body>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5234/" ]
296,685
<p>I am trying to autoreload my page after every 20 seconds. I am using JavaScript for this instead of the &lt;meta>.</p> <p>I have &lt;body onload="SetTimer()"> and here is my JavaScript function</p> <pre><code> function SetTimer(){ setTimeout('window.location.replace(window.location.pathname)', 20000) } </code></pre> <p>Now my problem is I also pass a parameter within the querystring when this page is loaded first. But when the page relaods again (<code>window.location.pathname</code> does not include the parameter) hence I am not able to assign values to the labels on the page which is based on the parameters passed.</p>
[ { "answer_id": 296727, "author": "ng.mangine", "author_id": 37784, "author_profile": "https://Stackoverflow.com/users/37784", "pm_score": 1, "selected": false, "text": "function SetTimer(){ \n setTimeout('window.location.replace(window.location)', 20000)\n}\n" }, { "answer_id": 296737, "author": "Mithil", "author_id": 34219, "author_profile": "https://Stackoverflow.com/users/34219", "pm_score": 2, "selected": true, "text": " setTimeout('window.location.replace(window.location.href)', 2000);\n" }, { "answer_id": 2687150, "author": "alemjerus", "author_id": 231224, "author_profile": "https://Stackoverflow.com/users/231224", "pm_score": 2, "selected": false, "text": "function SetTimer(){ \n setTimeout('window.location.reload(true)', 20000)\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296685", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34219/" ]
296,696
<p>In Excel VBA (2003), I've noticed that any <strong>Public</strong> or <strong>Friend</strong> <strong>Sub</strong> method in either a module or <em>ThisWorkbook</em> that doesn't have any arguments will show up as a Macro that can be run by the user. I.e. when the user goes to Tools --> Macro --> Macros... (or Alt+F8) the method will show up in the list that can be run.</p> <p>For sanity's sake (organization, maintenance, etc) I do need to separate the code into modules. I'm hoping to find a non-hacky way to hide some methods from the user, but still allow them to be visible to other code modules. Note that all the code is contained within the same <em>application</em>, so no external code is called.</p> <p>My current work-around is to use <strong>Function</strong>s that return a boolean instead of <strong>Sub</strong>s, and just ignore the return value. eJames suggested the option of using an optional argument in the <strong>Sub</strong>, which will also hide the method from the list of macros.</p> <p>Neither of these feel quite right, however, so any advice about how to structure a non-trivial Excel VBA application would be much appreciated.</p>
[ { "answer_id": 296765, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 3, "selected": false, "text": "Optional Public Sub myPublicSub(Optional dummy_var As Integer)\n ...\nEnd Sub" }, { "answer_id": 296839, "author": "Jason Z", "author_id": 2470, "author_profile": "https://Stackoverflow.com/users/2470", "pm_score": 7, "selected": true, "text": "Option Private Module\n" }, { "answer_id": 362604, "author": "Ant", "author_id": 11529, "author_profile": "https://Stackoverflow.com/users/11529", "pm_score": 3, "selected": false, "text": "Option Private Module Application.Run()" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296696", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1354/" ]
296,717
<p>I need to unzip a compressed file on the fly in my program. It works when I try it on my own linux computer, but for some reason the school computers fail whenever I tell them to do it. To unzip I'm using the following command:</p> <pre><code> zcat /file/address/file.tar.gz </code></pre> <p>and get the error:</p> <pre><code> /file/address/file.tar.gz.Z: No such file or directory </code></pre> <p>I tried looking through the documentation but couldn't find a flag to turn off this odd behavior.</p>
[ { "answer_id": 296725, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 7, "selected": true, "text": "gzcat zcat" }, { "answer_id": 311821, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 3, "selected": false, "text": "gzip -dc /file/address/file.tar.gz\n" }, { "answer_id": 1637258, "author": "problem", "author_id": 198106, "author_profile": "https://Stackoverflow.com/users/198106", "pm_score": 0, "selected": false, "text": "zcat archive.tgz | tar -x --wildcards apri/fls/filename\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296717", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21539/" ]
296,719
<p>What's a good rule of thumb for naming methods that return properties/attributes/members of an object? If an object has some immutable quality "blarg", should a method that returns that quality be called "blarg()" or "getBlarg()"? The Java API, for example, is inconsistent: most properties are accessed through "get" methods (even those that don't have corresponding "set" methods), but yet we also have things like Object.hashCode() instead of Object.getHashCode(). </p> <p>Update: Should whether or not it's the property is a field (in the implementation) be the determiner here? What about a class to represent immutable points in 2-d space? Regardless of whether the point is stored as (x,y) or (r,theta), I would still want accessors for all four properties. Should they be getX(), getY(), etc, or just x(), y(), etc? From the point of view of the user, shouldn't all four have the same naming convention since we don't want our user to know/care about our implementation?</p>
[ { "answer_id": 296734, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 2, "selected": false, "text": "GetBlarg() or getBlarg()\n GetHashCode() hashcode" }, { "answer_id": 296743, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "getProperty isProperty" }, { "answer_id": 296766, "author": "Ian Varley", "author_id": 37539, "author_profile": "https://Stackoverflow.com/users/37539", "pm_score": 1, "selected": false, "text": "car.engine\n car.getEngine\n" }, { "answer_id": 297611, "author": "Matthew Schinckel", "author_id": 188, "author_profile": "https://Stackoverflow.com/users/188", "pm_score": 0, "selected": false, "text": "[obj setFoo:newFoo];\n [obj foo];\n[obj getFoo:otherFoo];\n[obj isFoo];\n temp = obj.foo;\n class Class:\n\n def get_x(self):\n return self._x\n\n def set_x(self,x):\n self._x = x\n\n x = property(get_x, set_x)\n get_thing()\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38343/" ]
296,721
<p>When is it appropriate to use &lt;cflock scope="application"&gt; or it's ilk as opposed to &lt;cflock name="foo"&gt;? </p> <p>Specifically, I'm interested in using CFLock to protect shared objects in the application, session, or server scopes, but I'm also interested in finding out about different uses of locking in ColdFusion.</p>
[ { "answer_id": 296758, "author": "Anne Porosoff", "author_id": 28701, "author_profile": "https://Stackoverflow.com/users/28701", "pm_score": 0, "selected": false, "text": "<cflock scope=\"application\">" }, { "answer_id": 296833, "author": "Nathan Strutz", "author_id": 5918, "author_profile": "https://Stackoverflow.com/users/5918", "pm_score": 4, "selected": true, "text": "<cfquery name=\"application.myData\">\n select * from myTable\n</cfquery>\n <cflock name=\"write_file_#session.user_type#\" type=\"exclusive\">\n <cffile action=\"write\" name=\"file_#session.user_type#\" output=\"#content#\" />\n</cflock>\n" }, { "answer_id": 300224, "author": "rip747", "author_id": 31278, "author_profile": "https://Stackoverflow.com/users/31278", "pm_score": 2, "selected": false, "text": "<cflock scope=\"application\" timeout=\"5\" type=\"exlusive\">\n <cfset application.data = {}>\n <cfset application.data.firstname = \"tony\">\n</cflock>\n\n<cfset variables.firstname = duplicate(application.data.firstname)>\n" }, { "answer_id": 17701107, "author": "sugardaddy", "author_id": 1298166, "author_profile": "https://Stackoverflow.com/users/1298166", "pm_score": 0, "selected": false, "text": "<!--- Initialize local flag to false. --->\n<cfset app_is_initialized = False>\n<!--- Get a readonly lock --->\n<cflock scope=\"application\" type=\"readonly\">\n <!--- read init flag and store it in local variable --->\n <cfset app_is_initialized = IsDefined(\"APPLICATION.initialized\")>\n</cflock>\n<!--- Check the local flag --->\n<cfif not app_is_initialized >\n<!--- Not initialized yet, get exclusive lock to write scope --->\n <cflock scope=\"application\" type=\"exclusive\">\n <!--- Check nonlocal flag since multiple requests could get to the\n exclusive lock --->\n <cfif not IsDefined(\"APPLICATION.initialized\") >\n <!--- Do initializations --->\n <cfset APPLICATION.varible1 = someValue >\n ... \n <!--- Set the Application scope initialization flag --->\n <cfset APPLICATION.initialized = \"yes\">\n </cfif>\n </cflock>\n</cfif>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21973/" ]
296,728
<p>I'd like to setup a build server for unmanaged C++ code developed in Visual Studio 2005. The build server should be able to do the following:</p> <ul> <li>Monitor a Subversion repository for code changes and schedule a build</li> <li>Checkout code from Subversion and run unit tests</li> <li>Provide some sort of report on build success and changes from previous build</li> </ul> <p>I've initially been looking at using CruiseControl with Ant. Is there a better solution? Perhaps CruiseControl.Net, and NAnt? </p>
[ { "answer_id": 9909912, "author": "Jan Hudec", "author_id": 201725, "author_profile": "https://Stackoverflow.com/users/201725", "pm_score": 0, "selected": false, "text": "devenv.com whatever.sln /build 'Release|Win32' /project whatever\n whatever Release|Win32" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296728", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,730
<p>I am creating a new table inside mysql and I am trying to add a foreign key constraint to one of the fields.</p> <pre> CREATE TABLE `onlineorder` ( `receiptid` varchar(10) NOT NULL default '', `delivereddate` date default NULL, `cid` int(10) NOT NULL, `card#` int(10) default NULL, `expire` date default NULL, PRIMARY KEY (`receiptid`), FOREIGN KEY (receiptid) REFERENCES purchase ) ENGINE=MyISAM DEFAULT CHARSET=latin1; </pre> <p>However, after it creates it, I go into phpMyAdmin and export the table. and it seems like the foreign key constraint has disappeared.</p> <pre> CREATE TABLE `onlineorder` ( `receiptid` varchar(10) NOT NULL default '', `delivereddate` date default NULL, `cid` int(10) NOT NULL, `card#` int(10) default NULL, `expire` date default NULL, PRIMARY KEY (`receiptid`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1; </pre> <p>Does phpMyAdmin get rid of foreign keys or am I doing something wrong here?</p>
[ { "answer_id": 297305, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "FOREIGN KEY CHECK SHOW WARNINGS" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28462/" ]
296,732
<p>I've been wondering if it's possible to have Fluent-NHibernate communicate with stored procedures that already exist and assign mapping from the result set to my own domain objects.</p> <p>Also is Fluent-NHibernate able to directly execute procedures with no result set returned?</p> <p>Basically I've been considering the implications of using Fluent-NHibernate to replace a dated TypedDataSet model with a domain driven design that can return simple objects from the DAL. If Fluent-NHibernate cannot work with SPs easily, I think I would most likley have a combinational DAL that will take advantage of FNH for simple CRUD operations while leaving complex procedures to be managed by Enterprise Library. While I don't think it would be optimal to have 2 competing DALs if FNH cannot play well with SPs I'd love to hear any other ideas than using both EntLib and FNH together.</p>
[ { "answer_id": 2178506, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "SqlInsert(\"StoredProcName\");\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37055/" ]
296,738
<p>I'd love to know if there is a module to parse "human formatted" dates in Perl. I mean things like "tomorrow", "Tuesday", "next week", "1 hour ago".</p> <p>My research with CPAN suggest that there is no such module, so how would you go about creating one? NLP is way over the top for this.</p>
[ { "answer_id": 296739, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": true, "text": "#!/usr/bin/perl\n\nuse strict;\nuse Date::Manip;\n\nwhile (<DATA>)\n{\n chomp;\n print UnixDate($_, \"%Y-%m-%d %H:%M:%S\"), \" ($_)\\n\";\n}\n\n__DATA__\ntoday\nyesterday\ntomorrow\nlast Tuesday\nnext Tuesday\n1 hour ago\nnext week\n 2008-11-17 15:21:04 (today)\n2008-11-16 15:21:04 (yesterday)\n2008-11-18 15:21:04 (tomorrow)\n2008-11-11 00:00:00 (last Tuesday)\n2008-11-18 00:00:00 (next Tuesday)\n2008-11-17 14:21:04 (1 hour ago)\n2008-11-24 00:00:00 (next week)\n Date::Manip" }, { "answer_id": 297093, "author": "hakamadare", "author_id": 17597, "author_profile": "https://Stackoverflow.com/users/17597", "pm_score": 3, "selected": false, "text": "DateTime::Format use strict;\nuse warnings;\n\nuse DateTime::Format::Natural;\n\nmy( $parser ) = DateTime::Format::Natural->new;\n\nwhile ( <> ) {\n\n chomp;\n my( $dt ) = $parser->parse_datetime( $_ );\n\n if ( $parser->success ) {\n\n print join( ' ', $dt->ymd, $dt->hms ) . \"\\n\";\n }\n else {\n\n print $parser->error . \"\\n\";\n }\n}\n tomorrow \n2008-11-18 21:48:49 \nnext Tuesday \n2008-11-25 21:48:53 \n1 week from now \n2008-11-24 21:48:57 \n1 hour ago \n2008-11-17 20:48:59 \n" }, { "answer_id": 298006, "author": "cjm", "author_id": 8355, "author_profile": "https://Stackoverflow.com/users/8355", "pm_score": 2, "selected": false, "text": " Dow, dd Mon yy\n Dow, dd Mon yyyy\n Dow, dd Mon\n dd Mon yy\n dd Mon yyyy\n Month day{st,nd,rd,th}, year\n Month day{st,nd,rd,th}\n Mon dd yyyy\n yyyy/mm/dd\n yyyy-mm-dd (usually the best date specification syntax)\n yyyy/mm\n mm/dd/yy\n mm/dd/yyyy\n mm/yy\n yy/mm (only if year > 12, or > 31 if UK)\n yy/mm/dd (only if year > 12 and day < 32, or year > 31 if UK)\n dd/mm/yy (only if UK, or an invalid mm/dd/yy or yy/mm/dd)\n dd/mm/yyyy (only if UK, or an invalid mm/dd/yyyy)\n dd/mm (only if UK, or an invalid mm/dd)\n count \"days\"\n count \"weeks\"\n count \"months\"\n count \"years\"\n Dow \"after next\"\n Dow \"before last\"\n Dow (requires PREFER_PAST or PREFER_FUTURE)\n \"next\" Dow\n \"tomorrow\"\n \"today\"\n \"yesterday\"\n \"last\" dow\n \"last week\"\n \"now\"\n \"now\" \"+\" count units\n \"now\" \"-\" count units\n \"+\" count units \n \"-\" count units\n count units \"ago\"\n hh:mm:ss[.ddd] \n hh:mm \n hh:mm[AP]M\n hh[AP]M\n hhmmss[[AP]M] \n \"noon\"\n \"midnight\"\n count \"minutes\" (count can be franctional \"1.5\" or \"1 1/2\")\n count \"seconds\"\n count \"hours\"\n \"+\" count units\n \"+\" count\n \"-\" count units\n \"-\" count\n count units \"ago\"\n [+-]dddd\n GMT[+-]d+\n [+-]dddd (TZN)\n TZN\n [ d]d/Mon/yyyy:hh:mm:ss [[+-]dddd]\n yy/mm/dd.hh:mm\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296738", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38346/" ]
296,740
<p>I need to populate a context menu from a database at run time. I do not know the number of items that will be in the list, so I would like to handle the click event in a single place. How do I declare the handler so I can tell which menu item actually triggered the click.</p> <pre><code>Public Function GetBookmarkContextMenu(ByVal aBookmark As Bookmark) As System.Windows.Controls.ContextMenu Dim myContextMenu As New Controls.ContextMenu myContextMenu.Name = "BookmarkMenu" For Each aMailingList As MasterService.FalconBookmarkMailingListType In GlobalUserSettings.MailingLists Dim mySubMenuItem As New Controls.MenuItem mySubMenuItem.Name = "MailingListName" &amp; aMailingList.ID.ToString mySubMenuItem.Header = aMailingList.Title AddHandler (myMenuItem.Click), AddressOf ForwardToList_Click mySubMenuItem.IsEnabled = True myMenuItem.Items.Add(mySubMenuItem) Next myContextMenu.Items.Add(myMenuItem) return myContextMenu End Function Public Sub ForwardToList_Click() 'How do I know which of the dynamically created items was clicked? End Sub </code></pre>
[ { "answer_id": 296757, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 1, "selected": true, "text": "Public Sub ForwardToList_Click(sender As Object, e As EventArgs)\n'...\nEnd Sub\n" }, { "answer_id": 4529548, "author": "AundyKarthick", "author_id": 553715, "author_profile": "https://Stackoverflow.com/users/553715", "pm_score": 2, "selected": false, "text": "Dim mnuitm As New ToolStripMenuItem\nmnuitm.Name = name_cbk.Items(i)\nmnuitm.Text = name_cbk.Items(i)\nAddHandler (mnuitm.Click), AddressOf item_Click\nmenulist.Items.Add(mnuitm)\n" }, { "answer_id": 20902171, "author": "user3156869", "author_id": 3156869, "author_profile": "https://Stackoverflow.com/users/3156869", "pm_score": 2, "selected": false, "text": "Private Sub Form1_Load(sender As Object, e As System.EventArgs) Handles Me.Load\n NamesTableAdapter.Fill(DataSet.Names)\n For Each element In DataSet.Names\n Dim mnuitem As New ToolStripMenuItem\n mnuitem.Name = element.Item(1)\n mnuitem.Text = element.Item(1)\n AddHandler (mnuitem.Click), AddressOf ToolMenuItem_Click\n ContextMenuStrip1.Items.Add(mnuitem)\n Next\nEnd Sub\n\nPrivate Sub ToolMenuItem_Click(sender As Object, ByVal e As EventArgs) \n textbox1.Text = sender.name\nEnd Sub\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38349/" ]
296,747
<p>When I generate a default scaffold, the display tags on show.html.erb have</p> <pre><code>&lt;%=h @broker.name %&gt; </code></pre> <p>I know the difference between <code>&lt;%</code> and <code>&lt;%=</code>. What's the "h" do?</p>
[ { "answer_id": 297246, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<%=h <%= h <%=h person.first_name %>\n<%= h(person.first_name) %>\n h" }, { "answer_id": 303108, "author": "Tim Harding", "author_id": 38021, "author_profile": "https://Stackoverflow.com/users/38021", "pm_score": 4, "selected": false, "text": "h html_escape" }, { "answer_id": 926812, "author": "heycarsten", "author_id": 57774, "author_profile": "https://Stackoverflow.com/users/57774", "pm_score": 3, "selected": false, "text": "Rack::Utils.escape_html" }, { "answer_id": 42567856, "author": "bkunzi01", "author_id": 3998420, "author_profile": "https://Stackoverflow.com/users/3998420", "pm_score": 2, "selected": false, "text": "html_escape html_escape h() html_safe #some_view.html.erb\n<span><%= @user.name %></span> #This is 100% fine and will be automatically escaped by Rails 3+\n#Output => <span>Brian Kunzig</span>\n\n#Now say we want a link with html that we need preserved! OMG WHAT ARE DO??\n<%=link_to \"<span><i class='fa fa-user'></i>#{@user.name}</span>\".html_safe #DANGER!!!\n \"<script>alert('omg');</script>\" html_safe <%=link_to \"<span><i class='fa fa-user'></i>#{h(@user.name)}</span>\".html_safe #Winning!\n" }, { "answer_id": 48928797, "author": "Nesha Zoric", "author_id": 1660318, "author_profile": "https://Stackoverflow.com/users/1660318", "pm_score": 2, "selected": false, "text": "<%= h \"<p>Hello World</p>\" %> \n <p>Hello World</p>\n &lt;p&gt;Hello World&lt;/p&gt;.\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296747", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
296,750
<p>I have a class that has some properties. And I want something that calculates a Score out of these properties. Since this is a trivial task (some additions and divisions, but nothing spectacular).</p> <p>So naturally, the question is: "When to use a Property with some code in the getter, and when to use a function?", and <a href="https://stackoverflow.com/questions/67063/">that question was already answered</a>.</p> <p>Now, I wonder about one thing though: If - against all expectations - I ever needed to make this Getter so complicated that it should be a function (for example, because I need to put data in or because it can throw an exception or whatever), is it easy to change a Property into a Method?</p> <p>Of course, it seems really trivial, just changing</p> <pre><code>public double Score { get { return Math.Round(A + B / C * D,3); } } </code></pre> <p>to</p> <pre><code>public double Score(){ return Math.Round(A + B / C * D,3); } </code></pre> <p>But I wonder: Are there any side effects? Is anything going to break when changing stuff around like this? I can only ever see this as a possible problem when Reflection is involved, but what in situations where I have 2 Assemblies - one that defines the class and one that uses the class - and only change the one that contains the class without recompiling the consumer assembly. Is that a possible source of "weird bugs that are nearly impossible to track" or is it completely safe to change Properties to Methods?</p>
[ { "answer_id": 296777, "author": "Micah", "author_id": 17744, "author_profile": "https://Stackoverflow.com/users/17744", "pm_score": 2, "selected": true, "text": "get set get_MyPropertyName() set_MyPropertyName()" }, { "answer_id": 296802, "author": "PhilHoy", "author_id": 29547, "author_profile": "https://Stackoverflow.com/users/29547", "pm_score": 1, "selected": false, "text": "object ting = thing.score ting public void erm(double param){ //stuff here}\npublic void erm(func<double> param) {// different stuff here}\n erm(thing.score)\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91/" ]
296,755
<p>The following code fails to compile stating "A local variable named 'st' cannot be declared in this scope because it would give a different meaning to 'st', which is already used in a 'child' scope to denote something else": </p> <pre><code> var l = new List&lt;string&gt;(); l.Find(st =&gt; st.EndsWith("12")); string st = "why this fails?"; </code></pre> <p>I understand why this won't work:</p> <pre><code> string preParent = ""; { string preParent = "Should fail cause we change the meaning"; } </code></pre> <p>When we do the following we get "CS0103: The name 'postParent' does not exist in the current context":</p> <pre><code> { string postParent=string.Empty; } postParent = "Should this work?"; </code></pre> <p>What I don't get is why is the compiler smart enough to see that postParent is not within scope, but won't let me define a new variable that has the same name as a variable used within a child scope (which is obviously out of scope at this point). </p> <p>Is the compiler simple enforcing scope by refusing to let me use the variable? If so this makes sense.</p> <p>===========</p> <p>Edited: </p> <p>I guess what I also find interesting is how you can have the same variable within two child scopes in a single method, so this is valid:</p> <pre><code> { string thisWorks= string.Empty; } { string thisWorks= "Should this work?"; } </code></pre> <p>I'm just a little curious that you can have two variables with the same name as long as they are at the same level (if you look at scope as a tree). This makes sense because you can have local variables in two methods of the same class with the same name. </p> <p>I'm just surprised that the compiler is able to differentiate and allow this, while it wouldn't allow the postParent variable. And is this a technical limitation or was this a design decision? That's what I'm really trying to get at;-)</p>
[ { "answer_id": 296780, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "postParent postParent postParent" }, { "answer_id": 296790, "author": "Jared", "author_id": 14744, "author_profile": "https://Stackoverflow.com/users/14744", "pm_score": -1, "selected": false, "text": "for (int i=0; i<10; i++)\n{\n cout <<”In the loop i is “<< i << endl;\n}\ncout << “outside of the loop i is “ << i << endl; //this only compiles with old C/C++ compilers.\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26160/" ]
296,781
<p>I'm running an SQL query against a mainframe DB2 database using the OdbcDataReader class and ExecuteReader() method. This code is in production and has been running fine for months.</p> <p>The query normally takes 1-2 minutes to execute. This past Friday, the query encountered a ThreadAbortException. Below is the formatted stack trace. The ApplicationException in the trace is created in my catch block.</p> <p>In case it is important, the query is run when a client calls a web service method. The web service is hosted in a Windows Service. The web service is hosted in a Windows Service using the soap.tcp protocol.</p> <p>Any ideas why the TreadAbortException is happening?</p> <blockquote> <p>Stack trace for 2 exception(s). Root cause at the top.</p> <p>Exception 2: Thread was being aborted.<br> System.Threading.ThreadAbortException inside C:\WINDOWS\assembly\GAC_64\System.Data\2.0.0.0__b77a5c561934e089\System.Data.dll at System.Data.Common.UnsafeNativeMethods.SQLExecDirectW(OdbcStatementHandle StatementHandle, String StatementText, Int32 TextLength) at System.Data.Odbc.OdbcStatementHandle.ExecuteDirect(String commandText) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader, Object[] methodArguments, SQL_API odbcApiMethod) at System.Data.Odbc.OdbcCommand.ExecuteReaderObject(CommandBehavior behavior, String method, Boolean needReader) at System.Data.Odbc.OdbcCommand.ExecuteReader(CommandBehavior behavior) at MyCompany.MyDatabase.GetFolioList(String sqlWhereClause)</p> <p>Exception 1: Unable to retrieve the folio summary list where STAT_CD='V'.<br> System.ApplicationException inside D:\Production\DBGateway\bin\MyDatabase.dll at MyCompany.MyDatabase.GetFolioList(String sqlWhereClause) at MyCompany.MyDatabase.&lt;>c__DisplayClass18.b__17() at MyCompany.WebUtilities.WebServiceBase.WebMethodTemplate[T](String methodName, String exceptionFormat, WebMethodWorker<code>1 Worker, StringFormatter</code>1 FormatterMethod)</p> </blockquote>
[ { "answer_id": 422183, "author": "Dean Hill", "author_id": 3106, "author_profile": "https://Stackoverflow.com/users/3106", "pm_score": 3, "selected": true, "text": "<configuration>\n <microsoft.web.services3>\n <messaging>\n <executionTimeoutInSeconds value=\"360\" />\n </messaging>\n </microsoft.web.services3>\n</configuration>\n <configuration>\n<system.web>\n <httpRuntime executionTimeout=”360” />\n </system.web>\n</configuration\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3106/" ]
296,783
<p>Why does Resharper want you to change most variables to var type instead of the actual type in the code?</p>
[ { "answer_id": 296808, "author": "David Thibault", "author_id": 5903, "author_profile": "https://Stackoverflow.com/users/5903", "pm_score": 3, "selected": false, "text": "Person p = new Person();\n^^^^^^\n Person p = repository.GetPerson(1);\n¯¯¯\n" }, { "answer_id": 13526143, "author": "Ilya Chernomordik", "author_id": 1671558, "author_profile": "https://Stackoverflow.com/users/1671558", "pm_score": 2, "selected": false, "text": "var dictionary = new Dictionary<string, int>()" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11907/" ]
296,789
<p>In SQL Server Mgt Studio 2005, when I open the Object Explorer to script an object to a new Query Editor window, the tab for that new script window is titled something like 'MyServerName.MyDatabaseName - sqlquery37.sql' </p> <p>Not very descriptive. So when I get a bunch of windows open at the same time, I have no idea which one is which. </p> <p>The 'Active Files' dropdown is useless because of this.</p> <p>Is there a way to configure Mgt. Studio so that the Query Editor Window tab title more accurately reflects the object that I'm working on?</p> <p>Thanks!</p>
[ { "answer_id": 296980, "author": "Ken Gentle", "author_id": 8709, "author_profile": "https://Stackoverflow.com/users/8709", "pm_score": 1, "selected": false, "text": "MyServerName.MyDatabaseName - MyFileName.sql\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296789", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6624/" ]
296,792
<p>When I open a file for reading in Haskell, I've found that I can't use the contents of the file after closing it. For example, this program will print the contents of a file:</p> <pre><code>main = do inFile &lt;- openFile "foo" ReadMode contents &lt;- hGetContents inFile putStr contents hClose inFile </code></pre> <p>I expected that interchanging the <code>putStr</code> line with the <code>hClose</code> line would have no effect, but this program prints nothing:</p> <pre><code>main = do inFile &lt;- openFile "foo" ReadMode contents &lt;- hGetContents inFile hClose inFile putStr contents </code></pre> <p>Why does this happen? I'm guessing it has something to do with lazy evaluation, but I thought these expressions would get sequenced so there wouldn't be a problem. How would you implement a function like <code>readFile</code>?</p>
[ { "answer_id": 297404, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 1, "selected": false, "text": "hGetContents readFile main = do contents <- readFile \"foo\"\n putStr contents\n > main\nblahblahblah\n foo blahblahblah\n seq main = do inFile <- openFile \"foo\" ReadMode\n contents <- hGetContents $! inFile\n contents `seq` hClose inFile\n putStr contents\n > main\nb\n" }, { "answer_id": 297630, "author": "luqui", "author_id": 33796, "author_profile": "https://Stackoverflow.com/users/33796", "pm_score": 6, "selected": true, "text": "import Control.Parallel.Strategies (rnf)\n-- rnf means \"reduce to normal form\"\nmain = do inFile <- openFile \"foo\" \n contents <- hGetContents inFile\n rnf contents `seq` hClose inFile -- force the whole file to be read, then close\n putStr contents\n import qualified Data.ByteString as Str\n\nmain = do contents <- Str.readFile \"foo\"\n -- readFile is strict, so the the entire string is read here\n Str.putStr contents\n forceList [] = ()\n forceList (x:xs) = forceList xs\n" }, { "answer_id": 300742, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "go fname = do\n putStrLn \"reading\"\n body <- readFile fname\n let body' = \"foo\" ++ body ++ \"bar\"\n putStrLn body' -- comment this out to get a runtime exception.\n putStrLn \"writing\"\n writeFile fname body'\n return ()\n Test> go \"Foo.hs\"\nreading\nwriting\nException: Foo.hs: openFile: permission denied (Permission denied)\nTest> \n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296792", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1891/" ]
296,795
<p>I've got a Subversion repository, and there are a number of users checking things in and out. However, I also need to frequently check in work for other people. I need to track the original author of the work.</p> <p>I was considering creating a property in SVN, like "originalauthor", which could track this. In cases where it was empty, I could use the author. If it was filled in, I could attribute the changes appropriately.</p> <p><em>However</em>, I can't see a way to add a property that won't persist through multiple revisions. Similarly, there doesn't seem to be a way of using commit hooks to guarantee the "originalauthor" property will be removed if there's a commit which doesn't include it.</p> <p>I could always rewrite the password file on the server to allow me to commit under their username and then restore the original password file, but that seems clunky (and doesn't let me track the fact that it was checked in on their behalf). Or I could create an additional user (so for every "User A" there's a "User A Proxy") which I could use to check in changes. Neither of these options seem appealing.</p> <p>Any suggestions, or ideas?</p>
[ { "answer_id": 296829, "author": "Bert Huijben", "author_id": 2094, "author_profile": "https://Stackoverflow.com/users/2094", "pm_score": 4, "selected": true, "text": "Patch by: Jan Jansen <jan@example.com>\n svn commit --with-revprop \"original-author=Jan Jansen <jan@example.com>\" \n svn log <...> --with-revprop original-author\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296795", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9161/" ]
296,797
<p>Since you guys are having lots of questions or not enough info to work with, below is proprietary information and as such be careful as you can. The question – (please refer to if [$7 -eq "AAA"]...then statement - in bold ) has a problem with an output, where I can only output/print count of 'AAA' regardless the variable coming in either 'BBB' or ‘AAA’. As a result, and as an error, the program outputs/prints count of ‘AAA’. </p> <p>Again, in this situation I tried with my best knowledge to explain to those available and savvy. Thanks.</p> <pre><code>----------------------------------------------------------------------- # Print the run date echo "**********************" echo " TALK Program " echo " Run Date " date echo "**********************" # DIRECTORIES/VARIABLES/PARAMETERS p1=$1 p2=$2 p3=$3 p4=$4 p5=$5 p6=$6 p7=$7 p8=$8 echo "***********************************************" echo "The parameteres are" echo " " echo " Param 1 (Username/Password) = " echo " Param 2 (User account number) = "$2 echo " Param 3 (Requestor name) = "$3 echo " Param 4 (Requestor ID) = "$4 echo " Param 7 (AAA or BBB) = "$7 echo " Param 8 (TALK Data Filename) = "$8 echo "***********************************************" AREA1=$WILLS_TOP/bin # Switch-variable points to GENEX bin dir AREA2=$WILLS_TOP/sql # Switch-variable points to GENEX sql dir SQL_CTL=$AREA1/WILLSTALK.ctl # Name of SQL*Load ctrl file SQL_VALID=$AREA2/WILLSTALK.sql # Name of validation PL/SQL script FTP_BIN=/usr/local/bin # Where ftp program is UNIX_GET=$FTP_BIN/ftpmget.sh # Name of UNIX file get program UNIX_PUT=$FTP_BIN/ftpmput.sh # Name of UNIX file put program UNIX_DEL=$FTP_BIN/ftpdel.sh # Name of UNIX file delete program TEMP=/tmp # Name of temp dir INPUT_DIR=/oracle/inbound # For DVLP Where input file is comming from ARCHIVE_NT_DIR=/oracle/inbound/RFS_DVLP # For DVLP Modified on 2005 OUTPUT_DIR=/oracle/outbound/ # Where output file is going to OUTPUT_UNIX_DIR=$OUTCSF/$$OUTLOG/ # Directory of where output is DES_NAME=${OUTPUT_UNIX_DIR}${OUT_FILE} # Where output is going to be USERACCNUM=$p2 # User Account Number USERNAME=$p5 # Username PASSWORD=$p6 # Password AAA_OR_BBB=$p7 # Either 'AAA' or default of 'BBB' DATAFILE_NAME=$p8 # Datafile name (NT) SERVER='172.........' # Server (NT) LOG_DIR=$WILLS_TIP/log # Path of log dir LOCAL_DIR=$WILLS_TIP/data # Directory where file is at (UNIX) ARCHIVE_DIR=$WILLS_TIP/archive # Directory for archive (UNIX) FILE_NAME="" # File name (UNIX) FILE_TRAN_TYPE='ascii' # File transfer type #***************************************************************************** # MAIN PROCEDURE #***************************************************************************** if [ ! "$p7" ] then echo "At least one MS Excel Update Data File must be entered !" echo "No files were entered." exit 1 fi #---------------------------------------------------------------------- # Remove all MS Excel datafile in $GENEX_TOP/data directory if exist #---------------------------------------------------------------------- rm -f $WILLS_TIP/data/TALK* #-------- # FTP #-------- ${UNIX_GET} $p5 $p6 $SERVER $INPUT_DIR $DATAFILE_NAME $LOCAL_DIR "" $TEMP $FILE_TRAN_TYPE if [ $? != 0 ] then echo "The MS Excel Datafile(s) ftp has failed." exit 1 fi if [ ! -s $LOCAL_DIR/$p8 ] then echo "FTP command executed, but MS Excel file(s) did not get copied." exit 2 fi #----------------------------------------- # SQL*Loads - New MS Excel file to load #----------------------------------------- for i in $LOCAL_DIR/$DATAFILE_NAME do SQLOAD_DAT_FILE=`echo $i | sed "s/\// /g" | awk ' { print $NF } '` SQLOAD_LOG_FILE=$SQLOAD_DAT_FILE.log # Sqlload log file name SQLOAD_BAD_FILE=$SQLOAD_DAT_FILE.bad # Sqlload bad file name if [ -s $LOG_DIR/$SQLOAD_BAD_FILE ] then rm -f $LOG_DIR/$SQLOAD_BAD_FILE # Remove prev. bad file, if such exists echo "Previous bad file has been successfully removed." else echo "No bad file was identified and removed." echo "Resume Normal Processing." fi echo $i echo "Now loading datafile: $LOCAL_DIR/$SQLOAD_DAT_FILE" #--------------------------------------------------------------- sed "s/@USERACCNUM/$USERACCNUM/" $SQL_CTL &gt; $TEMP/WILLSTAL.ctl # Changing '@USERACCNUM' #--------------------------------------------------------------- sqlldr userid=${p1} control=$TEMP/WILLSTALK.ctl \ log=$LOG_DIR/$SQLOAD_LOG_FILE \ bad=$LOG_DIR/$SQLOAD_BAD_FILE \ data=$LOCAL_DIR/$SQLOAD_DAT_FILE if test ! -s $LOG_DIR/$SQLOAD_BAD_FILE then tail -20 $LOG_DIR/$SQLOAD_LOG_FILE echo "*** Done SQL*Loader Script ***" else echo "The SQL*Load for MS Excel Update file has FAILED due to BAD DATA." echo "*** Exitting Script On Failure ***" echo "*** Process is ready for NEXT LOAD! ***" exit 1 fi done #---------------------------------------- # To run a PL/SQL script #---------------------------------------- sqlplus -s $p1 @$SQL_VALID $AAA_OR_BBB if [ $? -ne 0 ] then echo "The PL/SQL script for validation has FAILED." exit 1 fi #---------------------------------------------------------- # Now run SQL*Plus script Flat File Report After Updating #---------------------------------------------------------- sqlplus -s $1 &lt;&lt;EOF set echo off set heading off set space 0 set newpage 0 set pagesize 0 set feed off set term on SPOOL $OUTCSF/$OUTLOG/l$4.log SELECT 'spool $OUTCSF/$APPLOUT/o$4.out' FROM dual; SPOOL OFF @$OUTCSF/$OUTLOG/l$4.log Select 'Run Date: '||to_char(sysdate, 'DD-MON-YYYY') From dual; Select '*************************************************************' From dual; SELECT 'ERRORS Found: '||count(*) FROM gnx_rel_date_temp WHERE error_text IS NOT NULL; Select '--------------- ----------- ---------------------------------' From dual; Select 'TRX NUMBER NEW DATE ERROR TEXT' From dual; Select '--------------- ----------- ---------------------------------' From dual; SELECT trx_num||'|'||new_date||'|'||error_text FROM will_rel_date_temp WHERE error_text IS NOT NULL; Select '*************************************************************' From dual; #------------- #---- AAA ---- #------------- if [ $7 -eq "AAA" ] then SELECT 'Total AAA Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND attr2 IS NOT NULL AND attr2 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); else exit 0 fi #--------------- #---- BBB ---- #--------------- if [ $7 -eq "BBB" ] then SELECT 'Total BBB Updated: '||count(*)||' records' FROM reldatetemp ,allcustomers WHERE trx_num = trx_no AND error_text IS NULL AND attr1 IS NOT NULL AND attr1 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); else exit 0 fi SPOOL OFF EOF #---------------------------------------------- # To delete the data files on NT #---------------------------------------------- ${UNIX_DEL} $p5 $p6 $SERVER $INPUT_DIR $DATAFILE_NAME $TEMP mv $WILLS_TIP/data/$DATAFILE_NAME $WILLS_TIP/archive/. # All Done! echo "*** End of program *** " </code></pre>
[ { "answer_id": 296905, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 2, "selected": false, "text": "if [ \"$7\" -eq \"AAA\" ] ; then\n attr=\"attr2\"\nelsif [ \"$7\" -eq \"BBB\" ] ; then\n attr=\"attr1\"\nelse\n echo \"Bogus $7 - need AAA or BBB\"\nfi\n\n....\n\nsqlplus -s $1 <<EOF\n...\nSELECT 'Total $7 Updated: '||count(*)||' records' \n FROM reldatetemp \n ,allcustomers \nWHERE trx_num = trx_no \n AND error_text IS NULL \n AND ${attr} IS NOT NULL \n AND ${attr} = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS');\n...\nEOF\n" }, { "answer_id": 296908, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 0, "selected": false, "text": "#-------------\n#---- AAA ----\n#-------------\nif [ $7 -eq \"AAA\" ] then\n SELECT 'Total AAA Updated: '||count(*)||' records' \n FROM reldatetemp \n ,allcustomers \n WHERE trx_num = trx_no \n AND error_text IS NULL \n AND attr2 IS NOT NULL \n AND attr2 = TO_CHAR(new_date,'YYYY/MM/DD HH24:MI:SS'); \nelse\n exit 0\nfi\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296797", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,799
<p>How can I get the name of a file in in PHP? What I want to do is have a function take a string of a filename and then do some stuff if it's actually on the page.</p> <pre><code>function onThisPageFunction(fileNameFromFunction) { if(onThisPage == fileNameFromFunction) { do stuff } } </code></pre>
[ { "answer_id": 296813, "author": "activout.se", "author_id": 20444, "author_profile": "https://Stackoverflow.com/users/20444", "pm_score": 2, "selected": false, "text": "__FILE__" }, { "answer_id": 296862, "author": "Eric Goodwin", "author_id": 1430, "author_profile": "https://Stackoverflow.com/users/1430", "pm_score": 4, "selected": true, "text": "__FILE__ $_SERVER['PHP_SELF']" }, { "answer_id": 296869, "author": "William Macdonald", "author_id": 2725, "author_profile": "https://Stackoverflow.com/users/2725", "pm_score": 0, "selected": false, "text": "_SERVER[\"PHP_SELF\"]\n if (isset($_SERVER[\"PHP_SELF\"]) AND ($_SERVER[\"PHP_SELF\"] == 'foo')){\necho 'do stuff';\n}\n" }, { "answer_id": 296901, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "if (realpath($_SERVER['SCRIPT_NAME']) === __FILE__) {\n echo \"Called directly\";\n}\n" }, { "answer_id": 299946, "author": "Paul Sheldrake", "author_id": 28672, "author_profile": "https://Stackoverflow.com/users/28672", "pm_score": 0, "selected": false, "text": "function menuStrikethrough($pageName)\n {\n // get the name of the page we're on\n $fileName = basename($_SERVER['PHP_SELF']);\n\n // if fileName equals pageName then output css to show a strikethrough\n if($fileName == $pageName)\n {\n echo ' style=\"text-decoration:line-through\" ';\n }\n }\n ____FILE____" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28672/" ]
296,830
<p>I have a 5GB database and a 20GB transaction log (SQL Server 2005). Not sure why it is so large or what happened to make it that large, it used to be around 1/2 the size of the DB. DB grows about 1GB/month. </p> <p>Are there any guidelines to how how big your transaction log should be relative to your database file size? </p> <p>EDIT: I'm not saying my transaction log is huge (I know some DBAs would laugh at my weenie-sized DB), just in relation to the DB file I think it is huge.</p>
[ { "answer_id": 296860, "author": "Otus", "author_id": 36613, "author_profile": "https://Stackoverflow.com/users/36613", "pm_score": 1, "selected": false, "text": "Backup Log DatabaseName With Truncate_Only\nGO\n\nDeclare @LogFileLogicalName sysname\nselect @LogFileLogicalName=RTRIM(Name) from sysfiles where filename like '%.ldf%'\n--SELECT @LogFileLogicalName\nDBCC Shrinkfile(@LogFileLogicalName,2)\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296830", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34133/" ]
296,834
<p>Suppose I have three classes. It is valid to instantiate A, but there are also special cases B and D which subclass A, adding additional information.</p> <p>How would I do the mapping files for this in (fluent) NHibernate?</p> <pre><code>public class A { public int ID { get; set;} public string CommonProperty1 { get; set; } public string CommonProperty2 { get; set; } } public class B : A { public string BSpecificProperty1 { get; set; } //not null public string BSpecificProperty2 { get; set; } //not null } public class D : A { public string DSpecificProperty { get; set; } //not null } </code></pre> <p>I tried the following, but it doesn't work at all:</p> <pre><code>public class AMap : ClassMap&lt;A&gt; { public AMap() { Id(x =&gt; x.ID); Map(x =&gt; x.CommonProperty1); Map(x =&gt; x.CommonProperty2); } } public class BMap : ClassMap&lt;B&gt; { public BMap() { References(x =&gt; x.ID); Map(x =&gt; x.BSpecificProperty1) .CanNotBeNull(); Map(x =&gt; x.BSpecificProperty2) .CanNotBeNull(); } } public class DMap : ClassMap&lt;D&gt; { public DMap() { References(x =&gt; x.ID); Map(x =&gt; x.DSpecificProperty) .CanNotBeNull(); } } </code></pre>
[ { "answer_id": 298329, "author": "Erik Öjebo", "author_id": 276, "author_profile": "https://Stackoverflow.com/users/276", "pm_score": 4, "selected": true, "text": "// Domain classes\npublic class Animal\n{\n public virtual int Id { get; set; }\n public virtual string Name { get; set; }\n}\n\npublic class Cat : Animal\n{\n public virtual int WhiskerLength { get; set; }\n public virtual int ClawCount { get; set; }\n}\n\npublic class Dog : Animal\n{\n public virtual int TailWagRate { get; set; }\n}\n\n\n\n// Mapping file\npublic class AnimalMap : ClassMap<Animal>\n{\n public AnimalMap()\n {\n Id(x => x.Id)\n .WithUnsavedValue(0)\n .GeneratedBy.Native();\n\n Map(x => x.Name);\n\n var catMap = JoinedSubClass<Cat>(\"CatId\", sm => sm.Map(x => x.Id));\n\n catMap.Map(x => x.WhiskerLength)\n .CanNotBeNull();\n catMap.Map(x => x.ClawCount)\n .CanNotBeNull();\n\n JoinedSubClass<Dog>(\"DogId\", sm => sm.Map(x => x.Id))\n .Map(x => x.TailWagRate)\n .CanNotBeNull();\n }\n}\n" }, { "answer_id": 1171461, "author": "Berryl", "author_id": 95245, "author_profile": "https://Stackoverflow.com/users/95245", "pm_score": 3, "selected": false, "text": "// Domain classes\npublic class Animal : Entity\n{\n public virtual string Name { get; set; }\n public virtual string Unwanted { get; set; }\n}\n\npublic class Cat : Animal\n{\n public virtual int WhiskerLength { get; set; }\n public virtual int ClawCount { get; set; }\n}\n\npublic class Dog : Animal\n{\n public virtual int TailWagRate { get; set; }\n}\n\npublic class Boxer : Dog\n{\n public string DroolBucket { get; set; }\n}\n\npublic class AnimalMapJoinedSubclassOverride : IAutoMappingOverride<Animal>\n{\n public void Override(AutoMap<Animal> mapping) {\n mapping.Map(x => x.Name);\n\n mapping.IgnoreProperty(x => x.Unwanted);\n\n mapping.JoinedSubClass(\"CatId\", CatMap.AsJoinedSubClass());\n mapping.JoinedSubClass(\"DogId\", DogMap.AsJoinedSubClass());\n //mapping.DiscriminateSubClassesOnColumn(\"Type\")\n // .SubClass<Cat>(\"CatId\", CatMap.AsSubClass())\n // .SubClass<Dog>(\"CatId\", DogMap.AsSubClass());\n }\n}\n\npublic class CatMap\n{\n public static Action<JoinedSubClassPart<Cat>> AsJoinedSubClass()\n {\n return part =>\n {\n part.Map(x => x.ClawCount).Not.Nullable();\n part.Map(x => x.WhiskerLength).Not.Nullable();\n };\n }\n\n public static Action<SubClassPart<Cat>> AsSubClass()\n {\n return part =>\n {\n part.Map(x => x.ClawCount);\n part.Map(x => x.WhiskerLength);\n };\n }\n}\n\npublic class DogMap\n{\n public static Action<JoinedSubClassPart<Dog>> AsJoinedSubClass()\n {\n return sub =>\n {\n sub.Map(x => x.TailWagRate).Not.Nullable();\n };\n }\n\n public static Action<SubClassPart<Dog>> AsSubClass()\n {\n return sub =>\n {\n sub.Map(x => x.TailWagRate);\n };\n }\n}\n\npublic class BoxerMap\n{\n public static Action<JoinedSubClassPart<Boxer>> AsJoinedSubClass()\n {\n return sub =>\n {\n sub.Map(x => x.DroolBucket);\n };\n }\n\n public static Action<SubClassPart<Boxer>> AsSubClass()\n {\n return sub =>\n {\n sub.Map(x => x.DroolBucket);\n };\n }\n}\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24954/" ]
296,842
<p>Given an amount of days, say 25, convert it into a duration text such as "3 Weeks, 4 Days"</p> <p>C# and F# solutions would both be great if the F# variation offers any improvement over C#.</p> <p>Edit: The solution should expand past weeks to include months and years. Bonus points for including centuries and so on. Extra bonus if it is somewhat configurable, meaning you can tell the method to exclude the normalization of weeks. </p>
[ { "answer_id": 296852, "author": "Gavin Miller", "author_id": 33226, "author_profile": "https://Stackoverflow.com/users/33226", "pm_score": 3, "selected": false, "text": "String.Format(\"{0} Weeks, {1} days\", days / 7, days % 7);\n" }, { "answer_id": 297067, "author": "Bob", "author_id": 45, "author_profile": "https://Stackoverflow.com/users/45", "pm_score": 0, "selected": false, "text": " public class UnitOfMeasure {\n public UnitOfMeasure(string name, int value) {\n Name = name;\n Value = value;\n }\n\n public string Name { get; set; }\n public int Value { get; set; }\n\n public static UnitOfMeasure[] All = new UnitOfMeasure[] {\n new UnitOfMeasure(\"Year\", 356),\n new UnitOfMeasure(\"Month\", 30),\n new UnitOfMeasure(\"Week\", 7),\n new UnitOfMeasure(\"Day\", 1)\n };\n\n public static string ConvertToDuration(int days) {\n List<string> results = new List<string>();\n\n for (int i = 0; i < All.Length; i++) {\n int count = days / All[i].Value;\n\n if (count >= 1) {\n results.Add((count + \" \" + All[i].Name) + (count == 1 ? string.Empty : \"s\"));\n days -= count * All[i].Value;\n }\n }\n\n return string.Join(\", \", results.ToArray());\n }\n }\n" }, { "answer_id": 297801, "author": "Brian", "author_id": 19299, "author_profile": "https://Stackoverflow.com/users/19299", "pm_score": 0, "selected": false, "text": "#light\nlet conversions = [|\n 365, \"Year\", \"Years\"\n 30, \"Month\", \"Months\"\n 7, \"Week\", \"Weeks\"\n 1, \"Day\", \"Days\" |]\nlet ToDuration numDays =\n conversions\n |> Array.fold_left (fun (remainDays,results) (n,sing,plur) ->\n let count = remainDays / n\n if count >= 1 then \n remainDays - (count * n),\n (sprintf \"%d %s\" count (if count=1 then sing else plur)) :: results\n else\n remainDays, results\n ) (numDays,[])\n |> snd |> (fun rs -> System.String.Join(\", \", List.rev rs |> List.to_array))\nprintfn \"%s\" (ToDuration 1008) \n" }, { "answer_id": 299406, "author": "simonuk", "author_id": 28136, "author_profile": "https://Stackoverflow.com/users/28136", "pm_score": 3, "selected": true, "text": "let divmod n m = n / m, n % m \n\nlet units = [\n (\"Centuries\", TimeSpan.TicksPerDay * 365L * 100L );\n (\"Years\", TimeSpan.TicksPerDay * 365L);\n (\"Weeks\", TimeSpan.TicksPerDay * 7L);\n (\"Days\", TimeSpan.TicksPerDay)\n]\n\nlet duration days =\n let rec duration' ticks units acc =\n match units with\n | [] -> acc\n | (u::us) ->\n let (wholeUnits, ticksRemaining) = divmod ticks (snd u)\n duration' ticksRemaining us (((fst u), wholeUnits) :: acc)\n duration' (TimeSpan.FromDays(float days).Ticks) units []\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/45/" ]
296,849
<p>What is the way of separating Line-Breaks and Space in MultiLine Textbox or HTML Text area while inserting database (Asp.Net). For example what should I do if I want to insert </p> <p>Hello </p> <p>World </p> <p>to database with line breaks? And also While displaying what should I do? I don't want to use Editor for it.</p> <hr> <p>But the problem is how to seperate line break and space. Now when I insert </p> <p>Hello</p> <p>World</p> <p>or hello world, it is saved with same character in the database. Therefore I can't separate them and I am showing hello world although user uses line breaks such as above. The value, which comes from TextBox or html area, are the same as with line break or space.</p>
[ { "answer_id": 296895, "author": "deadbug", "author_id": 4646, "author_profile": "https://Stackoverflow.com/users/4646", "pm_score": 5, "selected": true, "text": " < b r / > " }, { "answer_id": 297462, "author": "Grayside", "author_id": 38408, "author_profile": "https://Stackoverflow.com/users/38408", "pm_score": 0, "selected": false, "text": "&nbsp;" }, { "answer_id": 1573971, "author": "Old Web Guy", "author_id": 190783, "author_profile": "https://Stackoverflow.com/users/190783", "pm_score": 0, "selected": false, "text": "<& # 1 0 ;>" }, { "answer_id": 1574063, "author": "David R Tribble", "author_id": 170383, "author_profile": "https://Stackoverflow.com/users/170383", "pm_score": 2, "selected": false, "text": "<br/> <pre> <div>" }, { "answer_id": 3918426, "author": "Jazz", "author_id": 257024, "author_profile": "https://Stackoverflow.com/users/257024", "pm_score": 3, "selected": false, "text": "< br /> \\r\\n" }, { "answer_id": 10033256, "author": "Handprint", "author_id": 892340, "author_profile": "https://Stackoverflow.com/users/892340", "pm_score": 2, "selected": false, "text": "@Html.Raw(text_to_display.Replace(Environment.NewLine, \"<br/>\"))\n" }, { "answer_id": 53798712, "author": "Mick", "author_id": 10796267, "author_profile": "https://Stackoverflow.com/users/10796267", "pm_score": 1, "selected": false, "text": "textarea.Value = Server.HtmlDecode(myValue.Replace(\"\\r\\n\", \"&#13;\"));\n some blah blah\\r\\nblah blah\n some blah blah\nblah blah\n textarea.value.indexOf(\"\\n\");\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296849", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,861
<p>In ActionScript, how can you test if an object is defined, that is, not null?</p>
[ { "answer_id": 296870, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 2, "selected": false, "text": "var someObj:Object = getSomeObjectOrMaybeNull();\nif(someObj == null) {\n trace(\"someObj is null!\");\n} else {\n trace(\"someObj is not null!\");\n}\n" }, { "answer_id": 296921, "author": "Matthew Crumley", "author_id": 2214, "author_profile": "https://Stackoverflow.com/users/2214", "pm_score": 6, "selected": true, "text": "if (obj != null) {\n doSomethingWith(obj);\n}\n if (arr[0] != null && arr[0]>5) {\n doSomethingWith(arr[0]);\n}\n if (obj == null) {\n doSomethingWith(obj);\n}\n if (obj == undefined) {\n doSomethingWith(obj);\n}\n if (obj === undefined) {\n // obj was never assigned a value\n}\nelse if (obj === null) {\n // obj was explicitly set to null\n}\nelse {\n doSomethingWith(obj);\n}\n" }, { "answer_id": 410775, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "foundit=false;\nfor (var i in this) {\n if (this[i]._name == \"MyMovie\") {\n foundit=true;\n }\n}\n" }, { "answer_id": 574797, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 3, "selected": false, "text": "var a;\nvar b;\nvar c;\nvar d;\na = undefined;\nb = null;\nc = 5;\nif (a) \n trace(a);\nif (b) \n trace(b);\nif (c) // Will trace\n trace(c); \nif (d) \n trace(d);\n c if (obj)" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3858/" ]
296,873
<p>Lets say I am currently at: <code>http://example.com/folder/page.html</code></p> <p>Is it possible to create a relative link on this page that points to <code>http://example.com/folder/</code> without specifying <code>folder</code> anywhere? (And using only HTML.)</p> <p><strong>UPDATE:</strong> <strong>As it turned out <code>./</code> works only in non-strict doctype mode, while <code>.</code> works in both modes, so it is still a better answer in my opinion :) Thanks everybody.</strong></p>
[ { "answer_id": 296881, "author": "Bullines", "author_id": 27870, "author_profile": "https://Stackoverflow.com/users/27870", "pm_score": 4, "selected": false, "text": "<html>\n <head>\n <title>Page</title>\n </head>\n <body>\n <a href=\"./\">Folder directory</a> \n </body>\n</html>\n" }, { "answer_id": 296883, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 4, "selected": false, "text": " ../\n page2.html.\n ../page2.html\n" }, { "answer_id": 296885, "author": "Steve T", "author_id": 415, "author_profile": "https://Stackoverflow.com/users/415", "pm_score": 2, "selected": false, "text": "<a href=\"./\">Folder</a>\n" }, { "answer_id": 296888, "author": "MrChrister", "author_id": 24229, "author_profile": "https://Stackoverflow.com/users/24229", "pm_score": 8, "selected": true, "text": "<a href=\".\">Link to this folder</a>\n" }, { "answer_id": 24340516, "author": "Mark Giblin", "author_id": 2512745, "author_profile": "https://Stackoverflow.com/users/2512745", "pm_score": 6, "selected": false, "text": ". ./ . .filename.ext ./filename.ext ../ /cheese/crackers/yummy.html ../butter/spread.html yummy.html /cheese/butter/spread.html /" }, { "answer_id": 34675131, "author": "Jay", "author_id": 1366130, "author_profile": "https://Stackoverflow.com/users/1366130", "pm_score": 2, "selected": false, "text": " <a href=\"./page.html\">\n http://example.com/folder/index.html" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296873", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20128/" ]
296,879
<p>I am powering a web search using Sphinx, and am getting the following error message while building the indexes:</p> <blockquote> <p>WARNING: sort_hits: merge_block_size=76 kb too low, increasing mem_limit may improve performance</p> </blockquote> <p>The problem is I can't find any documentation on where this setting is configured. I'm somewhat versed on Sphinx setup, so I just need to know where the setting is configured.</p>
[ { "answer_id": 403722, "author": "Glen Solsberry", "author_id": 16645, "author_profile": "https://Stackoverflow.com/users/16645", "pm_score": 3, "selected": false, "text": "mem_limit merge_block_size mem_limit" }, { "answer_id": 5515318, "author": "juidanho", "author_id": 687822, "author_profile": "https://Stackoverflow.com/users/687822", "pm_score": 2, "selected": false, "text": "sql_query_range = SELECT MIN(id),MAX(id) FROM documents\nsql_range_step = 1000\nsql_query = SELECT * FROM documents WHERE id>=$start AND id<=$end\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296879", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38358/" ]
296,904
<p>My data is such that I want to display values for the Employee and the Supervisor for a particular record. Instead of describing it, I'll show you a rough example:</p> <pre><code>&lt;table&gt;&lt;tr&gt; &lt;th colspan="3"&gt;Employee&lt;/th&gt; &lt;th colspan="3"&gt;Supervisor&lt;/th&gt; &lt;/tr&gt;&lt;tr&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Last Activity&lt;/th&gt; &lt;th&gt;Count&lt;/th&gt; &lt;th&gt;Name&lt;/th&gt; &lt;th&gt;Last Activity&lt;/th&gt; &lt;th&gt;Count&lt;/th&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p>How can I create this for a GridView? I essentially want 2 rows for the headings, and some of the cells should span more than one column.</p>
[ { "answer_id": 403722, "author": "Glen Solsberry", "author_id": 16645, "author_profile": "https://Stackoverflow.com/users/16645", "pm_score": 3, "selected": false, "text": "mem_limit merge_block_size mem_limit" }, { "answer_id": 5515318, "author": "juidanho", "author_id": 687822, "author_profile": "https://Stackoverflow.com/users/687822", "pm_score": 2, "selected": false, "text": "sql_query_range = SELECT MIN(id),MAX(id) FROM documents\nsql_range_step = 1000\nsql_query = SELECT * FROM documents WHERE id>=$start AND id<=$end\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/337/" ]
296,906
<p>Is there a way to use Profiler to determine whether a table is being accessed by queries?</p> <p>I saw an event named <code>Object:Opened</code> (Indicates when an object has been accessed, such as for SELECT, INSERT, or DELETE statements) and <code>Object:Closed</code>, but these do not seem to work.</p> <p>In particular, I created a simple trace with both Object:Opened and Object:Closed with no filters (except the standard "Application Name not like 'SQL Profiler'" filter) and ran <code>SELECT TOP 1 * FROM TableName</code>, but no events were reported.</p> <p>So, is there a way to use Profiler to determine if a table is being SELECTed from?</p>
[ { "answer_id": 297316, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 0, "selected": false, "text": "SQL:StmtStarting SP:StmtStarting TextData %TABLE_NAME% SP:StmtStarting LIKE" }, { "answer_id": 312564, "author": "Nick Kavadias", "author_id": 40067, "author_profile": "https://Stackoverflow.com/users/40067", "pm_score": 3, "selected": true, "text": "OBJECT_NAME(objectid)" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3750/" ]
296,909
<p>I wouldn't dare do anything complex in a database without transactions. There is nearly always a simple to use in-built command. But when you start working with other persistent data you just don't get this simple to use transaction support. Some example are</p> <ul> <li>file systems</li> <li>web services (none that I've used)</li> </ul> <p>Even in non-persistent data it is often useful to undo a block of work, following an exception. None of the standard data structures you get with a language, support transactions.</p> <p>What I would like to know is, why are databases the special case?</p> <p>Are there any useful links to the topic of transactional behavior out-side of databases?</p>
[ { "answer_id": 297087, "author": "ddaa", "author_id": 11549, "author_profile": "https://Stackoverflow.com/users/11549", "pm_score": 3, "selected": false, "text": "/a/ /b/ mv /a /b/a mv /b /a/b" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296909", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
296,910
<p>I want to have an executable file that will call some other programs. The way I would do this in Linux is with a simple bash script that looks like this:</p> <pre><code>#!/bin/bash echo "running some-program" /home/murat/some-program arg1 arg2 </code></pre> <p>What's the best way to do this kind of thing under Windows?</p>
[ { "answer_id": 16494912, "author": "Ben P. Dorsi-Todaro", "author_id": 1940946, "author_profile": "https://Stackoverflow.com/users/1940946", "pm_score": 0, "selected": false, "text": "echo off\necho Backing up Images\n%homedrive%\\Backup\\7z.exe a -tzip photos.zip %userprofile%\\Photos\\*.jpg %userprofile%\\Photos\\*.png %userprofile%\\Photos\\*.gif %userprofile%\\Photos\\*.bmp\necho Backing up Music\n%userprofile%\\Backup\\7z.exe a -tzip music.zip %userprofile%\\Music\\*.mp3 %userprofile%\\Music\\*.wma %userprofile%\\Music\\*.ogg %userprofile%\\Music\\*.wav\necho All Done\n" }, { "answer_id": 41303583, "author": "Salathiel Genèse", "author_id": 3748178, "author_profile": "https://Stackoverflow.com/users/3748178", "pm_score": 1, "selected": false, "text": "sh -C ${custom command} cmd /C ${custom command}" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296910", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25910/" ]
296,913
<p>I am looking to write a function like </p> <pre><code>ref String TestIt( int index ) { return this.TestArray[index]; }; </code></pre> <p>so that I could write code like:</p> <pre><code>MyClass.TestIt(0) = "Hello World"; </code></pre> <p>My goal is to mimic this c++ declaration</p> <pre><code>CString&amp; MyClass::Data( UINT index); </code></pre> <p>By Reference I am referring to the c++ term the Address of the variable.<br> in other words after my call to TestIT(0) TestArray[0] would contain "Hello World".</p> <p><strong>EDIT</strong> I can't use an indexer because my goal is to convert a .cpp file to c# on an ongoing basis. The closer I can mimic this c++ code, the less of a converter I have to write.</p>
[ { "answer_id": 296946, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": true, "text": "class YourClass {\n public class Nested {\n public Nested(YourClass outer) { m_RefToOuterWorld = outer; }\n private readonly YourClass m_RefToOuterWorld;\n\n public string this[int index] {\n get { return m_RefToOuter.TestArray[index];\n set { m_RefToOuter.TestArray[index] = value; }\n }\n }\n\n private readonly Nested m_Nested;\n private string[] TestArray = new string[10];\n\n public YourClass() { m_Nested = new Nested(this); }\n\n public Nested TestIt { get { return m_Nested; } }\n}\n var test = new YourClass();\ntest.TestIt[2] = \"Hello world!\";\n" }, { "answer_id": 296982, "author": "Bjarke Ebert", "author_id": 31890, "author_profile": "https://Stackoverflow.com/users/31890", "pm_score": 2, "selected": false, "text": "myobj.SetString(0, \"Hello, world!\");\n Interface IStringReference\n{\n void SetString(string value);\n string GetString();\n}\n\n\nclass MyClass\n{\n public IStringReference TestIt()\n {\n ... details left out ;) ...\n }\n}\n" }, { "answer_id": 297042, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 0, "selected": false, "text": "private string []storage = new string[10];\npublic string this[int index]\n{\n get\n {\n return storage[index];\n }\n set\n {\n storage[index] = value;\n }\n}\n MyClass[0] = \"Hello World\";\n" }, { "answer_id": 297080, "author": "MichaelT", "author_id": 288629, "author_profile": "https://Stackoverflow.com/users/288629", "pm_score": 1, "selected": false, "text": " public class Test\n {\n Dictionary<int,string> str=new Dictionary<int,string>(); \n public string this[int i]\n {\n get\n {\n return str[i];\n }\n set\n {\n if(!str.ContainsKey(i))\n str.Add(i,value);\n else\n str[i] = value;\n }\n }\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5618/" ]
296,918
<p>This problem occurred during daylight saving time change. After the change occurred, we've noticed that our server application started writing into the log incorrect time - one hour ahead which means that .NET caches time zone offset. We had to restart our application to resolve this problem. I wrote a simple application to reproduce this problem. When I change the time zone while application is running, DateTime.Now property keeps producing the time in the old time zone. Does anybody know if there is a workaround for this problem apart from restarting the application?</p>
[ { "answer_id": 1047837, "author": "Paul Farry", "author_id": 97516, "author_profile": "https://Stackoverflow.com/users/97516", "pm_score": 0, "selected": false, "text": " Private mTZChangeFilter As WindowsMessageFilter\n\n\n mTZChangeFilter = New WindowsMessageFilter()\n AddHandler mTZChangeFilter.TimeChanged, AddressOf onTimeChanged\n\n Application.RemoveMessageFilter(mTZChangeFilter)\n\n\nPublic Class WindowsMessageFilter\n Implements IMessageFilter\n\n <System.Diagnostics.DebuggerStepThrough()> _\n Public Function PreFilterMessage(ByRef m As System.Windows.Forms.Message) As Boolean Implements System.Windows.Forms.IMessageFilter.PreFilterMessage\n ' Debug.Print(m.Msg.ToString)\n If m.Msg = 30 Then\n ResetTimeZone()\n RaiseEvent TimeChanged(Me)\n End If\n End Function\n\n Private Sub ResetTimeZone()\n Dim tz As Type = GetType(System.TimeZone)\n Dim mth As System.Reflection.MethodInfo\n\n Try\n mth = tz.GetMethod(\"ResetTimeZone\", BindingFlags.NonPublic Or BindingFlags.Static)\n mth.Invoke(mth, Nothing)\n Catch ex As Exception\n Debug.Print(ex.ToString)\n End Try\n End Sub \n\nend class\n" }, { "answer_id": 5758680, "author": "MacGyver", "author_id": 640205, "author_profile": "https://Stackoverflow.com/users/640205", "pm_score": 1, "selected": false, "text": "System.Globalization.CultureInfo.CurrentCulture.ClearCachedData()\n System.Globalization.CultureInfo DateTime.Now" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8653/" ]
296,920
<p>How do you get the current time (not date AND time)?</p> <p>Example: 5:42:12 PM</p>
[ { "answer_id": 296933, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 9, "selected": false, "text": "DateTime.Now.TimeOfDay TimeSpan DateTime.Now.ToString(\"h:mm:ss tt\")" }, { "answer_id": 296937, "author": "Stefan Schultze", "author_id": 6358, "author_profile": "https://Stackoverflow.com/users/6358", "pm_score": 4, "selected": false, "text": "Datetime.TimeOfDay TimeSpan" }, { "answer_id": 296941, "author": "benPearce", "author_id": 4490, "author_profile": "https://Stackoverflow.com/users/4490", "pm_score": 5, "selected": false, "text": "DateTime.Now.TimeOfDay\n DateTime.Now.ToShortTimeString()\n" }, { "answer_id": 296959, "author": "Oppositional", "author_id": 2029, "author_profile": "https://Stackoverflow.com/users/2029", "pm_score": 5, "selected": false, "text": "DateTime.Now.ToString(\"hh:mm:ss tt\", System.Globalization.DateTimeFormatInfo.InvariantInfo)\nDateTime.Now.ToString(\"hh:mm:ss.fff tt\", System.Globalization.DateTimeFormatInfo.InvariantInfo)\n DateTime.Now.ToString(\"HH:mm:ss\", System.Globalization.DateTimeFormatInfo.InvariantInfo)\nDateTime.Now.ToString(\"HH:mm:ss.fff\", System.Globalization.DateTimeFormatInfo.InvariantInfo)\n" }, { "answer_id": 296961, "author": "Khb", "author_id": 37817, "author_profile": "https://Stackoverflow.com/users/37817", "pm_score": 2, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n Console.WriteLine(DateTime.Now.ToLongTimeString().ToString());\n Console.WriteLine(DateTime.Now.ToShortTimeString().ToString());\n Console.ReadLine();\n }\n}\n" }, { "answer_id": 297644, "author": "Chris Fulstow", "author_id": 38126, "author_profile": "https://Stackoverflow.com/users/38126", "pm_score": 6, "selected": false, "text": "string.Format(\"{0:HH:mm:ss tt}\", DateTime.Now)\n" }, { "answer_id": 413170, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "\"'\" + DateTime.Now.ToString() + \"'\"\n string Command = @\"Insert Into CONFIG_USERS(smallint_empID,smallint_userID,str_username,str_pwd,str_secquestion,str_secanswer,tinyint_roleID,str_phone,str_email,Dt_createdOn,Dt_modifiedOn) values (\"\n + u.Employees + \",\"\n + u.UserID + \",'\"\n + u.Username + \"','\"\n + u.GetPassword() + \"','\"\n + u.SecQ + \"','\"\n + u.SecA + \"',\"\n + u.RoleID + \",'\"\n + u.Phone + \"','\"\n + u.Email + \"','\"\n + DateTime.Now.ToString() + \"','\"\n + DateTime.Now.ToString() + \"')\";\n DateTime" }, { "answer_id": 9126302, "author": "sadhana", "author_id": 1187153, "author_profile": "https://Stackoverflow.com/users/1187153", "pm_score": 2, "selected": false, "text": "DateTime theDate = DateTime.UtcNow;\n\nstring custom = theDate.ToString(\"d\");\n\nMessageBox.Show(custom);\n" }, { "answer_id": 9974622, "author": "Musikero31", "author_id": 440310, "author_profile": "https://Stackoverflow.com/users/440310", "pm_score": 6, "selected": false, "text": "DateTime.Now.ToString(\"HH:mm:ss tt\");\n" }, { "answer_id": 10629878, "author": "Sanjay", "author_id": 749956, "author_profile": "https://Stackoverflow.com/users/749956", "pm_score": 4, "selected": false, "text": " DateTime.Now.ToShortTimeString();\n" }, { "answer_id": 20924506, "author": "Ranjit Singh", "author_id": 1530742, "author_profile": "https://Stackoverflow.com/users/1530742", "pm_score": 2, "selected": false, "text": "DateTime.Now.ToString(\"hh:mm:ss tt\")" }, { "answer_id": 21145728, "author": "David Castro", "author_id": 3199531, "author_profile": "https://Stackoverflow.com/users/3199531", "pm_score": 2, "selected": false, "text": "MyEmail.Body = string.Format(\"The validation is done at {0:HH:mm:ss} Hrs.\",DateTime.Now);\n {0:HH:mm:ss} {0:HH:mm:ss.fff} {0:DD/mm/yyy HH:mm:ss}" }, { "answer_id": 21145970, "author": "Hannan Hossain", "author_id": 1872691, "author_profile": "https://Stackoverflow.com/users/1872691", "pm_score": 3, "selected": false, "text": "DateTime now = DateTime.Now;\nstring time = now.ToString(\"T\");\n" }, { "answer_id": 33289608, "author": "praguan", "author_id": 4640991, "author_profile": "https://Stackoverflow.com/users/4640991", "pm_score": 4, "selected": false, "text": " DateTime time = DateTime.Now;\n Console.WriteLine(time.ToString(\"h:mm:ss tt\"));\n" }, { "answer_id": 39679863, "author": "Douglas G. Allen", "author_id": 1207554, "author_profile": "https://Stackoverflow.com/users/1207554", "pm_score": 2, "selected": false, "text": "using System;\n\nnamespace JD\n{\n class Program\n {\n public static DateTime get_UTCNow()\n {\n DateTime UTCNow = DateTime.UtcNow;\n int year = UTCNow.Year;\n int month = UTCNow.Month;\n int day = UTCNow.Day;\n int hour = UTCNow.Hour;\n int min = UTCNow.Minute;\n int sec = UTCNow.Second;\n DateTime datetime = new DateTime(year, month, day, hour, min, sec);\n return datetime;\n }\n\n static void Main(string[] args)\n {\n DateTime datetime = get_UTCNow(); \n\n string time_UTC = datetime.TimeOfDay.ToString();\n Console.WriteLine(time_UTC);\n\n Console.ReadLine();\n\n }\n }\n}\n" }, { "answer_id": 41422533, "author": "Sarat Chandra", "author_id": 7121889, "author_profile": "https://Stackoverflow.com/users/7121889", "pm_score": 2, "selected": false, "text": "var CurDate= DateTime.Now;\nCurDate.Hour;\nCurDate.Minute;\nCurDate.Millisecond\n" }, { "answer_id": 47753938, "author": "Gupta", "author_id": 8247710, "author_profile": "https://Stackoverflow.com/users/8247710", "pm_score": 4, "selected": false, "text": "DateTime.Now.ToString(\"yyyy-MM-dd h:mm:ss tt\");\n" }, { "answer_id": 60394934, "author": "Bijeesh Raghavan", "author_id": 9315718, "author_profile": "https://Stackoverflow.com/users/9315718", "pm_score": 2, "selected": false, "text": "DateTime.Now.ToString(\"h:mm:ss tt\")\n" }, { "answer_id": 64263441, "author": "farsam", "author_id": 12362194, "author_profile": "https://Stackoverflow.com/users/12362194", "pm_score": 3, "selected": false, "text": "DateTime.Now.ToString(\"HH:mm\")\n" }, { "answer_id": 67353800, "author": "Santhosh N", "author_id": 8774514, "author_profile": "https://Stackoverflow.com/users/8774514", "pm_score": 0, "selected": false, "text": "var currentDateTime = DateTime.Now; \nvar currentTimeAlone = new TimeSpan(currentDateTime.Hour, currentDateTime.Minute, currentDateTime.Second); \nConsole.WriteLine(currentTimeAlone);\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296920", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,952
<p>How can I prevent the image tag that calls the associated image from displaying if no image is associated with the record?</p> <pre><code>&lt;%= image_tag @agent.avatar.url %&gt; </code></pre> <p>...gives me the text "Missing" if there is no image associated with that agent. I want to test to see there is an image available first, then render the above tag if the test returns true.</p> <p>Better yet, is there anyway for me to specify a default image if no image is specifically provided?</p>
[ { "answer_id": 296990, "author": "neezer", "author_id": 32154, "author_profile": "https://Stackoverflow.com/users/32154", "pm_score": 5, "selected": false, "text": "has_attached_file :avatar, :default_url => '/images/brokers/agents/anonymous_icon.jpg'\n" }, { "answer_id": 297329, "author": "Christoph Schiessl", "author_id": 20467, "author_profile": "https://Stackoverflow.com/users/20467", "pm_score": 7, "selected": true, "text": "<% if @agent.avatar.file? %>\n <%= image_tag @agent.avatar.url(:normal) %>\n<% else %>\n No attachment available!\n<% end %>\n" }, { "answer_id": 2363674, "author": "tig", "author_id": 96823, "author_profile": "https://Stackoverflow.com/users/96823", "pm_score": 4, "selected": false, "text": "<% if @agent.avatar? %>\n <%= image_tag @agent.avatar.url(:normal) %>\n<% else %>\n No attachment available!\n<% end %>\n" }, { "answer_id": 4197708, "author": "Voldy", "author_id": 235600, "author_profile": "https://Stackoverflow.com/users/235600", "pm_score": 6, "selected": false, "text": "has_attached_file :avatar, \n :styles => {:small => '30x30#', :large => '100x100#'}, \n :default_url => '/images/missing_:style.png'\n has_attached_file :avatar, \n :styles => {:small => '30x30#', :large => '100x100#'}, \n :default_url => '/assets/images/missing_:style.png'\n" }, { "answer_id": 25401936, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<% if @agent.avatar.present? %>\n <%= image_tag @agent.avatar.url(:normal) %>\n<% else %>\n No attachment available!\n<% end %>\n" }, { "answer_id": 27570182, "author": "stopanko", "author_id": 3549038, "author_profile": "https://Stackoverflow.com/users/3549038", "pm_score": 0, "selected": false, "text": "user.photo.exists?(:medium).\n" }, { "answer_id": 42777715, "author": "Nami", "author_id": 7652415, "author_profile": "https://Stackoverflow.com/users/7652415", "pm_score": 0, "selected": false, "text": "<% if @post.image.exists? %>\n<%= image_tag @post.image.url %>\n<% end %>\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296952", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32154/" ]
296,964
<p>What could the following line possibly mean?</p> <pre><code>my $x = shift; </code></pre>
[ { "answer_id": 296969, "author": "David Nehme", "author_id": 14167, "author_profile": "https://Stackoverflow.com/users/14167", "pm_score": 2, "selected": false, "text": "my ($x) = @_;\n" }, { "answer_id": 296991, "author": "Alnitak", "author_id": 6782, "author_profile": "https://Stackoverflow.com/users/6782", "pm_score": 4, "selected": false, "text": "shift @_ @ARGV $x" }, { "answer_id": 296995, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "shift @_ $x popped @_ $x = shift if @_;" }, { "answer_id": 297003, "author": "cowgod", "author_id": 6406, "author_profile": "https://Stackoverflow.com/users/6406", "pm_score": 6, "selected": false, "text": "shift() shift foo shift sub foo() {\n my $x = shift;\n my $y = shift;\n my $z = shift;\n # do something\n}\n @_ @ARGV" }, { "answer_id": 297919, "author": "Gaurav", "author_id": 27310, "author_profile": "https://Stackoverflow.com/users/27310", "pm_score": 3, "selected": false, "text": "$_ @_ my $x = shift @_;\n @_ perlsub shift @_ $x $_[0]" }, { "answer_id": 72054829, "author": "U. Windl", "author_id": 6607497, "author_profile": "https://Stackoverflow.com/users/6607497", "pm_score": -1, "selected": false, "text": "perldoc -f shift man perlbook @_ $x @_ @_ my $a = shift;\nmy $b = shift;\nmy $c = shift;\n my ($a, $b, $c) = @_;\n my $a = $_[0];\nmy $b = $_[1];\nmy $c = $_[2];\n @_" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
296,967
<p>I'm wondering where the callbacks are (or if there are anything) for animations in a CALayer. Specifically, for implied animations like altering the frame, position, etc. In a UIView, you could do something like this:</p> <pre><code>[UIView beginAnimations:@"SlideOut" context:nil]; [UIView setAnimationDuration:.3]; [UIView setAnimationDelegate:self]; [UIView setAnimationDidStopSelector:@selector(animateOut:finished:context:)]; CGRect frame = self.frame; frame.origin.y = 480; self.frame = frame; [UIView commitAnimations]; </code></pre> <p>Specifically, the <code>setAnimationDidStopSelector</code> is what I want for an animation in a CALayer. Is there anything like that?</p> <p>TIA.</p>
[ { "answer_id": 297045, "author": "Jeffrey Forbes", "author_id": 28019, "author_profile": "https://Stackoverflow.com/users/28019", "pm_score": 7, "selected": true, "text": "CABasicAnimation CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@\"frame\"];\nanim.fromValue = [NSValue valueWithCGRect:layer.frame];\nanim.toValue = [NSValue valueWithCGRect:frame];\nanim.delegate = self;\n[layer addAnimation:anim forKey:@\"frame\"];\n animationDidStop:finished:" }, { "answer_id": 11271165, "author": "bennythemink", "author_id": 467608, "author_profile": "https://Stackoverflow.com/users/467608", "pm_score": 7, "selected": false, "text": "[CATransaction begin];\nCABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:@\"strokeEnd\"];\n[pathAnimation setDuration:1];\n[pathAnimation setFromValue:[NSNumber numberWithFloat:0.0f]]; \n[pathAnimation setToValue:[NSNumber numberWithFloat:1.0f]];\n[CATransaction setCompletionBlock:^{_lastPoint = _currentPoint; _currentPoint = CGPointMake(_lastPoint.x + _wormStepHorizontalValue, _wormStepVerticalValue);}];\n[_pathLayer addAnimation:pathAnimation forKey:@\"strokeEnd\"];\n[CATransaction commit];\n" }, { "answer_id": 26643565, "author": "user3077725", "author_id": 3077725, "author_profile": "https://Stackoverflow.com/users/3077725", "pm_score": 6, "selected": false, "text": " [CATransaction begin];\n CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@\"opacity\"];\n animation.duration = 0.3;\n animation.fromValue = [NSNumber numberWithFloat:0.0f];\n animation.toValue = [NSNumber numberWithFloat:1.0f];\n animation.removedOnCompletion = NO;\n animation.fillMode = kCAFillModeBoth;\n /// [box addAnimation:animation forKey:@\"j\"]; Animation will not work if added here. Need to add this only after the completion block.\n\n [CATransaction setCompletionBlock:^{\n\n CABasicAnimation *animation2 = [CABasicAnimation animationWithKeyPath:@\"opacity\"];\n animation2.duration = 0.3;\n animation2.beginTime = CACurrentMediaTime()+1;\n animation2.fromValue = [NSNumber numberWithFloat:1.0f];\n animation2.toValue = [NSNumber numberWithFloat:0.0f];\n animation2.removedOnCompletion = NO;\n animation2.fillMode = kCAFillModeBoth;\n [box addAnimation:animation2 forKey:@\"k\"];\n\n }];\n\n [box addAnimation:animation forKey:@\"j\"];\n\n [CATransaction commit];\n" }, { "answer_id": 39671380, "author": "tdon", "author_id": 4333934, "author_profile": "https://Stackoverflow.com/users/4333934", "pm_score": 6, "selected": false, "text": " // Begin the transaction\n CATransaction.begin()\n let animation = CABasicAnimation(keyPath: \"strokeEnd\")\n animation.duration = duration //duration is the number of seconds\n animation.fromValue = 0\n animation.toValue = 1\n animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)\n circleLayer.strokeEnd = 1.0\n\n // Callback function\n CATransaction.setCompletionBlock { \n print(\"end animation\")\n }\n\n // Do the actual animation and commit the transaction\n circleLayer.add(animation, forKey: \"animateCircle\")\n CATransaction.commit() \n" }, { "answer_id": 47536770, "author": "Fattie", "author_id": 294884, "author_profile": "https://Stackoverflow.com/users/294884", "pm_score": 6, "selected": false, "text": "[weak self] func animeExample() {\n \n CATransaction.begin()\n \n let a = CABasicAnimation(keyPath: \"fillColor\")\n a.fromValue, duration = ... etc etc\n \n CATransaction.setCompletionBlock{ [weak self] in\n self?.animeExample()\n self?.ringBell()\n print(\"again...\")\n }\n \n someLayer.add(a, forKey: nil)\n CATransaction.commit()\n}\n setCompletionBlock someLayer.add forKey" }, { "answer_id": 48060333, "author": "Jack", "author_id": 7576100, "author_profile": "https://Stackoverflow.com/users/7576100", "pm_score": 4, "selected": false, "text": "delegate class CircleView: UIView,CAAnimationDelegate {\n...\n\nlet animation = CABasicAnimation(keyPath: \"strokeEnd\")\nanimation.delegate = self//Set delegate\n func animationDidStop(_ anim: CAAnimation, finished flag: Bool) {\n print(\"Animation END\")\n }\n" }, { "answer_id": 55623185, "author": "Jimmy_m", "author_id": 1449618, "author_profile": "https://Stackoverflow.com/users/1449618", "pm_score": 3, "selected": false, "text": "func blinkShadow(completion: @escaping (() -> Void)) {\n CATransaction.begin()\n let animation = CABasicAnimation(keyPath: \"shadowRadius\")\n animation.fromValue = layer.shadowRadius\n animation.toValue = 0.0\n animation.duration = 0.1\n animation.autoreverses = true\n CATransaction.setCompletionBlock(completion)\n layer.add(animation, forKey: nil)\n CATransaction.commit()\n}\n" }, { "answer_id": 60921060, "author": "IceSoul", "author_id": 10214105, "author_profile": "https://Stackoverflow.com/users/10214105", "pm_score": 0, "selected": false, "text": " class OnAnimationListener : AnimatorListener {\n\n weak var s : ViewController?\n\n init(_ ins: ViewController) {\n s = ins\n }\n func onAnimationStart(_ animation: Animator) {}\n func onAnimationEnd(_ animation: Animator) {\n\n print(\"end\")\n s?.label.text = \"end\"\n\n }\n func onAnimationCancel(_ animation: Animator) {}\n func onAnimationRepeat(_ animation: Animator) {}\n\n }\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296967", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28019/" ]
296,971
<p>The section <strong>Last links in the chain: Stashing and the reflog</strong> in <a href="http://ftp.newartisans.com/pub/git.from.bottom.up.pdf" rel="noreferrer">http://ftp.newartisans.com/pub/git.from.bottom.up.pdf</a> recommends stashing often to take snapshots of your work in progress. The author goes as far as recommending that you can use a cron job to stash your work regularly, without having to do a stash manually.</p> <blockquote> <p>The beauty of stash is that it lets you apply unobtrusive version control to your working process itself: namely, the various stages of your working tree from day to day. You can even use stash on a regular basis if you like, with something like the following snapshot script:</p> <pre><code>$ cat &lt;&lt;EOF &gt; /usr/local/bin/git-snapshot #!/bin/sh git stash &amp;&amp; git stash apply EOF $ chmod +x $_ $ git snapshot </code></pre> <p>There’s no reason you couldn’t run this from a cron job every hour, along with running the reflog expire command every week or month.</p> </blockquote> <p>The problem with this approach is:</p> <ol> <li>If there are no changes to your working copy, the "git stash apply" will cause your last stash to be applied over your working copy. </li> <li>There could be race conditions between when the cron job executes and the user working on the working copy. For example, "git stash" runs, then the user opens the file, then the script's "git stash apply" is executed.</li> </ol> <p>Does anybody have suggestions for making this automatic stashing work more reliably? </p>
[ { "answer_id": 417540, "author": "d0k", "author_id": 52109, "author_profile": "https://Stackoverflow.com/users/52109", "pm_score": 3, "selected": false, "text": "#!/bin/sh\nGIT_DIR=$(git rev-parse --git-dir) || exit\nref_stash=refs/stash\n\nw_commit=$(git stash create) # creates a commit for the wip\n\n# gather some info\nhead=$(git log --no-color --abbrev-commit --pretty=oneline -n 1 HEAD --)\nbranch=$(git symbolic-ref -q HEAD)\nbranch=${branch#refs/heads/}\nmsg=$(printf 'WIP on %s: %s' \"$branch\" \"$head\")\n\n# Make sure the reflog for stash is kept.\n: >>\"$GIT_DIR/logs/$ref_stash\"\n\ngit update-ref -m \"$msg\" $ref_stash $w_commit\n" }, { "answer_id": 15367176, "author": "Philippe", "author_id": 717372, "author_profile": "https://Stackoverflow.com/users/717372", "pm_score": 2, "selected": false, "text": "s = !sh -c \\\"git stash save | grep 'No local changes to save' && git $* || (git $* && git stash pop) \\\"\n" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4883/" ]
296,975
<p>I'm using <code>git-svn</code> to work against my company's central Subversion repository. We've recently created a new feature branch in the central repo. </p> <p>How do I tell Git about it? When I run <code>git branch -r</code> I can only see the branches that existed when I ran <code>fetch</code> against the Subversion repo to initialize my Git repo?</p>
[ { "answer_id": 297000, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 6, "selected": false, "text": "git svn fetch" }, { "answer_id": 1430782, "author": "vjangus", "author_id": 76516, "author_profile": "https://Stackoverflow.com/users/76516", "pm_score": 9, "selected": true, "text": "git config --add svn-remote.newbranch.url https://svn/path_to_newbranch/\ngit config --add svn-remote.newbranch.fetch :refs/remotes/newbranch\ngit svn fetch newbranch [-r<rev>]\ngit checkout -b local-newbranch -t newbranch\ngit svn rebase newbranch\n" }, { "answer_id": 4416172, "author": "Tyler", "author_id": 65977, "author_profile": "https://Stackoverflow.com/users/65977", "pm_score": 4, "selected": false, "text": "git diff-tree <sha1 from step 1> <sha1 from step 2> git checkout local-newbranch git rebase <sha1 from step 1> local-newbranch remotes/newbranch .git/refs/remotes/newbranch newbranch git-update-ref refs/remotes/newbranch <new-SHA> git svn dcommit newbranch gitk --all" }, { "answer_id": 8140157, "author": "MikeHoss", "author_id": 39188, "author_profile": "https://Stackoverflow.com/users/39188", "pm_score": 0, "selected": false, "text": "git svn init -s <svn path with no trunk> local_repo\ncd local_repo\ngit svn fetch \n## wait\n git checkout --track -b branch_name branch_name\n" }, { "answer_id": 9240692, "author": "Mikael Lepistö", "author_id": 360060, "author_profile": "https://Stackoverflow.com/users/360060", "pm_score": 3, "selected": false, "text": "trunk\nbranches\n -> branch1\n -> sub-dir1\n -> branch2\n -> branch3\n -> sub-dir2\n -> branch4\n -> sub-dir3\n -> branchX \n<... hundreds more ...>\n git svn clone -r 10000:HEAD https://svn.com/MyRepo myrepo --prefix=svn/ --trunk=trunk \n localhost: elhigu$ git config --get-regexp \"svn-remote.\"\nsvn-remote.svn.url https://svn.com/MyRepo\nsvn-remote.svn.fetch trunk:refs/remotes/svn/trunk\n git config --add svn-remote.svn.fetch branches/sub-dir2/branch4:refs/remotes/svn/branches/sub-dir2/branch4\n git svn fetch -r 10000:HEAD\n git svn fetch --all -r 10000:HEAD\n" }, { "answer_id": 10173516, "author": "janos", "author_id": 641955, "author_profile": "https://Stackoverflow.com/users/641955", "pm_score": 7, "selected": false, "text": "git svn fetch\n .git/config git svn fetch [svn-remote \"svn\"]\n url = https://svn/path_to_repo_root/\n fetch = path_to_trunk:refs/remotes/git-svn\n branches = path_to_branches/*:refs/remotes/*\n url fetch branches url git svn --help [svn-remote \"huge-project\"]\n url = http://server.org/svn\n fetch = trunk/src:refs/remotes/trunk\n branches = branches/{red,green}/src:refs/remotes/branches/*\n tags = tags/{1.0,2.0}/src:refs/remotes/tags/*\n git-svn git svn fetch fetch [svn-remote \"huge-project\"]\n url = http://server.org/svn\n fetch = trunk/src:refs/remotes/trunk\n fetch = branches/blue:refs/remotes/branches/blue\n fetch = branches/yellow:refs/remotes/branches/yellow\n branches = branches/{red,green}/src:refs/remotes/branches/*\n .git/svn/.metadata branches-maxRev tags-maxRev git svn fetch" }, { "answer_id": 11187873, "author": "vadishev", "author_id": 1065967, "author_profile": "https://Stackoverflow.com/users/1065967", "pm_score": 2, "selected": false, "text": "$ git commit\n$ git svn rebase\n$ git svn dcommit\n $ git commit\n$ git push\n $ git svn rebase\n $ git pull [--rebase]\n $ git svn branch foo\n$ git checkout -b foo -t remotes/foo\n$ git commit\n$ git svn dcommit\n $ git checkout -b foo\n$ git commit\n$ git push\n" }, { "answer_id": 21829194, "author": "Haddon CD.", "author_id": 1831696, "author_profile": "https://Stackoverflow.com/users/1831696", "pm_score": 2, "selected": false, "text": ".git/info/grafts <initial branch commit> <parent commit in trunk>\n 378b0ae0902f5c2d2ba230c429a47698810532e5 6c7144991381ce347d4e563e9912465700be0638\n" }, { "answer_id": 22819300, "author": "Gil Hamilton", "author_id": 1076479, "author_profile": "https://Stackoverflow.com/users/1076479", "pm_score": 3, "selected": false, "text": "svn+ssh://gil@svn.myplace.com/repo newbranch newbranch git-newbranch" } ]
2008/11/17
[ "https://Stackoverflow.com/questions/296975", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4203/" ]